Wiregurad: Simplify

We only explain in detail the concepts we've introduced and the things people often confuse, rather than over-explaining every single field. (wireguard official doc already has these for advance user)
This commit is contained in:
Fangliding
2026-09-17 01:09:47 +08:00
parent d5a84ee9bb
commit fecd37ebc3
6 changed files with 77 additions and 221 deletions
+6 -20
View File
@@ -1,6 +1,6 @@
# WireGuard
用户态 WireGuard 协议实现,用于与对端建立 WireGuard 隧道,并接收通过该隧道进入的流量
用户态 WireGuard 协议实现,用于与对端建立 WireGuard 隧道,将收到的 TCP 和 UDP 数据包转换为 Xray 内部的代理请求进行处理和响应
::: danger
**WireGuard 协议并非专门为翻墙而设计,若在最外层过墙,存在特征可能导致服务器被封锁**
@@ -40,21 +40,11 @@
服务器私钥。必填。
可以使用命令 `xray wg` 生成服务器密钥对将输出的 `PrivateKey` 填入此项;与其成对出现的 `Password (PublicKey)` 是服务器公钥。以 Xray 作为 WireGuard 客户端时,应将服务器公钥填入 `outbounds[].settings.peers[].publicKey`
使用命令 `xray wg` 生成服务器密钥对时。此处对应将输出的 `PrivateKey`
> `peers`: \[ [PeersObject](#peersobject) \]
WireGuard 客户端列表,其中每一项是一个客户端配置。配置多个客户端时,Xray 会将解密后内层 IP 包的源地址与各客户端的 `allowedIPs` 进行匹配,以识别流量所属的客户端
::: details Xray WireGuard 入站的网络模型
常规 WireGuard 组网(包括点到点、点到站和站到站)需要通信两端各自通过三层网络接口参与 IP 路由。
与之不同,Xray 的 WireGuard 入站无需在系统中创建 TUN,也无需为服务端配置用于组网的隧道内 IP。WireGuard 解密得到的内层 IP 包由内置网络栈处理,其中的 TCP 和 UDP 流量会转换为代理连接并交给 Xray 路由系统,而不是继续转发原始 IP 包。
客户端既可以发送自身流量,也可以作为网关转发其后方网段的流量。Xray 服务端不作为隧道内供客户端访问的三层网络节点,也不会将原始 IP 包交给系统内核继续转发或 NAT。
`allowedIPs` 同时参与两个方向的数据包处理:接收时,WireGuard 会校验解密后内层 IP 包的源地址,Xray 也会根据该地址识别客户端;回包时,WireGuard 会根据内层目标地址选择对应客户端。
:::
WireGuard 客户端 peers 列表。
> `mtu`: int
@@ -93,7 +83,7 @@ WireGuard 隧道内层 IP 包的 MTU。默认 1420。
客户端公钥,用于验证。必填。
以 Xray 作为 WireGuard 客户端时,此处应填写与客户端 `outbounds[].settings.secretKey` 成对`Password (PublicKey)`
使用 `xray wg` 生成密钥对时。此处对应将输出`Password (PublicKey)`
> `preSharedKey`: string
@@ -105,13 +95,9 @@ WireGuard 隧道内层 IP 包的 MTU。默认 1420。
> `allowedIPs`: \[ string \]
指定允许由该客户端发送的源 IP 地址或网段,每项使用 CIDR 表示。
指定允许由该客户端发送的源 IP 地址或网段,使用 CIDR 表示。默认值为 `["0.0.0.0/0", "::/0"]`,即允许所有 IPv4 和 IPv6 源地址。
客户端出站的 `address` 必须包含在对应服务端 peer 的 `allowedIPs` 中。例如,客户端 `outbounds[].settings.address``["10.0.0.2"]`,则此处可配置为 `["10.0.0.2/32"]`
`allowedIPs` 不只可以填写客户端的隧道内 IP,也可以包含由该 peer 负责转发的网段。例如,第三方 WireGuard 客户端作为 `192.168.10.0/24` 的网关时,可以将该网段填入此处;客户端还需自行配置路由并开启 IP 转发。
仅有一个客户端时可省略,默认值为 `["0.0.0.0/0", "::/0"]`。配置多个客户端时,应显式配置互不冲突的 `allowedIPs`,否则无法可靠地区分客户端。
仅有一个客户端时可省略,默认值为 `["0.0.0.0/0", "::/0"]`。配置多个客户端时,与客户端的 `allowedIPs` 不同,这里的 `allowedIPs`,不应重叠,轻则无法正确匹配客户端 peer,重则可能导致无法正确路由回包
> `email`: string
+20 -54
View File
@@ -1,6 +1,6 @@
# WireGuard
用户态 WireGuard 协议实现,用于与对端建立 WireGuard 隧道,并通过该隧道发送出站流量
用户态 WireGuard 协议实现,用于与对端建立 WireGuard 隧道,将被路由到此出站的 TCP/UDP 请求封装为 IP 包后通过 WireGuard 隧道发送
::: danger
**WireGuard 协议并非专门为翻墙而设计,若在最外层过墙,存在特征可能导致服务器被封锁**
@@ -16,20 +16,15 @@
{
// ...
"protocol": "wireguard",
// [!code focus:25]
// [!code focus:20]
"settings": {
"secretKey": "CLIENT_PRIVATE_KEY",
"address": [
"10.0.0.1",
"fd59:7153:2388:b5fd:0000:0000:0000:0001",
"and more..."
],
"address": ["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"],
"peers": [
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"allowedIPs": ["0.0.0.0/0", "::/0"]
// ...
}
],
"noKernelTun": false,
@@ -49,30 +44,28 @@
> `secretKey`: string
客户端私钥。必填。
客户端私钥。必填。
可以使用命令 `xray wg` 生成客户端密钥对将输出的 `PrivateKey` 填入此项;与其成对出现的 `Password (PublicKey)` 是客户端公钥。以 Xray 作为 WireGuard 服务器时,应将客户端公钥填入 `inbounds[].settings.peers[].publicKey`
使用命令 `xray wg` 生成客户端密钥对时。此处对应将输出的 `PrivateKey`
> `address`: \[ string \]
指定 WireGuard 出站生成的内层 IP 包所使用的本地源地址,即客户端的隧道内 IP。可以配置一个或多个 IPv4 或 IPv6 地址
Wireguard 接口的本地 IP 地址列表。存在多个时根据 peer 自动选择
默认值为 `["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"]`
Xray 会根据目标地址的地址族自动选择相应的 IP 作为源地址;如果同一地址族配置了多个 IP,则会按照内部规则选择合适的地址。<br>
WireGuard 服务器的入站配置必须允许这些 IP,并且这些 IP 在服务器的 WireGuard 入站配置中必须唯一。
> `noKernelTun`: true | false
是否禁用 TUN,默认值为 `false`;在 LXC 或 Docker 环境中可能需要设为 `true`
是否无视自动检测强制不使用系统 TUN,默认值为 `false`;在 LXC 或 Docker 环境中可能需要设为 `true`
::: details 我需要启用 `noKernelTun` 吗?
设为 `false` 时,Xray 会自动选择内层 IP 包的处理方式:在 Linux 上且 Xray 进程具有 `CAP_NET_ADMIN` 权限时,创建 TUN 并由内核网络栈处理;在其他平台或权限不足时,使用进程内的 gVisor 网络栈。设为 `true` 时,仅使用 gVisor 网络栈,不会创建 TUN。使用 TUN 通常性能更高
::: details 关于 kernel TUN
Xray 将 wiregurad 的 IP 包重新还原为 TCP/UDP 载荷的方式
默认情况下 Xray 会自动检测:在 Linux 上且 Xray 进程具有 `CAP_NET_ADMIN` 权限时,创建 TUN 并由内核网络栈处理;在其他平台或权限不足时,使用进程内的 gVisor 网络栈。设为 `true` 时,仅使用 gVisor 网络栈,不会创建 TUN。使用 TUN 通常性能更高。
上述自动判断不一定准确,例如某些 LXC 环境即使具有 `CAP_NET_ADMIN` 权限,也可能无法使用 TUN,导致出站无法工作,此时将 `noKernelTun` 设为 `true` 即可解决问题。
此选项只选择内层 IP 包的处理方式。WireGuard 协议本身仍由 Xray 的用户态实现处理,与内核 WireGuard 模块无关。
上述自动判断不一定准确,例如某些 LXC 环境即使具有 `CAP_NET_ADMIN` 权限,也可能无法使用 TUN,导致出站无法工作;此时应将本项设为 `true`
使用 TUN 时会占用 IPv6 的 10230 号路由表,每一个其他 WireGuard 出站会依次往后使用路由表,比如第二个会使用 10231 号路由表,以此类推。
注意如果在同一个机器上启动第二个 Xray 实例不会接着分配路由表号,会继续尝试使用 10230 号路由表,因为已经被第一个 Xray 实例占用所以会失败无法连接,如果实在需要也需要设置这个选项禁用 TUN。
@@ -104,43 +97,19 @@ WireGuard 协议保留字节,长度为 3,默认全 0,按需填写。
> `peers`: \[ [PeersObject](#peersobject) \]
WireGuard 服务器列表,其中每一项是一个服务器配置。配置多个服务器时,Xray 会根据目标 IP 地址对各服务器的 `allowedIPs` 进行前缀匹配,将流量路由至匹配的服务器,从而使不同目标网段可以通过不同的 WireGuard 服务器转发
::: details Xray WireGuard 出站的数据包模型
进入 WireGuard 出站的 TCP 和 UDP 连接会由网络栈转换为内层 IP 包。内层源地址从 `address` 中选择,内层目标地址则是被代理流量的目标 IP。
Xray 会使用内层目标地址对各 peer 的 `allowedIPs` 进行前缀匹配,由匹配到的 peer 加密封装,并将外层 UDP 数据包发送到该 peer 的 `endpoint`。因此,`address` 表示客户端使用的内层源地址,`allowedIPs` 相当于选择 peer 的目标路由表,而 `endpoint` 才是外层连接的服务器地址。
:::
::: tip
每个 WireGuard 服务器都应根据其 `allowedIPs`,放行 `address` 中相同 IP 族的所有地址:`allowedIPs` 仅包含 IPv4 网段时,应放行 `address` 中列出的所有 IPv4 地址;仅包含 IPv6 网段时同理;同时包含 IPv4 和 IPv6 网段时,应放行其中所有地址。
以 Xray 作为 WireGuard 服务器为例,应在 `inbounds[].settings.peers[].allowedIPs` 中列出这些地址。
:::
连接 WireGuard 远端 peers 列表
> `remoteDNS`: \[ string \]
用于解析被代理目标的域名。列表项必须为 IP。默认值为 `["1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001"]`
DNS 查询经 WireGuard 隧道发送;所有服务器 IP 均须包含在某个 peer 的 `allowedIPs` 中并能通过隧道访问
::: details `remoteDNS``targetStrategy`
不同于其他出站,WireGuard 隧道内的目标地址必须为 IP。当被代理目标为域名时,出站的 [`targetStrategy`](../outbound.md#outboundobject) 决定使用哪套 DNS 进行解析:
- `AsIs`:使用 `remoteDNS`
- `UseIP*`:优先使用 Xray 内置 DNS,解析失败时回退到 `remoteDNS`
- `ForceIP*`:使用 Xray 内置 DNS,解析失败时直接失败。
`UseIP*``ForceIP*` 的解析结果中,至少要有一个 IP 与 `address` 中的地址属于同一地址族,否则无法连接。地址族不匹配不视为解析失败,也不会触发任何回退。
如何取舍?`remoteDNS` 开箱即用,查询经 WireGuard 隧道发出,通常可获得与隧道出口匹配的 CDN 解析结果;若要让 [Xray 内置 DNS](../dns.md) 达到同样效果,通常还需配置相应的 DNS 服务器和路由规则。但若内置 DNS 事先解析过目标域名(例如使用 TUN/TProxy 的 RealIP 方案,或开启嗅探且 `routing.domainStrategy``AsIs`),建议使用 Xray 内置 DNS,以避免二次解析增加 RTT。
:::
不同于其他出站,WireGuard 隧道内的目标地址必须为 IP。当被代理目标为域名时,需要一个 DNS 服务器将域名转化为 IP 地址。这部分 DNS 服务器在这里配置,并且**直接通过这个 WireGuard 隧道发送 DNS 请求**。想将其接入 Xray 内置 DNS 系统请考虑在出站的 [`targetStrategy`](../outbound.md#outboundobject) 提前解析
### PeersObject
```json
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"preSharedKey": "PRE_SHARED_KEY",
"keepAlive": 0,
@@ -150,16 +119,13 @@ DNS 查询经 WireGuard 隧道发送;所有服务器 IP 均须包含在某个
> `endpoint`: address
服务器地址, 必填。
URL: 端口 格式,例如 `engage.cloudflareclient.com:2408`<br>
IP: 端口 格式,例如 `162.159.192.1:2408``[2606:4700:d0::a29f:c001]:2408`
服务器地址和端口,可以是 IP 或域名,必填。
> `publicKey`: string
服务器公钥,用于验证。必填。
peer 的公钥,用于验证。必填。
以 Xray 作为 WireGuard 服务器时,此处应填写与服务器 `inbounds[].settings.secretKey` 成对`Password (PublicKey)`
使用 `xray wg` 生成密钥对时。此处对应将输出`Password (PublicKey)`
> `preSharedKey`: string
@@ -171,4 +137,4 @@ IP: 端口 格式,例如 `162.159.192.1:2408` 或 `[2606:4700:d0::a29f:c001]:2
> `allowedIPs`: \[ string \]
指定由该服务器转发的目标 IP 网段,每项使用 CIDR 表示。仅配置一个服务器时可以省略,因为默认值为 `["0.0.0.0/0", "::/0"]`,即所有 IPv4 和 IPv6 目标流量均由该服务器转发。配置多个服务器时,需为每个服务器显式设置 `allowedIPs`,将不同的目标网段分配给相应服务器;Xray 会根据目标 IP 的前缀匹配结果选择服务器
应该使用该 peer 转发的请求,使用 CIDR 表示。默认值为 `["0.0.0.0/0", "::/0"]`,即所有 IPv4 和 IPv6 目标流量均由该服务器转发。多个命中时按最长前缀匹配原则选择
+6 -20
View File
@@ -1,6 +1,6 @@
# WireGuard
User-space WireGuard protocol implementation for establishing a WireGuard tunnel with a peer and receiving traffic through the tunnel.
User-space WireGuard protocol implementation for establishing a WireGuard tunnel with a peer, converting received TCP and UDP packets into internal Xray proxy requests for processing and response.
::: danger
**The WireGuard protocol is not designed specifically for bypassing firewalls. If used as the outer layer to cross the firewall, its distinct characteristics may lead to the server being blocked.**
@@ -40,21 +40,11 @@ User-space WireGuard protocol implementation for establishing a WireGuard tunnel
Server private key. Required.
You can generate a server key pair with the `xray wg` command. Enter the generated `PrivateKey` here; the accompanying `Password (PublicKey)` is the server public key. When using Xray as a WireGuard client, enter the server public key in `outbounds[].settings.peers[].publicKey`.
When generating a server key pair using the command `xray wg`, this corresponds to the output `PrivateKey`.
> `peers`: \[ [PeersObject](#peersobject) \]
List of WireGuard clients, where each item is a client configuration. When multiple clients are configured, Xray matches the source address of each decrypted inner IP packet against the clients' `allowedIPs` to identify which client the traffic belongs to.
::: details Network model of an Xray WireGuard inbound
A conventional WireGuard network—including point-to-point, point-to-site, and site-to-site configurations—requires both endpoints to participate in IP routing through Layer 3 network interfaces.
In contrast, an Xray WireGuard inbound does not create a TUN interface on the system, nor does the server need an in-tunnel IP address. The built-in network stack processes the decrypted inner IP packets, converts their TCP and UDP traffic into proxy connections, and passes those connections to the Xray routing system instead of forwarding the original IP packets.
A client can send its own traffic or act as a gateway for networks behind it. The Xray server does not act as a Layer 3 node that clients can access inside the tunnel, and it does not pass the original IP packets to the system kernel for further forwarding or NAT.
`allowedIPs` participates in packet processing in both directions: when receiving packets, WireGuard verifies the source address of the decrypted inner IP packet and Xray uses that address to identify the client; when sending response packets, WireGuard selects the corresponding client based on the inner destination address.
:::
List of WireGuard client peers.
> `mtu`: int
@@ -93,7 +83,7 @@ The structure of a WireGuard packet is as follows:
Client public key used for verification. Required.
When using Xray as a WireGuard client, enter the `Password (PublicKey)` paired with the client's `outbounds[].settings.secretKey` here.
When generating a key pair using `xray wg`, this corresponds to the output `Password (PublicKey)`.
> `preSharedKey`: string
@@ -105,13 +95,9 @@ Interval, in seconds, at which the server sends persistent keepalive packets to
> `allowedIPs`: \[ string \]
Specifies the source IP addresses or networks that this client is allowed to send, with each item expressed in CIDR notation.
Specifies the source IP addresses or networks that this client is allowed to send, using CIDR notation. The default value is `["0.0.0.0/0", "::/0"]`, meaning all IPv4 and IPv6 source addresses are allowed.
The client's outbound `address` must be included in the corresponding server peer's `allowedIPs`. For example, if the client's `outbounds[].settings.address` is `["10.0.0.2"]`, this field can be set to `["10.0.0.2/32"]`.
`allowedIPs` can contain not only the client's in-tunnel IP address, but also networks routed through that peer. For example, if a third-party WireGuard client acts as a gateway for `192.168.10.0/24`, that network can be included here; the client must also configure routing and enable IP forwarding itself.
This field can be omitted when only one client is configured; the default is `["0.0.0.0/0", "::/0"]`. When multiple clients are configured, explicitly specify non-overlapping `allowedIPs`; otherwise, Xray cannot reliably distinguish between clients.
Can be omitted when only one client is configured, with a default value of `["0.0.0.0/0", "::/0"]`. When configuring multiple clients, unlike the client-side `allowedIPs`, the `allowedIPs` here should not overlap; at best it prevents properly matching the client peer, and at worst it may prevent properly routing return packets.
> `email`: string
+19 -53
View File
@@ -1,6 +1,6 @@
# WireGuard
User-space WireGuard protocol implementation for establishing a WireGuard tunnel with a peer and sending outbound traffic through the tunnel.
User-space WireGuard protocol implementation for establishing a WireGuard tunnel with a peer, encapsulating TCP/UDP requests routed to this outbound into IP packets and sending them through the WireGuard tunnel.
::: danger
**The WireGuard protocol is not designed specifically for bypassing firewalls. If used as the outer layer to cross the firewall, its distinct characteristics may lead to the server being blocked.**
@@ -16,20 +16,15 @@ User-space WireGuard protocol implementation for establishing a WireGuard tunnel
{
// ...
"protocol": "wireguard",
// [!code focus:25]
// [!code focus:20]
"settings": {
"secretKey": "CLIENT_PRIVATE_KEY",
"address": [
"10.0.0.1",
"fd59:7153:2388:b5fd:0000:0000:0000:0001",
"and more..."
],
"address": ["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"],
"peers": [
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"allowedIPs": ["0.0.0.0/0", "::/0"]
// ...
}
],
"noKernelTun": false,
@@ -51,28 +46,26 @@ User-space WireGuard protocol implementation for establishing a WireGuard tunnel
Client private key. Required.
You can generate a client key pair with the `xray wg` command. Enter the generated `PrivateKey` here; the accompanying `Password (PublicKey)` is the client public key. When using Xray as a WireGuard server, enter the client public key in `inbounds[].settings.peers[].publicKey`.
When generating a client key pair using the command `xray wg`, this corresponds to the output `PrivateKey`.
> `address`: \[ string \]
Specifies the local source addresses used in the inner IP packets generated by the WireGuard outbound—that is, the client's in-tunnel IP addresses. One or more IPv4 or IPv6 addresses can be configured.
List of local IP addresses for the WireGuard interface. When multiple addresses are specified, it is automatically selected based on the peer.
The default is `["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"]`.
Xray automatically selects a source address from the appropriate address family based on the destination address. If multiple addresses from the same family are configured, it selects a suitable address according to its internal rules.<br>
The WireGuard server's inbound configuration must allow these addresses, and each address must be unique in the server's WireGuard inbound configuration.
> `noKernelTun`: true | false
Whether to disable TUN. The default is `false`; you may need to set it to `true` in LXC or Docker environments.
Whether to forcibly disable system TUN regardless of automatic detection. The default is `false`; you may need to set it to `true` in LXC or Docker environments.
::: details Do I need to enable `noKernelTun`?
When set to `false`, Xray automatically selects how to process inner IP packets: on Linux, if the Xray process has the `CAP_NET_ADMIN` capability, it creates a TUN interface and uses the kernel network stack; on other platforms or when permissions are insufficient, it uses the in-process gVisor network stack. When set to `true`, only the gVisor network stack is used and no TUN interface is created. Using TUN generally provides better performance.
::: details About kernel TUN
The way Xray restores WireGuard IP packets back into TCP/UDP payloads.
By default, Xray automatically detects: on Linux, if the Xray process has the `CAP_NET_ADMIN` capability, it creates a TUN interface and uses the kernel network stack; on other platforms or when permissions are insufficient, it uses the in-process gVisor network stack. When set to `true`, only the gVisor network stack is used and no TUN interface is created. Using TUN generally provides better performance.
The automatic detection described above is not always accurate. For example, some LXC environments may be unable to use TUN even when they have the `CAP_NET_ADMIN` capability, causing the outbound to fail; in this case, setting `noKernelTun` to `true` solves the problem.
This option only selects how inner IP packets are processed. The WireGuard protocol itself is still handled by Xray's user-space implementation and is unrelated to the kernel WireGuard module.
The automatic detection described above is not always accurate. For example, some LXC environments may be unable to use TUN even when they have the `CAP_NET_ADMIN` capability, causing the outbound to fail. In this case, set this option to `true`.
When TUN is used, it occupies IPv6 routing table 10230. Each additional WireGuard outbound uses the next routing table in sequence; for example, the second one uses routing table 10231, and so on.
If a second Xray instance is started on the same machine, it does not continue allocating routing table numbers. Instead, it also tries to use routing table 10230. Because that table is already occupied by the first Xray instance, the second instance cannot connect. If multiple instances are necessary, use this option to disable TUN.
@@ -104,43 +97,19 @@ The three WireGuard reserved bytes. All three default to 0; set them as needed.
> `peers`: \[ [PeersObject](#peersobject) \]
List of WireGuard servers, where each item is a server configuration. When multiple servers are configured, Xray prefix-matches the destination IP address against each server's `allowedIPs` and routes the traffic to the matching server, allowing different destination networks to be forwarded through different WireGuard servers.
::: details Packet model of an Xray WireGuard outbound
TCP and UDP connections entering the WireGuard outbound are converted by the network stack into inner IP packets. The inner source address is selected from `address`, while the inner destination address is the destination IP of the proxied traffic.
Xray prefix-matches the inner destination address against each peer's `allowedIPs`. The matching peer encrypts and encapsulates the packet, and Xray sends the resulting outer UDP packet to that peer's `endpoint`. Therefore, `address` specifies the inner source addresses used by the client, `allowedIPs` acts as the destination routing table used to select a peer, and `endpoint` is the server address used by the outer connection.
:::
::: tip
Each WireGuard server must allow all addresses in `address` that belong to the same address family as its `allowedIPs`: if `allowedIPs` contains only IPv4 networks, allow all IPv4 addresses listed in `address`; if it contains only IPv6 networks, the same rule applies to the IPv6 addresses; if it contains both IPv4 and IPv6 networks, allow all listed addresses.
When using Xray as the WireGuard server, list these addresses in `inbounds[].settings.peers[].allowedIPs`.
:::
List of remote WireGuard peers to connect to.
> `remoteDNS`: \[ string \]
Used to resolve proxied target domain names. Each item must be an IP address. The default is `["1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001"]`.
DNS queries are sent through the WireGuard tunnel; every server IP must be included in a peer's `allowedIPs` and reachable through the tunnel.
::: details `remoteDNS` and `targetStrategy`
Unlike other outbounds, targets inside a WireGuard tunnel must be IP addresses. When the proxied target is a domain name, the outbound's [`targetStrategy`](../outbound.md#outboundobject) determines which DNS is used to resolve it:
- `AsIs`: uses `remoteDNS`.
- `UseIP*`: tries Xray's built-in DNS first and falls back to `remoteDNS` if resolution fails.
- `ForceIP*`: uses Xray's built-in DNS and fails immediately if resolution fails.
The results returned by `UseIP*` or `ForceIP*` must contain at least one IP whose address family matches an address in `address`; otherwise, the connection fails. An address-family mismatch is not treated as a resolution failure and does not trigger any fallback.
Which should you choose? `remoteDNS` works out of the box and sends queries through the WireGuard tunnel, usually producing CDN resolution results suited to the tunnel's exit location. Achieving the same result with [Xray's built-in DNS](../dns.md) usually requires additional DNS server and routing rules. However, if the built-in DNS resolved the target domain earlier—for example, when using a RealIP setup with TUN/TProxy, or when sniffing is enabled and `routing.domainStrategy` is not `AsIs`—using Xray's built-in DNS is recommended to avoid the additional RTT of a second resolution.
:::
Unlike other outbounds, targets inside a WireGuard tunnel must be IP addresses. When a proxied target is a domain name, a DNS server is required to convert the domain name into an IP address. These DNS servers are configured here and **send DNS requests directly through this WireGuard tunnel**. If you wish to integrate this with Xray's built-in DNS system, consider resolving in advance via the outbound's [`targetStrategy`](../outbound.md#outboundobject).
### PeersObject
```json
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"preSharedKey": "PRE_SHARED_KEY",
"keepAlive": 0,
@@ -150,16 +119,13 @@ Which should you choose? `remoteDNS` works out of the box and sends queries thro
> `endpoint`: address
Server address. Required.
URL:Port format, for example, `engage.cloudflareclient.com:2408`<br>
IP:Port format, for example, `162.159.192.1:2408` or `[2606:4700:d0::a29f:c001]:2408`
Server address and port, can be an IP or a domain name. Required.
> `publicKey`: string
Server public key used for verification. Required.
Peer public key used for verification. Required.
When using Xray as a WireGuard server, enter the `Password (PublicKey)` paired with the server's `inbounds[].settings.secretKey` here.
When generating a key pair using `xray wg`, this corresponds to the output `Password (PublicKey)`.
> `preSharedKey`: string
@@ -171,4 +137,4 @@ Interval, in seconds, at which the client sends persistent keepalive packets to
> `allowedIPs`: \[ string \]
Specifies the destination IP networks forwarded by this server, with each item expressed in CIDR notation. This field can be omitted when only one server is configured because the default is `["0.0.0.0/0", "::/0"]`, meaning that the server forwards all IPv4 and IPv6 destination traffic. When multiple servers are configured, explicitly set `allowedIPs` for each server to assign different destination networks to the appropriate server; Xray selects the server by prefix-matching the destination IP address.
Requests that should be forwarded using this peer, represented in CIDR notation. The default value is `["0.0.0.0/0", "::/0"]`, meaning all IPv4 and IPv6 destination traffic is forwarded by this server. When multiple peers match, the longest prefix match rule is used.
+6 -20
View File
@@ -1,6 +1,6 @@
# WireGuard
Реализация протокола WireGuard в пространстве пользователя для установления туннеля WireGuard с удалённым узлом и приёма входящего через этот туннель трафика.
Реализация протокола WireGuard в пространстве пользователя для установления туннеля WireGuard с удалённым узлом, преобразующая полученные TCP- и UDP-пакеты во внутренние прокси-запросы Xray для обработки и ответа.
::: danger
**Протокол WireGuard не предназначен специально для обхода блокировок. При использовании на внешнем уровне его характерные признаки могут привести к блокировке сервера.**
@@ -40,21 +40,11 @@
Закрытый ключ сервера. Обязательное поле.
Пару ключей сервера можно создать командой `xray wg`. Укажите здесь полученный `PrivateKey`; выведенный вместе с ним `Password (PublicKey)` является открытым ключом сервера. Если Xray используется в качестве клиента WireGuard, открытый ключ сервера следует указать в `outbounds[].settings.peers[].publicKey`.
При создании пары ключей сервера с помощью команды `xray wg` здесь указывается выведенный `PrivateKey`.
> `peers`: \[ [PeersObject](#peersobject) \]
Список клиентов WireGuard, каждый элемент которого содержит конфигурацию одного клиента. Если настроено несколько клиентов, Xray сопоставляет адрес источника расшифрованного внутреннего IP-пакета с `allowedIPs` каждого клиента, чтобы определить, какому клиенту принадлежит трафик.
::: details Сетевая модель входящего подключения Xray WireGuard
В обычной сети WireGuard, включая соединения «точка — точка», «точка — сеть» и «сеть — сеть», обе стороны участвуют в IP-маршрутизации через сетевые интерфейсы третьего уровня.
В отличие от такой схемы, входящее подключение Xray WireGuard не создаёт TUN-интерфейс в системе, а серверу не требуется назначать внутренний IP-адрес туннеля. Расшифрованные внутренние IP-пакеты обрабатываются встроенным сетевым стеком: содержащийся в них TCP- и UDP-трафик преобразуется в прокси-соединения и передаётся системе маршрутизации Xray вместо дальнейшей пересылки исходных IP-пакетов.
Клиент может отправлять как собственный трафик, так и трафик сетей за ним, выступая в роли шлюза. Сервер Xray не является доступным клиентам узлом третьего уровня внутри туннеля и не передаёт исходные IP-пакеты системному ядру для дальнейшей маршрутизации или NAT.
`allowedIPs` используется при обработке пакетов в обоих направлениях: при приёме WireGuard проверяет адрес источника расшифрованного внутреннего IP-пакета, а Xray использует этот адрес для определения клиента; при отправке ответных пакетов WireGuard выбирает соответствующего клиента по внутреннему адресу назначения.
:::
Список пиров-клиентов WireGuard.
> `mtu`: int
@@ -93,7 +83,7 @@ MTU внутренних IP-пакетов в туннеле WireGuard. Знач
Открытый ключ клиента, используемый для проверки. Обязательное поле.
Если Xray используется в качестве клиента WireGuard, здесь следует указать `Password (PublicKey)`, соответствующий закрытому ключу клиента в `outbounds[].settings.secretKey`.
При создании пары ключей с помощью `xray wg` здесь указывается выведенный `Password (PublicKey)`.
> `preSharedKey`: string
@@ -105,13 +95,9 @@ MTU внутренних IP-пакетов в туннеле WireGuard. Знач
> `allowedIPs`: \[ string \]
Задаёт IP-адреса или подсети, которые этому клиенту разрешено использовать в качестве адреса источника. Каждый элемент указывается в формате CIDR.
Задаёт разрешённые для отправки этим клиентом IP-адреса или подсети источника в формате CIDR. Значение по умолчанию — `["0.0.0.0/0", "::/0"]`, то есть разрешены все адреса источников IPv4 и IPv6.
Значение `address` исходящего подключения клиента должно входить в `allowedIPs` соответствующего пира на сервере. Например, если `outbounds[].settings.address` клиента равно `["10.0.0.2"]`, здесь можно указать `["10.0.0.2/32"]`.
В `allowedIPs` можно указывать не только внутренний IP-адрес клиента, но и сети, трафик которых маршрутизируется через этот пир. Например, если сторонний клиент WireGuard служит шлюзом для `192.168.10.0/24`, эту сеть можно добавить сюда; на самом клиенте также необходимо настроить маршрутизацию и включить пересылку IP-пакетов.
При наличии только одного клиента поле можно опустить; значение по умолчанию — `["0.0.0.0/0", "::/0"]`. Если настроено несколько клиентов, необходимо явно указать непересекающиеся значения `allowedIPs`, иначе надёжно различать клиентов будет невозможно.
При наличии только одного клиента поле можно опустить; значение по умолчанию — `["0.0.0.0/0", "::/0"]`. При настройке нескольких клиентов, в отличие от `allowedIPs` на стороне клиента, `allowedIPs` здесь не должны пересекаться: в лучшем случае это приведёт к невозможности правильно определить пир клиента, в худшем — к нарушению маршрутизации ответных пакетов.
> `email`: string
+20 -54
View File
@@ -1,6 +1,6 @@
# WireGuard
Реализация протокола WireGuard в пространстве пользователя для установления туннеля WireGuard с удалённым узлом и отправки исходящего трафика через этот туннель.
Реализация протокола WireGuard в пространстве пользователя для установления туннеля WireGuard с удалённым узлом, инкапсулирующая перенаправленные в это исходящее подключение TCP/UDP-запросы в IP-пакеты и отправляющая их через туннель WireGuard.
::: danger
**Протокол WireGuard не предназначен специально для обхода блокировок. При использовании на внешнем уровне его характерные признаки могут привести к блокировке сервера.**
@@ -16,20 +16,15 @@
{
// ...
"protocol": "wireguard",
// [!code focus:25]
// [!code focus:20]
"settings": {
"secretKey": "CLIENT_PRIVATE_KEY",
"address": [
"10.0.0.1",
"fd59:7153:2388:b5fd:0000:0000:0000:0001",
"and more..."
],
"address": ["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"],
"peers": [
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"allowedIPs": ["0.0.0.0/0", "::/0"]
// ...
}
],
"noKernelTun": false,
@@ -51,28 +46,26 @@
Закрытый ключ клиента. Обязательное поле.
Пару ключей клиента можно создать командой `xray wg`. Укажите здесь полученный `PrivateKey`; выведенный вместе с ним `Password (PublicKey)` является открытым ключом клиента. Если Xray используется в качестве сервера WireGuard, открытый ключ клиента следует указать в `inbounds[].settings.peers[].publicKey`.
При создании пары ключей клиента с помощью команды `xray wg` здесь указывается выведенный `PrivateKey`.
> `address`: \[ string \]
Задаёт локальные адреса источника для внутренних IP-пакетов, создаваемых исходящим подключением WireGuard, то есть внутренние IP-адреса клиента в туннеле. Можно указать один или несколько адресов IPv4 или IPv6.
Список локальных IP-адресов интерфейса WireGuard. При наличии нескольких адресов выбирается автоматически в зависимости от пира.
Значение по умолчанию — `["10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"]`.
Xray автоматически выбирает адрес источника нужного семейства в зависимости от адреса назначения. Если настроено несколько адресов одного семейства, подходящий адрес выбирается по внутренним правилам.<br>
Конфигурация входящего подключения на сервере WireGuard должна разрешать эти адреса, и каждый из них должен быть уникальным в конфигурации входящего подключения WireGuard на сервере.
> `noKernelTun`: true | false
Отключает использование TUN. Значение по умолчанию — `false`; в средах LXC или Docker может потребоваться значение `true`.
Принудительно отключает системный TUN независимо от результатов автоматического определения. Значение по умолчанию — `false`; в средах LXC или Docker может потребоваться значение `true`.
::: details Нужно ли включать `noKernelTun`?
При значении `false` Xray автоматически выбирает способ обработки внутренних IP-пакетов: в Linux, если процесс Xray имеет привилегию `CAP_NET_ADMIN`, создаётся TUN-интерфейс и используется сетевой стек ядра; на других платформах или при недостаточных правах используется работающий внутри процесса сетевой стек gVisor. При значении `true` используется только сетевой стек gVisor и TUN-интерфейс не создаётся. Использование TUN обычно обеспечивает более высокую производительность.
::: details О kernel TUN
Способ восстановления IP-пакетов WireGuard обратно в TCP/UDP-нагрузку в Xray.
По умолчанию Xray определяет автоматически: в Linux, если процесс Xray имеет привилегию `CAP_NET_ADMIN`, создаётся TUN-интерфейс и используется сетевой стек ядра; на других платформах или при недостаточных правах используется работающий внутри процесса сетевой стек gVisor. При значении `true` используется только сетевой стек gVisor и TUN-интерфейс не создаётся. Использование TUN обычно обеспечивает более высокую производительность.
Описанное автоматическое определение не всегда работает точно. Например, некоторые среды LXC могут не позволять использовать TUN даже при наличии привилегии `CAP_NET_ADMIN`, из-за чего исходящее подключение не будет работать; в таком случае установка `noKernelTun` в `true` решает проблему.
Этот параметр определяет только способ обработки внутренних IP-пакетов. Сам протокол WireGuard по-прежнему обрабатывается пользовательской реализацией Xray и не связан с модулем WireGuard ядра.
Описанное автоматическое определение не всегда работает точно. Например, некоторые среды LXC могут не позволять использовать TUN даже при наличии привилегии `CAP_NET_ADMIN`, из-за чего исходящее подключение не будет работать. В таком случае установите значение `true`.
При использовании TUN задействуется таблица маршрутизации IPv6 с номером 10230. Каждое следующее исходящее подключение WireGuard последовательно использует следующую таблицу: например, второе подключение использует таблицу 10231 и так далее.
Если на том же компьютере запустить второй экземпляр Xray, нумерация таблиц не продолжится: второй экземпляр также попытается использовать таблицу 10230. Поскольку она уже занята первым экземпляром Xray, подключение установить не удастся. Если запуск нескольких экземпляров необходим, используйте этот параметр для отключения TUN.
@@ -104,43 +97,19 @@ MTU внутренних IP-пакетов в туннеле WireGuard. Знач
> `peers`: \[ [PeersObject](#peersobject) \]
Список серверов WireGuard, каждый элемент которого содержит конфигурацию одного сервера. Если настроено несколько серверов, Xray сопоставляет IP-адрес назначения с `allowedIPs` каждого сервера по префиксу и направляет трафик на совпавший сервер. Таким образом, разные сети назначения можно обслуживать через разные серверы WireGuard.
::: details Модель пакетов исходящего подключения Xray WireGuard
TCP- и UDP-соединения, поступающие в исходящее подключение WireGuard, преобразуются сетевым стеком во внутренние IP-пакеты. Внутренний адрес источника выбирается из `address`, а внутренним адресом назначения становится IP-адрес назначения проксируемого трафика.
Xray сопоставляет внутренний адрес назначения с `allowedIPs` каждого пира по префиксу. Совпавший пир шифрует и инкапсулирует пакет, после чего внешний UDP-пакет отправляется на `endpoint` этого пира. Таким образом, `address` задаёт внутренние адреса источника клиента, `allowedIPs` служит таблицей маршрутов назначения для выбора пира, а `endpoint` является адресом сервера для внешнего соединения.
:::
::: tip
Каждый сервер WireGuard должен разрешать все адреса из `address`, семейство которых совпадает с семейством адресов в его `allowedIPs`: если `allowedIPs` содержит только сети IPv4, необходимо разрешить все IPv4-адреса из `address`; если только сети IPv6 — все IPv6-адреса; если присутствуют сети обоих семейств — все указанные адреса.
Если в качестве сервера WireGuard используется Xray, перечислите эти адреса в `inbounds[].settings.peers[].allowedIPs`.
:::
Список удалённых пиров WireGuard для подключения.
> `remoteDNS`: \[ string \]
Используется для разрешения целевых доменных имён проксируемого трафика. Каждый элемент должен быть IP-адресом. Значение по умолчанию — `["1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001"]`.
DNS-запросы отправляются через туннель WireGuard; IP-адрес каждого сервера должен входить в `allowedIPs` одного из пиров и быть доступен через туннель.
::: details `remoteDNS` и `targetStrategy`
В отличие от других исходящих подключений, целью внутри туннеля WireGuard должен быть IP-адрес. Если целью проксируемого запроса является доменное имя, параметр [`targetStrategy`](../outbound.md#outboundobject) исходящего подключения определяет, какой DNS используется для его разрешения:
- `AsIs`: используется `remoteDNS`.
- `UseIP*`: сначала используется встроенный DNS Xray, а при ошибке разрешения выполняется переход на `remoteDNS`.
- `ForceIP*`: используется встроенный DNS Xray; ошибка разрешения сразу приводит к ошибке подключения.
Результаты `UseIP*` или `ForceIP*` должны содержать хотя бы один IP-адрес того же семейства, что и один из адресов в `address`; иначе соединение завершится ошибкой. Несовпадение семейств адресов не считается ошибкой разрешения и не запускает никакой переход на резервный вариант.
Что выбрать? `remoteDNS` работает сразу, без дополнительной настройки, и отправляет запросы через туннель WireGuard, что обычно позволяет получить результаты CDN, соответствующие расположению выхода из туннеля. Для достижения того же результата с помощью [встроенного DNS Xray](../dns.md) обычно требуется дополнительно настроить DNS-серверы и правила маршрутизации. Однако если встроенный DNS ранее уже разрешил целевое доменное имя — например, при использовании схемы RealIP с TUN/TProxy либо при включённом сниффинге и значении `routing.domainStrategy`, отличном от `AsIs`, — рекомендуется использовать встроенный DNS Xray, чтобы избежать дополнительной задержки RTT из-за повторного разрешения.
:::
В отличие от других исходящих подключений, адрес цели внутри туннеля WireGuard обязательно должен быть IP-адресом. Если проксируемая цель является доменным именем, необходим DNS-сервер для преобразования доменного имени в IP-адрес. Эти DNS-серверы настраиваются здесь и **отправляют DNS-запросы напрямую через этот туннель WireGuard**. Если вы хотите подключить встроенную систему DNS Xray, рассмотрите возможность предварительного разрешения через [`targetStrategy`](../outbound.md#outboundobject) исходящего подключения.
### PeersObject
```json
{
"endpoint": "SERVER_ADDR",
"endpoint": "example.com:2408",
"publicKey": "SERVER_PUBLIC_KEY",
"preSharedKey": "PRE_SHARED_KEY",
"keepAlive": 0,
@@ -150,16 +119,13 @@ DNS-запросы отправляются через туннель WireGuard;
> `endpoint`: address
Адрес сервера. Обязательное поле.
Формат URL:порт, например `engage.cloudflareclient.com:2408`<br>
Формат IP:порт, например `162.159.192.1:2408` или `[2606:4700:d0::a29f:c001]:2408`
Адрес и порт сервера, может быть IP-адресом или доменным именем. Обязательное поле.
> `publicKey`: string
Открытый ключ сервера, используемый для проверки. Обязательное поле.
Открытый ключ пира, используемый для проверки. Обязательное поле.
Если Xray используется в качестве сервера WireGuard, здесь следует указать `Password (PublicKey)`, соответствующий закрытому ключу сервера в `inbounds[].settings.secretKey`.
При создании пары ключей с помощью `xray wg` здесь указывается выведенный `Password (PublicKey)`.
> `preSharedKey`: string
@@ -167,8 +133,8 @@ DNS-запросы отправляются через туннель WireGuard;
> `keepAlive`: int
Интервал отправки клиентом этому серверу пакетов persistent keepalive, в секундах. Они поддерживают возможные сопоставления NAT или состояние межсетевого экрана в периоды простоя. Включайте этот параметр только при необходимости и только на стороне клиента. Значение по умолчанию — `0`, то есть пакеты не отправляются.
Интервал отправки клиентом этому серверу пакетов persistent keepalive, в секундах, для поддержания возможных сопоставлений NAT или состояния межсетевого экрана во время простоя. Требуется включать только в особых случаях и только на стороне клиента; значение по умолчанию — `0`, то есть пакеты не отправляются.
> `allowedIPs`: \[ string \]
Задаёт IP-сети назначения, пересылаемые через этот сервер. Каждый элемент указывается в формате CIDR. При наличии только одного сервера поле можно опустить: значение по умолчанию — `["0.0.0.0/0", "::/0"]`, то есть через сервер направляется весь трафик к адресам IPv4 и IPv6. Если настроено несколько серверов, необходимо явно задать `allowedIPs` для каждого из них и распределить сети назначения между соответствующими серверами; Xray выбирает сервер путём сопоставления префикса IP-адреса назначения.
Запросы, которые должны пересылаться через этот пир, в формате CIDR. Значение по умолчанию — `["0.0.0.0/0", "::/0"]`, то есть весь целевой трафик IPv4 и IPv6 пересылается через этот сервер. При совпадении нескольких пиров выбор осуществляется по принципу наибольшего совпадения префикса (longest prefix match).