EN: Retranslate all documents via Gemini Pro 3, Human proofreading

This commit is contained in:
Meow
2026-01-24 06:07:31 +08:00
parent a07654a1d1
commit b7ee2196c6
91 changed files with 6053 additions and 5509 deletions
+50 -54
View File
@@ -1,99 +1,95 @@
# [Chapter 1] Simple and Plain Language
# [Chapter 1] Plain English Guide for Absolute Beginners
## 1.1 Who is this document written for?
## 1.1 Who is this document for?
One sentence: Written for newbies who are **(1) absolute beginners** and **(2) interested in learning how to build their own VPS**.
In short: It is written for newcomers who have **① Zero technical background** and **② A desire to learn how to self-host a VPS**.
## 1.2 Who is this document not written for?
## 1.2 Who is this document NOT for?
Including but not limited to: experts and professionals, beginners who are too lazy to tinker on their own, advanced users who already know how to tinker, wealthy users who insist on using airport services, and those who prefer using one-click scripts. In short, if you have a technical background or don't want to build it yourself, you can close this article directly, because this article may not be suitable for you and may even make you upset.
Including but not limited to: various tech gurus, beginners too lazy to tinker, experts who already know the ropes, big spenders determined to use "Airports" (VPN service providers), and the "Carefree Sect" determined to use one-click scripts... In short, as long as you have a technical foundation or are unwilling/don't want to build it yourself, you can close this article right now. This article probably won't meet your high standards and might just make you angry over nothing, which isn't worth it.
## 1.3 Declaration and Other Statements
## 1.3 Solemn Declaration and Other Declarations
Declaration:
**Solemn Declaration:**
My technical skills are extremely limited, so this article is inevitably full of errors and flaws. If you find any problems, please kindly point them out and don't be too harsh on me.
My technical skills are incredibly poor, so this text will inevitably have omissions and be full of flaws. If you find issues, please remind me gently; do not engage in personal attacks.
Disclaimer:
**Disclaimer:**
Please judge the reliability and usability of the content of this article by yourself. If you encounter any problems or negative results when establishing and using a VPS server based on the content of this article, I am not responsible for it.
Please judge the credibility, reliability, and usability of this content yourself. I am not responsible for any issues or adverse results arising from building and using a VPS server based on this content.
Verbose statement:
**Verbose Declaration:**
Considering the target audience of this article, which is "users with zero experience", many details will be explained in great detail, so the language may be verbose. Please be mentally prepared for this.
Based on the target audience of this article (Zero-basis users), many contents will be explained as exhaustively as possible. Therefore, the language will lean towards being wordy/long-winded. Please be mentally prepared.
## 1.4 Why is self-hosting a challenge?
## 1.4 Why is self-hosting a difficult problem?
To answer this question, we need to provide a little more background information.
To answer this question, we need to provide a bit more background information.
1. On the matter of accessing the internet through scientific means
**I. The matter of Scientific Internet Access (Circumvention)**
The act of accessing the internet using scientific methods has been around for almost 20 years (shocking!!!.jpg). Initially, one could do it with a little effort (changing the host file, using SSH), then one had to find a web proxy, and later, one had to develop a private protocol (such as Shadowsocks) and so on.
The practice of "Scientific Internet Access" (circumventing the firewall) has been developing for nearly twenty years (Shocking!!!.jpg). Initially, you only needed to move your hands a little (tweak the hosts file, connect via SSH). Later, you needed to find a web proxy, and then later you needed to write a private protocol (like Shadowsocks), and so on.
With the continuous iteration and upgrade of GFW technology over the past decade, to achieve the goal of [building your own scientific Internet access], the things that need to be done include but are not limited to:
With the GFW technology constantly iterating and upgrading over the last decade, the tasks required to achieve the goal of "Do-It-Yourself Circumvention" now include but are not limited to:
- Understand basic Linux commands
- Understand network transmission protocols
- Have the technical and financial ability to purchase and manage a VPS
- Have the technical and financial ability to purchase and manage a domain name
- Have the technical ability to apply for a TLS certificate, and so on.
- Understanding basic Linux system commands
- Understanding network transmission protocols
- Having the technical and financial capability to complete VPS purchase and management
- Having the technical and financial capability to complete Domain purchase and management
- Having the technical capability to complete TLS certificate application, etc.
This has turned the once simple act of [setting up a self-built VPS for accessing the internet in a secure and unrestricted manner] into a daunting challenge that intimidates newcomers.
This has turned the once-simple act of "self-hosted VPS circumvention" into a daunting challenge for newcomers.
2. Helplessness of Zero-based Users
**II. The helplessness of zero-basis users**
For non-technical users with zero foundation, if they complete the above series of operations, they will inevitably need to learn a lot of knowledge. However, after a little searching, newbies are likely to become even more confused: a large amount of information is scattered in various corners of the Internet: blogs, Q&A sites, groups, forums, GitHub, Telegram, YouTube, and so on. These pieces of information are chaotic and complex, with varying levels of quality, and may even contradict each other. Basically, they won't stop until they completely confuse the newcomer.
If a zero-basis, non-technical user wants to complete the series of operations above, they inevitably have to learn a vast amount of knowledge. However, after a little searching, the newcomer will likely become even more lost: massive amounts of information are scattered across every corner of the Internet (blogs, Q&A sites, groups, forums, GitHub, Telegram, YouTube, etc.). This information is chaotic, complex, of varying quality, and potentially contradictory. Basically, it won't stop until the newcomer is completely dizzy.
Faced with such chaotic information, newcomers suddenly shift from [information scarcity] to [information overload]. If they fail after several attempts of groping and guessing (which is highly probable), their enthusiasm is bound to be greatly frustrated. In this process, if they happen to seek help in some unfriendly places, they may be ridiculed even more: "You're so inexperienced, just use the airport, why bother messing around!" "Go learn Linux first before coming back to ask."
Faced with this disorganized information, the newcomer suddenly goes from "information scarcity" to "information overload." If they try to muddle through a few times and end up failing (which is highly probable), their enthusiasm will inevitably suffer a major setback. During this process, if they happen to go to some unfriendly places to ask for help, they might be ridiculed, adding insult to injury: "If you're so bad at this, just use an Airport, why are you blindly tinkering?", "Go learn Linux first before coming back to ask."
At this moment, probably only an "hehe" can express the mood.
At this point, perhaps only a sarcastic "Heh" can express one's mood.
## 1.5 "Why not just use the airport?"
## 1.5 "Isn't using an airport enough?"
An Airport refers to a pre made solution, where a provider is responsible all technical aspects of hosting and providing the service as mentioned in section 1.4, with the user only paying for the right to use the service.
First, I want to ask those who sneer: Is "using an airport" really a panacea?
First of all, I would like to respond to critics by asking a question: Is using an airport really a cure all?
Secondly, I believe there is a fundamental difference between "not understanding" and "not wanting to understand." While entitled "giant babies" with bad attitudes are naturally annoying, people who genuinely want to self-study but can't find the way shouldn't be subjected to unwarranted eye-rolls and discrimination. It is precisely this toxic community atmosphere that makes no distinction regarding newcomers that prompted me to write this article. So, without further ado, let's look at the pros and cons of airports:
Secondly, I believe that there is a fundamental difference between "not understanding" and "not wanting to understand". The bad attitude of some people who just want handouts is naturally annoying, but those who sincerely want to learn but don't know how should not be subject to unjustified contempt and discrimination. It is precisely this kind of bad community atmosphere that does not distinguish between newcomers that prompted me to write this article. So without further ado, let's take a look at the advantages and disadvantages of using an airport:
**I. Advantages of "Airports"**
- Advantages of "Airports"
A so-called "Airport" is a "Line Provider" (VPN/Proxy Service). They handle the string of technical operations and management mentioned in 1.4, and the user pays for the right to use it. Therefore, its advantages are at least:
1. **Stability**: Airports usually feature multiple exit nodes, hence resistance to attempts at blocking these node, if one get block simply switch to another
2. **Speed**: Airports typically make use of high capacity machines and high throughput network infrastructures, therefore you can expect a higher overall network speed
3. **Safety**: Airports are generally have good security practices, such as encryption and firewalls to ensure the security of user data
4. **reliability**: Airports employ a dedicated team to manage their services ensuring they remain online and reliable
5. **support**: you can generally expect an Airport to have a support team to answer your queries.
6. **Simplicity**: One-click rule addition, Scannable configurations, etc.
7. **diverse-exit-nodes**: Useful to access geo-restricted content or to get a lower ping for gaming
1. **Simple User Operation**: Scanning QR codes, one-click rule addition, etc.
2. **Many Line Choices**: Can unlock network services in different countries and regions; such as IPLC dedicated lines, game acceleration services, etc.
3. **Many Access Nodes**: Stronger ability to resist node blocking; if one gets blocked, just switch to the next.
- Risks of "Airport"
**II. Risks of "Airports"**
"The counterpart of convenience in 'internet' security is 'risk', some risk of 'airports' you can find on the market are"
The other side of the "convenience" coin is "risk." Based on the technical characteristics and market situation of "Airports," the risks are at least:
1. service providers can obtain all infomation that passes through their servers, these data are very likely stored by the providers for a long time with little legal means to stop them
2. there is little governance on the market for "airports", meaning there are plenty cases of fraud where providers disappear after being paid
3. Service providers can face regulatory pressures, while large providers are relatively secure, they cannot avoid attention from the government, In 2020 there are many cases where several large airports experience major service disruptions
4. A providers technical prowess is difficult to determine, the quality of the service provided varies greatly, with false advertising being common
1. **"Airports" can fully access user information**: All user traces on the Internet *inevitably* pass through and are *very likely* stored on their servers for a long time. These records are not bound by any legally effective user privacy agreements (**peeping, recording your every move**).
2. **"Airports" lack market regulation**: There are inevitably malicious merchants aiming at fraud (**active exit scams/running away**).
3. **"Airports" face regulatory pressure**: While big airports are relatively secure, they cannot avoid attracting attention. In 2020, several large airports suspended operations or ran away, severely interfering with users' normal usage (**passive exit scams/forced shutdown**).
4. **"Airport" technical levels are hard to determine**: Line quality varies greatly, and deceptive practices are common (**slow speeds, frequent drops, inability to connect**).
## 1.6 So should you host your own tunnel?
## 1.6 So, do you want to self-host or not?
Now that you have seen the advantages and risks of using a service provider, please think carefully and make your own decision on what to use. After all, the best plan is the one that suits you best.
Now that you have seen the advantages and risks of airports, please think fully and decide for yourself what to use. After all, the solution that suits you best is the best solution.
![It's Your Choice!](./ch01-img01-choice.png)
1. If you decide to use an existing service provider, you can close this article now.
1. If you decide to use an airport, you can close this article now.
2. If you decide to build it yourself, please continue reading the following chapters!
2. If you decide to self-host, please continue reading the following chapters!!
In short, the goal of this article is to serve as a starting point for users with zero experience, providing thorough explanations and demonstrations for each step, even if it may seem overly detailed or repetitive. The aim is to assist beginners in completing the entire process of deploying a VPS server from the first command input to successfully accessing the internet via the client, and gradually introducing them to basic Linux operations, laying a foundation for further self-learning.
In short, the goal of this article is to become the knowledge starting point for zero-basis users. It provides full explanations and demonstrations for every step, clearly (even **naggingly, chattily, and wordily**) assisting newcomers to complete the entire process from **inputting the first command, deploying the VPS server, to successfully circumventing the firewall on the client side**. In this process, it helps newcomers gradually contact and become familiar with basic Linux operations, laying a foundation for further self-study.
## 1.7 Some digressions
## 1.7 A few extra words
1. There is a wealth of information beyond the wall, so please learn to think rationally and independently. Don't take sides easily and don't believe in sensational information. (This also serves as an reminder for friends live beyond the wall)
1. Information outside the wall is mixed. Please be sure to learn rational, independent critical thinking. Do not blindly take sides, and do not readily trust sensational information.
2. We sincerely hope that with a more open internet, everyone can access knowledge in real time, find better entertainment, experience this amazing world, and find like-minded individual to befriend, but do not become a scapegoat for anyone with ulterior motives.
2. I sincerely hope that after obtaining a smoother network, you can acquire fresh knowledge, richer entertainment, contact a better world, and make more like-minded friends, but do not become a scapegoat for anyone with ulterior motives.
3. Your internet identity is still your identity, and achieving absolute anonymity is extremely difficult. Therefore, please be sure to comply with the relevant laws and regulations in your personal location and the location of your IP address. Self-preservation should be your highest priority. (TLDR. Please take responsibility for your action on the internet)
3. Your internet identity is still your identity. Absolute anonymity is extremely difficult, so please be sure to comply with the relevant laws and regulations of your personal location and your IP location. At all times, self-protection is the most basic bottom line.
## 1.8 Your Progress
+29 -28
View File
@@ -1,52 +1,53 @@
# [Chapter 2] Prerequisite and preparations
# [Chapter 2] Raw Materials Preparation
This chapter is rather special because it involves monetary transactions. This article takes a neutral stance on the project and does not make specific recommendations. What I can do is to tell you what you need to prepare.
This chapter is somewhat special because it involves monetary transactions. Based on the neutral stance of this project, no specific recommendations will be made. What I can do is tell you what you need to prepare.
## 2.1 Acquiring a VPS
## 2.1 Obtain a VPS
You need to obtain a healthy VPS with an unblocked IP, and perform the following basic preparations in the management console:
You need to obtain a healthy VPS whose IP is not blocked, and complete the following basic preparations in the management panel:
1. Install Debian 10 64 bit Operating System on your VPS.
2. Note down the IP address of VPS (this article will use `"100.200.300.400"` as an example, which is an intentionally incorrect and illegal IP address. Please replace it with your real IP address).
3. Note down the SSH remote login port of VPS.
4. Note down the username and password for SSH remote login.
1. Install the **Debian 10 64bit** system in the VPS management panel.
2. Make a note of the VPS IP address (this article will use `"100.200.300.400"` to represent it).
::: tip
This is a deliberately written illegal IP; please replace it with your real IP.
:::
3. Make a note of the VPS SSH remote login port.
4. Make a note of the SSH remote login username and password.
Buying a VPS is a relatively complex matter. It is recommended to first learn the relevant knowledge and choose one that suits your own economic ability and network requirements. In addition, you can choose to take advantage of some benefits offered by tech giants (such as permanent free or limited-time free packages offered by Oracle Cloud Infrastructure and Google Cloud Platform). In any case, you must act within your means.
Purchasing a VPS is a relatively complex matter. It is recommended to learn some relevant knowledge first and choose one that fits your financial ability and line quality needs. Additionally, you can choose to take advantage of free offers from major international tech giants (such as the permanent free or limited-time free tiers provided by Oracle and Google). In short, please act according to your means.
:::tip Explanation
Regarding the choice of Debian 10 as the operating system, let me elaborate a bit: No matter what you have heard online, no matter which guru has told you that XXX version of Linux is better or XXX version of Linux is more powerful, these sectarian disputes have **nothing to do with you right now**! Using Debian 10 is enough to optimize your VPS server for security, stability, and performance (such as using cloud-optimized kernel, timely support of BBR, etc.). After you become familiar with Linux, you can try other Linux distributions.
::: tip Note
Regarding the choice of Debian 10 as the operating system, let me add a few words here: No matter what you hear online, no matter which "guru" tells you that XXX version of Linux is better or XXX version of Linux is cooler, these Linux distro wars **have absolutely nothing to do with you right now**! Using Debian 10 is sufficient to allow your VPS server to run securely and stably while receiving enough optimization (such as cloud-specific kernels, timely BBR support, etc.). Once you are familiar with Linux, it won't be too late to look back and try other Linux distributions.
:::
## 2.2 Obtaining a Desired Domain Name
## 2.2 Obtain a Desired Domain Name
You need to obtain a domain name and add an A record in the DNS settings, pointing to the IP address of your VPS.
You need to obtain a domain name and add an A record in the DNS settings pointing to your VPS IP address.
1. Please choose a reliable international domain name service provider. Choose some common domain name suffixes, and make sure not to use the `.cn` suffix.
2. In the DNS settings, add an A record pointing to the IP address of your VPS (the name of the A record can be anything, and in this article, it will be represented by `"a-name"`). The complete domain name will be represented by `"subdomain.yourdomain.com"` or `"a-name.yourdomain.com"`. The effect is as shown in the picture below:
1. Please choose a reliable international domain registrar. Choose some common domain suffixes, but be careful **not** to use the `.cn` suffix.
2. In the DNS settings, add an **A record** pointing to your VPS IP address (The name of the A record can be anything; this article will use `"a-name"` to represent it. The full domain name will be represented as `"subdomain.yourdomain.com"` or `"a-name.yourdomain.com"`). The effect is shown in the figure below:
![Add A Record](./ch02-img01-a-name.png)
::: tip
This is **not** a real usable website. Please replace it with your real website URL.
This is **not** a real, usable URL; please replace it with your real URL.
:::
## 2.3 Software you need to install on your local computer
## 2.3 Software to Install on Your Local Computer
1. SSH remote login tool
1. **SSH Remote Login Tool**
* Windows: [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)
* macOS/Linux: Terminal
- Windows: [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)
- macOS/Linux: Terminal
2. **Remote File Copy Tool**
* Windows: [WinSCP](https://winscp.net/eng/index.php)
* macOS/Linux: Terminal
2. Remote file copying tool
- Windows: [WinSCP](https://winscp.net/eng/index.php)
- macOS/Linux: Terminal
3. Reliable text editor
- Windows/macOS/Linux: [VSCode](https://code.visualstudio.com)
3. **Reliable Text Editor**
* Windows/macOS/Linux: [VSCode](https://code.visualstudio.com)
## 2.4 Your Progress
If you have all the raw materials ready as mentioned above, you have already obtained the key to unlocking the door to a new world. So, what are you waiting for? Let's quickly move on to the next chapter and step through this door!
If you have prepared all the raw materials above, you have obtained the key to opening the door to a new world. So what are you waiting for? Let's move on to the next chapter and walk through that door!
> ⬛⬛⬜⬜⬜⬜⬜⬜ 25%
+44 -49
View File
@@ -2,88 +2,83 @@
## 3.1 Remote Login to VPS (PuTTY)
First of all, considering that the user base of Windows is the largest among the zero-based population, this article uses Windows as an example for demonstration.
First, given that Windows has the largest user base among beginners, this article will use Windows as an example.
Secondly, although PowerShell and WSL after Windows 10 can also achieve a good SSH operation experience, not all versions of Windows have the latest components. Therefore, this article uses the classic PuTTY as an example to provide a detailed explanation of SSH remote login operation. (If you use other tools, the operations after the SSH login are the same.)
Secondly, although modern Windows 10 and later versions feature PowerShell and WSL which offer a great SSH experience, not all versions of Windows have the latest components. Therefore, we will use the classic tool **PuTTY** for this detailed SSH tutorial. (If you use other tools, the operations after logging in are identical.)
Follow me step by step and let's start the operation.
Now, follow me step by step.
1. Go to the [official website](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html) of PuTTY and download the version that suits your operating system (this article uses the 64-bit version as an example).
1. Go to PuTTY's [official website](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html) and download the version suitable for your operating system (this article uses the 64-bit version).
![Download PuTTY](./ch03-img01-putty-download.png)
![Download PuTTY](./ch03-img01-putty-download.png)
2. After installation and running, you will see the main interface of PuTTY. Now please take out your notebook from the previous chapter where you wrote down the **IP address (VPS IP)** and **port (VPS PORT)** of your VPS in the corresponding positions of the following figure. In order to save time and avoid repeatedly entering these details in the future, we can save the session (Saved Sessions), and simply load it in the future with one click.
2. After installation, open PuTTY. Now, take out the [notebook](./ch02-preparation.md#21-getting-a-vps) where you jotted things down in the previous chapter. Fill in your VPS **IP Address** and **Port** in the corresponding fields shown below. To avoid typing this every time, we can save the session. Just click `Save` under Saved Sessions, and in the future, click `Load` to restore settings instantly.
![PuTTY Settings](./ch03-img02-putty-settings.png)
![Configure PuTTY](./ch03-img02-putty-settings.png)
3. I suggest setting `keepalive` to `60` seconds in the `Connection` to prevent SSH from automatically disconnecting after a period of inactivity. Be sure to save the settings again.
3. I suggest setting `Seconds between keepalives` under `Connection` to `60`. This prevents SSH from automatically disconnecting due to inactivity. **Make sure to save your session settings again.**
![Prevent frequent disconnection](./ch03-img03-putty-keepalive.png)
![Prevent frequent disconnections](./ch03-img03-putty-keepalive.png)
::: warning Attention
Any update to the PuTTY configuration needs to be manually saved to the session again. Otherwise, it will be lost after closing.
::: warning Note
Any setting updates in PuTTY must be manually saved to the Session again, otherwise, they will be lost when you close the program.
:::
4. Click on Open to enter the SSH connection window, then enter the username and password corresponding to the following figure to establish a connection with your VPS remote host. (This article assumes that the default username is `root`. Also, when entering a password in the Linux system, there will be no prompt like `******`, which can avoid password length leakage. It's not that your keyboard is broken!)
1. Click `Open` to enter the SSH connection window. Enter your username and password as shown below to connect to your VPS. (This article assumes the default username is `root`. Also, when typing passwords in Linux, **no asterisks `******` will appear**. This prevents password length leakage—your keyboard isn't broken!)
![SSH Remote Login](./ch03-img04-ssh-login.png)
![SSH Remote Login](./ch03-img04-ssh-login.png)
## 3.2 Successfully Logging in SSH! Introduction to Command Line Interface!
## 3.2 Successfully Logged into SSH! Meet the Command Line Interface
1. If you have filled in your information correctly, you will see a similar interface as the picture below, indicating that you have successfully logged in:
1. If you entered everything correctly, you will see a screen similar to the one below, indicating a successful login:
![Logging in to VPS for the first time](./ch03-img05-ssh-login-success.png)
![First Login to VPS](./ch03-img05-ssh-login-success.png)
This interface is equivalent to the "desktop" of a remote server, but it does not have familiar icons and a mouse, nor does it have colorful graphics. Instead, all you see is simple text. This is the "**Command Line Interface**" - shortened as `CLI`.
This interface is the remote server's [Desktop], but without the icons, mouse, or colorful graphics you are used to. It's just simple text. This is the **Command Line Interface** (CLI).
All the following operations require you to act like a hacker in a movie and complete them in this command-line interface. Maybe you will feel unfamiliar, but please believe me, using the command-line interface is neither scary nor mysterious. In the end, it just turns your familiar mouse operations into textual commands, **you say it, it does it**.
All subsequent operations require you to work in this interface, just like a hacker in the movies. It might feel strange, but trust me, the command line is neither scary nor mysterious. Ultimately, it just turns your mouse clicks into text commands: **You say it, it does it**.
2. Now, you can observe and familiarize yourself with the command line environment a little bit. This interface has actually provided you with some useful information, such as the system kernel version (e.g. `4.19.37-5` in the picture), last login time and IP address. Of course, depending on the VPS, the interface you see may be slightly different.
2. Now, look around and get familiar with the CLI environment. This interface actually tells you some useful info, like the system kernel version (e.g., `4.19.37-5` in the image), last login time, and IP. Of course, depending on your VPS, what you see might differ slightly.
3. Please pay attention to the line at the bottom of the command line, to the left of the flashing cursor, there is a string of characters. The one shown in the figure is `root@vps-server:~#`. How to understand this string? It's very simple:
3. Pay attention to the last line, to the left of the flashing cursor. There is a string of characters. In the image, it shows `root@vps-server:~#`. How should you understand this? Simple:
- The current user is `root`
- The server `root` is on is `vps-server`
- The folder `root` is currently in is `~`
- The `#` indicates where you can type commands
- The current user is `root`
- The server where `root` is located is `vps-server`
- The current directory where `root` is located is `~`
- After `#` is the place where you can input commands.
The first two are intuitive. The third is about the Linux file system; for now, just know that "`~`" is the [Current User's Home Base]. The fourth, the prompt `#`, doesn't need much thought. Just know that in future articles, commands you need to type will start with `#` or `$`, indicating **where** you start typing. (So when copying commands, **only copy the content after this symbol**, do not copy the prompt itself.)
The first two are pretty straightforward, no need to explain further. The third one is about the folder system in Linux. You don't need to go too deep into it for now. Just know that "`~`" represents **the home directory of the current user**. As for the fourth one, the prompt symbol "`#`", you don't need to worry about it either. Just know that in future articles, there will be some commands that you need to input, and they will be preceded by "`#`" or "`$`" to indicate **where you should input the command**. (So when you copy the command, **just copy the content after the prompt symbol** and don't copy the prompt symbol itself.)
## 3.3 Updating Linux Software for the First Time
## 3.3 Updating software on Linux for the first time!
1. Just like your phone (Android or iPhone) checks the App Store for updates (security patches and new features), Linux has a very similar update logic. If you can update apps on your phone, you can update Linux software!
1. Just like your phone, whether it's Android or iPhone, in order to keep your apps up-to-date (to get security patches and new features), you will occasionally receive update notifications from the app store, telling you how many apps need to be updated. Linux systems also have a similar update mechanism that works logically. So as long as you know how to update phone apps, you can learn how to update Linux software!
2. In Linux, every app is called a "package". The program that manages apps is naturally called the "Package Manager". You can install, update, and uninstall software, or even update the Linux system itself through it. The package manager is powerful, but for now, you only need to know that the Debian system's manager is called `apt`. Next, let's use `apt` to perform a full software update to get familiar with it.
2. In Linux, each application is called a "package". The program that manages the applications is naturally called a "package manager". You can use it to install, update, and uninstall various software, and even update the Linux system itself. Package managers in Linux are very powerful, but we won't go into details here. For now, you only need to know that the package manager for the Debian system is called `apt`. Next, we will first use `apt` to do a comprehensive update of the software to familiarize you with its basic operations.
3. Basic Linux commands for beginners:
3. Tiny White Linux Basic Commands:
| Code | Command Name | Description |
| :---: | :---: | :---: |
| `cmd-01` | `apt update` | Check for software updates |
| `cmd-02` | `apt upgrade` | Execute software updates |
| Number | Command Name | Command Description |
| :------: | :-----------: | :----------------------: |
| `cmd-01` | `apt update` | Query software updates |
| `cmd-02` | `apt upgrade` | Perform software updates |
4. Now enter the first command to fetch update information:
4. Now, please enter the first command to get update information.
```shell
apt update
```
```shell
apt update
```
5. Then enter the second command. When asked whether to continue `(Y/n)`, type `y` and hit Enter to start the installation:
This is a command used in a Linux terminal to update the package list from the repositories configured on the system.
```shell
apt upgrade
```
5. Then enter the second command, and when asked if you want to continue installing `(Y/n)`, type `y` and press enter to confirm and start the installation.
6. The complete process is demonstrated below:
```shell
apt upgrade
```
This is a command in the shell terminal to upgrade the installed packages on a Debian or Ubuntu Linux system.
6. The complete demonstration of the process is as follows:
![Demonstration of the software update process for the first time](./ch03-img06-apt-upgrade-full.gif)
![First Software Update Demo](./ch03-img06-apt-upgrade-full.gif)
## 3.4 Your Progress
**Congratulations on taking another solid step!** Now, you can log in to your remote server via SSH! After logging in, besides upgrading the software, what else should you do? Please enter the next chapter to find out!
**Congratulations on taking another solid step!** Now, you can log in to your remote server via SSH! After logging in and updating software, what should you do next? Head to the next chapter to find out!
> ⬛⬛⬛⬜⬜⬜⬜⬜ 37.5%
+265 -297
View File
@@ -1,351 +1,319 @@
# [Chapter 4] Security and Protection
# [Chapter 4] Security Protection
## 4.1 Why Do We Need Security Protection?
## 4.1 Why Security Protection is Necessary
Security protection for Linux servers is a complex and huge subject. Countless websites, apps, services, and even offline infrastructure are built on the foundation of Linux, which involves huge economic benefits and commercial value. This also means that there is a huge motivation for black and gray industries to launch attacks. However, these services are so important that major security vulnerabilities are not allowed. Therefore, countless operation and maintenance professionals are working hard on the battlefield of security attacks and defense, which enables us to enjoy a basic stable modern digital life.
Security protection for Linux servers is a vast and complex topic. Countless websites, apps, services, and even offline infrastructure are built upon the foundation of Linux. Behind this lies enormous economic interest and commercial value, which naturally implies that the black/gray market has a huge motivation to attack. However, these services are so critical that major security vulnerabilities simply cannot be allowed. Consequently, countless operations professionals strive on the battlefield of security offense and defense, allowing everyone to enjoy a basically stable modern digital life.
Now, you have a VPS and will open its data access channel to achieve the goal of traffic forwarding, which means you are now on the front line of the security battle and face all risks. However, at the same time, newcomers tend to have a polarized view of security issues due to lack of knowledge and information: either they feel it is as light as a feather and has nothing to do with them, or they feel it is as heavy as Mount Tai and feel anxious all day long.
Now that you own a VPS and will be opening up its data access channels to achieve traffic forwarding, you have effectively placed yourself on the front lines of this security battlefield, facing all risks directly. However, due to a lack of knowledge and information, newcomers often view security issues with polarized attitudes: they either feel it's trivial and has nothing to do with them, or they feel the weight is unbearable and live in constant fear.
- For the former, my suggestion is: safety is of utmost importance. Try to gather more information on safety issues to avoid regretting after experiencing losses.
* **For the former**, my advice is: No security matter is too small. Try to research security information as much as possible to avoid regretting it only after you have suffered a loss.
* **For the latter**, my advice is: Don't panic. Our servers generally don't hold high value and won't attract high-level targeted attacks. We mostly face malicious scanning and login attempts by automated scripts. Just follow this article to implement basic protections.
- For the latter, my suggestion is: don't worry too much, our servers still don't have too much value and generally won't attract high-level attacks. The basic threats we need to face are mostly malicious scans and login attempts from some automated scripts. Just follow this article to do some basic protection.
## 4.2 What Exactly Are the Specific Risks?
## 4.2 What are the specific risks
Just as we configured in the "Remote Login" chapter, anyone only needs to know four elements—**[IP Address] + [Port] + [Username] + [Password]**—to log into your VPS server. Obviously, the security of these four elements is the baseline we need to protect. Let's analyze them one by one:
Just like the configuration we did in the "Remote Login" section, anyone who knows the four elements of [IP address] + [port] + [username] + [password] can log in to your VPS server. So obviously, the security of these four elements is the bottom line that we need to protect. Let's analyze them one by one:
1. **[IP Address]**: Malicious scripts randomly attempt and scan IP ranges. You can simply consider this public information; it cannot be hidden.
2. **[Port]**: If using the default port, then **[Port = `22`]**.
3. **[Username]**: If using the default user, then **[Username = `root`]**.
4. **[Password]**: There is no default password; it is definitely randomly generated by the VPS backend or set by you. This means if your server uses default settings, three of the four elements are already known. The security of your entire server relies entirely on a small string of passwords. Here are a few scenarios:
* If you use the random password generated by the VPS panel, it usually contains a dozen mixed-case letters and symbols, which is relatively safe.
* If, for the sake of memory, you changed the password to something ultra-weak like `123456`, cracking your VPS server would be effortless.
* If, for the sake of memory, you changed the password to something complex but used elsewhere, it is essentially unsafe. You must understand that hackers have "cheat sheets," such as **Password Dictionaries**, containing tens of thousands to millions of leaked real passwords.
1. [IP Address]: Malicious scripts randomly attempt to scan IP ranges, which can be regarded as public information and cannot be hidden.
5. **But you must understand**, no hacker is actually sitting in front of a computer trying your password one by one. All attack attempts are carried out automatically by malicious scripts working 24/7. Perhaps while you are sound asleep, your server is enduring round after round of impacts.
2. [Port]: If you are using the default port, then [Port = `22`].
Once the password is successfully brute-forced, it means all your four elements are mastered by the attacker. The malicious script will quickly log in, obtain the highest `root` control of the server, install/deploy its malicious services, and then use your server to do various bad things 24 hours a day (such as mining, spreading viruses, sending spam/phishing emails, acting as a BT relay, or even becoming a public node for the dark web, etc.). If the malicious script is restrained, it can be quite stealthy. Since newcomers generally don't observe VPS login records, process changes, CPU usage, or traffic changes, it is difficult to discover that you have been hacked until your VPS provider bans your account or you receive a lawyer's letter.
3. [Username]: If using the default user, then [Username = `root`]
6. **Don't forget**, you likely used real payment information to obtain the VPS, and you leave your IP address when logging into various websites and social platforms. These are directly or indirectly related to your identity. **Once these bad things happen, they will inevitably be linked to you.**
4. [Password]: There is no default value for the password. It must be randomly generated by the VPS backend or set by you. In other words, if all the settings of your server are default, then three of the four elements are already known. Therefore, the security of your entire server relies on a small password. In this case, there are several situations:
## 4.3 What Security Protections Will We Implement?
- If you use a VPS management background to generate passwords randomly, it usually contains random uppercase and lowercase letters, symbols, and is relatively secure.
Based on the analysis above, what we need to do is naturally strengthen the **[Port]**, **[Username]**, and **[Password]** elements to reduce the risk of being breached:
- If you changed your password to something super weak like `123456` just for the sake of easy memorization, hacking into your VPS server would be a piece of cake.
1. **[Port]**: Change the SSH remote login port to a **[Non-22 Port]** (Section 4.4).
2. **[Username]**: Create a **[Non-root]** new user and disable root SSH remote login (Sections 4.5, 4.6).
3. **[Password]**: Enable SSH RSA key authentication and disable password authentication (Section 4.7).
- If you change your password to a more complex one that you have used elsewhere just for the sake of easy memory, it is not really safe. You should understand that hackers have cheats in their hands, such as `password tables`, which contain tens of thousands, hundreds of thousands, millions, or even more real leaked passwords.
Remember to follow the order so you don't lock yourself out.
5. But you should understand that no hacker really sits in front of a computer and tries your password repeatedly. All attack attempts are carried out automatically by malicious scripts, which work tirelessly for 24 hours. Perhaps while you are sleeping soundly every night, your server is enduring round after round of attacks.
## 4.4 Change SSH Remote Login Port to Non-22 Port
Once the password is successfully cracked, it means that all four of your elements have been mastered by the attacker. The malicious script will quickly log in to the server, obtain the highest `root` control of the server, install and deploy its malicious services, and then use your server to do all kinds of bad things 24 hours a day (such as mining, spreading viruses, sending spam emails, fraudulent emails, acting as a BT relay, and even dark web public nodes, and so on). If the malicious script is relatively restrained, it can actually achieve considerable concealment. Generally, newcomers will not observe and pay attention to indicators such as login records, process changes, CPU usage changes, and traffic changes of the VPS, so it is difficult for you to discover that you have been hacked. Until your VPS service provider blocks your account or you receive a lawyer's letter.
Now, let's solve the **[Port = `22`]** issue. (Note: Some VPS providers already use a non-22 port by default. You can skip this step or follow along to change it to another port).
6. Don't forget that when you obtain a VPS, you probably need to use your real payment information, and when you log in to various websites and social platforms, your IP address will also be recorded, which has a direct or indirect relationship with your identity. Therefore, once these bad things happen, they will inevitably be associated with you.
1. **Newbie Linux Basic Commands:**
## 4.3 What security measures do we need to take
| ID | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-03` | `nano` | Text Editor |
| `cmd-04` | `systemctl restart` | Restart a specific service |
Based on the above analysis, what we need to do is to strengthen the three elements of [port], [username], and [password] to reduce the risk of being hacked.
2. **Newbie Linux Basic Configuration Files:**
1. [Port]: Modify the SSH remote login port to a [non-22 port] (4.4).
2. [Username]: Create a [non-root] new user and disable root user SSH remote login (4.5, 4.6).
3. [Password]: Enable RSA key verification for SSH login and disable password verification login (4.7).
| ID | Config File Location | File Description |
| :---: | :---: | :---: |
| `conf-01` | `/etc/ssh/sshd_config` | SSH Remote Login Program Settings |
Remember to follow the order and don't lock yourself out.
3. The first thing we need to do is **[Use the `nano` text editor to open the `SSH Remote Login Program Settings`]**. In Windows, you would "find the file and double-click it." What about in Linux? Look at the command description above; isn't it simple? That's right, it is:
## 4.4 Change the SSH Remote Login Port to a Non-22 Port
```shell
nano /etc/ssh/sshd_config
```
Now, let's solve the problem of "port = `22`". (Note: some VPS service providers have non-22 ports set as default, so you can ignore this step if that's the case. Of course, you can also follow this article to change it to another port.)
4. After the file opens, you enter the `nano` interface. Observe briefly, and you'll find that it displays important shortcut keys at the bottom of the screen (in the red box below). It's like an open-book exam; no need for rote memorization. Isn't that thoughtful?
1. Basic commands of Little White Linux:
![nano interface](./ch04-img01-nano-ui.png)
| ID | Command Name | Description |
| :------: | :-----------------: | :---------------: |
| `cmd-03` | `nano` | Text editor |
| `cmd-04` | `systemctl restart` | Restart a service |
5. The second thing we need to do is **[Find `Port` in the opened file and modify its port number]**. The number after `Port` is the SSH port. It is generally recommended to change it to an integer greater than `1024` and less than `65535` (this article uses `9753` as an example). Combining with `nano` shortcuts, how should we operate? As expected, you got it right again!
* Use `ctrl+w` to enter search mode, then type `Port 22` and hit Enter.
* Delete `22` and change it to `9753`.
* **Note:** If the line starts with a `#`, it means this line is **[Not Effective]** (commented out). You can write a new one without `#` at the end of the file like I did, or just delete the `#`.
2. Basic Configuration Files of Little White Linux
::: warning
Using `9753` as an example in this article means that with the release of this article, this port will become a minor characteristic. It might be prioritized by attackers or interfered with/blocked by the GFW. Therefore, I strongly suggest you use a different port number you come up with yourself. After all, you have over 60,000 ports to choose from freely.
:::
| Number | Configuration File Location | File Description |
| :-------: | :-------------------------: | :-------------------------------: |
| `conf-01` | `/etc/ssh/sshd_config` | SSH Remote Login Program Settings |
6. The third thing we need to do is **[Save the file and exit]**.
* If you observed carefully in step 3, you'd notice that save isn't the common `ctrl+s`.
* **Correct Shortcuts:** Save is `ctrl+o` + `Enter`, Exit is `ctrl+x`.
* **(Some Operating Systems)** Add a firewall rule for the new SSH port; otherwise, you won't be able to login via SSH after the instance restarts.
* Example for Ubuntu `ufw`:
3. The first thing we need to do, of course, is to [open the SSH remote login program settings with the text editor `nano`]. In Windows, you will [find the file and double-click] it. What should you do in Linux? Take a close look at the command instructions above, isn't it simple? Yes, it is:
```shell
sudo ufw allow 9753/tcp
```
```shell
nano /etc/ssh/sshd_config
```
7. The final thing to do is **[Restart the SSH service to make changes take effect]**:
This is a command in the shell terminal to open the `sshd_config` file located in the `/etc/ssh/` directory using the `nano` text editor.
```shell
systemctl restart ssh
```
4. Once the file is opened, you will enter the interface of `nano`. After observing for a while, you will find that it displays important shortcut keys at the bottom of the screen (enclosed in a red box in the figure below). You can take the exam directly without memorizing them, which is very user-friendly, isn't it?
*Then try to open a new session in your SSH software to see if you can connect. If there are issues, you can modify the configuration via the old SSH session (the SSH session that was already open when sshd restarted will not be closed).*
![Interface of nano](./ch04-img01-nano-ui.png)
8. Full process demonstration:
5. The second thing we need to do is to **find the `Port` item in the opened file and modify its port**. The number after `Port` is the SSH port. It is generally recommended to change it to an integer greater than `1024` and less than `65535` (this article takes `9753` as an example). Please think about how to operate it with the shortcut keys of `nano`. You are right again! It is:
![Changing port demonstration](./ch04-img02-sshd-conf-full.gif)
- Use `ctrl+w` to enter search mode, then type `Port 22` and press Enter
- Delete `22` and replace it with `9753`
- Note: If this line starts with `#`, it means that this line is [commented out] and [does not take effect]. You can write a new line at the end of the file without `#`, or delete the `#` to enable this line.
9. **Modify PuTTY Configuration**
Now that the new port is effective, you must use `9753` the next time you log in with PuTTY. So, please go to PuTTY settings, change the port number, and **Save Session**. You know where to change it, right? (If not, re-read the previous content!)
## 4.5 Create a Non-root New User
Step two, let's solve the **[Username = `root`]** issue.
First, you need to understand that `root` in a Linux system is not just a simple administrator account. It is the **foundation** of the entire system, the master, the supreme god. Once the `root` account has a security issue, the entire system is at the mercy of others with nowhere to run. So follow me to operate:
1. **Newbie Linux Basic Commands:**
| ID | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-05` | `adduser` | Add a user to the system |
| `cmd-06` | `apt install` | Install specific software |
| `cmd-07` | `visudo` | Dedicated editor for modifying sudo permissions |
2. The first thing to do is **[Add a new user and set a login password]**. You can name it whatever you want; I will use `vpsadmin` as an example:
```shell
adduser vpsadmin
```
After executing the command, follow the prompts. **Be sure to set a user password** (don't forget that you won't see `******` when typing the password). Afterward, the system will ask for some additional user info; you can ignore these and just keep hitting Enter.
![Create new user](./ch04-img03-adduser.png)
::: warning
Using `vpsadmin` as an example means this username will also become a minor characteristic upon this article's release. Like the port, I strongly suggest you use a different username you create yourself.
:::
3. Full process demonstration:
![Create new user demonstration](./ch04-img04-adduser-full.gif)
4. The second thing to do is **[Install the `sudo` function]** (`sudo` allows a standard account to temporarily gain the power of `root` at critical moments to save the world).
```shell
apt update && apt install sudo
```
Smart users may have noticed this line is actually two commands. The first half `apt update` you've seen and used before; it refreshes software version info. The latter `apt install` is the **[Install Command]**. Joined by `&&`, it means [Refresh available software, AND THEN install the latest version of the `sudo` program].
5. The third thing to do is **[Add the `vpsadmin` user to the `sudo` list, granting them eligibility to borrow `root` powers]**.
```shell
visudo
```
Under `User Privilege Specification`, add a line: `vpsadmin ALL=(ALL) NOPASSWD: ALL`.
::: warning
I want to specifically explain the `NOPASSWD` setting. It means the `vpsadmin` user does not need to enter an extra password when using `root` privileges. **This is contrary to general security advice.** The reason I recommend this is that many newcomers ignore danger and persist in using the `root` account simply because they find repeatedly entering passwords annoying. Weighing the lesser of two evils, I believe **[The risk of using the `root` user directly]** is greater than **[The risk of not entering a password when using `sudo`]**, hence the recommendation.
If you prefer to follow tradition and enter a password every time you use `sudo`, change that line to `vpsadmin ALL=(ALL:ALL) ALL`.
:::
6. Full process demonstration:
![Sudo config demonstration](./ch04-img05-sudo-full.gif)
## 4.6 Disable Root SSH Remote Login
1. Now you are getting familiar with Linux, so let's have you think: what is the first thing we need to do? Correct, it is still **[Use the `nano` editor to open `SSH Remote Login Program Settings`]**. What? Can't remember how? Go review the content above and come back! ... Correct Answer:
```shell
nano /etc/ssh/sshd_config
```
2. Find the `PermitRootLogin Yes` item, and change its setting to `no`. Remember how? ... Correct Answer:
* Use `ctrl+w` to enter search mode, type `PermitRootLogin`, and Enter.
* Delete `yes` and change it to `no`.
3. Save the file and exit. Remember how? ... Correct Answer:
* Save is `ctrl+o`, then `Enter` to confirm.
* Exit is `ctrl+x`.
4. Restart the SSH service to make changes take effect. Remember... Never mind, here is the answer:
```shell
systemctl restart ssh
```
5. Full process demonstration:
![Disable root login demonstration](./ch04-img06-ssh-no-root-full.gif)
6. Next time you log in via PuTTY, the `root` user will no longer connect; you must switch the username to `vpsadmin`! For convenience, set `vpsadmin` as the default login username in PuTTY. (Nagging Note: Don't forget to Save Session).
![PuTTY default user](./ch04-img07-putty-default-user.png)
## 4.7 Use RSA Key Login and Disable Password Login
Step three, let's solve the problem of the **[Password]** potentially being brute-forced.
As mentioned earlier, hackers don't stupidly try every combination; they use cheat methods like "password dictionaries." Unless you use a randomly generated ultra-long password (via 1Password, macOS Keychain, etc.), you are easily vulnerable.
While ultra-long random passwords improve security, they are basically impossible to memorize and tedious to type manually. To solve this dilemma, we can abandon **[Password Authentication]** and switch to the more secure **[Key Authentication]**.
**[Key Authentication]** involves generating a **[Pair]** of related key files (Public Key and Private Key). You upload the **[Public Key]** to the VPS. Every time you log in, SSH matches the **[Public Key]** with the **[Private Key]**. If the validation confirms it is the correct **[Key Pair]**, authentication passes. (In other words, you don't need to remember or type complex passwords; you just need to protect the **[Private Key]** file from leaking).
::: warning
This article uses `9753` as an example, which means that with the release of this article, this port will become a feature that may be prioritized or blocked by attackers or the Great Firewall of China. Therefore, I strongly recommend that you use another port that you come up with yourself, after all, you have over 60,000 ports to choose from freely.
:::
6. The third thing we need to do is to [save the file and exit].
- If you observed carefully in step 3, you would have noticed that saving is not done by the common `ctrl+s`.
- The correct shortcut keys: save is `ctrl+o` + `enter`, and exit is `ctrl+x`.
- (For some operating systems) Add a firewall rule to set the new SSH port, otherwise, you won't be able to log in via SSH after the instance restarts.
- For example, on Ubuntu using ufw.
```shell
sudo ufw allow 9753/tcp
```
7. The last thing we need to do is to [restart the SSH service to make the changes take effect].
```shell
systemctl restart ssh
```
Then you can try opening a new session in your SSH software to check if you can connect. If there are any issues, you can modify the configuration through the old SSH session (SSH connections that are already open will not be closed when restarting sshd).
8. The complete process demonstration is as follows:
![Demonstration of modifying non-22 port](./ch04-img02-sshd-conf-full.gif)
9. Modify PuTTY Configuration
"Now that the new port is in effect, you will need to use `9753` the next time you log in with PuTTY. So please go to the PuTTY settings to change the port number and save the session. Well, you should know where to change it, right? (If you don't know, you need to reread the previous content!)"
## 4.5 Creating a New User Without Root Access
In the second step, let's solve the issue of the username being `root`.
Firstly, you need to understand that `root` in Linux system is not just a simple administrator account. It is the foundation of the entire system, the ruler and the supreme god of the system. Once the `root` account has security issues, the entire system will be vulnerable and there will be nowhere to hide. So, let's follow me to carry out the operations:
1. Little White Linux Basic Commands:
| Number | Command Name | Command Description |
| :------: | :-----------: | :-----------------------------------------------: |
| `cmd-05` | `adduser` | Add new user to the system |
| `cmd-06` | `apt install` | Install a software package |
| `cmd-07` | `visudo` | Special editor to modify sudo permission settings |
2. The first thing we need to do is to [add a new user and set a login password]. You can choose any name you want, here I will use `vpsadmin` as an example:
```shell
adduser vpsadmin
```
This is a command in the shell terminal to add a new user named "vpsadmin".
After executing the command, follow the prompts to operate. Be sure to set a user password (remember that you won't see `******` when setting the password). Afterwards, the system will ask you for some additional user information, which can be ignored by pressing Enter all the way.
![Creating a new user](./ch04-img03-adduser.png)
::: warning
This article takes "vpsadmin" as an example, which means that with the release of this article, this username will also become a significant feature, and may be the first choice for attackers to try. Therefore, just like ports, I strongly recommend that you use another username that you come up with yourself.
:::
3. The complete process demonstration is as follows:
![Creating a new user](./ch04-img04-adduser-full.gif)
4. The second thing we need to do is to install the `sudo` function (which allows ordinary accounts to temporarily obtain the power of `root` at critical moments and unleash their full power to save the world).
```shell
apt update && apt install sudo
```
This is a shell command to update the package list and install the "sudo" package.
You may have noticed that this command actually consists of two commands. The first half, `apt update`, you have seen and used before, is to refresh the software version information on the server. The latter half, `apt install`, is the installation command that will be used this time. The two commands are connected together to instruct the system to refresh the latest available software and then install the latest version of the `sudo` program. `&&` is used to link the two commands together for execution.
5. The third thing we need to do is to add the `vpsadmin` user to the `sudo` list, so that they have the privilege to borrow the power of `root`.
```shell
visudo
```
(Note: `visudo` is a command used in Linux/Unix systems to edit the sudoers file, which specifies which users or groups are allowed to run certain commands with administrative privileges.)
Simply add the following line under `User Privilege Specification`: `vpsadmin ALL=(ALL) NOPASSWD: ALL`.
::: warning
I want to specifically explain the setting of `NOPASSWD`. It means that when the `vpsadmin` user temporarily uses the `root` permission, no additional password needs to be entered. This is contrary to general security recommendations. The reason why I recommend this is that many newcomers insist on using the `root` account because they feel relaxed when using `root` without repeatedly entering passwords. "Choosing the lesser of two evils," I believe that the risk of [directly using the `root` user] is greater than the risk of [not entering a password when using `sudo`], so I made the above suggestion.
If you want to follow the traditional practice and enter a password every time you use `sudo`, then you can change this line to `vpsadmin ALL=(ALL:ALL) ALL`.
6. The complete process demonstration is as follows:
![Creating a new user](./ch04-img05-sudo-full.gif)
## 4.6 Disabling SSH Remote Login for Root User
1. Now that you're gradually getting familiar with Linux, it's time for you to think. What's the first thing we need to do? That's right, it's still to use the `nano` editor to open the `SSH remote login program settings`. What? You can't remember how to do it? Then go back and review the content above and come back! ............ Correct answer:
```shell
nano /etc/ssh/sshd_config
```
This is a command line instruction to open and edit the `sshd_config` file located at `/etc/ssh/` using the `nano` text editor.
2. Find the line `PermitRootLogin Yes`, and change the value after it to `no`. Do you remember how to do it? ............ Correct answer:
- Use `ctrl+w` to enter search mode, then enter `PermitRootLogin` and press enter.
- Delete `yes` and change it to `no`.
3. Save the file and exit. Do you remember how to do it? ............ Correct answer: N/A (The correct answer is not provided in the given text.)
- Save is `ctrl+o`, then press `Enter` to confirm.
- Exit is `ctrl+x`.
4. Restart the ssh service to make the changes take effect. Do you remember...? Never mind, let's just reveal the correct answer:
```shell
systemctl restart ssh
```
(This is a Linux shell command to restart the SSH service.)
5. The complete process is demonstrated as follows:
![Disable SSH remote login for root user](./ch04-img06-ssh-no-root-full.gif)
6. Next time you log in remotely via SSH using PuTTY, you will no longer be able to connect as the `root` user. You will need to use the username `vpsadmin` instead. For convenience, you can set `vpsadmin` as the default login username in PuTTY. (Tip: Don't forget to save the session.)
![PuTTY Setting Default User Name](./ch04-img07-putty-default-user.png)
## 4.7 Login with RSA Key and Disable Password Login
In the third step, we will solve the problem of the password being cracked.
As mentioned earlier, hackers are not foolish enough to crack your password by brute force, but rather they use cheating methods such as "password tables". Unless you use a randomly generated super long password (such as with 1Password, or macOS keychain and other password management tools), it's easy to fall victim to this.
Although a very long random password can improve security, it is usually difficult to remember and manually enter, which can also lead to mistakes. To solve this problem, we can simply abandon the "password verification" method and switch to a more secure "key verification" method.
The so-called "key authentication" refers to generating a pair of related key files (public key and private key), uploading the "public key" to the VPS for backup. Each time you log in, SSH will match the "public key" and "private key". If the verification is correct, the "key pair" will be verified and the authentication will pass. (In other words, you don't need to remember and enter complex passwords, just protect the "private key" file from being leaked.)
::: warning
This article uses `RSA` keys as an example because `RSA` keys have a long history of support in various devices and `SSH` clients and can still provide sufficient security. However, it is not the only choice available.
This article uses `RSA` keys as an example because `RSA` has a long history of support across various devices and SSH clients, and it currently provides sufficient security. However, it is by no means the only choice.
Other common keys include:
- `DSA` - It has been mathematically proven to be insecure, so never use it.
- `ECDSA` - It has high security with small keys, but its algorithm is suspected to have a backdoor by the NSA. If there is something on your VPS that is worth the attention of the NSA, do not use it.
- `Ed25519` - This is an algorithm that is very similar to `ECDSA`, and it has similar performance advantages. At the same time, all of its documentation is public, so it is generally considered to be free of backdoors.
* `DSA` - Mathematically proven insecure. Never use it.
* `ECDSA` - Small key size, high security, but its algorithm is suspected of having an NSA backdoor. If you have things on your VPS the NSA cares about, don't use it.
* `Ed25519` - An algorithm very similar to `ECDSA` with similar performance benefits. Its documentation is fully public, so it is generally considered backdoor-free.
So, if your device and software both support it, I recommend choosing `Ed25519` keys as a priority.
Therefore, if your devices and software support it, I recommend prioritizing `Ed25519` keys.
:::
Now let's configure the [Key Authentication]!
Now, let's configure **[Key Authentication]**!
1. Run `PuTTYgen` (PuTTY Key Generator). The location is `Start Menu` --> `All Programs` --> `PuTTY (64-bit)` --> `PuTTYgen`.
1. Run `PuTTYgen` (PuTTY Key Generator). Location: `Start Menu` --> `All Programs` --> `PuTTY (64-bit)` --> `PuTTYgen`.
1. Click `Generate` to start (move your mouse randomly in the blank area to increase randomness).
1. Click on `Generate` to start the generation process (move the mouse randomly in the blank area of the interface to add random numbers).
![Generate key](./ch04-img08-puttygen-save.png)
![Generate Key](./ch04-img08-puttygen-save.png)
::: warning
The image uses a `2048` bit `RSA` key as an example. However, to achieve security equivalent to `ECDSA/Ed25519` `256` bit keys, you need to use a `3072` bit `RSA` key (change the number in the bottom right to `3072`).
:::
1. You can set a password for the private key to add a layer of security.
2. Click `Save public key` to save the public key, name it `id_rsa.pub`.
3. Click `Save private key` to save the private key, name it `id_rsa` (PuTTY private keys come with a `.ppk` extension).
4. **Most Importantly:** Scroll down and copy **all** the content in the red box above, save it as a file named `authorized_keys`. (Saving with vscode might default to a `.txt` extension; that's fine, we will remove the extension when uploading to VPS).
![Save key content](./ch04-img09-puttygen-save-keys.png)
2. **Upload the public key to the `vpsadmin` user on the VPS.**
1. This step requires `WinSCP` which we prepared earlier.
2. Download and install from the [official site](https://winscp.net/eng/index.php). It will prompt you to import PuTTY settings; do it!
![Import session](./ch04-img10-winscp-import-session.png)
3. If it doesn't prompt or you installed it earlier, configure it as shown below.
![WinSCP login](./ch04-img11-winscp-ui.png)
4. The left directory in WinSCP is your local computer; locate the folder where your keys are.
5. The right directory in WinSCP is the VPS. Default is `/home/vpsadmin/`. Click `X hidden` in the bottom right to show hidden files.
![Local and Remote folders](./ch04-img12-winscp-locations.png)
6. Right-click on the right side (VPS) and create a new folder named `.ssh` (Note the dot `.`).
![Create .ssh folder](./ch04-img13-winscp-newfolder-key.png)
7. Upload the **[Public Key]** `authorized_keys` into the `.ssh` folder.
![Upload key](./ch04-img14-winscp-upload-key.png)
8. During upload (or after), rename `authorized_keys.txt` to `authorized_keys` (remove the `.txt` extension).
![Rename key](./ch04-img15-winscp-rename-key.png)
9. Full process demonstration:
![WinSCP full demo](./ch04-img16-winscp-full.gif)
3. **Configure VPS to Enable RSA Key Login and Disable Password Login.**
1. **Newbie Linux Basic Commands:**
| ID | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-08` | `sudo` | Run a command with `root` privileges |
| `cmd-09` | `chmod` | Change permissions of target file/folder |
2. Remote SSH into your VPS (PuTTY).
3. Change permissions of `authorized_keys` to `600` (Read/Write for owner only).
```shell
chmod 600 ~/.ssh/authorized_keys
```
4. Modify SSH Configuration. We've done this many times, but now we are the normal user `vpsadmin`, not the omnipotent `root`. We don't have permission to edit SSH config directly. We need the `sudo` command:
```shell
sudo nano /etc/ssh/sshd_config
```
5. Find (`ctrl+w`) `PasswordAuthentication` and change it to `no`.
6. Find (`ctrl+w`) `PubkeyAuthentication` and change it to `yes`. Save (`ctrl+o`) and Exit (`ctrl+x`).
7. Restart SSH service. (Nagging Note: Don't forget you need `sudo` for permission now).
```shell
sudo systemctl restart ssh
```
8. Full process follows:
![Disable password login full demo](./ch04-img17-rsa-login-full.gif)
4. **Configure PuTTY to use the Private Key.**
The VPS side has the public key. Now specify the private key location for PuTTY to use during login (Nagging Note: Don't forget to Save Session).
![PuTTY private key](./ch04-img18-putty-privatekey-location.png)
5. At this point, **[Key Login]** is enabled, **[Password Authentication]** is disabled, and PuTTY has the default username and private key saved. In the future, just load the `VPS-SERVER` config in PuTTY and click `Open` for one-click login.
If you set a password for your private key, you will need to enter that passphrase to unlock the key when logging in, as shown below:
![Private key passphrase](./ch04-img19-putty-privatekey-passphrase.png)
6. Don't forget to configure the key for `WinSCP` as well, otherwise, you won't be able to log in to transfer files later:
![WinSCP private key](./ch04-img20-winscp-privatekey-location.png)
::: warning
The example in this image is based on a `2048`-bit `RSA` key. However, in reality, if you want to achieve the same level of security as a `256`-bit key for `EDCSA/Ed25519`, you need to use a `3072`-bit `RSA` key. (i.e., change the number in the bottom right corner to `3072`)
:::
2. You can add a password to your private key to increase security.
3. Click on `Save public key` to save the public key with the file name `id_rsa.pub`.
4. Click on `Save private key` to save the private key with the file name `id_rsa` (PuTTY private keys come with the `.ppk` extension).
5. Most importantly, copy and save all the content inside the red box below by scrolling down, with the file name `authorized_keys`. (If you save it using vscode, it will be saved as a text file with a `.txt` extension, which is fine. We will remove the extension when uploading it to VPS later.)
![Save Key](./ch04-img09-puttygen-save-keys.png)
2. Upload the public key to the "vpsadmin" user on the VPS.
1, This step requires the use of the previously prepared `WinSCP`.
2, Go to the [official website](https://winscp.net/eng/index.php) to download and install. It will prompt you to import PuTTY settings, and of course, you can import them with one click!
![One-click Import Session](./ch04-img10-winscp-import-session.png)
3, If there is no prompt for import or you have already installed it in advance, configure it according to the following figure.
![WinSCP login settings](./ch04-img11-winscp-ui.png)
4, The directory on the left side of WinSCP is the folder and files on your local computer. Please locate the folder where the key is stored.
5, The directory on the right side of WinSCP is the folder and files on the VPS server, which are located in the `/home/vpsadmin/` folder by default. To display hidden files, please click on `X hidden` in the lower right corner.
![Local and remote folders](./ch04-img12-winscp-locations.png)
6, Right-click on the right side (in VPS) and create a new folder named `.ssh` (note the period at the beginning).
![Create a folder to place public key in VPS](./ch04-img13-winscp-newfolder-key.png)
7, Upload the [public key] `authorized_keys` to the `.ssh` folder.
![Upload authorized_keys](./ch04-img14-winscp-upload-key.png)
8, When uploading, rename the [public key] from `authorized_keys.txt` to `authorized_keys` (remove the `.txt` extension).
![Ensure there is no file extension](./ch04-img15-winscp-rename-key.png)
9, The complete process demonstration is as follows:
![Complete demonstration of WinSCP operation](./ch04-img16-winscp-full.gif)
3. Enable RSA key authentication for SSH login and disable password authentication login on the VPS side.
- Basic Linux Commands:
| Number | Command | Description |
| :------: | :-----: | :-----------------------------------------------: |
| `cmd-08` | `sudo` | Run a command with `root` privileges |
| `cmd-09` | `chmod` | Change the permissions of a target file/directory |
- SSH remote connection to VPS (PuTTY)
- Change the permission of the `authorized_keys` file to `600` (only the owner can read and write).
```shell
chmod 600 ~/.ssh/authorized_keys
```
This is a command in shell script to change the permissions of the `authorized_keys` file to `600` for the current user's SSH directory (`~/.ssh/`).
4. Modify SSH configuration. We have used this many times, but now that we have changed from the almighty `root` to the ordinary user `vpsadmin`, we do not have the permission to edit SSH configuration directly. At this time, we need to use the `sudo` command:
```shell
sudo nano /etc/ssh/sshd_config
```
(This is a command in the shell/terminal to open the sshd_config file located in the /etc/ssh/ directory with the sudo privilege using the nano text editor.)
5. Find (`ctrl+w`) `PasswordAuthentication` and change it to `no`.
6. Find (`ctrl+w`) `PubkeyAuthentication`, change it to `yes`, then save (`ctrl+o`) and exit (`ctrl+x`).
7. Restart the SSH service. (Note: Don't forget to use `sudo` to gain permission.)
```shell
sudo systemctl restart ssh
```
This is a command in the shell terminal to restart the SSH service with root privileges using the `systemctl` command.
8. The complete process is as follows:
![Enable SSH key verification and disable password verification](./ch04-img17-rsa-login-full.gif)
4. The public key has been set up on the VPS end. Now we need to specify the private key location for PuTTY to use when logging in. (Reminder: Don't forget to save the session.)
![Specify private key location in PuTTY](./ch04-img18-putty-privatekey-location.png)
5. Now, the [Key-based login] has been successfully enabled, [Password authentication] has been successfully disabled, and the default login username and private key have been saved for PuTTY. In the future, when using PuTTY to log in, simply load the `VPS-SERVER` configuration, click `Open`, and you can log in with just one click.
If you have set a password for your private key, you need to enter this password to use the key when logging in, as shown in the following figure:
![Enter Private Key Password](./ch04-img19-putty-privatekey-passphrase.png)
6. Don't forget to set the corresponding key for `WinSCP`, otherwise you won't be able to log in when you want to transfer files later.
![WinSCP Specify Private Key Location](./ch04-img20-winscp-privatekey-location.png)
::: warning
Any software that requires SSH login needs key verification. As there are too many software, it is impossible to show them one by one. Please set it up according to your needs.
Any software that needs to log in via SSH will now require key authentication. There are too many software options to show individually, so please configure them yourself according to your needs.
:::
## 4.8 Your Progress
Up to this point, your VPS has completed the basic security measures of [port], [username], and [password]. Although it is not completely impregnable, most malicious scripts should no longer be able to harm you.
Up to this point, your VPS has completed the basic security guarantees for the three elements: **[Port]**, **[Username]**, and **[Password]**. While far from impregnable, common malicious scripts should no longer be able to harm you!
Now that we finally have a secure system foundation, in the next chapter, we can start step by step to install and configure the infrastructure that Xray needs! (What infrastructure? A web page, a certificate)
Now we finally have a secure system foundation. In the next chapter, we can start gradually installing and configuring the infrastructure required for Xray! (What infrastructure? A webpage, a certificate).
> ⬛⬛⬛⬛⬜⬜⬜⬜ 50%
+148 -109
View File
@@ -1,160 +1,199 @@
# Chapter 5: Website Building
# [Chapter 5] Website Setup
## 5.1 Why should you create a website?
## 5.1 Why create a website?
Some newcomers may be confused: why do I need to build a website for securing an open digital environment? I don't know how to code! Isn't it very complicated?
Newcomers might be confused: why do I need to build a website just to access the "scientific internet" (circumvent the firewall)? I don't know programming; isn't it very troublesome?
First, let's answer the first question. The reasons for building a website are:
Let's answer the first question. Reasons for building a website:
1. Apply for a legitimate TLS certificate (very important)
2. Provide reasonable fallback to prevent active probing attacks and improve security
3. Set up a camouflage site (such as a blog, private cloud storage, multimedia site, game site, etc.) with a reasonable frontend when directly accessed, making traffic usage look more legitimate.
1. To apply for a legitimate TLS certificate (Very important).
2. To provide a reasonable fallback mechanism to prevent active probing attacks and improve security.
3. To build a camouflage site (such as a blog, private cloud drive, multimedia site, game site, etc.) so that there is a legitimate front-end when accessed directly, making traffic usage look more reasonable.
Now let's answer the second question:
Now for the second question:
1. As a demonstration, this article uses only the simplest "single-file HTML page + Nginx" setup to achieve the above objectives, so it is **very easy**.
2. This website can not only be used for camouflage but also for real development and growth. The complexity depends entirely on you.
3. For the goals of "camouflage" and "website operation", uniqueness and personalization are needed. Students who need this can search and learn by themselves. This content has completely deviated from scientific online access, so this article will not go into depth.
1. This article, as a demonstration, uses only a very simple [single-file HTML page + Nginx] to achieve the above goals, so it is **very simple**.
2. This website can be more than just camouflage; you can actually make it big and strong. The complexity depends entirely on you.
3. For the goals of "camouflage" and "website operation," what is needed is individuality and showing your true self. Interested students can search and learn on their own. This content has completely deviated from "scientific internet access," so this article will not delve into it.
## 5.2 Log in to VPS, install and run Nginx
## 5.2 Login to VPS, Install and Run Nginx
1. Here we use commands that have been explained in detail before, so they won't be repeated. If you don't understand, please refer to the previous chapters.
1. The commands used here have been explained in detail previously, so they won't be repeated. Students who don't understand can review the previous chapters.
```shell
sudo apt update && sudo apt install nginx
```
```shell
sudo apt update && sudo apt install nginx
```
2. After completion, Nginx will automatically run. Open the browser on Windows and enter `http://100.200.300.400:80`. If you see the interface shown below, it means Nginx is running normally.
2. After completion, Nginx runs automatically. Now open a browser on Windows and enter `http://100.200.300.400:80`. If you see the interface below, Nginx is running normally.
![Nginx default interface](./ch05-img01-nginx-default-running.png)
![Nginx Default Page](./ch05-img01-nginx-default-running.png)
## 5.3 Create the simplest web page
3. If you cannot see the Nginx default page mentioned above, you may need to configure the default firewall component, Uncomplicated Firewall (UFW), on the Debian system to enable HTTP (80) and HTTPS (443) port traffic.
1. Basic Linux commands for beginners:
| No. | Command Name | Command Description |
| :------: | :----------------: | :-----------------------: |
| `cmd-10` | `mkdir` | Create a new folder |
| `cmd-11` | `systemctl reload` | Reload a specific service |
a. Verification method, input:
2. Basic Linux configuration files for beginners:
| No. | Configuration File Location | File Description |
| :-------: | :-------------------------: | :--------------------: |
| `conf-02` | `/etc/nginx/nginx.conf` | Nginx program settings |
```shell
sudo ufw status
```
3. Create a dedicated folder `/home/vpsadmin/www/webpage/` for the website and create the web page file `index.html`
```shell
mkdir -p ~/www/webpage/ && nano ~/www/webpage/index.html
```
b. If the output is as follows, indicating ports 80 and 443 are not enabled, proceed to step c.
::: warning
If you are not using the username `vpsadmin`, please be sure to understand the meaning of the "~" symbol in this command (this is related to Step 5 content):
```shell
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
```
- If it is a **non-root user**, "~" is equivalent to `/home/username`
- If it is a **root user**, "~" is equivalent to `/root`
:::
c. Command to enable Nginx ports 80 and 443 in UFW:
4. Copy the entire content below, save (`ctrl+o`) and exit (`ctrl+x`).
```shell
sudo ufw allow 'Nginx Full'
```
```html
<html lang="">
<!-- Text between angle brackets is an HTML tag and is not displayed.
Most tags, such as the HTML and /HTML tags that surround the contents of
a page, come in pairs; some tags, like HR, for a horizontal rule, stand
alone. Comments, such as the text you're reading, are not displayed when
the Web page is shown. The information between the HEAD and /HEAD tags is
not displayed. The information between the BODY and /BODY tags is displayed.-->
<head>
<title>Enter a title, displayed at the top of the window.</title>
</head>
<!-- The information between the BODY and /BODY tags is displayed.-->
<body>
<h1>Enter the main heading, usually the same as the title.</h1>
<p>Be <b>bold</b> in stating your key points. Put them in a list:</p>
<ul>
<li>The first item in your list</li>
<li>The second item; <i>italicize</i> key words</li>
</ul>
<p>Improve your image by including an image.</p>
<p>
<img src="https://i.imgur.com/SEBww.jpg" alt="A Great HTML Resource" />
</p>
<p>
Add a link to your favorite
<a href="https://www.dummies.com/">Web site</a>. Break up your page
with a horizontal rule or two.
</p>
<hr />
<p>
Finally, link to <a href="page2.html">another page</a> in your own Web
site.
</p>
<!-- And add a copyright notice.-->
<p>© Wiley Publishing, 2011</p>
</body>
</html>
```
d. Enter the command from step a again to verify. If the output is as follows, it means Nginx traffic has been allowed by the firewall, and you should be able to see the Nginx default page mentioned in point 2.
5. Modify `nginx.conf` and restart the `Nginx` service, directing the http access on port 80 to the newly created `html` page.
1. Modify `nginx.conf`.
```shell
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
Nginx Full ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
Nginx Full (v6) ALLOW Anywhere (v6)
```
```shell
sudo nano /etc/nginx/nginx.conf
```
## 5.3 Create a Very Simple Web Page
2. Add the following content inside`http{}`, then save (`ctrl+o`) and exit (`ctrl+x`). (Remember to replace the domain name with the real domain name you prepared earlier, including the subdomain)
1. **Basic Linux Commands for Beginners:**
```
| Code | Command Name | Description |
| :---: | :---: | :---: |
| `cmd-10` | `mkdir` | Create a new directory |
| `cmd-11` | `systemctl reload` | Reload a service |
2. **Basic Linux Configuration Files for Beginners:**
| Code | File Location | Description |
| :---: | :---: | :---: |
| `conf-02` | `/etc/nginx/nginx.conf` | Nginx program settings |
3. Create a dedicated folder for the website `/home/vpsadmin/www/webpage/` and create the webpage file `index.html`.
```shell
mkdir -p ~/www/webpage/ && nano ~/www/webpage/index.html
```
::: warning
If you are not using the username `vpsadmin`, please understand the meaning of the `“~”` symbol in this command (this relates to the content you will write in [Step 5]):
- If you are a [non-root user], `“~”` is equivalent to `/home/username`.
- If you are the [root user], `“~”` is equivalent to `/root`.
:::
4. Copy the content below completely into the file, then save (`ctrl+o`) and exit (`ctrl+x`).
```html
<html lang="">
<head>
<title>Enter a title, displayed at the top of the window.</title>
</head>
<body>
<h1>Enter the main heading, usually the same as the title.</h1>
<p>Be <b>bold</b> in stating your key points. Put them in a list:</p>
<ul>
<li>The first item in your list</li>
<li>The second item; <i>italicize</i> key words</li>
</ul>
<p>Improve your image by including an image.</p>
<p>
<img src="[https://i.imgur.com/SEBww.jpg](https://i.imgur.com/SEBww.jpg)" alt="A Great HTML Resource" />
</p>
<p>
Add a link to your favorite
<a href="[https://www.dummies.com/](https://www.dummies.com/)">Web site</a>. Break up your page
with a horizontal rule or two.
</p>
<hr />
<p>
Finally, link to <a href="page2.html">another page</a> in your own Web
site.
</p>
<p>&#169; Wiley Publishing, 2011</p>
</body>
</html>
```
Grant read permissions to other users for this file:
```shell
chmod -R a+r .
```
5. Modify `nginx.conf` and restart the `Nginx` service to point http access on port `80` to the `html` page just created.
1. Modify `nginx.conf`.
```shell
sudo nano /etc/nginx/nginx.conf
```
2. Add the following segment inside `http{}`, then save (`ctrl+o`) and exit (`ctrl+x`). (Remember to replace the domain name with the real domain name including the subdomain you prepared earlier).
```nginx
server {
listen 80;
server_name subdomain.your_domain.com;
server_name subdomain.yourdomain.com;
root /home/vpsadmin/www/webpage;
index index.html;
}
```
```
::: warning Be extra careful!
As mentioned in Step 3 of section 5.3, make sure to change `/home/vpsadmin/www/webpage` to your actual file path.
:::
::: warning Special Note!
As mentioned in my hint in [Step 3], please make sure `/home/vpsadmin/www/webpage` is changed to your actual file path.
:::
3. Make `nginx` reload the configuration to take effect.
3. Reload the `nginx` configuration to make it effective.
```shell
sudo systemctl reload nginx
```
```shell
sudo systemctl reload nginx
```
4. The complete setup process is as follows:
4. The complete setup process is shown below:
![Web page settings demonstration](./ch05-img02-nginx-conf-full.gif)
![Webpage Setup Demo](./ch05-img02-nginx-conf-full.gif)
5. Now, if you visit `http://subdomain.your_domain.com`, you should see this page, indicating success:
5. Now, if you visit `http://subdomain.yourdomain.com` and see a page like this, it means success:
![http web page success](./ch05-img03-nginx-http-running.png)
![HTTP Webpage Success](./ch05-img03-nginx-http-running.png)
## 5.4 Common error explanations
## 5.4 Explanation of Common Errors
First of all, if you follow the instructions in the article step by step and are careful enough, you will definitely not encounter any errors. So, I don't intend to change how this article is written.
First, if you followed the instructions in the article step by step and were careful enough, you definitely wouldn't encounter errors. Therefore, I do not intend to modify how this article is written.
Then why do some students still get stuck at this step, and the web page just won't open? There are basically two words: **carelessness**. Because there are only two possible issues with the configuration here, and there are only two reasons for them.
So why do many students still get stuck at this step and can't open the webpage? Basically, it comes down to one word: **carelessness**. There are only two potential configuration problems here, and only two causes.
I. Two types of issues:
**I. Two Problems:**
- In `nginx.conf`, the `/home/vpsadmin/www/webpage` does not match the actual file path; `nginx` cannot find the file
- The path is correct, but `nginx` doesn't have permission to access it
- The path `/home/vpsadmin/www/webpage` in `nginx.conf` does not match your actual file path, so `nginx` cannot find the file.
- The path is correct, but `nginx` does not have permission to read it.
II. Two reasons:
**II. Two Causes:**
- Use a **non-root user** but still directly copy the commands in the text without modification. (This is basically like copying the name of another student when copying answers)
- Insist on using a **root user**
- Using a [non-root user] but still copying the commands from the article directly without modification. (This is basically like copying a classmate's name along with their answers during a test).
- Insisting on using the [root user].
If you encounter any errors, please carefully review the explanations in Steps 3 and 5-2 of Section 5.3.
Students encountering errors should look back carefully at the instructions in [Step 3] and [Step 5-2] of section [5.3].
::: warning
In the early stages of this article, a lot of space has been devoted to explaining the importance of using a **non-root user** for security, and the entire article is written based on this premise. So, issues caused by using a **root user** are not within the scope of this article.
Earlier in this article, a significant amount of space was dedicated to explaining the importance of using a [non-root user] for security, and the entire text is written based on this premise. Therefore, problems caused by using the [root user] are not within the scope of this article's design.
But I believe that students who persist in using the `root` user should have their own opinions, strong hands-on ability, or have a certain foundation in Linux. I have already explained the crux of the problem, and I believe you can solve it on your own.
However, I believe that students who insist on using the [root user] likely have their own opinions, strong hands-on abilities, or a certain Linux foundation. I have explained the crux of the problem, and I trust you can solve it on your own.
:::
## 5.5 Your Progress
So far, Xray's first infrastructure [webpage] has been established. Let's now move on to the second infrastructure [certificate]!
At this point, Xray's first infrastructure component, the [Website], is in place. We will immediately move on to the second infrastructure component: [Certificates]!
> ⬛⬛⬛⬛⬛⬜⬜⬜ 62.5%
+124 -173
View File
@@ -2,222 +2,173 @@
## 6.1 Applying for a TLS Certificate
Next, we need to apply for a real TLS certificate for our domain name, so that the website has the ability to encrypt with standard TLS and the ability to access via HTTPS. This is the most important tool for Xray and other current security proxy tools to ensure fully encrypted traffic.
Next, we need to apply for a real TLS certificate for our domain name. This enables standard TLS encryption and HTTPS access for the website. This is the most crucial tool for modern secure proxy tools like Xray to ensure traffic is fully encrypted.
::: warning
Please do not use self-signed certificates lightly. It does not make the operation much simpler, but adds unnecessary risks (such as man-in-the-middle attacks).
Please do not use self-signed certificates lightly. They don't make the operation much simpler, but they add senseless risks (such as Man-in-the-Middle attacks).
:::
Here, I will use a certificate management tool called [`acme.sh`](https://github.com/acmesh-official/acme.sh), which is simple, lightweight, efficient, and capable of automatically updating certificates.
Here, I will use a certificate management tool called [`acme.sh`](https://github.com/acmesh-official/acme.sh). It is simple, lightweight, efficient, and handles automatic certificate renewals.
In addition, I believe that you have gradually become familiar with the basic operations of Linux. Therefore, from this chapter on, commands that have appeared multiple times will no longer have screenshots and will only be briefly described. If you really can't remember how to use them, just review the previous chapters.
Additionally, I trust that by now you are gradually becoming familiar with basic Linux operations. Therefore, starting from this chapter, commands that have appeared multiple times will no longer be accompanied by screenshots, but only simple descriptions. If you really can't remember how to use them, please review the previous chapters.
## 6.2 Install `acme.sh`
## 6.2 Installing `acme.sh`
1. Basic Linux commands for beginners:
| Number | Command | Description |
| :------: | :-------: | :------------------------------------------------: |
| `cmd-12` | `wget` | Retrieve (or download) a webpage file |
| `cmd-13` | `acme.sh` | Commands related to acme.sh certificate management |
1. Basic Linux Commands for Beginners:
2. Run the installation script.
| ID | Command | Description |
|:--:|:--:|:--:|
| `cmd-12` | `wget` | Visit (or download) a web file |
| `cmd-13` | `acme.sh` | Commands related to acme.sh certificate management |
```shell
wget -O - https://get.acme.sh | sh
```
2. Run the installation script
3. Make the `acme.sh` command effective.
```shell
wget -O - [https://get.acme.sh](https://get.acme.sh) | sh
```
```shell
. .bashrc
```
3. Make the `acme.sh` command effective
(Note: This command is used to source (load) the `.bashrc` file in the shell environment.)
```shell
. .bashrc
```
4. Enable `acme.sh` automatic upgrade.
4. Enable auto-upgrade for `acme.sh`
```shell
acme.sh --upgrade --auto-upgrade
```
```shell
acme.sh --upgrade --auto-upgrade
```
5. The complete process up to this point is shown in the following diagram:
5. The complete process up to this step is shown below:
![acme.sh installation demo](./ch06-img01-acme-install.gif)
![acme.sh installation demo](./ch06-img01-acme-install.gif)
## 6.3 Testing Certificate Application
## 6.3 Testing Certificate Issuance
Before officially applying for the certificate, we use the testing command (`--issue --server letsencrypt_test`) to verify if the application can be successfully submitted. This can avoid repeated failures in applying for a certificate due to incorrect local configuration, exceeding the frequency limit of Let's Encrypt (such as a maximum of 5 failures per hour, per domain, or per user), which may prevent the subsequent steps from being carried out.
Before officially applying for a certificate, let's use a test command (`--issue --server letsencrypt_test`) to verify if the application can be successful. This avoids repeated failures due to local configuration errors, which could exceed Let's Encrypt's frequency limits (e.g., maximum of 5 failures per hour, per domain, per user), blocking subsequent steps.
1. The command to apply for a test certificate is as follows (this article uses ECC certificate as an example, because there is really no reason not to use it nowadays):
1. The command to test certificate issuance is as follows (This article uses `ECC` certificates as an example, because nowadays, there is really no reason not to use them):
```shell
acme.sh --issue --server letsencrypt_test -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256
```
```shell
acme.sh --issue --server letsencrypt_test -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256
```
(Note: This is a command in shell script for obtaining SSL certificate from Let's Encrypt CA using ACME protocol. It specifies the test server, the subdomain for which the certificate is requested, the webroot directory of the subdomain, and the key length to use for the certificate.)
::: warning Note
The main advantage of `ECC` certificates lies in their smaller Key size, which means improved security and faster encryption/decryption speeds for the same size. For instance, the strength of ECC-256bit is roughly equivalent to RSA-3072bit, so why not? Of course, some say ECC certificate handshakes are noticeably faster; I think that's a bit of an exaggeration. RSA handshakes aren't that slow, and even if there is a difference, it should be in milliseconds, which is hard to perceive directly.
::: warning Explanation
The main advantage of the `ECC` certificate is that its `Keysize` is smaller, which means that security is improved and encryption and decryption speed is faster for the same size. Why not choose ECC-256bit, which is approximately equivalent to RSA-3072bit in strength? Of course, some people say that the ECC certificate handshake is significantly faster, which I think is a bit exaggerated, because RSA handshake is not too slow either. Even if there is a difference, it should be in milliseconds and difficult to perceive directly.
However, if some websites specifically need to be compatible with very ancient devices, please choose `RSA` certificates as needed.
:::
In addition, if some websites do need to be compatible with certain old devices, please still choose RSA certificates according to your needs.
2. You should ultimately see a log similar to this:
2. You should eventually see a prompt similar to this:
```log
[Wed 30 Dec 2022 04:25:12 AM EST] Using ACME_DIRECTORY: [https://acme-staging-v02.api.letsencrypt.org/directory](https://acme-staging-v02.api.letsencrypt.org/directory)
[Wed 30 Dec 2022 04:25:13 AM EST] Using CA: [https://acme-staging-v02.api.letsencrypt.org/directory](https://acme-staging-v02.api.letsencrypt.org/directory)
[Wed 30 Dec 2022 04:25:13 AM EST] Create account key ok.
[Wed 30 Dec 2022 04:25:13 AM EST] Registering account: [https://acme-staging-v02.api.letsencrypt.org/directory](https://acme-staging-v02.api.letsencrypt.org/directory)
[Wed 30 Dec 2022 04:25:13 AM EST] Registered
[Wed 30 Dec 2022 04:25:13 AM EST] ACCOUNT_THUMBPRINT='CU6qmPKuRqhyTAIrF4swosR375194z_1ddUlWef8xDc'
[Wed 30 Dec 2022 04:25:13 AM EST] Creating domain key
[Wed 30 Dec 2022 04:25:13 AM EST] The domain key is here: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 04:25:13 AM EST] Single domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 04:25:13 AM EST] Getting domain auth token for each domain
[Wed 30 Dec 2022 04:25:14 AM EST] Getting webroot for domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 04:25:14 AM EST] Verifying: subdomain.yourdomain.com
[Wed 30 Dec 2022 04:25:23 AM EST] Pending
[Wed 30 Dec 2022 04:25:25 AM EST] Success
[Wed 30 Dec 2022 04:25:25 AM EST] Verify finished, start to sign.
[Wed 30 Dec 2022 04:25:25 AM EST] Lets finalize the order.
[Wed 30 Dec 2022 04:25:25 AM EST] Le_OrderFinalize='[https://acme-staging-v02.api.letsencrypt.org/acme/finalize/490205995/7730242871](https://acme-staging-v02.api.letsencrypt.org/acme/finalize/490205995/7730242871)'
[Wed 30 Dec 2022 04:25:25 AM EST] Downloading cert.
[Wed 30 Dec 2022 04:25:25 AM EST] Le_LinkCert='[https://acme-staging-v02.api.letsencrypt.org/acme/cert/xujss5xt8i38waubafz2xujss5xt8i38waubz2](https://acme-staging-v02.api.letsencrypt.org/acme/cert/xujss5xt8i38waubafz2xujss5xt8i38waubz2)'
[Wed 30 Dec 2022 15:21:52 AM EST] Cert success.
--BEGIN CERTIFICAT--
sxlYqPvWreKgD5b8JyOQX0Yg2MLoRUoDyqVkd31PthIiwzdckoh5eD3JU7ysYBtN
cTFK4LGOfjqi8Ks87EVJdK9IaSAu7ZC6h5to0eqpJ5PLhaM3e6yJBbHmYA8w1Smp
wAb3tdoHZ9ttUIm9CrSzvDBt6BBT6GqYdDamMyCYBLooMyDEM4CUFsOzCRrEqqvC
... (omitted for brevity) ...
yiLKcBFc5H7dgJCImo7us7aJeftC44uWkPIjw9AKH=
--END CERTIFICAT--
[Wed 30 Dec 2022 15:21:52 AM EST] Your cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.cer
[Wed 30 Dec 2022 15:21:52 AM EST] Your cert key is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:21:52 AM EST] The intermediate CA cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/ca.cer
[Wed 30 Dec 2022 15:21:52 AM EST] And the full chain certs is there: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/fullchain.cer
```
```log
[Wed 30 Dec 2022 04:25:12 AM EST] Using ACME_DIRECTORY: https://acme-staging-v02.api.letsencrypt.org/directory
[Wed 30 Dec 2022 04:25:13 AM EST] Using CA: https://acme-staging-v02.api.letsencrypt.org/directory
[Wed 30 Dec 2022 04:25:13 AM EST] Create account key ok.
[Wed 30 Dec 2022 04:25:13 AM EST] Registering account: https://acme-staging-v02.api.letsencrypt.org/directory
[Wed 30 Dec 2022 04:25:13 AM EST] Registered
[Wed 30 Dec 2022 04:25:13 AM EST] ACCOUNT_THUMBPRINT='CU6qmPKuRqhyTAIrF4swosR375194z_1ddUlWef8xDc'
[Wed 30 Dec 2022 04:25:13 AM EST] Creating domain key
[Wed 30 Dec 2022 04:25:13 AM EST] The domain key is here: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 04:25:13 AM EST] Single domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 04:25:13 AM EST] Getting domain auth token for each domain
[Wed 30 Dec 2022 04:25:14 AM EST] Getting webroot for domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 04:25:14 AM EST] Verifying: subdomain.yourdomain.com
[Wed 30 Dec 2022 04:25:23 AM EST] Pending
[Wed 30 Dec 2022 04:25:25 AM EST] Success
[Wed 30 Dec 2022 04:25:25 AM EST] Verify finished, start to sign.
[Wed 30 Dec 2022 04:25:25 AM EST] Lets finalize the order.
[Wed 30 Dec 2022 04:25:25 AM EST] Le_OrderFinalize='https://acme-staging-v02.api.letsencrypt.org/acme/finalize/490205995/7730242871'
[Wed 30 Dec 2022 04:25:25 AM EST] Downloading cert.
[Wed 30 Dec 2022 04:25:25 AM EST] Le_LinkCert='https://acme-staging-v02.api.letsencrypt.org/acme/cert/xujss5xt8i38waubafz2xujss5xt8i38waubz2'
[Wed 30 Dec 2022 15:21:52 AM EST] Cert success.
--BEGIN CERTIFICAT--
sxlYqPvWreKgD5b8JyOQX0Yg2MLoRUoDyqVkd31PthIiwzdckoh5eD3JU7ysYBtN
cTFK4LGOfjqi8Ks87EVJdK9IaSAu7ZC6h5to0eqpJ5PLhaM3e6yJBbHmYA8w1Smp
wAb3tdoHZ9ttUIm9CrSzvDBt6BBT6GqYdDamMyCYBLooMyDEM4CUFsOzCRrEqqvC
2mTTEmhvpojo5rhdTSJxibozyNWTGwoTj0v9pTUeQcGqLIzqi4DowjBHD5guwRid
SjAFnm6JT2xUQgWFm58A1gv1OhbH1TRPUUmtE1nFEN7YiSjI4xgxqAXT3CLD2EUb
wXlUrO6c75zSsQP4bRMzgOjJUqHtSb6IEqELzt4M7KzL5iCOruCChCo2DZxUwvVX
tOoaAyQJzCbTqE6aUqwiKi3gVyoxvDP9mI5JdRYzsDL6GVud7EHPnYeMl9ubLZAK
0vg84mbMP3f6mYM4KRa1cqiyOIcQPT4AzGFYVv4sm049bZQg7sd0Bz9CaFvE7yDA
1y17XlgCDnsjxl66bqI1vkENN9XT5xeFHONqc18b5fZEKSIvdX7iWPFWp1PyMPpG
0pMCP1EymZNFxIMJLgbWqExwLWfPc5Ib3PjBaIqhXPnw6sT2MQSxXwDupq1UJVhV
7E3hQRVlwI4CXi6WLHJMNvNRyyK87gCrLH1bKYsPeRVaz77poWBq49zwBCts6hPY
IeF4ltGXyANNIOPEi8vy138fRU4LYh81d8FjOtFfJZogMjwhfNvapqxPMsioPlmX
TnZu0n7setrVNUEfTMHWqPpDgk5MPrWLA4LapqaDfEX4pwnQJLMwMi6s94z165c0
iMRSKA1yU5zqv8aNsDfPoY4OkSPWs4MaXgRRSLBsUfZ15DwQXPk76kegHIyxWvwF
tYw9HKR5QCMK66fa0z4aJoFVFLK0IIOGEZOanRFUCnkLUDd3QZ3YU8lEcrj7Uxos
haiRNICyC6UfsCJ94a8vcNyMosPv3xBLMp19WXgiFYqEFQkntkv1FLRI35fjeJmg
0fmD9VG9bkzGPHihJgQLRlCHasGf6XrdfkSsODAyCUHUHJ0RzqF4YEZMcxDxzuQ2
YO7bFwj7S3mUdVPZ6MPasjxdyBjJgEBMch2uy4AhmudXfEBQBye8W6ZI4ztZjLVV
FmP4SIuaNUmMe20TjR8b9NVC96AhxOanWT3mRROsdokpKQGTJvl27EHH8KuAbUOc
G6KtPy4wslNZNXWcBy9n63RcWak12r7kAIFn38tZxmlw2WUKoRSMAH64GcDTjRQd
Am65hBHzvGrj93wEuVNIebvNIsJOlng3HFjpIxVqKGMCIfWIKGDE3YzK3p4LbGZ6
NZFQWYJLNVf2M9CCJfbEImPYgvctrxl39H6KVYPCw1SAdaj9NneUqmREOQkKoEB0
x6PmNirbMscHhQPSC0JQaqUgaQFgba1ALmzRYAnYhNb0twkTxWbY7DBkAarxqMIp
yiLKcBFc5H7dgJCImo7us7aJeftC44uWkPIjw9AKH=
--END CERTIFICAT--
[Wed 30 Dec 2022 15:21:52 AM EST] Your cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.cer
[Wed 30 Dec 2022 15:21:52 AM EST] Your cert key is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:21:52 AM EST] The intermediate CA cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/ca.cer
[Wed 30 Dec 2022 15:21:52 AM EST] And the full chain certs is there: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/fullchain.cer
```
3. Note: What we applied for here is a test certificate. It cannot be used directly; it merely proves that your domain and configuration are all correct. Look closely, and you will find that the issuer domain is `https://acme-staging-v02.api.letsencrypt.org`. You can understand this `staging` as the "Test Server"!
3. Note: The certificate applied for here is a test certificate, which cannot be used directly. It is only used to prove that your domain and configuration are correct. If you observe carefully, you will find that the domain that issues the certificate to you is `https://acme-staging-v02.api.letsencrypt.org`, and this `staging` can be understood as a "test server"!
4. If an error occurs in this step, you can run the following command to view the detailed application process and specific errors. (If you don't understand it, hide sensitive information and ask in the Xray community group).
4. If this step goes wrong, you can run the following command to check the detailed application process and specific errors. If you don't understand, you can hide sensitive information and ask in the Xray group.
```shell
acme.sh --issue --server letsencrypt_test -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256 --debug
```
```shell
acme.sh --issue --server letsencrypt_test -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256 --debug
```
Yes, that's right, just add a `--debug` parameter at the end of the command.
(Note: This command is written in Chinese characters, therefore I have translated it into English. The command is used to issue SSL/TLS certificates using acme.sh client with Let's Encrypt CA in test mode for a subdomain of your domain with the specified webroot path, key length and in debug mode.)
5. After confirming this step is successful, you can apply for the official certificate. (You don't need to delete the test certificate; it will be automatically overwritten by the official certificate).
Hmm, that's right. Just added a `--debug` parameter at the end of the command.
## 6.4 Official Certificate Issuance
5. Once this step is confirmed to be successful, you can apply for the formal certificate. (The test certificate does not need to be deleted, as it will be automatically replaced by the formal certificate.)
1. The command to apply for the official certificate is as follows (change the `--server letsencrypt_test` parameter to `--server letsencrypt`, and add the `--force` parameter at the end):
## 6.4 Application for Official Certification
```shell
acme.sh --set-default-ca --server letsencrypt
```
1. The command for applying for an official certificate is as follows (i.e., replace `letsencrypt_test` with `letsencrypt` and add the `--force` parameter at the end):
```shell
acme.sh --issue -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256 --force
```
```shell
acme.sh --set-default-ca --server letsencrypt
```
::: warning Note
The `--force` parameter means to manually (forcefully) update the certificate before the existing certificate expires. Although the certificate we applied for from the "Test Server" in the previous step cannot be used directly, it has not yet expired, so this parameter is needed.
:::
This is a command in the shell language. It sets the default Certificate Authority (CA) to Let's Encrypt by using the `acme.sh` script.
2. You should ultimately see a log very similar to the one above:
```shell
acme.sh --issue -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256 --force
```
```log
vpsadmin@vps-server:~$ acme.sh --issue -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256
[Wed 30 Dec 2022 15:22:51 AM EST] Using CA: [https://acme-v02.api.letsencrypt.org/directory](https://acme-v02.api.letsencrypt.org/directory)
[Wed 30 Dec 2022 15:22:51 AM EST] Creating domain key
[Wed 30 Dec 2022 15:22:51 AM EST] The domain key is here: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:22:51 AM EST] Single domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 15:22:51 AM EST] Getting domain auth token for each domain
[Wed 30 Dec 2022 15:22:51 AM EST] Getting webroot for domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 15:22:51 AM EST] Verifying: subdomain.yourdomain.com
[Wed 30 Dec 2022 15:22:51 AM EST] Pending
[Wed 30 Dec 2022 15:22:51 AM EST] Success
[Wed 30 Dec 2022 15:22:51 AM EST] Verify finished, start to sign.
[Wed 30 Dec 2022 15:22:51 AM EST] Lets finalize the order.
[Wed 30 Dec 2022 15:22:51 AM EST] Le_OrderFinalize='[https://acme-v02.api.letsencrypt.org/acme/finalize/490205996/7730242872](https://acme-v02.api.letsencrypt.org/acme/finalize/490205996/7730242872)'
[Wed 30 Dec 2022 15:22:51 AM EST] Downloading cert.
[Wed 30 Dec 2022 15:22:51 AM EST] Le_LinkCert='[https://acme-v02.api.letsencrypt.org/acme/cert/vsxvk0oldnuobe51ayxz4dms62sk2dwmw9zhuw](https://acme-v02.api.letsencrypt.org/acme/cert/vsxvk0oldnuobe51ayxz4dms62sk2dwmw9zhuw)'
[Wed 30 Dec 2022 15:22:51 AM EST] Cert success.
--BEGIN CERTIFICAT--
sxlYqPvWreKgD5b8JyOQX0Yg2MLoRUoDyqVkd31PthIiwzdckoh5eD3JU7ysYBtN
cTFK4LGOfjqi8Ks87EVJdK9IaSAu7ZC6h5to0eqpJ5PLhaM3e6yJBbHmYA8w1Smp
... (omitted for brevity) ...
yiLKcBFc5H7dgJCImo7us7aJeftC44uWkPM=
--END CERTIFICAT--
[Wed 30 Dec 2022 15:22:52 AM EST] Your cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.cer
[Wed 30 Dec 2022 15:22:52 AM EST] Your cert key is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:22:52 AM EST] The intermediate CA cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/ca.cer
[Wed 30 Dec 2022 15:22:52 AM EST] And the full chain certs is there: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/fullchain.cer
```
(Note: This is a command written in shell script that requests a SSL certificate from ACME server using the ACME client "acme.sh". It specifies the subdomain of the domain name, the web root directory of the website, the key length, and forces the re-issuance of the certificate.)
::: warning Explanation
The meaning of the `--force` parameter is to manually (forcefully) update the certificate before the existing certificate expires. Although the certificate we applied for from the "test server" in the previous step cannot be used directly, it has not expired yet, so this parameter is needed.
:::
2. You should eventually see a prompt that looks similar to the one above.
```log
vpsadmin@vps-server:~$ acme.sh --issue -d subdomain.yourdomain.com -w /home/vpsadmin/www/webpage --keylength ec-256
[Wed 30 Dec 2022 15:22:51 AM EST] Using CA: https://acme-v02.api.letsencrypt.org/directory
[Wed 30 Dec 2022 15:22:51 AM EST] Creating domain key
[Wed 30 Dec 2022 15:22:51 AM EST] The domain key is here: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:22:51 AM EST] Single domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 15:22:51 AM EST] Getting domain auth token for each domain
[Wed 30 Dec 2022 15:22:51 AM EST] Getting webroot for domain='subdomain.yourdomain.com'
[Wed 30 Dec 2022 15:22:51 AM EST] Verifying: subdomain.yourdomain.com
[Wed 30 Dec 2022 15:22:51 AM EST] Pending
[Wed 30 Dec 2022 15:22:51 AM EST] Success
[Wed 30 Dec 2022 15:22:51 AM EST] Verify finished, start to sign.
[Wed 30 Dec 2022 15:22:51 AM EST] Lets finalize the order.
[Wed 30 Dec 2022 15:22:51 AM EST] Le_OrderFinalize='https://acme-v02.api.letsencrypt.org/acme/finalize/490205996/7730242872'
[Wed 30 Dec 2022 15:22:51 AM EST] Downloading cert.
[Wed 30 Dec 2022 15:22:51 AM EST] Le_LinkCert='https://acme-v02.api.letsencrypt.org/acme/cert/vsxvk0oldnuobe51ayxz4dms62sk2dwmw9zhuw'
[Wed 30 Dec 2022 15:22:51 AM EST] Cert success.
--BEGIN CERTIFICAT--
sxlYqPvWreKgD5b8JyOQX0Yg2MLoRUoDyqVkd31PthIiwzdckoh5eD3JU7ysYBtN
cTFK4LGOfjqi8Ks87EVJdK9IaSAu7ZC6h5to0eqpJ5PLhaM3e6yJBbHmYA8w1Smp
wAb3tdoHZ9ttUIm9CrSzvDBt6BBT6GqYdDamMyCYBLooMyDEM4CUFsOzCRrEqqvC
2mTTEmhvpojo5rhdTSJxibozyNWTGwoTj0v9pTUeQcGqLIzqi4DowjBHD5guwRid
SjAFnm6JT2xUQgWFm58A1gv1OhbH1TRPUUmtE1nFEN7YiSjI4xgxqAXT3CLD2EUb
wXlUrO6c75zSsQP4bRMzgOjJUqHtSb6IEqELzt4M7KzL5iCOruCChCo2DZxUwvVX
tOoaAyQJzCbTqE6aUqwiKi3gVyoxvDP9mI5JdRYzsDL6GVud7EHPnYeMl9ubLZAK
0vg84mbMP3f6mYM4KRa1cqiyOIcQPT4AzGFYVv4sm049bZQg7sd0Bz9CaFvE7yDA
1y17XlgCDnsjxl66bqI1vkENN9XT5xeFHONqc18b5fZEKSIvdX7iWPFWp1PyMPpG
0pMCP1EymZNFxIMJLgbWqExwLWfPc5Ib3PjBaIqhXPnw6sT2MQSxXwDupq1UJVhV
7E3hQRVlwI4CXi6WLHJMNvNRyyK87gCrLH1bKYsPeRVaz77poWBq49zwBCts6hPY
IeF4ltGXyANNIOPEi8vy138fRU4LYh81d8FjOtFfJZogMjwhfNvapqxPMsioPlmX
TnZu0n7setrVNUEfTMHWqPpDgk5MPrWLA4LapqaDfEX4pwnQJLMwMi6s94z165c0
iMRSKA1yU5zqv8aNsDfPoY4OkSPWs4MaXgRRSLBsUfZ15DwQXPk76kegHIyxWvwF
tYw9HKR5QCMK66fa0z4aJoFVFLK0IIOGEZOanRFUCnkLUDd3QZ3YU8lEcrj7Uxos
haiRNICyC6UfsCJ94a8vcNyMosPv3xBLMp19WXgiFYqEFQkntkv1FLRI35fjeJmg
0fmD9VG9bkzGPHihJgQLRlCHasGf6XrdfkSsODAyCUHUHJ0RzqF4YEZMcxDxzuQ2
YO7bFwj7S3mUdVPZ6MPasjxdyBjJgEBMch2uy4AhmudXfEBQBye8W6ZI4ztZjLVV
FmP4SIuaNUmMe20TjR8b9NVC96AhxOanWT3mRROsdokpKQGTJvl27EHH8KuAbUOc
G6KtPy4wslNZNXWcBy9n63RcWak12r7kAIFn38tZxmlw2WUKoRSMAH64GcDTjRQd
Am65hBHzvGrj93wEuVNIebvNIsJOlng3HFjpIxVqKGMCIfWIKGDE3YzK3p4LbGZ6
NZFQWYJLNVf2M9CCJfbEImPYgvctrxl39H6KVYPCw1SAdaj9NneUqmREOQkKoEB0
x6PmNirbMscHhQPSC0JQaqUgaQFgba1ALmzRYAnYhNb0twkTxWbY7DBkAarxqMIp
yiLKcBFc5H7dgJCImo7us7aJeftC44uWkPM=
--END CERTIFICAT--
[Wed 30 Dec 2022 15:22:52 AM EST] Your cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.cer
[Wed 30 Dec 2022 15:22:52 AM EST] Your cert key is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/subdomain.yourdomain.com.key
[Wed 30 Dec 2022 15:22:52 AM EST] The intermediate CA cert is in /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/ca.cer
[Wed 30 Dec 2022 15:22:52 AM EST] And the full chain certs is there: /home/vpsadmin/.acme.sh/subdomain.yourdomain.com_ecc/fullchain.cer
```
3. If you observe carefully, you will find that the domain name that issues the certificate to you this time is `https://acme-v02.api.letsencrypt.org`, which lacks the word `staging`. Therefore, this is the [Production Environment]!
3. Look closely, and you will find that the issuer domain this time is `https://acme-v02.api.letsencrypt.org`. The `staging` is gone, which naturally means it is the "Official Server" (Production)!
## 6.5 Certificate Installation
1. After completing the certificate application, it needs to be installed to a specified location and referenced in the configuration file to take effect:
1. After the certificate application is complete, it needs to be installed. Install it to the specified location and reference it in the configuration file:
```shell
vpsadmin@vps-server:~$ acme.sh --installcert -d subdomain.yourdomain.com --cert-file /path/to/install/cert.crt --key-file /path/to/install/cert.key --fullchain-file /path/to/install/fullchain.crt --ecc
[Mon 14 Feb 2022 03:00:25 PM CST] Installing cert to: /etc/xray/cert/cert.crt
[Mon 14 Feb 2022 03:00:25 PM CST] Installing key to: /etc/xray/cert/cert.key
[Mon 14 Feb 2022 03:00:25 PM CST] Installing full chain to: /etc/xray/cert/fullchain.crt
```
(Note: This is a shell command for installing a SSL certificate using acme.sh. The command is specifying the domain, file paths for the certificate, private key, and full chain, as well as indicating that an ECC certificate should be used.)
```shell
vpsadmin@vps-server:~$ acme.sh --installcert -d subdomain.yourdomain.com --cert-file /path/to/installation/cert.crt --key-file /path/to/installation/cert.key --fullchain-file /path/to/installation/fullchain.crt --ecc
[Mon 14 Feb 2022 03:00:25 PM CST] Installing cert to: /etc/xray/cert/cert.crt
[Mon 14 Feb 2022 03:00:25 PM CST] Installing key to: /etc/xray/cert/cert.key
[Mon 14 Feb 2022 03:00:25 PM CST] Installing full chain to: /etc/xray/cert/fullchain.crt
```
## 6.6 Your Progress
At this point, the two basic infrastructures required by Xray are finally in place! Xray, which has been eagerly awaited, is about to be revealed, and we are finally about to enter the most exciting chapter!
At this point, the two pieces of infrastructure required by Xray are finally in place! The long-awaited Xray is about to be unveiled. We are finally entering the most exciting chapter!
> ⬛⬛⬛⬛⬛⬛⬜⬜ 75%
+401 -416
View File
@@ -1,580 +1,565 @@
# [Chapter 7]Xray Server
# [Chapter 7] Xray Server Guide
## 7.1 Study broadly, Act decisively.
## 7.1 Extensive Preparation, Effortless Execution
During the writing of this article, the boss joked: Your tutorial has been serialized for 6 chapters and has not yet reached Xray. People who don’t know would think that you are a "hand-in-hand teaching you to build a website" tutorial. (I can't refute it.jpg!)
During the writing of this article, a pro jokingly complained to me: "Your tutorial has been running for 6 chapters and still hasn't reached Xray? People who don't know better might think this is a 'Build Your Own Website' tutorial." (I couldn't even refute that.jpg!)
In fact, this structure is my decision after much thinking. After all, only by laying a solid foundation can you quickly surpass others with half the effort. I saw many newcomers in the group who can't even use `nano` correctly, nor can they use `WinSCP`. The `config.json` edited by remote handwriting is naturally full of errors, and even error checking becomes difficult.
Actually, this structure was a decision made after much deliberation. Only by laying a solid foundation can you achieve twice the result with half the effort later on and overtake others quickly. I've seen many newcomers in groups who can't even use `nano` correctly, don't know how to use `WinSCP`, and naturally, the `config.json` they hand-edit remotely is full of errors, making debugging a struggle.
::: warning
After the preparation of the first 6 chapters, you have already climbed over several mountains with me, such as basic Linux operations, VPS remote management, web page construction, domain name management, certificate application, etc. Do you think it is actually very simple when you look back? Now that we have such solid preparations, we will have a light feeling of [smooth success] when installing and configuring Xray.
After the preparations in the first 6 chapters, we have climbed over several mountains together: Basic Linux operations, VPS remote management, website setup, domain management, certificate application, etc. Looking back, doesn't it seem quite simple? Now that we have such solid preparation, the upcoming installation and configuration of Xray will feel completely natural and effortless.
:::
The things to do next are very simple:
What needs to be done next is very simple:
1. Installation
2. Configuration (such as installing TLS certificates, `config.json`)
3. Run
4. Optimization (such as updating the kernel, enabling `bbr`, automatically redirecting `http` visits to `https`, etc.)
1. Installation
2. Configuration (e.g., installing TLS certificates, `config.json`)
3. Running
4. Optimization (e.g., updating the kernel, enabling `bbr`, auto-redirecting `http` to `https`, etc.)
## 7.2 Install Xray
## 7.2 Installing Xray
First of all, the official carrier of Xray is the binary program generated by the open source project [xray-core](https://github.com/XTLS/Xray-core) (Open sourced with License `MPL 2.0`
). If you put this binary on the server and run it, it is the server side; if you download it to the local computer and run it, it is the client side. The main difference comes from [configuration].
First, the official carrier of Xray is the binary program generated by the [xray-core](https://github.com/XTLS/Xray-core) open-source project (based on the `MPL 2.0` open-source license). If you run this binary on a server, it is the server-side; if you download it to your local computer and run it, it is the client-side. The main difference lies in the [Configuration].
When installing, it is very simple and direct to use the official installation script directly. It provides a variety of installation options. If you are interested, you can go to the official [installation script repository](https://github.com/XTLS/Xray-install) to see the script instructions. **This article uses the [non-root
user] installation mode**.
For installation, using the official installation script is simple and direct. It provides multiple installation options. Interested users can check the script instructions in the official [installation script repository](https://github.com/XTLS/Xray-install). **This article uses the [Non-root User] installation mode.**
When writing this article, the installation script had some minor bugs when using a non-root account, so I decided to separate these steps and explain the deletion command under Linux.
At the time of writing, the installation script has a few small bugs when using a non-root account, so I decided to separate these steps. This also serves as a good opportunity to explain the delete command in Linux.
1. Basic Linux commands for beginners:
1. Linux 101 - Basic Commands:
| Number | Command name | Command description |
| :------: | :----------: | :-----------------: |
| `cmd-14` | `rm` | delete |
| Number | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-14` | `rm` | Delete command |
2. Download the installation script:
2. Download the installation script locally:
```shell
wget https://github.com/XTLS/Xray-install/raw/main/install-release.sh
```
```shell
wget [https://github.com/XTLS/Xray-install/raw/main/install-release.sh](https://github.com/XTLS/Xray-install/raw/main/install-release.sh)
```
3. Execute the installation command
3. Execute the installation command:
```shell
sudo bash install-release.sh
```
```shell
sudo bash install-release.sh
```
4. You can delete the script after use
4. After use, you can delete the script:
```shell
rm ~/install-release.sh
```
::: warning
When you use the `rm` command to delete files, the default is to delete the files in the current folder. However, **I still wrote the full path**: `~/install-release.sh`, which is a safety habit I have when using `rm`, and it is also what I want to emphasize after I divide the installation into several steps. If you have heard some jokes like "Programmers go from deleting libraries to running away", you probably know why.
:::
5. The complete process is demonstrated as follows:
![Xray server installation process demonstration](./ch07-img01-xray-install.gif)
## 7.3 Configure TLS certificate for Xray
Although we have applied for TLS
certificate before, according to the official instructions of [`acme.sh`](https://github.com/acmesh-official/acme.sh/wiki/%E8%AF%B4%E6%98%8E#3-copy%E5%AE%89%E8%A3%85-%E8%AF%81%E4%B9%A6), it is not recommended to use the applied certificate directly. The correct way is to use the `--install-cert`
command to install it for the required program. Let's install the certificate for `xray-core` now.
1. In order to avoid various potential permission problems of non-root accounts, we create a certificate folder under the vpsadmin account
```shell
mkdir ~/xray_cert
```
2. Use `--install-cert` of `acme.sh` to correctly install (copy) the certificate file
```shell
acme.sh --install-cert -d secondary domain name.your domain name.com --ecc \
--fullchain-file ~/xray_cert/xray.crt \
--key-file ~/xray_cert/xray.key
```
3. The `xray.key` file is not readable by other users by default, so it needs to be given readability
```shell
chmod +r ~/xray_cert/xray.key
```
4. The process is relatively simple, so no animated picture:
![Xray server installation process demonstration](./ch07-img02-xray-cert-install.png)
5. `acme.sh` will check the certificate every 60 days and automatically renew the expiring certificate. But as far as I know, it does not automatically install the new certificate to `xray-core`, so we need to add a system automatic periodic task to complete this step.
1. Basic Linux commands for beginners:
| Number | Command name | Command description |
| :------: | :----------: | :------------------------------------: |
| `cmd-15` | `crontab -e` | Edit the current user's scheduled task |
2. Create a script file (`xray-cert-renew.sh`)
```shell
nano ~/xray_cert/xray-cert-renew.sh
```
3. Copy the following content, remember to replace your real domain name, then save and exit
```bash
#!/bin/bash
/home/vpsadmin/.acme.sh/acme.sh --install-cert -d a-name.yourdomain.com --ecc --fullchain-file /home/vpsadmin/xray_cert/xray.crt --key-file /home/vpsadmin/xray_cert/xray.key
echo "Xray Certificates Renewed"
chmod +r /home/vpsadmin/xray_cert/xray.key
echo "Read Permission Granted for Private Key"
sudo systemctl restart xray
echo "Xray Restarted"
```
```shell
rm ~/install-release.sh
```
::: warning
As you have reminded, `acme.sh` has a `reloadcmd` command that can automatically execute a specific command when the certificate is updated, so you can specify to automatically install the certificate for `Xray`, but because `crontab` is a very useful and commonly used function in Linux, this article retains the `crontab` method to update the `Xray` certificate. (If you interested in `reloadcmd` can check out the [official documentation](https://github.com/acmesh-official/acme.sh) of `acme.sh`)
When using the `rm` command to delete a file, it defaults to deleting the file in the current folder. However, **I still wrote the full path**: `~/install-release.sh`. This is a safety habit of mine when using `rm`, and it is also something I wanted to emphasize by breaking the installation into steps. If you've heard jokes about "programmers deleting the database and running away," you probably understand why.
:::
In addition, when recording animated images, the script did not include a command to restart `Xray` because `Xray` plans to support the [Certificate Hot Update] function, which means that `Xray` will automatically identify certificate updates and reload certificates without manual restart. After the function is added, I will modify `config.json` appropriately
to enable this setting and delete the restart command in the script.
::: 4. Add [executable] permissions to this file
5. The complete process demonstration is as follows:
![Xray Server Installation Demo](./ch07-img01-xray-install.gif)
## 7.3 Configuring TLS Certificates for Xray
Although we have already applied for TLS certificates earlier, according to the [official documentation of `acme.sh`](https://github.com/acmesh-official/acme.sh/wiki/%E8%AF%B4%E6%98%8E#3-copy%E5%AE%89%E8%A3%85-%E8%AF%81%E4%B9%A6), it is not recommended to use the applied certificates directly. The correct method is to use the `--install-cert` command to install them for the required program. Now, let's install the certificate for `xray-core` to use.
1. To avoid various potential permission issues with non-root accounts, we create a certificate folder under the vpsadmin account.
```shell
mkdir ~/xray_cert
```
2. Use `acme.sh`'s `--install-cert` to correctly install (copy) the certificate files.
```shell
acme.sh --install-cert -d subdomain.yourdomain.com --ecc \
--fullchain-file ~/xray_cert/xray.crt \
--key-file ~/xray_cert/xray.key
```
3. The `xray.key` file is not readable by other users by default, so we need to grant it read permissions.
```shell
chmod +r ~/xray_cert/xray.key
```
4. The process is simple, so no GIF is provided:
![Xray Certificate Install Demo](./ch07-img02-xray-cert-install.png)
5. `acme.sh` checks the certificate every 60 days and automatically renews it if it's close to expiration. However, as far as I know, it does not automatically install the new certificate to `xray-core`, so we need to add a system automatic periodic task to complete this step.
1. Linux 101 - Basic Commands:
| Number | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-15` | `crontab -e` | Edit the current user's scheduled tasks |
2. Create a script file (`xray-cert-renew.sh`):
```shell
nano ~/xray_cert/xray-cert-renew.sh
```
3. Copy the content below into it, remembering to replace it with your real domain name, then save and exit.
```bash
#!/bin/bash
/home/vpsadmin/.acme.sh/acme.sh --install-cert -d a-name.yourdomain.com --ecc --fullchain-file /home/vpsadmin/xray_cert/xray.crt --key-file /home/vpsadmin/xray_cert/xray.key
echo "Xray Certificates Renewed"
chmod +r /home/vpsadmin/xray_cert/xray.key
echo "Read Permission Granted for Private Key"
sudo systemctl restart xray
echo "Xray Restarted"
```
::: warning
As pointed out by others, `acme.sh` has a `reloadcmd` command that can automatically execute specific commands when the certificate is updated. This could be used to automatically install certificates for `Xray`. However, since `crontab` is a very useful and common function in Linux systems, this article retains the `crontab` method for updating `Xray` certificates. (Those interested in `reloadcmd` can check the [official documentation](https://github.com/acmesh-official/acme.sh) of `acme.sh`).
Additionally, in the GIF recording, the script did not include the `Xray` restart command because `Xray` plans to support [Certificate Hot Reload], meaning `Xray` will automatically recognize certificate updates and reload them without a manual restart. Once this feature is added, I will modify `config.json` appropriately to enable this setting and remove the restart command from the script.
:::
4. Add [Executable] permission to this file.
```shell
chmod +x ~/xray_cert/xray-cert-renew.sh
```
5. Run `crontab -e` and add an automatic task [Automatically run `xray-cert-renew.sh` once a month] (Note that you should not add `sudo`, because we are adding an automatic task for the `vpsadmin`
account. When you run it for the first time, you will be asked to choose an editor. Of course, choose the familiar `nano`!)
5. Run `crontab -e` to add an automatic task [Run `xray-cert-renew.sh` automatically once a month] (Note: do not add `sudo`, because we are adding the automatic task for the `vpsadmin` account. When running for the first time, it will ask you to choose an editor; choose the familiar `nano`!).
```shell
crontab -e
```
```shell
crontab -e
```
6. Add the following content to the end of the file, save and exit.
6. Add the following content to the end of the file, save, and exit.
```
# 1:00am, 1st day each month, run `xray-cert-renew.sh`
0 1 1 * * bash /home/vpsadmin/xray_cert/xray-cert-renew.sh
```
7. The complete process is demonstrated as follows:
7. The complete process demonstration is as follows:
![Automatically install certificates for Xray every month](./ch07-img03-crontab-cert-renew.gif)
![Automatically install certificates for Xray monthly](./ch07-img03-crontab-cert-renew.gif)
## 7.4 Configure Xray
## 7.4 Configuring Xray
First, you can refer to the [official VLESS configuration example](https://github.com/XTLS/Xray-examples) for various configurations. This article will configure a simplest method based on the official example: [Single `VLESS` protocol inbound + `80` Port fallback], which meets the maximum speed and necessary security of most scenarios.
First, various configurations can refer to the [official VLESS configuration examples](https://github.com/XTLS/Xray-examples). This article will configure a most streamlined method based on the official examples: [Single `VLESS` protocol inbound + Port `80` fallback], satisfying maximum speed and necessary security for most scenarios.
1. Generate a legal `UUID` and save it for backup (`UUID` can be simply and roughly understood as an ID that is almost never repeated like a fingerprint)
1. Generate a valid `UUID` and save it for later use (`UUID` can be simply understood as an ID, like a fingerprint, that almost never repeats).
```shell
xray uuid
```
```shell
xray uuid
```
2. Create log files and folders for backup
1. Basic Linux commands for beginners:
| Number | Command name | Command description |
|:--:|:--:|:--:|
| `cmd-16` | `touch` | Create a blank file |
2. Create log files and folders for later use.
1. Linux 101 - Basic Commands:
2. Create a [log dedicated folder] in the `vpsadmin` folder
| Number | Command Name | Command Description |
| :---: | :---: | :---: |
| `cmd-16` | `touch` | Create a blank file |
```shell
mkdir ~/xray_log
```
2. Create a [Log Dedicated Folder] inside the `vpsadmin` folder.
3. Generate the two required log files (access log, error log)
```shell
mkdir ~/xray_log
```
```shell
touch ~/xray_log/access.log && touch ~/xray_log/error.log
```
3. Generate the two required log files (access log, error log).
::: warning
This location is not the standard log file location of `Xray`. It is placed here to avoid permission issues that cause trouble for new users. Once you are familiar with it, it is recommended to return to the default location: `/var/log/xray/access.log` and `/var/log/xray/error.log`.
::: 4. Because Xray is used by the nobody user by default, we need to allow other users to have "write" permissions (`*.log` means all files with the suffix `log`, and the efficiency advantage of the `CLI` interface gradually appears at this time)
```shell
touch ~/xray_log/access.log && touch ~/xray_log/error.log
```
```shell
chmod a+w ~/xray_log/*.log
```
::: warning
This location is not the standard `Xray` log file location. Placing it here is to avoid permission issues causing trouble for newcomers. Once you are familiar with it, it is recommended to revert to the default location: `/var/log/xray/access.log` and `/var/log/xray/error.log`.
:::
3. Use `nano` to create the configuration file of `Xray`
4. Since Xray defaults to running as the `nobody` user, we need to allow other users to have "write" permissions (`*.log` means all files with the `log` suffix; the efficiency advantage of the `CLI` interface gradually appears here).
```shell
sudo nano /usr/local/etc/xray/config.json
```
```shell
chmod a+w ~/xray_log/*.log
```
4. Copy all the files below and fill in the previously generated `UUID` into the 61st line `"id": "",`. (After filling in, it will look like `"id": "uuiduuid-uuid-uuid-uuid-uuiduuiduuid"`
) This configuration file in this article adds my various verbose comments to help you understand the function of each configuration module.
3. Use `nano` to create the `Xray` configuration file.
```json
// REFERENCE:
// https://github.com/XTLS/Xray-examples
// https://xtls.github.io/config/
// Commonly used config files, whether server or client, have 5 parts. Plus Xiao Xiaobai's interpretation:
// ┌─ 1*log Log settings - what to write in the log and where to write (there is evidence when errors occur)
// ├─ 2_dns DNS-settings - how to check DNS (anti-DNS pollution, anti-peeping, avoid matching domestic and foreign sites to foreign servers, etc.)
// ├─ 3_routing Diversion settings - how to classify and process traffic (whether to filter ads, whether to divert traffic domestically and internationally)
// ├─ 4_inbounds Inbound settings - what traffic can flow into Xray
// └─ 5_outbounds Outbound settings - where does the traffic out of Xray go
{
// 1\_Log settings
"log": {
"loglevel": "warning", // content from less to more: "none", "error", "warning", "info", "debug"
"access": "/home/vpsadmin/xray_log/access.log", // access record
"error": "/home/vpsadmin/xray_log/error.log" // Error log
},
// 2_DNS settings
"dns": {
"servers": [
"https+local://1.1.1.1/dns-query", // Prefer 1.1.1.1 DoH query, sacrificing speed but preventing ISP snooping
"localhost"
]
},
// 3*Diversion settings
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
// 3.1 Prevent local server flow problems: such as intranet attacks or abuse, incorrect local loopbacks, etc.
{
"ip": [
"geoip:private" // Diversion condition: In the geoip file, the rule named "private" (local)
],
"outboundTag": "block" // Diversion strategy: Hand over to the outbound "block" for processing (black hole shielding)
},
{
// 3.2 Prevent the server from connecting directly to China
"ip": ["geoip:cn"],
"outboundTag": "block"
},
// 3.3 Block ads
{
"domain": [
"geosite:category-ads-all" // Diversion conditions: In the geosite file, the rule named "category-ads-all" (various advertising domain names)
],
"outboundTag": "block" // Diversion strategy: Hand it over to the outbound "block" for processing (black hole shielding)
}
]
},
// 4* Inbound settings
// 4.1 Here is only the simplest vless+xtls inbound, because this is the most powerful mode of Xray. If you need other, please add it according to the template.
"inbounds": [
```shell
sudo nano /usr/local/etc/xray/config.json
```
4. Copy the entire file below into it, and fill in the previously generated `UUID` into line 61 `"id": "",`. (After filling it in, it looks like `"id": "uuiduuid-uuid-uuid-uuid-uuiduuiduuid"`). I have added various verbose annotations to this configuration file in this article to help you understand the function of each configuration module.
```json
// REFERENCE:
// [https://github.com/XTLS/Xray-examples](https://github.com/XTLS/Xray-examples)
// [https://xtls.github.io/config/](https://xtls.github.io/config/)
// Common config files, whether server or client, have 5 parts. Plus newbie interpretation:
// ┌─ 1*log Log Settings - What to write, where to write (evidence available when errors occur)
// ├─ 2_dns DNS Settings - How to query DNS (prevent DNS pollution, prevent snooping, avoid matching domestic sites to foreign servers, etc.)
// ├─ 3_routing Routing Settings - How to classify and process traffic (whether to filter ads, split domestic/international traffic)
// ├─ 4_inbounds Inbound Settings - What traffic can flow into Xray
// └─ 5_outbounds Outbound Settings - Where the traffic flowing out of Xray goes
{
"port": 443,
"protocol": "vless",
"settings": {
"clients": [
// 1_Log Settings
"log": {
"loglevel": "warning", // Content from least to most: "none", "error", "warning", "info", "debug"
"access": "/home/vpsadmin/xray_log/access.log", // Access record
"error": "/home/vpsadmin/xray_log/error.log" // Error record
},
// 2_DNS Settings
"dns": {
"servers": [
"https+local://1.1.1.1/dns-query", // Prefer 1.1.1.1 DoH query, sacrifices speed but prevents ISP snooping
"localhost"
]
},
// 3_Routing Settings
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
// 3.1 Prevent local server loop issues: e.g., intranet attacks or abuse, wrong local loops, etc.
{
"id": "", // Fill in your UUID
"flow": "xtls-rprx-vision",
"level": 0,
"email": "vpsadmin@yourdomain.com"
}
],
"decryption": "none",
"fallbacks": [
"ip": [
"geoip:private" // Routing condition: rules named "private" in the geoip file (local)
],
"outboundTag": "block" // Routing strategy: hand over to outbound "block" processing (blackhole blocking)
},
{
"dest": 80 // Fall back to anti-detection proxy by default
// 3.2 Prevent server from directly connecting to domestic (CN) IPs
"ip": ["geoip:cn"],
"outboundTag": "block"
},
// 3.3 Block Ads
{
"domain": [
"geosite:category-ads-all" // Routing condition: rules named "category-ads-all" in the geosite file (various ad domains)
],
"outboundTag": "block" // Routing strategy: hand over to outbound "block" processing (blackhole blocking)
}
]
},
"streamSettings": {
"network": "tcp",
"security": "tls",
"tlsSettings": {
"alpn": "http/1.1",
"certificates": [
{
"certificateFile": "/home/vpsadmin/xray_cert/xray.crt",
"keyFile": "/home/vpsadmin/xray_cert/xray.key"
// 4_Inbound Settings
// 4.1 Here only one simplest vless+xtls inbound is written, because this is Xray's most powerful mode. If needed, please add others based on templates.
"inbounds": [
{
"port": 443,
"protocol": "vless",
"settings": {
"clients": [
{
"id": "", // Fill in your UUID
"flow": "xtls-rprx-vision",
"level": 0,
"email": "vpsadmin@yourdomain.com"
}
],
"decryption": "none",
"fallbacks": [
{
"dest": 80 // Default fallback to the probe-resistant proxy
}
]
},
"streamSettings": {
"network": "tcp",
"security": "tls",
"tlsSettings": {
"alpn": "http/1.1",
"certificates": [
{
"certificateFile": "/home/vpsadmin/xray_cert/xray.crt",
"keyFile": "/home/vpsadmin/xray_cert/xray.key"
}
]
}
]
}
}
}
],
// 5_Outbound Settings
"outbounds": [
// 5.1 The first outbound is the default rule, freedom is direct connection (VPS is already on the external network, so direct connection)
{
"tag": "direct",
"protocol": "freedom"
},
// 5.2 Blocking rule, blackhole protocol sends traffic into a black hole (blocking)
{
"tag": "block",
"protocol": "blackhole"
}
]
}
],
// 5*Outbound settings
"outbounds": [
// 5.1 The first outbound is the default rule, freedom is a direct connection to the outside (vps is already an external network, so it is a direct connection)
{
"tag": "direct",
"protocol": "freedom"
},
// 5.2 Blocking rules, blackhole protocol is to import traffic into the black hole (blocking)
{
"tag": "block",
"protocol": "blackhole"
}
]
}
```
```
5. The complete process is demonstrated as follows:
![Create log file and `config.json` configuration file](./ch07-img04-xray-log-and-config.gif)
5) The complete process demonstration is as follows:
![Creating log files and `config.json` configuration file](./ch07-img04-xray-log-and-config.gif)
## 7.5 Start Xray service! ! (and check the service status)
## 7.5 Start Xray Service!! (And check service status)
If you follow this article step by step, you have actually avoided the two most common pitfalls of **insufficient log file permissions** and **insufficient certificate file permissions**. Now running `Xray` should be very smooth.
If you have followed this article step by step, you have actually avoided the most common pitfalls of **insufficient log file permissions** and **insufficient certificate file permissions**. So now, running `Xray` should naturally be incredibly smooth.
1. Enter the following command and enjoy the historic moment of starting `Xray`! ! !
1. Enter the command below and enjoy the historic moment of starting `Xray`!!!
```shell
sudo systemctl start xray
```
```shell
sudo systemctl start xray
```
2. Just `start` does not determine whether the Xray service has been successfully started. To determine its status, use the following command.
2. Just `start` doesn't confirm if we have successfully opened the Xray service. To determine its status, use the following command.
```shell
sudo systemctl status xray
```shell
sudo systemctl status xray
```
```
See that green, delightful `active (running)`? It says `Xray` is running correctly.
Do you see the green, pleasant `active (running)`? It means that `Xray` is running correctly
3. The complete process demonstration is as follows:
3. The complete process is demonstrated as follows:
![Start and check Xray running status](./ch07-img05-xray-start-and-status.gif)
![Start and check the running status of Xray](./ch07-img05-xray-start-and-status.gif)
## 7.6 Reviewing `systemd` for Basic Service Management
## 7.6 Review `systemd` for basic service management
So far, we have used `systemctl` related commands like `start`, `status`, `reload`, etc. These are general commands for managing various services in the Linux system based on the `systemd` management module. Now is a good time to familiarize yourself with a few other related commands.
So far, we have used `systemctl` related commands such as `start`, `status`, `reload`, etc. These are general commands based on the `systemd` management module to manage various services in the Linux
system. Now it is a good time to get familiar with several other related commands.
1. If you need to temporarily stop the `Xray` service, use the `stop` command:
1. If you need to temporarily shut down the `Xray` service, use the `stop` command
```shell
sudo systemctl stop xray
```
```shell
sudo systemctl stop xray
```
2. If you need to restart the `Xray` service, use the `restart` command:
2. If you need to restart the `Xray` service, use the `restart` command
```shell
sudo systemctl restart xray
```
```shell
sudo systemctl restart xray
```
3. If you need to disable the `Xray` service (prevent Xray from running automatically after computer restart), use the `disable` command:
3. If you need to disable the `Xray` service (disable Xray from running automatically after the computer is restarted), use the `disable` command
```shell
sudo systemctl disable xray
```
```shell
sudo systemctl disable xray
```
4. If you need to enable the `Xray` service (ensure Xray runs automatically after computer restart), use the `enable` command:
4. If you need to enable the `Xray` service (ensure that Xray runs automatically after the computer is restarted), use the `enable` command
```shell
sudo systemctl enable xray
```
```shell
sudo systemctl enable xray
```
## 7.7 Server Optimization 1: Enable BBR
1. The legendary `BBR`
1. The Legendary `BBR`
I believe that when you search for various scientific Internet technologies, you must have heard of the thing `bbr` more than once. With the exaggeration of various blogs, people feel that it is magical. There are also a lot of derivatives such as `bbrplus`, `bbr2`, `magic bbr`, etc. It's like a magic, which can turn a poorly routed lines become dedicated connections.
I believe that when you search for various scientific internet access technologies (censorship circumvention), you must have heard of `bbr` more than once. Under the embellishment of various blogs, it seems miraculous. There are also a bunch of derivatives like `bbrplus`, `bbr2`, `modified bbr`, etc., as if they were magic oils that can turn a cheap line into a dedicated line.
So, what is this thing? Is it useful? Which version should I use?
So, what exactly is this thing? Is it useful? And which version should be used?
2. The actual `BBR`
2. The Actual `BBR`
**BBR** = **B**ottleneck **B**andwidth and **R**ound-trip propagation time, which is a **congestion control algorithm** of TCP. A simple and rough understanding is **traffic management of data traffic**
: When the road is no longer congested, each car can naturally maintain a faster speed.
**BBR** = **B**ottleneck **B**andwidth and **R**ound-trip propagation time. It is a TCP **congestion control algorithm**. To understand it simply and crudely, it is **traffic management for data**: when the highway is not jammed, every car can naturally maintain a faster speed.
So is it useful? Generally speaking, there will be a perceptible difference between `with BBR` and `without BBR` (there will be some improvements in speed, stability, and latency), so **[It is highly recommended to turn on `BBR`]**.
So is it useful? Generally speaking, there is a perceptible difference between `With BBR` and `Without BBR` (improvements in speed, stability, and latency), so **[It is highly recommended to enable `BBR`]**.
But after it is enabled, the difference between `BBR` in `4.x` and `5.x` is often subtle and subjective, and the decisive factor that causes the difference in experience is still the line quality. So **[Don't worry about the version, don't blindly chase the new, just follow your distribution to update the kernel]**
However, after enabling it, the difference between `BBR` in `4.x` and `5.x` is often subtle and subjective. The decisive factor causing the experience difference is still the line quality. So **[Do not obsess over versions, do not blindly chase the new, just follow your distribution's kernel updates]**.
3. Are `bbrplus`, `bbr2`, `magic bbr` and other versions that sound cool better?
3. Are `bbrplus`, `bbr2`, `modified bbr` and other versions with cool-sounding names better?
In a word: **No! Don't use these! These names are just to attract attention! **
In one word: **No! Don't use these! These are names made up just to attract attention!**
The update and release of `BBR` are all carried out in accordance with the Linux kernel (`Kernel`). In other words, as long as you use a relatively new kernel, you will naturally use the new version of `BBR`.
The update and release of `BBR` follow the Linux kernel (`Kernel`). In other words, as long as you use a relatively new kernel, you will naturally use the new version of `BBR`.
And these things with cool names are, to put it bluntly, kernels that have not yet been officially released and are still in the testing stage and their corresponding `BBR` versions. These scripts are just the first to enable by downloading the preview version of the kernel (even a third-party magic kernel).
And those things with cool names are essentially unreleased kernels still in the testing phase and their corresponding `BBR` versions. These scripts merely enable them by downloading preview kernels (or even third-party modified kernels).
The stability of the kernel is the cornerstone of the stable operation of a server. **The slight performance difference brought by the BBR beta is definitely not worth changing to an unstable Kernel. 】** Please choose the latest kernel supported by your Linux distribution, so as to maximize the long-term stability and compatibility of the server.
Kernel stability is the cornerstone of a stable server operation. **[The subtle performance difference brought by the BBR beta version is absolutely not worth swapping for an unstable kernel.]** Please choose the latest kernel supported by your Linux distribution, which maximizes the long-term stability and compatibility of the server.
::: warning
The so-called "leading" of the magic modification `bbr` is very time-sensitive. For example, many `bbrplus` scripts, because they have not been updated for several years, will still change your kernel to `4.19`. You should know that Debian is now stable and it is already the era of `5.9`. Then this script may be a little ahead in January 2018, but it has lost its meaning when 4.19 is released in October 2018. It can even be said to be completely [downgraded] and [degraded] now.
:::
::: warning
The so-called "lead" of modified `bbr` has a very strong timeliness. For example, many `bbrplus` scripts have not been updated for several years, and even now they will replace your kernel with `4.19`. You should know that stable distributions like Debian are already in the `5.9` era. So maybe this script was a little ahead in January 2018, but by October 2018 when 4.19 was officially released, it had lost its meaning. Putting it in use now can even be considered a complete [Downgrade] and [Degradation].
:::
4. Which of `fq`, `fq_codel`, `fq_pie`, `cake` and other algorithms is better?
4. Which algorithm is better: `fq`, `fq_codel`, `fq_pie`, `cake` or others?
In one sentence: **If you don't understand, please keep `fq`, which is enough and will not degrade your line**
In one word: **If you don't understand, please keep `fq`. It is sufficient and will not degrade your line.**
5. Ruisu, Finalspeed, LotServer and other "acceleration tools"
5. RuiSu (ServerSpeeder), Finalspeed, LotServer, and other "Acceleration Tools"
In one sentence: **Don't use these! Throw them into the trash can of history! **
In one word: **Do not use these! Throw them into the trash bin of history!**
It can only solve the problem of packet loss rate. A not very accurate analogy is that you originally used a car to deliver your goods, and sometimes the car broke down halfway (packet loss). After using these, you directly sent out 3 copies of the same goods and let three cars deliver them at the same time. As long as one of them is not broken, it can be delivered. The road is full of your cars, so you can naturally squeeze others out. But it is conceivable that when you squeeze others, others will also squeeze you, and the exit road of the entire computer room is so wide, and it is bound to become a collective traffic jam in the end.
The only problem they can solve is the packet loss rate. To use an imprecise analogy: originally you used one car to deliver your goods, sometimes the car broke down halfway (packet loss). After using these, you directly send out 3 identical copies of the goods, letting three cars deliver at the same time. As long as one doesn't break down, it gets delivered. The road is full of your cars, so naturally, you squeeze others out. But predictably, when you squeeze others, others will also squeeze you. The exit road of the entire computer room is only so wide, and eventually, it is bound to turn into a massive collective traffic jam.
::: warning Description
Their principle is not algorithm optimization, not speed-up, most of them are simple and crude **multiple packet delivery**. It may be useful for bad lines with very high packet loss rates, but it has no optimization effect on good lines with low packet loss rates. Instead, it will consume your traffic exponentially, causing unnecessary pressure on the server and your neighbors.
::: warning Note
Their principle is not algorithm optimization or speed boosting; most are simple and crude **multi-packet sending**. For poor lines with [very high packet loss rates], they might have some effect, but for good lines with low packet loss rates, [they have no optimization effect, and instead will multiply your traffic consumption], thereby causing unnecessary pressure on the server and your neighbors.
If your line really has a very high packet loss rate, the only reliable solution is to **change the line**.
:::
If your line really has a ridiculously high packet loss rate, the truly reliable solution is to [Change the Line].
:::
6. I have said so much because there are too many misconceptions and scam scripts around `BBR` to fool novices. I hope you now have a relatively clear understanding of `BBR`. Next, let's install the latest Debian kernel and enable `BBR`! (It's really simple)
6. I've been rambling so much because there are too many misconceptions and pitfall scripts fooling newbies surrounding `BBR`. I hope you now have a relatively clear understanding of `BBR`. Next, let's install the latest Debian kernel and enable `BBR`! (It's really simple)
7. Add the official `backports` source to Debian 10 to get the updated software library
7. Add the official `backports` source to Debian 10 to get updated software libraries.
```shell
sudo nano /etc/apt/sources.list
```
```shell
sudo nano /etc/apt/sources.list
```
::: warning Description
This article takes Debian 10 as an example, so there is still no problem using `/etc/apt/sources.list`, but if you are not starting from scratch according to this article, or using other Linux
distributions, it is recommended that you create a `/etc/apt/sources.list.d/` folder and create your own configuration file in this folder, such as `/etc/apt/sources.list.d/vpsadmin.list`
, to ensure compatibility and avoid the default file being overwritten in unforeseen circumstances and causing configuration loss.
:::
::: warning Note
This article takes Debian 10 as an example, so using `/etc/apt/sources.list` is fine. However, if you are not starting from scratch following this article, or are using another Linux distribution, I suggest you create a `/etc/apt/sources.list.d/` folder and create your own configuration file inside this folder, like `/etc/apt/sources.list.d/vpsadmin.list`. This ensures compatibility and avoids configuration loss caused by default files being overwritten in unforeseen circumstances.
:::
8. Then add the following item at the end, save and exit.
8. Then add the following line at the end, save, and exit.
```
deb http://deb.debian.org/debian buster-backports main
```
```
deb [http://archive.debian.org/debian](http://archive.debian.org/debian) buster-backports main
```
9. Refresh the software library and query the latest version of the official Debian kernel and install it. Please be sure to install the version corresponding to your VPS (this article takes the more common [amd64] as an example).
9. Refresh the software library, query the latest official Debian kernel, and install it. Please be sure to install the version corresponding to your VPS (this article uses the common [amd64] as an example).
```shell
sudo apt update && sudo apt -t buster-backports install linux-image-amd64
```
```shell
sudo apt update && sudo apt -t buster-backports install linux-image-amd64
```
::: warning Note
::: warning Attention
If your VPS supports it, you can try the [Cloud Server Dedicated Kernel] `linux-image-cloud-amd64`. The advantage is that it is streamlined and uses fewer resources. The downside is that some students reported that forcing installation on unsupported systems leads to boot failure (Kernel cannot be recognized).
If your VPS supports it, you can try the [cloud server dedicated kernel] `linux-image-cloud-amd64`. The advantages are simplicity and low resource usage. The disadvantage is that some students have reported that forced installation on an unsupported system will cause the system to fail to boot (the kernel cannot be recognized).
To avoid the tragedy of being unable to recognize the kernel, please ensure:
- Take a system snapshot before trying, or
- You have `vnc` to save the situation (and you know how to use it)
:::
To avoid the tragedy of being unable to identify, please make sure:
10. Modify the `kernel` parameter configuration file `sysctl.conf` and specify enabling `BBR`.
- Take a system snapshot before trying, or
- You have `vnc` to save the day (and you know how to use it)
```shell
sudo nano /etc/sysctl.conf
```
:::
::: warning Note
This article takes Debian 10 as an example, so using `/etc/sysctl.conf` is fine. However, if you are not starting from scratch following this article, or are using another Linux distribution, I suggest you create a `/etc/sysctl.d/` folder and create your own configuration file inside this folder, like `/etc/sysctl.d/vpsadmin.conf`. This ensures compatibility because some distributions no longer read parameters from `/etc/sysctl.conf` after `systemd` version 207. Using a custom configuration file also avoids configuration loss caused by default files being overwritten in unforeseen circumstances.
:::
10. Modify the `kernel` parameter configuration file `sysctl.conf` and specify to enable `BBR`
11. Add the following content into it:
```shell
sudo nano /etc/sysctl.conf
```
```
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
```
::: warning Description
This article takes Debian 10 as an example, so it is still no problem to use `/etc/sysctl.conf`, but if you are not following this article from scratch, or use other Linux distributions, it is recommended that you create a `/etc/sysctl.d/`
folder and create your own configuration file in this folder, such as `/etc/sysctl.d/vpsadmin.conf`, to ensure compatibility, because some distributions no longer read parameters from `/etc/sysctl.conf` after `systemd`
207 ​​version. Using a custom configuration file can also prevent the default file from being overwritten in unexpected circumstances, resulting in configuration loss.
:::
12. Reboot the VPS to make the kernel update and `BBR` settings take effect.
11. Add the following content
```shell
sudo reboot
```
```
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
```
13. The complete process demonstration is as follows:
12. Restart the VPS to make the kernel update and `BBR` settings take effect
::: tip Mr. Verbose
Because the VPS I used for the demonstration supports the cloud server dedicated kernel, I used `linux-image-cloud-amd64` in the GIF. If you are not sure if your VPS supports it, please be sure to follow the command in step 3 and use the regular kernel `linux-image-amd64`.
:::
```shell
sudo reboot
```
![Update Debian Kernel and Enable BBR](./ch07-img06-bbr-proper.gif)
13. The complete process is demonstrated as follows:
14. Confirm `BBR` is enabled
::: tip
Because the VPS I am demonstrating supports the cloud server-specific kernel, I used `linux-image-cloud-amd64` in the animation.
If you want to confirm if `BBR` is enabled correctly, you can use the following command:
If you are not sure whether your VPS supports it, please follow the command in step 3 and use the regular kernel `linux-image-amd64`.
:::
```shell
lsmod | grep bbr
```
![Update Debian kernel and enable `BBR`](./ch07-img06-bbr-proper.gif)
It should return a result like this:
14. Confirm that `BBR` is enabled
```
tcp_bbr
```
If you want to confirm whether `BBR` is enabled correctly, you can use the following command:
If you want to confirm if the `fq` algorithm is enabled correctly, you can use the following command:
```shell
lsmod | grep bbr
```
```shell
lsmod | grep fq
```
This should return the following result:
It should return a result like this:
```
tcp_bbr
```
```
sch_fq
```
If you want to confirm whether the `fq` algorithm is enabled correctly, you can use the following command:
## 7.8 Server Optimization 2: Enable Auto-Redirect from HTTP to HTTPS
```shell
lsmod | grep fq
```
1. We previously set up an `http` webpage on port `80` and used it to apply for a TLS certificate.
This should return the following result:
But if you tried to access our interface using a browser, you would find that `http` access does not automatically upgrade to `https` access like most websites. In other words, under our current settings, `http(80)` and `https(443)` are completely independent. To solve this problem, some modifications are needed.
```
sch_fq
```
2. Edit the Nginx configuration file.
## 7.8 Server Optimization 2: Enable HTTP to automatically redirect to HTTPS
```shell
sudo nano /etc/nginx/nginx.conf
```
1. We have previously built an `http` webpage on port `80` and applied for a TLS certificate.
3. Add the following statement to the Server block listening on port 80 that we set up, then save and exit (you can also delete the `root` and `index` lines):
But if you try to access our interface with a browser, you will find that `http` access will not automatically upgrade to `https` access like most websites. In other words, under our current settings, `http(80)` and `https(443)` are completely independent. If you want to solve this problem, you need to make some changes.
```
return 301 https://$http_host$request_uri;
```
2. Edit the Nginx configuration file
4. Add a local port listener at the same level as port `80` to provide webpage display. This article uses port `8080` for demonstration. (It can be any port).
```shell
sudo nano /etc/nginx/nginx.conf
```
```
server {
listen 127.0.0.1:8080;
root /home/vpsadmin/www/webpage;
index index.html;
add_header Strict-Transport-Security "max-age=63072000" always;
}
```
3. Add the following statement to the 80 port server we set, save and exit (you can delete the `root` and `index` lines at the same time)
5. Restart the Nginx service.
```
return 301 https://$http_host$request_uri;
```
```shell
sudo systemctl restart nginx
```
4. Add a local port listener at the same level as the `80` port to provide web page display. This article uses the `8080` port for demonstration. (Can be any port)
6. Modify the Xray fallback setting, changing the fallback from port `80` to port `8080`. (Find `"dest": 80` and change it to `"dest": 8080`).
```
server {
listen 127.0.0.1:8080;
root /home/vpsadmin/www/webpage;
index index.html;
add_header Strict-Transport-Security "max-age=63072000" always;
}
```
```shell
sudo nano /usr/local/etc/xray/config.json
```
5. Restart Nginx service
7. Restart the `Xray` service to complete the setup.
```shell
sudo systemctl restart nginx
```
```shell
sudo systemctl restart xray
```
6. Modify the fallback settings of Xray, changing the fallback from `80` port to `8080` port. (Find `"dest": 80`, and change it to `"dest": 8080`)
8. The complete process demonstration is as follows:
```shell
sudo nano /usr/local/etc/xray/config.json
```
![http auto redirect to https](./ch07-img07-http-to-https.gif)
7. Restart the `Xray` service to complete the configuration
9. When you enter `http://a-name.yourdomain.com`, it should now automatically redirect to https.
```shell
sudo systemctl restart xray
```
![http auto redirect to https active](./ch07-img08-http-to-https-check.png)
8. The complete process is demonstrated as follows:
## 7.9 Server Optimization 3: Richer Fallbacks
![http automatically jumps to https](./ch07-img07-http-to-https.gif)
If you need richer fallback functionality, you can refer to [《Fallbacks (fallbacks) Feature Analysis》](../level-1/fallbacks-lv1.md)
9. When you enter `http://a-name.yourdomain.com`, it should automatically jump to https
## 7.10 Your Progress
![http automatically jumps to https](./ch07-img08-http-to-https-check.png)
## 7.9 Server Optimization 3: More Fallbacks
If you need more fallback functions, please refer to [《Fallbacks (fallbacks) Functional Analysis》](../level-1/fallbacks-lv1.md)
## 7.10 Your progress
Congratulations!! At this point, you already have a server that can access the Internet normally and scientifically, and also have a disguised website that can prevent active detection attacks. Next, just install the appropriate software on your client and you can enjoy a smooth network!
Congratulations!! At this step, you already possess a server capable of proper scientific internet access (censorship circumvention), and also a camouflage website that prevents active probing attacks. Next, just install the appropriate software on your client, and you can enjoy a smooth network!
> ⬛⬛⬛⬛⬛⬛⬛⬜ 87.5%
## 7.11 Important errata
## 7.11 Important Errata
1. The folder location of the `Xray` configuration file `config.json` in the first version is wrong. If you have already operated according to the previous location, `Xray` will not start correctly. Therefore, the errata is explained here, please check it yourself, and I am very sorry for the inconvenience!
1. In the first edition, the `Xray` configuration file `config.json` folder location was incorrect. If you operated according to the previous location, `Xray` would not start correctly. Therefore, the correction is explained here. Please check yourself. Sorry for the inconvenience!
- Correct location: `/usr/local/etc/xray/config.json`
- Wrong location: `/usr/local/etc/config.json`
- Correct location: `/usr/local/etc/xray/config.json`
- Incorrect location: `/usr/local/etc/config.json`
Affected sections:
Affected sections:
- 7.4 Configuring `Xray` - 3. Use `nano` to create the `Xray` configuration file
- 7.8 Server Optimization 2 - 6. Modify `Xray`'s fallback settings
- 7.4 Configure `Xray` - 3. Use `nano` to create `Xray` configuration file
- 7.8 Server Optimization 2 - 6. Modify `Xray` fallback settings
2. In the first edition, when modifying the `Nginx` configuration file `nginx.conf`, the content was incorrect (webpage folder location error). If you operated according to the previous location, `Nginx` would not find the correct website. Please check yourself. Sorry for the inconvenience!
2. In the first version, the content of the `Nginx` configuration file `nginx.conf` was modified incorrectly (the webpage folder location was incorrect). If you have already performed the operation according to the previous location, `Nginx` will not be able to find the correct website. Please check it yourself. Sorry for the inconvenience!
- Correct folder location: `root /home/vpsadmin/www/webpage;`
- Incorrect folder location: `root /var/www/website/html`
- Correct folder location: `root /home/vpsadmin/www/webpage;`
- Wrong folder location: `root /var/www/website/html`
Affected sections:
- 7.8 Server Optimization 2 - 4. Add a local port listener at the same level as the `80` port to provide web page display
Affected sections:
- 7.8 Server Optimization 2 - 4. Add a local port listener at the same level as port `80` to provide webpage display
+148 -150
View File
@@ -1,220 +1,218 @@
# 【第 8 章】Xray 客户端篇
# 【Chapter 8】 Xray Clients
## 8.1 Xray 的工作原理简述
## 8.1 Brief Description of Xray's Working Principles
要正确的配置和使用`Xray`,就需要正确的理解其工作原理,对于新人,可以先看看下面简化的示意图(省略了许多复杂的设置):
To configure and use `Xray` correctly, you need to properly understand how it works. For newcomers, you can first take a look at the simplified diagram below (many complex settings have been omitted):
![Xray数据流向](./ch08-img01-flow.png)
![Xray Data Flow](./ch08-img01-flow.png)
这其中的关键点是:
The key points are:
1. APP 要主动或借助转发工具,将数据【流入(`inbounds`)】`Xray` 客户端
1. Apps must, either actively or via a forwarding tool, send data so it **[flows in (`inbounds`)]** to the `Xray` client.
2. 流量进入客户端后,会被【客户端路由(`routing`)】按规则处理后,向不同方向【流出`(outbounds)`】`Xray` 客户端。比如:
1. 国内流量直连(`direct`)
2. 国外流量转发 VPS(`proxy`)
3. 广告流量屏蔽(`block`)
2. After traffic enters the client, it is processed by the **[Client Routing (`routing`)]** according to rules, and then sent to **[flow out (`outbounds`)]** of the `Xray` client in different directions. For example:
1. Domestic traffic connects directly (`direct`).
2. Foreign traffic is forwarded to the VPS (`proxy`).
3. Ad traffic is blocked (`block`).
3. 向 VPS 转发的国外流量,会跨过防火墙,【流入(`inbounds`)】 `Xray` 服务器端
3. Foreign traffic forwarded to the VPS will cross the firewall and **[flow in (`inbounds`)]** to the `Xray` server-side.
4. 流量进入服务器端后,与客户端一样,会被【服务器端路由(`routing`)】按规则处理后,向不同方向【流出`(outbounds)`】:
1. 因为已经在防火墙之外,所以流量默认直连,你就可以访问到不存在网站们了(`direct`)
2. 如果需要在不同的 VPS 之间做链式转发,就可以继续配置转发规则(`proxy`)
3. 你可以在服务器端继续禁用各种你想禁用的流量,如广告、BT 下载等(`block`)
4. After traffic enters the server-side, just like on the client, it is processed by the **[Server Routing (`routing`)]** according to rules, and then sent to **[flow out (`outbounds`)]** in different directions:
1. Since it is already outside the firewall, traffic connects directly by default, allowing you to access those "non-existent" websites (`direct`).
2. If you need to perform chained forwarding between different VPSs, you can continue to configure forwarding rules (`proxy`).
3. You can continue to disable various traffic you want to ban on the server side, such as ads, BitTorrent downloads, etc. (`block`).
:::warning 注意
:::warning Note
请务必记得,`Xray` 的路由配置非常灵活,上面的说明只是无限可能性中的一种。
Please remember that `Xray`'s routing configuration is extremely flexible. The explanation above is just one of infinite possibilities.
借助 `geosite.dat` 和 `geoip.dat` 这两个文件,可以很灵活的从【域名】和【IP】这两个角度、不留死角的控制流量流出的方向。这比曾经单一笼统的 `GFWList` 强大很多很多,可以做到非常细致的微调:比如可以指定 Apple 域名直连或转发、指定亚马逊域名代理或转发,百度的域名屏蔽等等。。。)
With the help of the `geosite.dat` and `geoip.dat` files, you can flexibly control the direction of traffic outflow from the perspectives of [Domain Name] and [IP], leaving no blind spots. This is much, much more powerful than the old, singular, and generalized `GFWList`, allowing for very fine-grained tuning: for example, you can specify Apple domains to connect directly or be forwarded, Amazon domains to be proxied or forwarded, Baidu domains to be blocked, etc...
现在,[《路由 (routing) 功能简析》](../level-1/routing-lv1-part1.md) 已经上线,我建议对路由功能有兴趣的同学,先继续跟着本文完成客户端的基础配置,之后再去这里详细学习。
Now, [《Analysis of the Routing Feature》](../level-1/routing-lv1-part1.md) is online. I suggest that students interested in routing functions continue to follow this article to complete the basic client configuration first, and then go there for detailed learning.
:::
## 8.2 客户端与服务器端正确连接
## 8.2 Connecting Client and Server Correctly
现在你已经理解了 `Xray` 的工作原理,那么接下来的配置,其实就是【告诉你的客户端如何连接 VPS 服务器】。这和你已经很熟悉的、告诉`PuTTY`如何远程连接服务器是一样的。只不过 Xray 连接时的要素不止是【IP 地址】+【端口】+【用户名】+【密码】这四要素了。
Now that you understand how `Xray` works, the next configuration step is simply **[telling your client how to connect to the VPS server]**. This is exactly the same as what you are already familiar with: telling `PuTTY` how to remotely connect to a server. The only difference is that the connection elements for Xray are more than just the four elements of [IP Address] + [Port] + [Username] + [Password].
实际上,`Xray`的连接要素是由不同的[协议](../../config/inbounds/)决定的。本文在第 7 章的配置文件 `config.json` 里,我们使用 `Xray` 下独特而强大的 `VLESS` 协议 + `XTLS` 流控。所以看看那个配置文件的内容就能知道,这个协议组合的连接要素有:
In fact, `Xray`'s connection elements are determined by different [protocols](../../config/inbounds/). In the `config.json` configuration file in Chapter 7, we used the unique and powerful `VLESS` protocol + `XTLS` flow control found in `Xray`. So, looking at the content of that configuration file, we know the connection elements for this protocol combination are:
- 服务器【地址】: `a-name.yourdomain.com`
- 服务器【端口】: `443`
- 连接的【协议】: `vless`
- 连接的【流控】: `xtls-rprx-vision` (vision 模式适合全平台)
- 连接的【验证】: `uuiduuid-uuid-uuid-uuiduuiduuid`
- 连接的【安全】: `"allowInsecure": false`
- Server [Address]: `a-name.yourdomain.com`
- Server [Port]: `443`
- Connection [Protocol]: `vless`
- Connection [Flow]: `xtls-rprx-vision` (vision mode is suitable for all platforms)
- Connection [Authentication]: `uuiduuid-uuid-uuid-uuiduuiduuid`
- Connection [Security]: `"allowInsecure": false`
鉴于新人一般都会使用手机 APP 或者电脑的 GUI 客户端,我就把常用的客户端罗列在下面。每个客户端都有自己独特的配置界面,逐一截图展示并不现实,所以请你务必仔细阅读这些客户端的说明、然后把上述要素填入合适的地方即可。
Given that newcomers generally use mobile apps or GUI clients on computers, I have listed common clients below. Each client has its own unique configuration interface, and it is not realistic to take screenshots of each one. Therefore, please be sure to read the instructions for these clients carefully, and then fill in the above elements in the appropriate places.
:::warning 注意
许多工具其实是同时支持 `xray-core` 和 `v2fly-core` 的,但默认内置的不一定是哪个,所以别忘记检查一下是否是你想要的那个在工作哦!
:::warning Note
Many tools actually support both `xray-core` and `v2fly-core` simultaneously, but the default built-in core may vary. Don't forget to check if the one you want is the one working!
:::
- **v2rayN - 适用于 Windows 平台**
- 请从它的[GitHub 仓库 Release 页面](https://github.com/2dust/v2rayN/releases)获取最新版
- 请根据该客户端的说明进行设置
- **v2rayN - Suitable for Windows Platform**
- Please get the latest version from its [GitHub Repository Release Page](https://github.com/2dust/v2rayN/releases)
- Please configure according to the client's instructions
- **v2rayNG - 适用于 Android 平台**
- 请从它的[GitHub 仓库 Release 页面](https://github.com/2dust/v2rayNG/releases)获取最新版
- 请根据该客户端的说明进行设置
- **v2rayNG - Suitable for Android Platform**
- Please get the latest version from its [GitHub Repository Release Page](https://github.com/2dust/v2rayNG/releases)
- Please configure according to the client's instructions
- **Shadowrocket - 适用于 iOS, 基于苹果 M 芯片的 macOS**
- 你需要注册一个【非中国区】的 iCloud 账户
- 你需要通过 App Store 搜索并购买
- 请根据该客户端的说明进行设置
- **Shadowrocket - Suitable for iOS, and macOS with Apple M chips**
- You need to register a [Non-Mainland China] iCloud account
- You need to search for and purchase it in the App Store
- Please configure according to the client's instructions
- **Qv2ray - 跨平台图形界面,适用于 Linux, Windows, macOS**
- 请从它的[GitHub 仓库 Release 页面](https://github.com/Qv2ray/Qv2ray/releases)获取最新版(还可以从它的[GitHub 自动构建仓库](https://github.com/Qv2ray/Qv2ray/actions)寻找更新的版本)
- 请从它的[项目主页](https://qv2ray.net/)学习文档
- 请根据该客户端的说明进行设置
- **Qv2ray - Cross-platform GUI, suitable for Linux, Windows, macOS**
- Please get the latest version from its [GitHub Repository Release Page](https://github.com/Qv2ray/Qv2ray/releases) (You can also find newer versions from its [GitHub Actions builds](https://github.com/Qv2ray/Qv2ray/actions))
- Please study the documentation from its [Project Homepage](https://qv2ray.net/)
- Please configure according to the client's instructions
- **V2RayXS - 基于 V2RayX 开发的一款使用 xray-core 的 macOS 客户端**
- 请从它的 [GitHub 仓库 Release 页面](https://github.com/tzmax/v2rayXS/releases) 获取最新版
- 支持一键导入 [VMessAEAD / VLESS 分享链接标准提案](https://github.com/XTLS/Xray-core/issues/91) 为标准的分享链接
- 请根据该客户端的说明进行设置
- **V2RayXS - A macOS client using xray-core, based on V2RayX**
- Please get the latest version from its [GitHub Repository Release Page](https://github.com/tzmax/v2rayXS/releases)
- Supports one-click import of [VMessAEAD / VLESS Share Link Standard Proposal](https://github.com/XTLS/Xray-core/issues/91) as standard share links
- Please configure according to the client's instructions
到这一步,你的全套配置就已经可以正常使用啦!
At this step, your full set of configurations is ready for normal use!
## 8.3 附加题 1:在 PC 端手工配置 `xray-core`
## 8.3 Bonus Task 1: Manually Configuring `xray-core` on PC
虽然到上面一步已经可以结束了,但是如果你是个好奇心强、记忆力好的的同学,一定会想起来我在上一章说过,你把`xray-core` 的二进制文件“放在服务器运行,它就是服务器端;你把它下载到本地电脑运行,它就是客户端。” 那究竟要怎样直接使用 `xray-core` 做客户端呢?
Although you could stop at the previous step, if you are a student with strong curiosity and a good memory, you will definitely recall that I said in the previous chapter: "Put the `xray-core` binary on the server and run it, and it is the server-side; download it to your local computer and run it, and it is the client." So, how exactly do you use `xray-core` directly as a client?
为了回答这个问题,我加入了附加题章节,有一点点超纲,有一点点麻烦,但费这个笔墨是因为这个方式有它的优势:
To answer this question, I added this bonus chapter. It's a bit beyond the syllabus and a bit troublesome, but I spent the ink on this because this method has its advantages:
- 第一时间获得最新版而无需等待 APP 升级适配
- Get the latest version immediately without waiting for APP updates and adaptations.
- Flexible and free routing configuration capabilities (Of course, the advanced routing editor in the GUI client Qv2ray is also very powerful and can fully implement xray-core's routing configuration functions).
- Save system resources (GUI interfaces will inevitably consume resources; the amount depends on the client's implementation).
- 灵活自由的路由配置能力(当然 GUI 客户端中 Qv2ray 的高级路由编辑器非常强大,也可以完整实现 xray-core 的路由配置功能)
Its disadvantage is probably that [hand-writing configuration files] is a bit troublesome. But actually, think about it, you have already successfully written it once on the server, so what is the difference now? Next, as usual, let's break down the steps:
- 节约系统资源 (GUI 界面一定会有资源消耗,消耗的多少则取决于客户端的实现)
它的劣势应该就是【需要手写配置文件】有点麻烦了。但其实,你想想,服务器上你已经成功的写过一次了,现在又有什么区别呢?接下来,还是老样子,我们分解一下步骤:
1. 首先请从 Xray 官方的 [GitHub 仓库 Release 页面](https://github.com/XTLS/Xray-core/releases) 获取对应平台的版本,并解压缩到合适的文件夹
2. 在合适的文件夹建立空白配置文件:`config.json` (自己常用平台下新建文件大家肯定都会,这就真不用啰嗦了)
3. 至于什么是“合适的文件夹”?这就取决于具体的平台了~
4. 填写客户端配置
- 我就以 `8.1` 原理说明里展示的基本三类分流(国内流量直连、国际流量转发 VPS、广告流量屏蔽),结合 `8.2` 的连接要素,写成一个配置文件
- 请将 `uuid` 替换成与你服务器一致的 `uuid`
- 请将 `address` 替换成你的真实域名
- 请将 `serverName` 替换成你的真实域名
- 各个配置模块的说明我都已经(很啰嗦的)放在对应的配置点上了
1. First, please get the version for your platform from the official Xray [GitHub Repository Release Page](https://github.com/XTLS/Xray-core/releases) and unzip it to a suitable folder.
2. Create a blank configuration file in that folder: `config.json`. (I surely don't need to nag about how to create a new file on your OS).
3. As for what constitutes a "suitable folder"? That depends on the specific platform~
4. Fill in the client configuration.
- I will use the three basic categories of traffic splitting demonstrated in the `8.1` principle explanation (Domestic traffic direct, International traffic forwarded to VPS, Ad traffic blocked), combined with the connection elements from `8.2`, to write a configuration file.
- Please replace `uuid` with the `uuid` consistent with your server.
- Please replace `address` with your real domain name.
- Please replace `serverName` with your real domain name.
- Explanations for each configuration module have been (very verbosely) placed on the corresponding configuration points.
```json
// REFERENCE:
// https://github.com/XTLS/Xray-examples
// https://xtls.github.io/config/
// 常用的config文件,不论服务器端还是客户端,都有5个部分。外加小小白解读:
// ┌─ 1_log 日志设置 - 日志写什么,写哪里(出错时有据可查)
// ├─ 2_dns DNS-设置 - DNS怎么查(防DNS污染、防偷窥、避免国内外站匹配到国外服务器等)
// ├─ 3_routing 分流设置 - 流量怎么分类处理(是否过滤广告、是否国内外分流)
// ├─ 4_inbounds 入站设置 - 什么流量可以流入Xray
// └─ 5_outbounds 出站设置 - 流出Xray的流量往哪里去
// A common config file, whether for server or client, has 5 parts. plus Newbie interpretation:
// ┌─ 1_log Log Settings - What to write, where to write (evidence for troubleshooting)
// ├─ 2_dns DNS Settings - How to query DNS (prevent DNS pollution, prevent snooping, avoid matching domestic/foreign sites to foreign servers, etc.)
// ├─ 3_routing Routing Settings - How to classify and process traffic (filter ads? split domestic/foreign traffic?)
// ├─ 4_inbounds Inbound Settings - What traffic can flow into Xray
// └─ 5_outbounds Outbound Settings - Where the traffic flowing out of Xray goes
{
// 1_日志设置
// 注意,本例中我默认注释掉了日志文件,因为windows, macOS, Linux 需要写不同的路径,请自行配置
// 1_Log Settings
// Note: In this example, I commented out the log file by default because windows, macOS, and Linux require different paths. Please configure it yourself.
"log": {
// "access": "/home/local/xray_log/access.log", // 访问记录
// "error": "/home/local/xray_log/error.log", // 错误记录
"loglevel": "warning" // 内容从少到多: "none", "error", "warning", "info", "debug"
// "access": "/home/local/xray_log/access.log", // Access record
// "error": "/home/local/xray_log/error.log", // Error record
"loglevel": "warning" // Content from least to most: "none", "error", "warning", "info", "debug"
},
// 2_DNS设置
// 2_DNS Settings
"dns": {
"servers": [
// 2.1 国外域名使用国外DNS查询
// 2.1 Foreign domains use foreign DNS queries
{
"address": "1.1.1.1",
"domains": ["geosite:geolocation-!cn"]
},
// 2.2 国内域名使用国内DNS查询,并期待返回国内的IP,若不是国内IP则舍弃,用下一个查询
// 2.2 Domestic domains use domestic DNS queries, expecting a domestic IP return. If not a domestic IP, discard and use the next query.
{
"address": "223.5.5.5",
"domains": ["geosite:cn"],
"expectIPs": ["geoip:cn"]
},
// 2.3 作为2.2的备份,对国内网站进行二次查询
// 2.3 As a backup for 2.2, perform a secondary query for domestic websites
{
"address": "114.114.114.114",
"domains": ["geosite:cn"]
},
// 2.4 最后的备份,上面全部失败时,用本机DNS查询
// 2.4 Final backup: if all above fail, use local machine DNS
"localhost"
]
},
// 3_分流设置
// 所谓分流,就是将符合否个条件的流量,用指定`tag`的出站协议去处理(对应配置的5.x内容)
// 3_Routing Settings
// Traffic splitting means traffic meeting certain conditions is processed by the outbound protocol with a specific `tag` (corresponding to content in 5.x)
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
// 3.1 广告域名屏蔽
// 3.1 Ad domain blocking
{
"domain": ["geosite:category-ads-all"],
"outboundTag": "block"
},
// 3.2 国内域名直连
// 3.2 Domestic domains direct connection
{
"domain": ["geosite:cn"],
"outboundTag": "direct"
},
// 3.3 国外域名代理
// 3.3 Foreign domains proxy
{
"domain": ["geosite:geolocation-!cn"],
"outboundTag": "proxy"
},
// 3.4 走国内"223.5.5.5"的DNS查询流量分流走direct出站
// 3.4 Traffic for domestic DNS query "223.5.5.5" is split to go through direct outbound
{
"ip": ["223.5.5.5"],
"outboundTag": "direct"
},
// 3.5 国内IP直连
// 3.5 Domestic IPs direct connection
{
"ip": ["geoip:cn", "geoip:private"],
"outboundTag": "direct"
}
// 3.6 默认规则
// 在Xray中,任何不符合上述路由规则的流量,都会默认使用【第一个outbound(5.1)】的设置,所以一定要把转发VPS的outbound放第一个
// 3.6 Default Rule
// In Xray, any traffic that does not match the above routing rules will default to using the setting of the [First Outbound (5.1)]. So be sure to put the VPS forwarding outbound first.
]
},
// 4_入站设置
// 4_Inbound Settings
"inbounds": [
// 4.1 一般都默认使用socks5协议作本地转发
// 4.1 Generally, socks5 protocol is used by default for local forwarding
{
"tag": "socks-in",
"protocol": "socks",
"listen": "127.0.0.1", // 这个是通过socks5协议做本地转发的地址
"port": 10800, // 这个是通过socks5协议做本地转发的端口
"listen": "127.0.0.1", // This is the address for local forwarding via socks5
"port": 10800, // This is the port for local forwarding via socks5
"settings": {
"udp": true
}
},
// 4.2 有少数APP不兼容socks协议,需要用http协议做转发,则可以用下面的端口
// 4.2 A few APPs are incompatible with socks protocol and need http protocol for forwarding, use the port below
{
"tag": "http-in",
"protocol": "http",
"listen": "127.0.0.1", // 这个是通过http协议做本地转发的地址
"port": 10801 // 这个是通过http协议做本地转发的端口
"listen": "127.0.0.1", // This is the address for local forwarding via http
"port": 10801 // This is the port for local forwarding via http
}
],
// 5_出站设置
// 5_Outbound Settings
"outbounds": [
// 5.1 默认转发VPS
// 一定放在第一个,在routing 3.6 里面已经说明了,这等于是默认规则,所有不符合任何规则的流量都走这个
// 5.1 Default forwarding to VPS
// Must be placed first. As explained in routing 3.6, this acts as the default rule; all unmatched traffic goes here.
{
"tag": "proxy",
"protocol": "vless",
"settings": {
"vnext": [
{
"address": "a-name.yourdomain.com", // 替换成你的真实域名
"address": "a-name.yourdomain.com", // Replace with your real domain
"port": 443,
"users": [
{
"id": "uuiduuid-uuid-uuid-uuid-uuiduuiduuid", // 和服务器端的一致
"id": "uuiduuid-uuid-uuid-uuid-uuiduuiduuid", // Consistent with server-side
"flow": "xtls-rprx-vision",
"encryption": "none",
"level": 0
@@ -227,18 +225,18 @@
"network": "tcp",
"security": "tls",
"tlsSettings": {
"serverName": "a-name.yourdomain.com", // 替换成你的真实域名
"allowInsecure": false, // 禁止不安全证书
"fingerprint": "chrome" // 通过 uTLS 库 模拟 Chrome / Firefox / Safari 或随机生成的指纹
"serverName": "a-name.yourdomain.com", // Replace with your real domain
"allowInsecure": false, // Disallow insecure certificates
"fingerprint": "chrome" // Use uTLS library to simulate Chrome / Firefox / Safari or randomized fingerprint
}
}
},
// 5.2 用`freedom`协议直连出站,即当routing中指定'direct'流出时,调用这个协议做处理
// 5.2 Direct outbound using `freedom` protocol. Called when routing specifies 'direct'.
{
"tag": "direct",
"protocol": "freedom"
},
// 5.3 用`blackhole`协议屏蔽流量,即当routing中指定'block'时,调用这个协议做处理
// 5.3 Block traffic using `blackhole` protocol. Called when routing specifies 'block'.
{
"tag": "block",
"protocol": "blackhole"
@@ -247,76 +245,76 @@
}
```
## 8.4 附加题 2:在 PC 端手工运行 `xray-core`
## 8.4 Bonus Task 2: Manually Running `xray-core` on PC
写好了配置文件该,要怎么让 `xray-core` 运行起来呢?双击好像并没有反应啊?
After writing the configuration file, how do you make `xray-core` run? Double-clicking seems to have no reaction?
首先,你要找到电脑上的【命令行界面】。
First, you need to find the [Command Line Interface] on your computer.
1. Linux 桌面、macOS 系统的同学肯定已经比较熟悉了,搜索 `Console` 或者 `Terminal` 就可以
2. Windows 就可以搜索使用 `Cmd` 或者 `Powershell` 等程序(WSL 的同学你坐下,你的 `Console` 当然也可以)
1. Linux desktop and macOS users are certainly familiar with this; just search for `Console` or `Terminal`.
2. Windows users can search for and use `Cmd` or `Powershell` programs (WSL users, sit down, your `Console` works too, of course).
其次,我们要做的事情是【让 `xray` 找到并读取配置文件 `config.json`,然后运行】,所以:
Secondly, what we need to do is [make `xray` find and read the configuration file `config.json`, and then run]. So:
1. 在 Windows 下,假设你的 `Xray` 程序位置是 `C:\Xray-windows-64\xray.exe`,配置文件位置是`C:\Xray-windows-64\config.json`,那么正确的启动命令就是:
1. On Windows, assuming your `Xray` program location is `C:\Xray-windows-64\xray.exe` and the configuration file location is `C:\Xray-windows-64\config.json`, the correct startup command is:
```shell
C:\Xray-windows-64\xray.exe -c C:\Xray-windows-64\config.json
```
```shell
C:\Xray-windows-64\xray.exe -c C:\Xray-windows-64\config.json
```
:::tip 说明
这里的 `-c` 就是指定配置文件路径的参数,告诉 `xray` 去后面的位置找配置文件
:::
:::tip Explanation
The `-c` here is the parameter to specify the configuration file path, telling `xray` to look for the configuration file at the location following it.
:::
2. 相似的,在 Linux 和 macOS 下,假设你的 `Xray` 程序位置是 `/usr/local/bin/xray`,配置文件位置是`/usr/local/etc/xray/config.json`,那么正确的启动命令就是
2. Similarly, on Linux and macOS, assuming your `Xray` program location is `/usr/local/bin/xray` and the configuration file location is `/usr/local/etc/xray/config.json`, the correct startup command is:
```shell
/usr/local/bin/xray -c /usr/local/etc/xray/config.json
```
```shell
/usr/local/bin/xray -c /usr/local/etc/xray/config.json
```
:::tip 说明
每个系统都有系统路径变量,所以写 `Xray` 程序时不一定要写绝对路径。但是写了肯定没错,所以我就如此演示了。
:::
:::tip Explanation
Every system has system path variables, so you don't necessarily have to write the absolute path when typing the `Xray` program. But writing it is definitely not wrong, so I demonstrated it that way.
:::
## 8.5 附加题 3:在 PC 端开机自动运行 `xray-core`
## 8.5 Bonus Task 3: Auto-start `xray-core` on PC Boot
如果你真的尝试了手动运行 `xray-core`,你一定会发现这个方式还有点小问题:
If you really tried running `xray-core` manually, you must have found a small problem with this method:
1. 每次运行 `Xray` 都要出现一个黑乎乎的窗口,很丑
2. 不能开机自动运行,每次都要手工输入,十分不方便
1. Every time `Xray` runs, a dark window appears, which is ugly.
2. It cannot run automatically at startup; manually typing it every time is very inconvenient.
我可以肯定的告诉你:**完全可以解决**。但是具体的解决方式,就当作课外作业留给大家吧!(友情提示,文档站的问答区有线索哦)
I can tell you with certainty: **It is completely solvable**. But as for the specific solution, let's leave it as homework for everyone! (Friendly hint: there are clues in the Q&A section of the documentation site).
## 8.6 圆满完成!
## 8.6 Mission Accomplished
我相信,有耐心看到这里的同学,都是兼具好奇心和行动力的学习派!我现在要郑重的恭喜你,因为到了这里,你已经完完整整的【**从第一条命令开始,完成了 VPS 服务器部署,并成功的在客户端配置使用 Xray**】了!这毫无疑问是一个巨大的胜利!
I believe that students who have the patience to read this far are learners with both curiosity and the ability to take action! I want to solemnly congratulate you now, because by this point, you have completely **[started from the first command, completed the VPS server deployment, and successfully configured and used Xray on the client]**! This is undoubtedly a huge victory!
我相信,你现在一定对`Linux`不再恐惧,对`Xray`不再陌生了吧!
I believe you are no longer afraid of `Linux` and no longer unfamiliar with `Xray`!
**至此,小小白白话文圆满结束!**
**Here, the Absolute Beginner's Plain Guide concludes successfully!**
> ⬛⬛⬛⬛⬛⬛⬛⬛ 100%
## 8.7 TO INFINITY AND BEYOND!
## 8.7 TO INFINITY AND BEYOND
**但现在你看到的,远远不是 Xray 的全貌。**
**But what you see now is far from the full picture of Xray.**
`Xray`是一个强大而丰富的网络工具集合,平台化的提供了众多模块,可以像瑞士军刀一样,通过灵活的配置组合解决各种不同的问题。而本文,仅仅蜻蜓点水的用了**最简单**、**最直观**的配置来做**基础演示**。
`Xray` is a powerful and rich collection of network tools. It provides numerous modules as a platform, which can solve various problems through flexible configuration combinations like a Swiss Army knife. This article only skimmed the surface using the **simplest** and **most intuitive** configuration for a **basic demonstration**.
如果你觉得现在已经完全够用了,那就好好的享受它给你带来的信息自由。但如果你的好奇心依然不能停歇,那就去继续挖掘它无限的可能性吧!
If you feel that it is completely sufficient now, then enjoy the information freedom it brings you. But if your curiosity still cannot rest, then go ahead and continue to dig into its infinite possibilities!
需要更多信息,可以到这里寻找:
For more information, you can find it here:
1. [xtls.github.io](https://xtls.github.io/) - 官方文档站
2. [官方 Telegram 群组](https://t.me/projectXray) - 活跃而友善的官方讨论社区
1. [xtls.github.io](https://xtls.github.io/) - Official Documentation Site
2. [Official Telegram Group](https://t.me/projectXray) - Active and friendly official discussion community
![TO INFINITY AND BEYOND!](./ch08-img02-buzz.png)
:::tip 不算后记的后记
:::tip A Postscript that isn't really a Postscript
希望我陪你走过的这一段小小的旅程,可以成为你网络生活中的一份小小助力。
I hope this small journey I accompanied you on can become a small boost in your online life.
这篇文章里的工具和信息难免会一点点的陈旧过时,但你一定会逐渐成长为大佬。未来的某个时间,若你能偶尔想起这篇教程、想起我写下本文的初衷,那我衷心希望你能够薪火相传、把最新的知识分享给后来人,让这一份小小的助力在社区里坚定的传递下去。
The tools and information in this article will inevitably become slightly outdated, but you will surely grow into an expert. Sometime in the future, if you occasionally recall this tutorial and the original intention with which I wrote it, I sincerely hope you can pass on the torch, share the latest knowledge with newcomers, and let this small boost continue to be passed down firmly in the community.
这是个大雪封山乌云密布的世界,人们孤独的走在各自的路上试图寻找阳光,如果大家偶尔交汇时不能守望相助互相鼓励,那最终剩下的,恐怕只有【千山鸟飞绝 万径人踪灭】的凄凉了吧。
This is a world where heavy snow seals the mountains and dark clouds loom. People walk lonely on their respective paths trying to find sunlight. If we cannot watch out for and encourage each other when we occasionally cross paths, then ultimately, I fear only the desolation of "a thousand mountains with no birds flying, ten thousand paths with no human footprints" will remain.
:::
+40 -40
View File
@@ -1,46 +1,46 @@
# 【第 9 章】附录
# [Chapter 9] Appendix
## 1. 小小白白 Linux 基础命令索引
## 1. Index of Basic Linux Commands for Beginners
| 编号 | 命令名称 | 命令说明 | 出现篇章 |
| :------: | :------------------ | :--------------------------- | :----------------------------------------: |
| `cmd-01` | `apt update` | 查询软件更新 | [《远程登录篇》](./ch03-ssh.md) |
| `cmd-02` | `apt upgrade` | 执行软件更新 | [《远程登录篇》](./ch03-ssh.md) |
| `cmd-03` | `nano` | 文本编辑器 | [《安全防护篇》](./ch04-security.md) |
| `cmd-04` | `systemctl restart` | 重启某个服务 | [《安全防护篇》](./ch04-security.md) |
| `cmd-05` | `adduser` | 给系统新增用户 | [《安全防护篇》](./ch04-security.md) |
| `cmd-06` | `apt install` | 安装某个软件 | [《安全防护篇》](./ch04-security.md) |
| `cmd-07` | `visudo` | 修改 sudo 权限设置专用编辑器 | [《安全防护篇》](./ch04-security.md) |
| `cmd-08` | `sudo` | 用`root`权限运行某个命令 | [《安全防护篇》](./ch04-security.md) |
| `cmd-09` | `chmod` | 修改目标文件/文件夹的权限 | [《安全防护篇》](./ch04-security.md) |
| `cmd-10` | `mkdir` | 新建文件夹 | [《网站建设篇》](./ch05-webpage.md) |
| `cmd-11` | `systemctl reload` | 重新加载某个服务 | [《网站建设篇》](./ch05-webpage.md) |
| `cmd-12` | `wget` | 访问(或下载)某个网页文件 | [《证书管理篇》](./ch06-certificates.md) |
| `cmd-13` | `acme.sh` | acme.sh 证书管理相关的命令 | [《证书管理篇》](./ch06-certificates.md) |
| `cmd-14` | `rm` | 删除命令 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `cmd-15` | `crontab -e` | 编辑当前用户的定时任务 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `cmd-16` | `touch` | 建立空白文件 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `cmd-17` | `systemctl` | `systemd`基本服务管理命令 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `cmd-18` | `reboot` | 重启 Linux 系统 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| ID | Command Name | Description | Featured Chapter |
| :----: | :------------------ | :--------------------------- | :------------------------------------------: |
| `cmd-01` | `apt update` | Check for software updates | [[Chapter 3: Remote Login]](./ch03-ssh.md) |
| `cmd-02` | `apt upgrade` | Execute software updates | [[Chapter 3: Remote Login]](./ch03-ssh.md) |
| `cmd-03` | `nano` | Text editor | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-04` | `systemctl restart` | Restart a service | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-05` | `adduser` | Add a new user to the system | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-06` | `apt install` | Install a software package | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-07` | `visudo` | Dedicated editor for sudo privileges | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-08` | `sudo` | Run a command with `root` privileges | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-09` | `chmod` | Change permissions of a file/folder | [[Chapter 4: Security Protection]](./ch04-security.md) |
| `cmd-10` | `mkdir` | Create a new directory (folder) | [[Chapter 5: Website Building]](./ch05-webpage.md) |
| `cmd-11` | `systemctl reload` | Reload a service | [[Chapter 5: Website Building]](./ch05-webpage.md) |
| `cmd-12` | `wget` | Access (or download) a web file | [[Chapter 6: Certificate Management]](./ch06-certificates.md) |
| `cmd-13` | `acme.sh` | Commands related to acme.sh certificate management | [[Chapter 6: Certificate Management]](./ch06-certificates.md) |
| `cmd-14` | `rm` | Remove (delete) command | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `cmd-15` | `crontab -e` | Edit current user's scheduled tasks | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `cmd-16` | `touch` | Create an empty file | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `cmd-17` | `systemctl` | Basic `systemd` service management command | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `cmd-18` | `reboot` | Reboot the Linux system | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
## 2. 小小白白 Linux 重要配置文件索引
## 2. Index of Important Linux Configuration Files for Beginners
| 编号 | 配置文件位置 | 文件说明 | 出现篇章 |
| :-------: | :-------------------------------------- | :----------------------------- | :----------------------------------------: |
| `conf-01` | `/etc/ssh/sshd_config` | SSH 远程登录程序设置 | [《远程登录篇》](./ch03-ssh.md) |
| `conf-02` | `/etc/nginx/nginx.conf` | Nginx 程序设置 | [《网站建设篇》](./ch05-webpage.md) |
| `conf-03` | `/etc/apt/sources.list` | apt 软件源列表 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `conf-04` | `/etc/apt/sources.list.d/vpsadmin.list` | 用户自定义软件源列表列表 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `conf-05` | `crontab -e` | 当前用户的定时任务 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `conf-06` | `/etc/sysctl.conf` | 手动设置 kernel 参数 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `conf-07` | `/etc/sysctl.d/vpsadmin.conf` | 用户自定义 kernel 参数配置文件 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| ID | Config File Location | File Description | Featured Chapter |
| :-------: | :-------------------------------------- | :----------------------------- | :------------------------------------------: |
| `conf-01` | `/etc/ssh/sshd_config` | SSH remote login program settings | [[Chapter 3: Remote Login]](./ch03-ssh.md) |
| `conf-02` | `/etc/nginx/nginx.conf` | Nginx program settings | [[Chapter 5: Website Building]](./ch05-webpage.md) |
| `conf-03` | `/etc/apt/sources.list` | apt software source list | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `conf-04` | `/etc/apt/sources.list.d/vpsadmin.list` | User-defined software source list | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `conf-05` | `crontab -e` | Current user's scheduled tasks | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `conf-06` | `/etc/sysctl.conf` | Manual kernel parameter settings | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `conf-07` | `/etc/sysctl.d/vpsadmin.conf` | User-defined kernel parameter config file | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
## 3. 小小白白 Xray 重要文件索引
## 3. Index of Important Xray Files for Beginners
| 编号 | 配置文件位置 | 文件说明 | 出现篇章 |
| :-------: | :----------------------------------- | :------------ | :----------------------------------------: |
| `xray-01` | `/usr/local/etc/xray/config.json` | Xray 程序设置 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `xray-02` | `/home/vpsadmin/xray_cert/xray.cert` | TLS 证书 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `xray-03` | `/home/vpsadmin/xray_cert/xray.key` | TLS 私钥 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `xray-04` | `/home/vpsadmin/xray_log/access.log` | Xray 访问日志 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| `xray-05` | `/home/vpsadmin/xray_log/error.log` | Xray 错误日志 | [《Xray 服务器篇》](./ch07-xray-server.md) |
| ID | Config File Location | File Description | Featured Chapter |
| :-------: | :----------------------------------- | :--------------- | :------------------------------------------: |
| `xray-01` | `/usr/local/etc/xray/config.json` | Xray program settings | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `xray-02` | `/home/vpsadmin/xray_cert/xray.cert` | TLS Certificate | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `xray-03` | `/home/vpsadmin/xray_cert/xray.key` | TLS Private Key | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `xray-04` | `/home/vpsadmin/xray_log/access.log` | Xray Access Log | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
| `xray-05` | `/home/vpsadmin/xray_log/error.log` | Xray Error Log | [[Chapter 7: Xray Server]](./ch07-xray-server.md) |
+11 -11
View File
@@ -1,25 +1,25 @@
# Plain and Simple Language
# Absolute Beginner's Plain Guide
**This chapter is a basic lesson of [Starting from Scratch]. New students, please watch and learn carefully.**
**This section is a [From Scratch] foundation course. Newcomers, please read and study carefully!**
::: tip
Made with ❤️ by [@ricuhkaen](https://github.com/ricuhkaen)
:::
[【Chapter 1】 Preface: Rambling](./ch01-preface.md) - Airport or Self-built? That is the question.
[[Chapter 1] Preface](./ch01-preface.md) - Commercial Provider or Self-Hosted? That Is the Question
[Chapter 2: Preparation of Raw Materials](./ch02-preparation.md) - Tools must be sharpened before they can be used proficiently.
[[Chapter 2] Preparation](./ch02-preparation.md) - To Do a Good Job, One Must First Sharpen One's Tools
[Chapter 3: Remote Login](./ch03-ssh.md) - A bridge connecting the north and south, turning a natural obstacle into a thoroughfare.
[[Chapter 3] Remote Login (SSH)](./ch03-ssh.md) - Bridging the Gap
[【Chapter 4】Security Protection](./ch04-security.md) - If you don't pay attention to security, you will shed tears for your loved ones.
[[Chapter 4] Security](./ch04-security.md) - Safety First, or Regret Later
[【Chapter 5】Website Construction] - Show Your Beauty (Link to webpage.md file)
[[Chapter 5] Website Setup](./ch05-webpage.md) - Show Your Style
[Chapter 6: Certificate Management](./ch06-certificates.md) - Only those who obtain certificates are considered legitimate.
[[Chapter 6] Certificates](./ch06-certificates.md) - It's Only Legal with a License
[Chapter 7: Xray Server](./ch07-xray-server.md) - Finally, waited for you.
[[Chapter 7] Xray Server](./ch07-xray-server.md) - The Moment You've Been Waiting For
[Chapter 8: Xray Client](./ch08-xray-clients.md) - A New Beginning.
[[Chapter 8] Xray Clients](./ch08-xray-clients.md) - A New Beginning
[Chapter 9] Appendix - All the exam points are here.
[[Chapter 9] Appendix](./ch09-appendix.md) - Key Takeaways Are Here