Skip to content

Commit b74969f

Browse files
committed
XHTTP & WS & HU & gRPC servers: Require sockopt.trustedXForwardedFor
XTLS/Xray-core#6309
1 parent fb95880 commit b74969f

6 files changed

Lines changed: 6 additions & 19 deletions

File tree

docs/config/transports/sockopt.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,9 @@ Sockopt 用于配置底层网络行为。
159159

160160
> `trustedXForwardedFor`: [ string ]
161161
162-
仅用于 `XHTTP``WebSocket``HTTPUpgrade` 这三个基于 HTTP 的 transport,以控制其是否认为 XFF(`X-Forwarded-For`头来自可信的反向代理
162+
仅适用于 `XHTTP``WebSocket``HTTPUpgrade``gRPC` 这四种基于 HTTP 的传输方式,用于控制是否信任 XFF(`X-Forwarded-For`头,即是否将其视为来自可信反向代理
163163

164-
默认为空,为空时 Xray 无条件接受 XFF 头并使用其中的 IP 覆盖源 IP。
165-
166-
当不为空时,检查该数组中设置的数个字符串的其中一个是否在请求中存在对应 Header(不论其内容为何)如果存在则使用其覆盖源 IP,否则 Xray 将无视该 XFF 头。
164+
Xray 会检查该数组中的各个字符串对应的 Header 是否出现在请求中;只要任意一项存在(无论其值为何),就允许使用 XFF 头的第 0 个值覆盖源 IP,否则将忽略该 XFF 头。
167165

168166
> `tcpKeepAliveIdle`: number
169167

docs/document/level-2/vless_reverse.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -970,4 +970,3 @@ server {
970970
- 承接反向代理流量的内网 `freedom`(也就是常说的 `direct`)出站,建议按最小权限原则配置。把默认出站设为 `blackhole`,只把允许访问的目标显式路由到专用 `freedom`。再通过 `finalRules` 只放行必要的地址和端口。
971971
- 如果你使用的是别人提供的穿透服务用于远程回家,或者你并不完全信任公网 VPS,建议不要让反向代理流量直接落到真实内网业务。可以在内网再部署一个带 `VLESS Encryption` 的服务端专门承接这部分流量,再由它转发给实际业务,以补上身份认证和数据保护,否则有权限接触到公网服务器的人可以漫游你的内网。
972972
- 通过 `VLESS` 等入站协议把流量送到内网端时,路由系统里看到的 `Source` / `Local` 所属协议,不一定与最终 `Target` 一致。涉及 `source``local``network` 等条件时,应以实际流量形态为准,不要想当然地把它们等同起来。
973-
- `XHTTP``WebSocket``HTTPUpgrade` 这三个基于 HTTP 的入站默认会读取 `X-Forwarded-For`。如果你的前面链路里没有可信的 HTTP 反代,建议配合 [`sockopt.trustedXForwardedFor`](../../config/transports/sockopt.md#trustedxforwardedfor) 限制何时信任它,避免客户端伪造来源 IP。

docs/en/config/transports/sockopt.md

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,13 +154,9 @@ When set to `true`, the peer must send PROXY protocol v1 or v2 immediately after
154154

155155
> `trustedXForwardedFor`: [ string ]
156156
157-
Only applies to the three HTTP-based inbounds: `XHTTP`, `WebSocket`, and `HTTPUpgrade`.
157+
Only applies to the four HTTP-based transport methods: `XHTTP`, `WebSocket`, `HTTPUpgrade`, and `gRPC`. It controls whether to trust the XFF (`X-Forwarded-For`) header, that is, whether to treat it as coming from a trusted reverse proxy.
158158

159-
It controls when Xray trusts `X-Forwarded-For` and uses it to overwrite `SourceIP`.
160-
161-
If left unset, the old behavior remains: as long as the request contains `X-Forwarded-For`, Xray reads it.
162-
163-
After setting this field, each array item is treated as an additional required header name. Xray trusts `X-Forwarded-For` only when the request also contains at least one of those headers. The header values do not matter; only the presence of the key is checked.
159+
Xray checks whether the headers corresponding to the strings in this array are present in the request. If any one of them is present, regardless of its value, Xray allows the value at index 0 in the XFF header to override the source IP; otherwise, it ignores the XFF header.
164160

165161
> `tcpKeepAliveIdle`: number
166162

docs/en/document/level-2/vless_reverse.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -970,4 +970,3 @@ The following points are more about deployment safety and boundary control. It i
970970
- The internal `freedom` outbound that receives reverse proxy traffic, often called the `direct` outbound, should be configured according to the principle of least privilege. Set the default outbound to `blackhole`, only route explicitly allowed targets to a dedicated `freedom`, and then use `finalRules` to allow only the necessary addresses and ports.
971971
- If you are using a penetration service provided by someone else for remote access home, or if you do not fully trust the public VPS, it is recommended not to let reverse proxy traffic land directly on your real internal services. Instead, deploy another server on the internal side with `VLESS Encryption` enabled specifically to receive that traffic, and let it forward traffic to the actual service. This adds authentication and data protection; otherwise anyone with sufficient access to the public server may be able to roam through your internal network.
972972
- When traffic is delivered to the internal side through inbound protocols such as `VLESS`, the protocol shown by `Source` or `Local` in the routing system is not necessarily the same as the final `Target`. When using conditions such as `source`, `local`, or `network`, rely on the actual traffic shape instead of assuming they are all equivalent.
973-
- The three HTTP-based inbounds `XHTTP`, `WebSocket`, and `HTTPUpgrade` trust `X-Forwarded-For` by default. If there is no HTTP reverse proxy in front that you trust, consider combining this with [`sockopt.trustedXForwardedFor`](../../config/transports/sockopt.md#trustedxforwardedfor) to control when it is trusted and to avoid client-forged source IPs.

docs/ru/config/transports/sockopt.md

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,9 @@ Sockopt используется для настройки низкоуровн
152152

153153
> `trustedXForwardedFor`: [ string ]
154154
155-
Применяется только к трем HTTP-ориентированным inbound: `XHTTP`, `WebSocket` и `HTTPUpgrade`.
155+
Применяется только к четырем транспортным способам на базе HTTP: `XHTTP`, `WebSocket`, `HTTPUpgrade` и `gRPC`. Этот параметр определяет, доверять ли заголовку XFF (`X-Forwarded-For`), то есть считать ли его переданным доверенным обратным прокси.
156156

157-
Позволяет ограничить, в каких случаях Xray будет доверять заголовку `X-Forwarded-For` и использовать его для подмены `SourceIP`.
158-
159-
Если поле не задано, сохраняется старое поведение: если в запросе есть `X-Forwarded-For`, Xray его читает.
160-
161-
После настройки этого поля каждый элемент массива рассматривается как имя дополнительного заголовка, которое должно присутствовать в запросе. Xray будет доверять `X-Forwarded-For` только если в запросе есть хотя бы один из этих заголовков. Их значения не важны, проверяется только наличие самого ключа.
157+
Xray проверяет, присутствуют ли в запросе заголовки, соответствующие строкам из этого массива. Если найден хотя бы один из них, независимо от его значения, Xray разрешает использовать значение с индексом 0 в заголовке XFF для подмены исходного IP; в противном случае заголовок XFF игнорируется.
162158

163159
> `tcpKeepAliveIdle`: number
164160

docs/ru/document/level-2/vless_reverse.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -970,4 +970,3 @@ server {
970970
- Внутренний outbound `freedom`, который принимает трафик обратного прокси, то есть привычный `direct`, желательно настраивать по принципу минимально необходимых привилегий. Сделайте outbound по умолчанию равным `blackhole`, явно маршрутизируйте только разрешенные цели в выделенный `freedom`, а затем через `finalRules` открывайте только действительно нужные адреса и порты.
971971
- Если вы используете сервис проникновения, предоставленный кем-то другим, для удаленного доступа домой, или если вы не полностью доверяете публичному VPS, лучше не направлять трафик обратного прокси напрямую на реальные внутренние сервисы. Вместо этого можно развернуть на внутренней стороне еще один сервер с включенным `VLESS Encryption`, специально для приема такого трафика, и уже через него пересылать трафик к настоящему сервису. Это добавляет аутентификацию и защиту данных; иначе любой, кто имеет достаточный доступ к публичному серверу, потенциально сможет перемещаться по вашей внутренней сети.
972972
- Когда трафик доставляется на внутреннюю сторону через входящие протоколы вроде `VLESS`, протокол, который routing system показывает у `Source` или `Local`, не обязательно совпадает с итоговым `Target`. При использовании условий вроде `source`, `local` или `network` ориентируйтесь на реальную форму трафика, а не на предположение, что они эквивалентны.
973-
- Три HTTP-ориентированных inbound `XHTTP`, `WebSocket` и `HTTPUpgrade` по умолчанию доверяют `X-Forwarded-For`. Если перед ними нет доверенного HTTP reverse proxy, рекомендуется сочетать это с [`sockopt.trustedXForwardedFor`](../../config/transports/sockopt.md#trustedxforwardedfor), чтобы ограничить случаи доверия и не допустить подделки исходного IP клиентом.

0 commit comments

Comments
 (0)