Compare commits

...
Author SHA1 Message Date
MeowandGitHub 939ca80bed README: Fix star history chart 2026-11-16 19:57:26 +08:00
yangdujunandRPRXX f781c68715 XMC finalmask: Switch to native frame padding (breaking); delay supports range (receiver waits at least minimal ms) (#7402)
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6117945421
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6855385193
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6880324101
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6887468010
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6890345279
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6896090317
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6897315492
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6912788851
2026-11-16 09:49:32 +00:00
5d17b872ed XMC finalmask: Make startup paddings configurable (direction, length and delay) (#6769)
https://github.com/XTLS/Xray-core/pull/6487#issuecomment-5008140264
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-5861391675
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6056420905
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6876480694
https://github.com/XTLS/Xray-core/pull/7401#issuecomment-6876702404
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6876963752

Closes https://github.com/XTLS/Xray-core/issues/6732#issuecomment-5575293343

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-14 15:58:21 +00:00
𐲓𐳛𐳪𐳂𐳐 𐲀𐳢𐳦𐳫𐳢 𐲥𐳔𐳛𐳪𐳌𐳑𐳖𐳇andGitHub c456141815 Build: Build list optimization; build tags clean-up (#5824)
https://github.com/XTLS/Xray-core/pull/5824#issuecomment-6796919801
2026-11-11 13:42:32 +00:00
LjhAUMEMandGitHub f082058590 Hysteria transport: Proper Brutal behavior; Bump quic-go (#7356)
Fixes https://github.com/XTLS/Xray-core/issues/7353
2026-11-11 08:45:54 +00:00
e184d774a2 Metrics: Close HTTP connections when stopping Xray Instance (#7361)
https://github.com/XTLS/Xray-core/pull/7361#pullrequestreview-5840920982

---------

Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-11 08:23:01 +00:00
LjhAUMEMandGitHub 14df0738f3 XDNS finalmask: Implement worker for TCP resolver (#7354)
Fixes https://github.com/XTLS/Xray-core/issues/7349
2026-11-11 08:12:22 +00:00
36cc9ff510 VLESS Multiplex (mux.cool): Raise maxConcurrency to 128 only for XDRIVE (#7375)
Closes https://github.com/XTLS/Xray-core/issues/7358#issuecomment-6785007489 and https://github.com/XTLS/Xray-core/pull/7365#issuecomment-6785026850

---------

Co-authored-by: Ivan Zorin <creator@localzet.com>
2026-11-11 07:37:36 +00:00
c43ee98ec7 VLESS Multiplex (mux.cool): Replace MutexWriter with buf.BufferedWriter (#7359)
Fixes https://github.com/XTLS/Xray-core/pull/7355#issuecomment-6738888441

---------

Co-authored-by: Medium1992 <Medium1992@users.noreply.github.com>
2026-11-10 22:13:21 +00:00
RPRXandGitHub 676eaf66f8 Xray-core v26.11.9
Sponsor & Donation & NFTs: https://github.com/XTLS/Xray-core/issues/3668
Project X Channel: https://t.me/projectXtls

Announcement of NFTs by Project X: https://github.com/XTLS/Xray-core/discussions/3633
Project X NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/1

VLESS Post-Quantum Encryption: https://github.com/XTLS/Xray-core/pull/5067
VLESS NFT: https://opensea.io/collection/vless

XHTTP: Beyond REALITY: https://github.com/XTLS/Xray-core/discussions/4113
REALITY NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/2
2026-11-09 05:27:09 +00:00
af8f9673af XDRIVE transport: Release notes & more optimizations for the Google Drive backend (#7352)
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6722011966

Syncs with https://github.com/anonymously-hidden/Xray-core/commit/a7722231a19b40afa91106eb03bb2b7097d55a86

---------

Co-authored-by: anonymously-hidden <106820058+anonymously-hidden@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 02:44:42 +00:00
RPRX 924a5e7814 uTLS: Temporarily switch to official 20261108164504, with REALITY 20261108101329
https://github.com/XTLS/Xray-core/pull/7135#issuecomment-6724425673
https://github.com/refraction-networking/utls/commit/a13c59ffe98bb01b2ca14143eb2e887664b1f138
https://github.com/XTLS/REALITY/commit/4bb46b2afd8b4f1f082fbaccae34fd3c7a3f8973
2026-11-09 01:06:40 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2a773ffb3d Bump docker/login-action from 4.7.0 to 4.8.0 (#7351)
Bumps [docker/login-action](https://github.com/docker/login-action) from 4.7.0 to 4.8.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.7.0...v4.8.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-09 00:39:53 +00:00
3a88ccb2d3 GitHub Actions: Use Android packed relocations for Android builds (#7343)
https://github.com/XTLS/Xray-core/pull/7343#issuecomment-6716954281

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: KobeArthurScofield <26771058+KobeArthurScofield@users.noreply.github.com>
2026-11-08 11:32:35 +00:00
RPRX a5d52d2d95 Update github.com/xtls/reality to 20261108102217
https://github.com/XTLS/REALITY/commit/4a26e87788f5e08cb9d433c1fab94bc15a8bf653
https://github.com/XTLS/REALITY/commit/4bb46b2afd8b4f1f082fbaccae34fd3c7a3f8973
https://github.com/XTLS/REALITY/commit/4836aa0229ff581bdbb728c9d1da3e739e2582f6
2026-11-08 11:23:44 +00:00
GlebandGitHub 3d3a504159 uTLS: Switch to XTLS/utls fork; Register hellochrome_155, which is also the new default fingerprint (#7135)
https://github.com/XTLS/Xray-core/discussions/7333#discussioncomment-19433184
https://github.com/XTLS/Xray-core/issues/7259#issuecomment-6718349626
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6677620667
https://github.com/XTLS/Xray-core/pull/7187#issuecomment-6314784068
https://github.com/XTLS/Xray-core/discussions/7144#discussioncomment-18912091
https://github.com/XTLS/Xray-core/issues/6299#issuecomment-4658601714
https://github.com/XTLS/Xray-core/pull/6181#issuecomment-4567373533
...

Closes https://github.com/XTLS/Xray-core/issues/7131#issuecomment-6139192035
2026-11-08 07:59:54 +00:00
2d287bbdee TUN inbound: Log IPv6 setup errors (gateway, dns and autoSystemRoutingTable) instead of exiting on Windows when DisabledComponents turns IPv6 off, with autoSystemWfpBlockLeak's "misconfigtun" blocking IPv6 then (#7341)
https://github.com/XTLS/Xray-core/pull/7325#issuecomment-6628514757
https://github.com/XTLS/Xray-core/pull/7332#issuecomment-6676374920
https://github.com/XTLS/Xray-core/pull/7341#issuecomment-6700092032

Replaces https://github.com/XTLS/Xray-core/pull/7332, https://github.com/XTLS/Xray-core/pull/7325 and https://github.com/XTLS/Xray-core/pull/6874

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 04:01:04 +00:00
RPRXandStarProxima 5745dea2b4 VLESS Multiplex (mux.cool): Apply MutexWriter to avoid concurrent writes to the underlayer
https://github.com/XTLS/Xray-core/pull/7337#issuecomment-6692618802
https://github.com/XTLS/Xray-core/pull/7345#issuecomment-6714114884

Fixes https://github.com/XTLS/Xray-core/issues/5845 and https://github.com/XTLS/Xray-core/issues/7336

---------

Co-authored-by: StarProxima <34741787+StarProxima@users.noreply.github.com>
2026-11-08 02:45:14 +00:00
2e4c13d8c4 Inbound: Close and remove the handler when it fails to start (#7223)
https://github.com/XTLS/Xray-core/pull/7223#pullrequestreview-5722817769

---------

Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-06 17:57:42 +00:00
RPRX bb335c6b0c VLESS Multiplex (mux.cool): Increase default maxConcurrency to 128, maxReuseTimes to 1024, mainly for XDRIVE, XDNS, XMC, XICMP
https://github.com/XTLS/Xray-core/pull/4231#issuecomment-6679992732
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6677620667
https://github.com/XTLS/Xray-core/pull/6748#issuecomment-5752780799
https://github.com/XTLS/Xray-core/pull/5581#issuecomment-3798801188
https://github.com/XTLS/Xray-core/pull/5872#issuecomment-4162202731
https://github.com/XTLS/Xray-core/pull/6487#issuecomment-5092235757
2026-11-06 08:43:07 +00:00
043d2e47fc XDRIVE transport: A bunch of optimizations for the Google Drive backend (#7340)
https://github.com/XTLS/Xray-core/pull/7217#issuecomment-6489554617
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6490366098
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6558792002
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6583177537
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6634955793
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-6677620667

Syncs with https://github.com/anonymously-hidden/Xray-core/commit/f7a8d213ac69410c23b4484d6eeea8dc55b580bd

---------

Co-authored-by: anonymously-hidden <106820058+anonymously-hidden@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 05:50:58 +00:00
36756ad672 TUN inbound: IPv6 entries in dns exit the core on Windows when IPv6 cannot be set up, as in gateway and autoSystemRoutingTable (#7332)
https://github.com/XTLS/Xray-core/pull/7325#issuecomment-6637932641
https://github.com/XTLS/Xray-core/pull/7332#issuecomment-6643930058
https://github.com/XTLS/Xray-core/pull/7332#issuecomment-6676374920

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:53:19 +00:00
MeowandRPRX abecd7d9f1 Geodata: Download .dat.gz when the URL belongs to XTLS/Xray-rules-dat (#7334)
https://github.com/XTLS/Xray-core/pull/7185#issuecomment-6633801536
https://github.com/XTLS/Xray-core/pull/7334#issuecomment-6643558279
https://github.com/XTLS/Xray-core/pull/4809#issuecomment-6510221797

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-06 03:14:21 +00:00
Wu ShuwenandGitHub a52db8f6ed common/buf/io.go: TimeoutWrapperReader returns ErrReadTimeout when timeout (#7327)
https://github.com/XTLS/Xray-core/pull/7327#issuecomment-6634105144

Fixes https://github.com/XTLS/Xray-core/issues/7318
2026-11-04 21:45:18 +00:00
MinyandGitHub 858c44f410 UdpHop finalmask: Avoid spurious error logs on closed hop sockets (#7319)
https://github.com/XTLS/Xray-core/pull/7319#issuecomment-6628950766
2026-11-04 11:01:44 +00:00
Hossin AsaadiandGitHub fff4acac52 WireGuard proxy: Give up on the endpoint lookup at the connection's deadline (#7323)
https://github.com/XTLS/Xray-core/pull/7323#issuecomment-6623261000
2026-11-04 10:53:08 +00:00
ad98ffd42b TUN inbound: Ignore dns IPv6 setup error when neither gateway nor autoSystemRoutingTable has an IPv6 entry on Windows (#7325)
https://github.com/XTLS/Xray-core/pull/7325#issuecomment-6619158295

---------

Co-authored-by: patterniha <71074308+patterniha@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:20:31 +00:00
MeowandGitHub 63ca2e0c1d Direct/Freedom outbound's finalRules: Add logLevel; blockDelay->delay; Apply default safe policy on MASQUE as well (#7329)
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6482226042
https://github.com/XTLS/Xray-core/issues/7240#issuecomment-6601762396
https://github.com/XTLS/Xray-core/pull/7324#issuecomment-6621358849
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6622083462
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6625219097
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6625305192
2026-11-04 08:34:58 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
ab88e0118f Bump github.com/klauspost/cpuid/v2 from 2.4.1 to 2.4.2 (#7328)
Bumps [github.com/klauspost/cpuid/v2](https://github.com/klauspost/cpuid) from 2.4.1 to 2.4.2.
- [Release notes](https://github.com/klauspost/cpuid/releases)
- [Commits](https://github.com/klauspost/cpuid/compare/v2.4.1...v2.4.2)

---
updated-dependencies:
- dependency-name: github.com/klauspost/cpuid/v2
  dependency-version: 2.4.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-04 02:41:21 +00:00
556767e40b XDRIVE transport: Retry "local" Get on Windows sharing violations (#7316)
https://github.com/XTLS/Xray-core/pull/7316#issuecomment-6575472342

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:02:23 +00:00
967ade1e03 TUN inbound's autoSystemWfpBlockLeak: Add "all", "allexceptlan", port alone, port range, "tcp"/"udp" alone or with port range, "icmp", and a CIDR in front of any value; Always allow loopback, DHCP and IPv6 neighbor discovery (#7315)
https://github.com/XTLS/Xray-core/pull/7288#issuecomment-6559954865
https://github.com/XTLS/Xray-core/pull/7315#issuecomment-6582481840
https://github.com/XTLS/Xray-core/pull/7315#issuecomment-6588253141

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:40:36 +00:00
120 changed files with 5803 additions and 2307 deletions
+1 -2
View File
@@ -1,5 +1,6 @@
{
"android-arm64": { "friendlyName": "android-arm64-v8a" },
"android-amd64": { "friendlyName": "android-amd64" },
"darwin-amd64": { "friendlyName": "macos-64" },
"darwin-arm64": { "friendlyName": "macos-arm64-v8a" },
"freebsd-386": { "friendlyName": "freebsd-32" },
@@ -14,9 +15,7 @@
"linux-arm7": { "friendlyName": "linux-arm32-v7a" },
"linux-mips64le": { "friendlyName": "linux-mips64le" },
"linux-mips64": { "friendlyName": "linux-mips64" },
"linux-mipslesoftfloat": { "friendlyName": "linux-mips32le-softfloat" },
"linux-mipsle": { "friendlyName": "linux-mips32le" },
"linux-mipssoftfloat": { "friendlyName": "linux-mips32-softfloat" },
"linux-mips": { "friendlyName": "linux-mips32" },
"linux-ppc64le": { "friendlyName": "linux-ppc64le" },
"linux-ppc64": { "friendlyName": "linux-ppc64" },
+3 -3
View File
@@ -9,8 +9,8 @@ ARG TARGETARCH
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
# Download geodat into a staging directory
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geoip-full.dat /tmp/geodat/geoip.dat
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geosite-expand.dat /tmp/geodat/geosite.dat
RUN mkdir -p /tmp/empty
@@ -20,7 +20,7 @@ RUN cat <<EOF >/tmp/usr/local/etc/xray/00_log.json
{
"log": {
"error": "/var/log/xray/error.log",
"loglevel": "warning",
"logLevel": "warning",
"access": "none",
"dnsLog": false
}
+3 -3
View File
@@ -9,8 +9,8 @@ ARG TARGETARCH
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
# Download geodat into a staging directory
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geoip-full.dat /tmp/geodat/geoip.dat
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geosite-expand.dat /tmp/geodat/geosite.dat
RUN mkdir -p /tmp/empty
@@ -20,7 +20,7 @@ RUN cat <<EOF >/tmp/usr/local/etc/xray/00_log.json
{
"log": {
"error": "/var/log/xray/error.log",
"loglevel": "warning",
"logLevel": "warning",
"access": "none",
"dnsLog": false
}
+1 -1
View File
@@ -82,7 +82,7 @@ jobs:
uses: docker/setup-buildx-action@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
+8 -13
View File
@@ -1,17 +1,14 @@
name: Build and Release for Windows 7
# Pre-compiling support removal since 1.29
on:
workflow_dispatch:
release:
types: [published]
push:
pull_request:
types: [opened, synchronize, reopened]
jobs:
check-assets:
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
steps:
- name: Restore Geodat Cache
uses: actions/cache/restore@v6
@@ -115,8 +112,6 @@ jobs:
COMMID=$(git describe --always --dirty)
echo 'Building Xray for Windows 7...'
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
# The line below is for without running conhost.exe version. Commented for not being used. Provided for reference.
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
- name: Restore Geodat Cache
uses: actions/cache/restore@v6
@@ -152,6 +147,13 @@ jobs:
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
- name: Upload files to Artifacts
uses: actions/upload-artifact@v7
with:
name: Xray-${{ env.ASSET_NAME }}
path: |
./build_assets/*
- name: Create ZIP archive
if: github.event_name == 'release'
shell: bash
@@ -175,10 +177,3 @@ jobs:
file: ./Xray-${{ env.ASSET_NAME }}.zip*
tag: ${{ github.ref }}
file_glob: true
- name: Upload files to Artifacts
uses: actions/upload-artifact@v7
with:
name: Xray-${{ env.ASSET_NAME }}
path: |
./build_assets/*
+179 -86
View File
@@ -79,86 +79,23 @@ jobs:
contents: write
strategy:
matrix:
# Include amd64 on all platforms.
goos: [windows, freebsd, openbsd, linux, darwin]
goarch: [amd64, 386]
# Include amd64 and arm64 on all platforms.
goos: [windows, freebsd, openbsd, linux, darwin, android]
goarch: [amd64, arm64]
patch-assetname: [""]
exclude:
# Exclude i386 on darwin
- goarch: 386
goos: darwin
include:
# BEGIN MacOS ARM64
- goos: darwin
goarch: arm64
# END MacOS ARM64
# BEGIN Linux ARM 5 6 7
- goos: linux
goarch: arm
goarm: 7
- goos: linux
goarch: arm
goarm: 6
- goos: linux
goarch: arm
goarm: 5
# END Linux ARM 5 6 7
# BEGIN Android ARM 8
- goos: android
goarch: arm64
# END Android ARM 8
# BEGIN Android AMD64
- goos: android
goarch: amd64
patch-assetname: android-amd64
# END Android AMD64
# Windows ARM
- goos: windows
goarch: arm64
# BEGIN Other architectures
# BEGIN riscv64 & ARM64 & LOONG64
- goos: linux
goarch: arm64
- goos: linux
goarch: riscv64
- goos: linux
goarch: loong64
# END riscv64 & ARM64 & LOONG64
# BEGIN MIPS
- goos: linux
goarch: mips64
- goos: linux
goarch: mips64le
- goos: linux
goarch: mipsle
- goos: linux
goarch: mips
# END MIPS
# BEGIN PPC
# BEGIN Linux specified
- goos: linux
goarch: ppc64
- goos: linux
goarch: ppc64le
# END PPC
# BEGIN FreeBSD ARM
- goos: freebsd
goarch: arm64
- goos: freebsd
goarch: arm
goarm: 7
# END FreeBSD ARM
# BEGIN S390X
- goos: linux
goarch: s390x
# END S390X
# END Other architectures
# BEGIN OPENBSD ARM
- goos: openbsd
goarch: arm64
- goos: openbsd
goarch: arm
goarm: 7
# END OPENBSD ARM
- goos: linux
goarch: riscv64
- goos: linux
goarch: loong64
# END Linux specified
fail-fast: false
runs-on: ubuntu-latest
@@ -166,7 +103,6 @@ jobs:
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
GOARM: ${{ matrix.goarm }}
CGO_ENABLED: 0
steps:
- name: Checkout codebase
@@ -188,8 +124,8 @@ jobs:
- name: Show workflow information
run: |
_NAME=${{ matrix.patch-assetname }}
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH$GOARM$GOMIPS\"].friendlyName" -r < .github/build/friendly-filenames.json)
echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, GOMIPS: $GOMIPS, RELEASE_NAME: $_NAME"
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH\"].friendlyName" -r < .github/build/friendly-filenames.json)
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
- name: Set up Go
@@ -203,6 +139,18 @@ jobs:
- name: Build Xray
run: |
case "${GOARCH}:${GOOS}" in
# Special processing for x86-64 and ARM64
amd64:windows|amd64:darwin)
GOAMD64="v2"
;;
arm64:windows)
GOARM64="v8.2"
;;
arm64:darwin)
GOARM64="v8.4"
;;
esac
mkdir -p build_assets
COMMID=$(git describe --always --dirty)
if [[ ${GOOS} == 'windows' ]]; then
@@ -212,16 +160,10 @@ jobs:
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
elif [[ ${GOOS} == 'android' ]]; then
echo 'Building Xray for Android...'
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid= -checklinkname=0" -v ./main
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
else
echo 'Building Xray...'
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
echo 'Building soft-float Xray for MIPS/MIPSLE 32-bit...'
GOMIPS=softfloat go build -o build_assets/xray_softfloat -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
else
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
fi
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
fi
- name: Restore Geodat Cache
@@ -248,9 +190,6 @@ jobs:
if [[ ${GOARCH} == 'amd64' ]]; then
mv resources/wintun/bin/amd64/wintun.dll build_assets/
fi
if [[ ${GOARCH} == '386' ]]; then
mv resources/wintun/bin/x86/wintun.dll build_assets/
fi
if [[ ${GOARCH} == 'arm64' ]]; then
mv resources/wintun/bin/arm64/wintun.dll build_assets/
fi
@@ -262,6 +201,13 @@ jobs:
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
- name: Upload files to Artifacts
uses: actions/upload-artifact@v7
with:
name: Xray-${{ env.ASSET_NAME }}
path: |
./build_assets/*
- name: Create ZIP archive
if: github.event_name == 'release'
shell: bash
@@ -286,9 +232,156 @@ jobs:
tag: ${{ github.ref }}
file_glob: true
build-release-only:
needs: check-assets
permissions:
contents: write
strategy:
matrix:
# First batch (since Go 1.29) of removal:
# x86: windows, linux, freebsd, openbsd
# arm: linux(v5), linux(v6)
# other: linux(mips), linux(mips64), linux(mips64le)
# Second batch (needs discussion) of removal
# arm(v7): freebsd, openbsd, linux
# other: linux(mipsle)
goos: [windows, freebsd, openbsd, linux]
goarch: [arm, 386]
goarm: [7]
exclude:
- goos: windows
goarch: arm
include:
# Second batch of removal [In the future]
- goos: linux
goarch: mipsle
# END of second batch
# First batch of removal [Go 1.29]
- goos: linux
goarch: arm
goarm: 5
- goos: linux
goarch: arm
goarm: 6
- goos: linux
goarch: mips
- goos: linux
goarch: mips64
- goos: linux
goarch: mips64le
# END of first batch
fail-fast: false
runs-on: ubuntu-latest
if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
GOARM: ${{ matrix.goarm }}
CGO_ENABLED: 0
steps:
- name: Checkout codebase
uses: actions/checkout@v7
- name: Show workflow information
run: |
_NAME=${{ matrix.patch-assetname }}
if [[ ${GOARCH} == 'arm' ]]; then
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH$GOARM\"].friendlyName" -r < .github/build/friendly-filenames.json)
echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, RELEASE_NAME: $_NAME"
else
echo "GOARM=''" >> $GITHUB_ENV
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH\"].friendlyName" -r < .github/build/friendly-filenames.json)
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
fi
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: go.mod
check-latest: true
- name: Get project dependencies
run: go mod download
- name: Build Xray
run: |
mkdir -p build_assets
COMMID=$(git describe --always --dirty)
if [[ ${GOOS} == 'windows' ]]; then
echo 'Building Xray for Windows...'
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
else
echo 'Building Xray...'
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
go build -o build_assets/xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
echo 'Building soft-float Xray for MIPS/MIPSLE 32-bit...'
GOMIPS=softfloat go build -o build_assets/xray_softfloat -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
else
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
fi
fi
- name: Restore Geodat Cache
uses: actions/cache/restore@v6
with:
path: resources
key: xray-geodat-
- name: Restore Wintun Cache
if: matrix.goos == 'windows'
uses: actions/cache/restore@v6
with:
path: resources
key: xray-wintun-
- name: Add additional assets into package
run: |
mv -f resources/geo* build_assets/
if [[ ${GOOS} == 'windows' ]]; then
cp .github/build/windows/* build_assets/
fi
if [[ ${GOOS} == 'windows' ]]; then
echo 'Adding Wintun into packages'
if [[ ${GOARCH} == '386' ]]; then
mv resources/wintun/bin/x86/wintun.dll build_assets/
fi
mv resources/wintun/LICENSE.txt build_assets/LICENSE-Wintun
fi
- name: Copy README.md & LICENSE
run: |
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
- name: Upload files to Artifacts
uses: actions/upload-artifact@v7
with:
name: Xray-${{ env.ASSET_NAME }}
path: |
./build_assets/*
- name: Create ZIP archive
if: github.event_name == 'release'
shell: bash
run: |
pushd build_assets || exit 1
touch -mt $(date +%Y01010000) *
zip -9vr ../Xray-${{ env.ASSET_NAME }}.zip .
popd || exit 1
FILE=./Xray-${{ env.ASSET_NAME }}.zip
DGST=$FILE.dgst
for METHOD in {"md5","sha1","sha256","sha512"}
do
openssl dgst -$METHOD $FILE | sed 's/([^)]*)//g' >>$DGST
done
- name: Upload binaries to release
uses: svenstaro/upload-release-action@v2
if: github.event_name == 'release'
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: ./Xray-${{ env.ASSET_NAME }}.zip*
tag: ${{ github.ref }}
file_glob: true
+26 -5
View File
@@ -231,19 +231,40 @@ Make sure that you are using the same Go version, and remember to set the git co
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
```
For Windows (x86-64 and AArch64, not win7):
```bash
GOOS=windows GOARCH=amd64 GOAMD64=v2 CGO_ENABLED=0 go build -o xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=windows GOARCH=arm64 GOARM64=v8.2 CGO_ENABLED=0 go build -o xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
```
For macOS:
```bash
GOOS=darwin GOARCH=amd64 GOAMD64=v2 CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=darwin GOARCH=arm64 GOARM64=v8.4 CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
```
For Android:
```bash
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC=/path/to/x86_64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC=/path/to/x86_64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
```
If you are compiling a 32-bit MIPS/MIPSLE target, use this command instead:
For Linux (MIPS32 and MIPS32LE):
```bash
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=linux GOARCH=mips GOMIPS=hardfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=linux GOARCH=mips GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=linux GOARCH=mipsle GOMIPS=hardfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
```
## Stargazers over time
[![Stargazers over time](https://starchart.cc/XTLS/Xray-core.svg)](https://starchart.cc/XTLS/Xray-core)
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
</picture>
+13 -5
View File
@@ -29,6 +29,7 @@ type MetricsHandler struct {
listen string
tcpListener xnet.Listener
listener *OutboundListener
server *http.Server
}
// NewMetricsHandler creates a new MetricsHandler based on the given config.
@@ -50,7 +51,8 @@ func (p *MetricsHandler) Type() interface{} {
}
func (p *MetricsHandler) Start() error {
handler := p.httpHandler()
server := &http.Server{Handler: p.httpHandler()}
p.server = server
// direct listen a port if listen is set
if p.listen != "" {
@@ -61,7 +63,7 @@ func (p *MetricsHandler) Start() error {
p.tcpListener = TCPlistener
errors.LogInfo(context.Background(), "Metrics server listening on ", p.listen)
go p.serve(TCPlistener, handler)
go p.serve(TCPlistener, server)
}
if p.tag == "" {
@@ -77,7 +79,7 @@ func (p *MetricsHandler) Start() error {
}
p.listener = listener
go p.serve(listener, handler)
go p.serve(listener, server)
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
errors.LogInfo(context.Background(), "failed to remove existing handler")
@@ -106,6 +108,12 @@ func (p *MetricsHandler) Close() error {
errs = append(errs, p.listener.Close())
p.listener = nil
}
if p.server != nil {
if err := p.server.Close(); !isClosedListenerError(err) {
errs = append(errs, err)
}
p.server = nil
}
if p.ohm != nil && p.tag != "" {
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
errors.LogInfo(context.Background(), "failed to remove metrics handler")
@@ -114,8 +122,8 @@ func (p *MetricsHandler) Close() error {
return errors.Combine(errs...)
}
func (p *MetricsHandler) serve(listener xnet.Listener, handler http.Handler) {
if err := http.Serve(listener, handler); err != nil && !isClosedListenerError(err) {
func (p *MetricsHandler) serve(listener xnet.Listener, server *http.Server) {
if err := server.Serve(listener); err != nil && !isClosedListenerError(err) {
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
}
}
+11 -1
View File
@@ -51,7 +51,17 @@ func (m *Manager) AddHandler(ctx context.Context, handler inbound.Handler) error
}
if m.running {
return handler.Start()
if err := handler.Start(); err != nil {
if len(tag) > 0 {
delete(m.taggedHandlers, tag)
} else {
m.untaggedHandlers = m.untaggedHandlers[:len(m.untaggedHandlers)-1]
}
if err := handler.Close(); err != nil {
errors.LogWarningInner(ctx, err, "failed to close handler ", tag)
}
return err
}
}
return nil
+5 -2
View File
@@ -125,6 +125,9 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
if config.Concurrency == 0 {
config.Concurrency = 8 // same as before
}
if config.Concurrency > 0 && config.Concurrency < 128 && h.streamSettings != nil && h.streamSettings.ProtocolName == "xdrive" {
config.Concurrency = 128
}
if config.Concurrency > 0 {
h.mux = &mux.ClientManager{
Enabled: true,
@@ -134,7 +137,7 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
Dialer: h,
Strategy: mux.ClientStrategy{
MaxConcurrency: uint32(config.Concurrency),
MaxConnection: 128,
MaxConnection: 1024,
},
},
},
@@ -155,7 +158,7 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
Dialer: h,
Strategy: mux.ClientStrategy{
MaxConcurrency: uint32(config.XudpConcurrency),
MaxConnection: 128,
MaxConnection: 1024,
},
},
},
+1 -1
View File
@@ -73,7 +73,7 @@ func (r *TimeoutWrapperReader) ReadMultiBufferTimeout(duration time.Duration) (M
}
return r.mb, r.err
case <-timeout:
return nil, nil
return nil, ErrReadTimeout
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build !windows && !wasm && !illumos && !openbsd
// +build !windows,!wasm,!illumos,!openbsd
//go:build !windows && !openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build !wasm && !openbsd
// +build !wasm,!openbsd
//go:build !openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build wasm || openbsd
// +build wasm openbsd
//go:build openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build !wasm && !openbsd
// +build !wasm,!openbsd
//go:build !openbsd
package buf_test
-37
View File
@@ -1,37 +0,0 @@
//go:build illumos
// +build illumos
package buf
import "golang.org/x/sys/unix"
type unixReader struct {
iovs [][]byte
}
func (r *unixReader) Init(bs []*Buffer) {
iovs := r.iovs
if iovs == nil {
iovs = make([][]byte, 0, len(bs))
}
for _, b := range bs {
iovs = append(iovs, b.v)
}
r.iovs = iovs
}
func (r *unixReader) Read(fd uintptr) int32 {
n, e := unix.Readv(int(fd), r.iovs)
if e != nil {
return -1
}
return int32(n)
}
func (r *unixReader) Clear() {
r.iovs = r.iovs[:0]
}
func newMultiReader() multiReader {
return &unixReader{}
}
+4
View File
@@ -236,6 +236,10 @@ func (w *BufferedWriter) Close() error {
return common.Close(w.writer)
}
func (w *BufferedWriter) Interrupt() {
common.Interrupt(w.writer)
}
// SequentialWriter is a Writer that writes MultiBuffer sequentially into the underlying io.Writer.
type SequentialWriter struct {
io.Writer
@@ -1,5 +1,4 @@
//go:build generate
// +build generate
package main
+3
View File
@@ -188,6 +188,9 @@ var (
// NewClientWorker creates a new mux.Client.
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
writer := buf.NewBufferedWriter(stream.Writer)
writer.SetBuffered(false)
stream.Writer = writer
c := &ClientWorker{
sessionManager: NewSessionManager(),
link: stream,
+3 -1
View File
@@ -93,9 +93,11 @@ type ServerWorker struct {
}
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
writer := buf.NewBufferedWriter(link.Writer)
writer.SetBuffered(false)
worker := &ServerWorker{
dispatcher: d,
link: link,
link: &transport.Link{Reader: link.Reader, Writer: writer},
sessionManager: NewSessionManager(),
done: done.New(),
timer: time.NewTicker(60 * time.Second),
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package platform
-1
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package platform
+1 -1
View File
@@ -134,7 +134,7 @@ func TestMarshalConfigJson(t *testing.T) {
func getConfig() string {
return `{
"log": {
"loglevel": "debug"
"logLevel": "debug"
},
"stats": {},
"policy": {
+2 -2
View File
@@ -19,8 +19,8 @@ import (
var (
Version_x byte = 26
Version_y byte = 10
Version_z byte = 31
Version_y byte = 11
Version_z byte = 9
)
var (
+6 -6
View File
@@ -3,24 +3,24 @@ module github.com/xtls/xray-core
go 1.27
require (
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
github.com/bufbuild/protocompile v0.14.1
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
github.com/golang/mock v1.7.0-rc.1
github.com/google/go-cmp v0.7.0
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/klauspost/cpuid/v2 v2.4.1
github.com/klauspost/cpuid/v2 v2.4.2
github.com/libp2p/go-nat v1.0.1-0.20250821073202-01afc089f138
github.com/miekg/dns v1.1.73
github.com/pelletier/go-toml v1.9.5
github.com/pion/stun/v3 v3.1.7
github.com/pires/go-proxyproto v0.16.0
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b
github.com/robfig/cron/v3 v3.0.1
github.com/stretchr/testify v1.12.1
github.com/vishvananda/netlink v1.3.1
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b
github.com/yuin/gopher-lua v1.1.2
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
golang.org/x/crypto v0.58.0
@@ -41,14 +41,14 @@ require (
)
require (
github.com/andybalholm/brotli v1.2.3 // indirect
github.com/google/gopacket v1.1.19 // indirect
github.com/huin/goupnp v1.2.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.20.0 // indirect
github.com/klauspost/compress v1.20.1 // indirect
github.com/koron/go-ssdp v0.0.4 // indirect
github.com/libp2p/go-netroute v0.2.1 // indirect
github.com/molecule-man/go-brrr v1.2.0 // indirect
github.com/pion/dtls/v3 v3.1.5 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/transport/v4 v4.1.0 // indirect
+12 -14
View File
@@ -1,7 +1,5 @@
github.com/andybalholm/brotli v1.2.3 h1:8H1qwOkl2LPfjf3YezB90JnCliZb6SInJ/OJkEbA5NQ=
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e h1:5mgtR5gwIgBKMiGI1QdXldZZ+SNor06Nbu1wCBulQBg=
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e/go.mod h1:x7qxEvX6MCVtDuBKHj3E+88+BtrbEMuAL5qGUKItjW8=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
@@ -33,10 +31,10 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.1 h1:I9KxadAkvo+QjtcEE2f2tyfEvmIla/T0m+14PrZNl0U=
github.com/klauspost/cpuid/v2 v2.4.1/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
github.com/koron/go-ssdp v0.0.4/go.mod h1:oDXq+E5IL5q0U8uSBcoAXzTzInwy5lEgC91HoKtbmZk=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -49,6 +47,8 @@ github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9t
github.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ=
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
github.com/molecule-man/go-brrr v1.2.0 h1:dOJU45BC3Gc2WXoxAW0rgCAgVuu2gruAOGncfieA0Jw=
github.com/molecule-man/go-brrr v1.2.0/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc=
@@ -67,8 +67,8 @@ github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af h1:er2acxbi3N1nvEq6HXHUAR1nTWEJmQfqiGR8EVT9rfs=
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b h1:Mi/DuaTxHeNIQ9g1ylZicAqa6Cb9wkHRiNtQH9uZ7Ts=
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b/go.mod h1:rc/ctWeKlh9LSk5k90KlSPcwF7P6D31mn/9GI2NAfBI=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
@@ -81,10 +81,8 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8 h1:RjLnVvlzK4q6zWaSBPNRGsrgx2fbJDeUWffjw574uzs=
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b h1:fAn11r21QiUY2oAGwENWb5ummjhWwMcs2WzkbjDMh+k=
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
+33 -3
View File
@@ -9,6 +9,7 @@ import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/log"
xnet "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/proxy/freedom"
@@ -48,6 +49,8 @@ type FreedomFinalRuleConfig struct {
Network *NetworkList `json:"network"`
Port *PortList `json:"port"`
IP *StringList `json:"ip"`
Delay *Int32Range `json:"delay"`
LogLevel string `json:"logLevel"`
BlockDelay *Int32Range `json:"blockDelay"`
}
@@ -280,10 +283,37 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
}
if c.BlockDelay != nil {
rule.BlockDelay = &freedom.Range{
Min: uint64(c.BlockDelay.From),
Max: uint64(c.BlockDelay.To),
errors.PrintDeprecatedFeatureWarning("finalRules.blockDelay", "finalRules.delay")
c.Delay = c.BlockDelay
}
if rule.Action != freedom.RuleAction_Block {
if c.Delay != nil || c.LogLevel != "" {
return nil, errors.New("delay and logLevel are only supported for block finalRules")
}
return rule, nil
}
if c.Delay != nil {
rule.Delay = &freedom.Range{
Min: uint64(c.Delay.From),
Max: uint64(c.Delay.To),
}
}
switch strings.ToLower(c.LogLevel) {
case "", "info":
rule.LogLevel = log.Severity_Info.Enum()
case "none":
rule.LogLevel = log.Severity_Unknown.Enum()
case "debug":
rule.LogLevel = log.Severity_Debug.Enum()
case "warning":
rule.LogLevel = log.Severity_Warning.Enum()
case "error":
rule.LogLevel = log.Severity_Error.Enum()
default:
return nil, errors.New("unknown finalRules.logLevel: ", c.LogLevel)
}
return rule, nil
+5 -5
View File
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
. "github.com/xtls/xray-core/infra/conf"
@@ -46,7 +47,8 @@ func TestFreedomConfig(t *testing.T) {
"network": "tcp,udp",
"port": "53,443",
"ip": ["10.0.0.0/8", "2001:db8::/32"],
"blockDelay": "30-60"
"delay": "30-60",
"logLevel": "debug"
}, {
"action": "allow",
"network": ["udp"]
@@ -86,10 +88,8 @@ func TestFreedomConfig(t *testing.T) {
},
},
},
BlockDelay: &freedom.Range{
Min: 30,
Max: 60,
},
Delay: &freedom.Range{Min: 30, Max: 60},
LogLevel: log.Severity_Debug.Enum(),
},
{
Action: freedom.RuleAction_Allow,
+11 -1
View File
@@ -2,6 +2,7 @@ package conf
import (
"net/url"
"strings"
"github.com/robfig/cron/v3"
"github.com/xtls/xray-core/app/geodata"
@@ -19,11 +20,20 @@ func (c *GeodataAssetConfig) Build() (*geodata.Asset, error) {
return nil, errors.New("invalid geodata asset url: ", c.URL).Base(err)
}
return &geodata.Asset{
Url: c.URL,
Url: migrateGeodataURL(c.URL),
File: c.File,
}, nil
}
func migrateGeodataURL(assetURL string) string {
if strings.HasSuffix(strings.ToLower(assetURL), ".dat") && (strings.HasPrefix(strings.ToLower(assetURL), "https://github.com/xtls/xray-rules-dat/") ||
strings.HasPrefix(strings.ToLower(assetURL), "https://raw.githubusercontent.com/xtls/xray-rules-dat/")) {
errors.PrintDeprecatedFeatureWarning(assetURL, assetURL+".gz")
return assetURL + ".gz"
}
return assetURL
}
func validateHTTPS(s string) error {
u, err := url.ParseRequestURI(s)
if err != nil {
+1 -1
View File
@@ -18,7 +18,7 @@ func DefaultLogConfig() *log.Config {
type LogConfig struct {
AccessLog string `json:"access"`
ErrorLog string `json:"error"`
LogLevel string `json:"loglevel"`
LogLevel string `json:"logLevel"`
DNSLog bool `json:"dnsLog"`
MaskAddress string `json:"maskAddress"`
}
+2 -2
View File
@@ -18,7 +18,7 @@ func TestLoaderError(t *testing.T) {
"log": {
// abcd
0,
"loglevel": "info"
"logLevel": "info"
}
}`,
Output: "line 4 char 6",
@@ -27,7 +27,7 @@ func TestLoaderError(t *testing.T) {
Input: `{
"log": {
// abcd
"loglevel": "info",
"logLevel": "info",
}
}`,
Output: "line 5 char 5",
+50 -10
View File
@@ -932,9 +932,17 @@ func (c *XDNS) Build() (proto.Message, error) {
}
type XMC struct {
Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
}
type XMCPaddingTurn struct {
Length string `json:"length"`
Direction string `json:"direction"`
// Delay is an optional millisecond value or inclusive min-max range.
Delay string `json:"delay,omitempty"`
}
type XMCProfile struct {
@@ -977,6 +985,41 @@ func (c *XMC) Build() (proto.Message, error) {
if c.Password == "" {
return nil, fmt.Errorf("empty password")
}
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname}
for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
return nil, fmt.Errorf("minecraft padding turn %d length: %w", i, err)
}
delayMinimum, delayMaximum, err := ParseRangeString(turn.Delay)
if err != nil {
return nil, fmt.Errorf("minecraft padding turn %d delay: %w", i, err)
}
var direction int32
switch turn.Direction {
case "c2s", "client-to-server":
direction = 1
case "s2c", "server-to-client":
direction = 2
default:
return nil, fmt.Errorf("minecraft padding turn %d: invalid direction %q (must be \"c2s\" or \"s2c\")", i, turn.Direction)
}
config.Paddings = append(config.Paddings, &xmc.Padding{
LengthMin: int64(minimum),
LengthMax: int64(maximum),
Direction: direction,
DelayMin: int64(delayMinimum),
DelayMax: int64(delayMaximum),
})
}
if err := config.ValidatePadding(); err != nil {
return nil, fmt.Errorf("minecraft padding: %w", err)
}
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
if err != nil {
@@ -997,13 +1040,10 @@ func (c *XMC) Build() (proto.Message, error) {
profiles = append(profiles, profile)
}
return &xmc.Config{
Password: c.Password,
Hostname: c.Hostname,
RsaPrivateKey: x509.MarshalPKCS1PrivateKey(rsaPrivateKey),
RsaPublicKey: rsaPublicKey,
Profiles: profiles,
}, nil
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
config.RsaPublicKey = rsaPublicKey
config.Profiles = profiles
return config, nil
}
type Xicmp struct {
@@ -1,6 +1,7 @@
package conf
import (
"encoding/json"
"strings"
"testing"
@@ -10,6 +11,11 @@ import (
func TestXMCBuildProfile(t *testing.T) {
built, err := (&XMC{
Password: "test-password",
Paddings: []XMCPaddingTurn{
{Length: "3", Direction: "c2s"},
{Length: "127-129", Direction: "s2c", Delay: "100"},
{Length: "8388608", Direction: "c2s", Delay: "50-150"},
},
Profiles: []XMCProfile{
{
Username: "TestUser",
@@ -26,6 +32,19 @@ func TestXMCBuildProfile(t *testing.T) {
if len(config.Profiles) != 1 || len(config.Profiles[0].Uuid) != 16 {
t.Fatalf("unexpected profiles: %+v", config.Profiles)
}
if len(config.Paddings) != 3 || config.Paddings[0].LengthMin != 3 || config.Paddings[0].LengthMax != 3 ||
config.Paddings[1].LengthMin != 127 || config.Paddings[1].LengthMax != 129 ||
config.Paddings[2].LengthMin != 8388608 || config.Paddings[2].LengthMax != 8388608 {
t.Fatalf("unexpected padding: %v", config.Paddings)
}
if config.Paddings[0].Direction != 1 || config.Paddings[1].Direction != 2 || config.Paddings[2].Direction != 1 {
t.Fatalf("unexpected padding directions: %v, %v, %v", config.Paddings[0].Direction, config.Paddings[1].Direction, config.Paddings[2].Direction)
}
if config.Paddings[0].DelayMin != 0 || config.Paddings[0].DelayMax != 0 ||
config.Paddings[1].DelayMin != 100 || config.Paddings[1].DelayMax != 100 ||
config.Paddings[2].DelayMin != 50 || config.Paddings[2].DelayMax != 150 {
t.Fatalf("unexpected padding delays: %v, %v, %v", config.Paddings[0].DelayMin, config.Paddings[1].DelayMin, config.Paddings[2].DelayMin)
}
}
func TestXMCBuildRequiresProfile(t *testing.T) {
@@ -34,3 +53,62 @@ func TestXMCBuildRequiresProfile(t *testing.T) {
t.Fatalf("expected required profiles error, got %v", err)
}
}
func TestXMCBuildRejectsPadding(t *testing.T) {
for name, padding := range map[string]string{
"empty_length": `[{"length": "", "direction": "c2s"}]`,
"zero_length": `[{"length": "0", "direction": "c2s"}]`,
"one_length": `[{"length": "1", "direction": "c2s"}]`,
"two_length": `[{"length": "2", "direction": "c2s"}]`,
"negative_length": `[{"length": "-1", "direction": "c2s"}]`,
"reversed_range": `[{"length": "64-32", "direction": "c2s"}]`,
"oversized_length": `[{"length": "8388609", "direction": "c2s"}]`,
"huge_length": `[{"length": "4294967299", "direction": "c2s"}]`,
"overflow_length": `[{"length": "9223372036854775808", "direction": "c2s"}]`,
"invalid_range_format": `[{"length": "1-2-3", "direction": "c2s"}]`,
"invalid_direction": `[{"length": "3", "direction": "invalid"}]`,
"missing_direction": `[{"length": "3"}]`,
"numeric_direction": `[{"length": "3", "direction": "1"}]`,
"negative_delay": `[{"length": "3", "direction": "c2s", "delay": "-1"}]`,
"reversed_delay": `[{"length": "3", "direction": "c2s", "delay": "10-5"}]`,
"invalid_delay_format": `[{"length": "3", "direction": "c2s", "delay": "abc"}]`,
"huge_delay": `[{"length": "3", "direction": "c2s", "delay": "9223372036854775807"}]`,
} {
t.Run(name, func(t *testing.T) {
var config XMC
if err := json.Unmarshal([]byte(`{"paddings":`+padding+`}`), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}}
if _, err := config.Build(); err == nil {
t.Fatalf("expected error for padding %s, got success", padding)
} else {
t.Logf("correctly rejected: %v", err)
}
})
}
}
func TestXMCBuildRejectsLongPassword(t *testing.T) {
profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}
// The verify token and the password share one RSA-1024 PKCS#1 v1.5 block,
// so the password cannot exceed xmc.MaxLegacyPasswordLength bytes.
valid := strings.Repeat("p", xmc.MaxLegacyPasswordLength)
if _, err := (&XMC{Password: valid, Profiles: []XMCProfile{profile}}).Build(); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", len(valid), err)
}
tooLong := valid + "p"
_, err := (&XMC{Password: tooLong, Profiles: []XMCProfile{profile}}).Build()
if err == nil || !strings.Contains(err.Error(), "longer than") {
t.Fatalf("expected a password length error, got %v", err)
}
}
+4 -4
View File
@@ -697,10 +697,10 @@ func (c *HttpUpgradeConfig) Build() (proto.Message, error) {
const (
Byte = 1
Kilobyte = 1024 * Byte
Megabyte = 1024 * Kilobyte
Gigabyte = 1024 * Megabyte
Terabyte = 1024 * Gigabyte
Kilobyte = 1000 * Byte
Megabyte = 1000 * Kilobyte
Gigabyte = 1000 * Megabyte
Terabyte = 1000 * Gigabyte
)
type Bandwidth string
+1 -1
View File
@@ -52,7 +52,7 @@ func (v *TunConfig) Build() (proto.Message, error) {
return nil, errors.New("autoSystemWfpBlockLeak needs autoSystemRoutingTable to be set")
}
if tun.BlocksSystemDNS(leaks) && len(v.DNS) == 0 {
return nil, errors.New(`autoSystemWfpBlockLeak "dns", "udp/53", "tcp/53" or "windnsclient" needs dns to be set`)
return nil, errors.New(`autoSystemWfpBlockLeak "all", "allexceptlan", "dns", "windnsclient", or TCP or UDP port 53, needs dns to be set`)
}
case "linux", "freebsd":
if v.AutoSystemDnsToGateway && len(v.Gateway) == 0 {
+49 -5
View File
@@ -29,18 +29,38 @@ func TestTunConfigAutoSystem(t *testing.T) {
{
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["dns", "misconfigtun"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853", "misconfigtun"}},
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"53", "853", "windnsclient", "misconfigtun"}},
},
{
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["DNS"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}},
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"53", "853", "windnsclient"}},
},
{
Input: `{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["TCP/853", "udp/853", "tcp/0853"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"tcp/853", "udp/853"}},
},
{
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["All", "UDP", "tcp/8000-9000", "icmp"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"all", "udp", "tcp/8000-9000", "icmp"}},
},
{
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["AllExceptLAN"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"allexceptlan", "53", "853", "windnsclient"}},
},
{
Input: `{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["1.1.1.1/24:TCP/853", "[2001:DB8::/32]:udp/10-20", "[::/0]:ICMP", "853"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"1.1.1.0/24:tcp/853", "[2001:db8::/32]:udp/10-20", "[::/0]:icmp", "853"}},
},
{
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["0.0.0.0/0:dns", "[::/0]:All", "53"]}`,
Parser: loadJSON(creator),
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"0.0.0.0/0:53", "0.0.0.0/0:853", "0.0.0.0/0:windnsclient", "[::/0]:all", "53"}},
},
})
}
@@ -57,6 +77,21 @@ func TestTunConfigAutoSystemNeeds(t *testing.T) {
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["udp/53"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["windnsclient"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["tcp/853", "udp/853"]}`, nil},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["all"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["udp"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["tcp/50-60"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["tcp/54-60", "icmp"]}`, nil},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["53"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["50-60"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["[::/0]:udp/53"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["1.1.1.1/32:dns"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["[2001:db8::/32]:all"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["0.0.0.0/0:windnsclient"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["0.0.0.0/0:tcp/853", "1.1.1.0/24:icmp", "[::/0]:misconfigtun", "54-60"]}`, nil},
{`{"name": "xray0", "autoSystemWfpBlockLeak": ["[::/0]:misconfigtun"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemWfpBlockLeak": ["all"]}`, []string{"windows"}},
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["allexceptlan"]}`, []string{"windows"}},
{`{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["allexceptlan"]}`, nil},
{`{"name": "xray0", "autoSystemDnsToGateway": true}`, []string{"linux", "freebsd"}},
} {
config := new(TunConfig)
@@ -70,12 +105,21 @@ func TestTunConfigAutoSystemNeeds(t *testing.T) {
}
func TestTunConfigAutoSystemWfpBlockLeakUnknown(t *testing.T) {
for _, value := range []string{"ip", "tcp/0", "icmp/1"} {
// With the settings the values need on Windows, so that only an unknown
// one fails.
build := func(value string) error {
config := new(TunConfig)
if err := json.Unmarshal([]byte(`{"name": "xray0", "autoSystemWfpBlockLeak": ["dns", "`+value+`"]}`), config); err != nil {
if err := json.Unmarshal([]byte(`{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["dns", "`+value+`"]}`), config); err != nil {
t.Fatal(err)
}
if _, err := config.Build(); err == nil {
_, err := config.Build()
return err
}
if err := build("1.1.1.0/24:53"); err != nil {
t.Fatal(err)
}
for _, value := range []string{"ip", "tcp/0", "tcp/0-10", "icmp/1", "udp/20-10", "0", "20-10", "53/tcp", "tcpv4", "ipv4:udp", "1.1.1.1:53", "2001:db8::/32:53", "[1.1.1.0/24]:53", "[::ffff:1.1.1.0/120]:53", "1.1.1.0/24"} {
if build(value) == nil {
t.Errorf("autoSystemWfpBlockLeak value %q was accepted", value)
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ func TestXrayConfig(t *testing.T) {
Input: `{
"log": {
"access": "/var/log/xray/access.log",
"loglevel": "error",
"logLevel": "error",
"error": "/var/log/xray/error.log"
},
"inbounds": [{
-1
View File
@@ -1,5 +1,4 @@
//go:build coveragemain
// +build coveragemain
package main
-1
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package dokodemo
-1
View File
@@ -1,5 +1,4 @@
//go:build openbsd
// +build openbsd
package dokodemo
-1
View File
@@ -1,5 +1,4 @@
//go:build !linux && !openbsd
// +build !linux,!openbsd
package dokodemo
+34 -20
View File
@@ -8,6 +8,7 @@ package freedom
import (
geodata "github.com/xtls/xray-core/common/geodata"
log "github.com/xtls/xray-core/common/log"
net "github.com/xtls/xray-core/common/net"
protocol "github.com/xtls/xray-core/common/protocol"
internet "github.com/xtls/xray-core/transport/internet"
@@ -357,7 +358,8 @@ type FinalRuleConfig struct {
Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"`
PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"`
Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"`
BlockDelay *Range `protobuf:"bytes,5,opt,name=block_delay,json=blockDelay,proto3" json:"block_delay,omitempty"`
Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"`
LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -420,13 +422,20 @@ func (x *FinalRuleConfig) GetIp() []*geodata.IPRule {
return nil
}
func (x *FinalRuleConfig) GetBlockDelay() *Range {
func (x *FinalRuleConfig) GetDelay() *Range {
if x != nil {
return x.BlockDelay
return x.Delay
}
return nil
}
func (x *FinalRuleConfig) GetLogLevel() log.Severity {
if x != nil && x.LogLevel != nil {
return *x.LogLevel
}
return log.Severity(0)
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
DomainStrategy internet.DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"domain_strategy,omitempty"`
@@ -523,7 +532,7 @@ var File_proxy_freedom_config_proto protoreflect.FileDescriptor
const file_proxy_freedom_config_proto_rawDesc = "" +
"\n" +
"\x1aproxy/freedom/config.proto\x12\x12xray.proxy.freedom\x1a!common/protocol/server_spec.proto\x1a\x1ftransport/internet/config.proto\x1a\x15common/net/port.proto\x1a\x18common/net/network.proto\x1a\x1bcommon/geodata/geodat.proto\"S\n" +
"\x1aproxy/freedom/config.proto\x12\x12xray.proxy.freedom\x1a!common/protocol/server_spec.proto\x1a\x1ftransport/internet/config.proto\x1a\x15common/net/port.proto\x1a\x18common/net/network.proto\x1a\x1bcommon/geodata/geodat.proto\x1a\x14common/log/log.proto\"S\n" +
"\x13DestinationOverride\x12<\n" +
"\x06server\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\x06server\"\x98\x02\n" +
"\bFragment\x12!\n" +
@@ -549,14 +558,16 @@ const file_proxy_freedom_config_proto_rawDesc = "" +
"\bapply_to\x18\x06 \x01(\tR\aapplyTo\"+\n" +
"\x05Range\x12\x10\n" +
"\x03min\x18\x01 \x01(\x04R\x03min\x12\x10\n" +
"\x03max\x18\x02 \x01(\x04R\x03max\"\xa0\x02\n" +
"\x03max\x18\x02 \x01(\x04R\x03max\"\xe0\x02\n" +
"\x0fFinalRuleConfig\x126\n" +
"\x06action\x18\x01 \x01(\x0e2\x1e.xray.proxy.freedom.RuleActionR\x06action\x124\n" +
"\bnetworks\x18\x02 \x03(\x0e2\x18.xray.common.net.NetworkR\bnetworks\x126\n" +
"\tport_list\x18\x03 \x01(\v2\x19.xray.common.net.PortListR\bportList\x12+\n" +
"\x02ip\x18\x04 \x03(\v2\x1b.xray.common.geodata.IPRuleR\x02ip\x12:\n" +
"\vblock_delay\x18\x05 \x01(\v2\x19.xray.proxy.freedom.RangeR\n" +
"blockDelay\"\xaf\x03\n" +
"\x02ip\x18\x04 \x03(\v2\x1b.xray.common.geodata.IPRuleR\x02ip\x12/\n" +
"\x05delay\x18\x05 \x01(\v2\x19.xray.proxy.freedom.RangeR\x05delay\x12;\n" +
"\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01B\f\n" +
"\n" +
"_log_level\"\xaf\x03\n" +
"\x06Config\x12P\n" +
"\x0fdomain_strategy\x18\x01 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0edomainStrategy\x12Z\n" +
"\x14destination_override\x18\x03 \x01(\v2'.xray.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12\x1d\n" +
@@ -599,7 +610,8 @@ var file_proxy_freedom_config_proto_goTypes = []any{
(net.Network)(0), // 8: xray.common.net.Network
(*net.PortList)(nil), // 9: xray.common.net.PortList
(*geodata.IPRule)(nil), // 10: xray.common.geodata.IPRule
(internet.DomainStrategy)(0), // 11: xray.transport.internet.DomainStrategy
(log.Severity)(0), // 11: xray.common.log.Severity
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
}
var file_proxy_freedom_config_proto_depIdxs = []int32{
7, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint
@@ -607,17 +619,18 @@ var file_proxy_freedom_config_proto_depIdxs = []int32{
8, // 2: xray.proxy.freedom.FinalRuleConfig.networks:type_name -> xray.common.net.Network
9, // 3: xray.proxy.freedom.FinalRuleConfig.port_list:type_name -> xray.common.net.PortList
10, // 4: xray.proxy.freedom.FinalRuleConfig.ip:type_name -> xray.common.geodata.IPRule
4, // 5: xray.proxy.freedom.FinalRuleConfig.block_delay:type_name -> xray.proxy.freedom.Range
11, // 6: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
1, // 7: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride
2, // 8: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment
3, // 9: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise
5, // 10: xray.proxy.freedom.Config.final_rules:type_name -> xray.proxy.freedom.FinalRuleConfig
11, // [11:11] is the sub-list for method output_type
11, // [11:11] is the sub-list for method input_type
11, // [11:11] is the sub-list for extension type_name
11, // [11:11] is the sub-list for extension extendee
0, // [0:11] is the sub-list for field type_name
4, // 5: xray.proxy.freedom.FinalRuleConfig.delay:type_name -> xray.proxy.freedom.Range
11, // 6: xray.proxy.freedom.FinalRuleConfig.log_level:type_name -> xray.common.log.Severity
12, // 7: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
1, // 8: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride
2, // 9: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment
3, // 10: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise
5, // 11: xray.proxy.freedom.Config.final_rules:type_name -> xray.proxy.freedom.FinalRuleConfig
12, // [12:12] is the sub-list for method output_type
12, // [12:12] is the sub-list for method input_type
12, // [12:12] is the sub-list for extension type_name
12, // [12:12] is the sub-list for extension extendee
0, // [0:12] is the sub-list for field type_name
}
func init() { file_proxy_freedom_config_proto_init() }
@@ -625,6 +638,7 @@ func file_proxy_freedom_config_proto_init() {
if File_proxy_freedom_config_proto != nil {
return
}
file_proxy_freedom_config_proto_msgTypes[4].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
+3 -1
View File
@@ -11,6 +11,7 @@ import "transport/internet/config.proto";
import "common/net/port.proto";
import "common/net/network.proto";
import "common/geodata/geodat.proto";
import "common/log/log.proto";
message DestinationOverride {
xray.common.protocol.ServerEndpoint server = 1;
@@ -51,7 +52,8 @@ message FinalRuleConfig {
repeated xray.common.net.Network networks = 2;
xray.common.net.PortList port_list = 3;
repeated xray.common.geodata.IPRule ip = 4;
Range block_delay = 5;
Range delay = 5;
optional xray.common.log.Severity log_level = 6;
}
message Config {
+42 -20
View File
@@ -15,6 +15,7 @@ import (
"github.com/xtls/xray-core/common/dice"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/platform"
"github.com/xtls/xray-core/common/retry"
@@ -72,23 +73,26 @@ func init() {
}
defaultBlockPrivateRule = &FinalRule{
action: RuleAction_Block,
network: allNetworks,
ip: geodata.GetPrivateIPMatcher(),
action: RuleAction_Block,
network: allNetworks,
ip: geodata.GetPrivateIPMatcher(),
logLevel: log.Severity_Warning.Enum(),
}
defaultBlockAllRule = &FinalRule{
action: RuleAction_Block,
network: allNetworks,
action: RuleAction_Block,
network: allNetworks,
logLevel: log.Severity_Warning.Enum(),
}
}
type FinalRule struct {
action RuleAction
network [8]bool
port net.MemoryPortList
ip geodata.IPMatcher
blockDelay *Range
action RuleAction
network [8]bool
port net.MemoryPortList
ip geodata.IPMatcher
delay *Range
logLevel *log.Severity
}
// Handler handles Freedom connections.
@@ -102,8 +106,9 @@ type Handler struct {
func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) {
rule := &FinalRule{
action: config.GetAction(),
blockDelay: config.GetBlockDelay(),
action: config.GetAction(),
delay: config.GetDelay(),
logLevel: config.LogLevel,
}
if len(config.Networks) == 0 {
@@ -164,7 +169,7 @@ func getDefaultFinalRule(inbound *session.Inbound) *FinalRule {
switch inbound.Name {
case "vless-reverse":
return defaultBlockAllRule
case "vless", "vmess", "trojan", "hysteria", "wireguard":
case "vless", "vmess", "trojan", "hysteria", "wireguard", "masque":
return defaultBlockPrivateRule
default:
if strings.HasPrefix(inbound.Name, "shadowsocks") {
@@ -212,12 +217,12 @@ func (h *Handler) policy() policy.Session {
return p
}
func (h *Handler) blockDelay(rule *FinalRule) time.Duration {
func (r *FinalRule) blockDuration() time.Duration {
min := uint64(30)
max := uint64(90)
if rule.blockDelay != nil {
min = rule.blockDelay.Min
max = rule.blockDelay.Max
if r.delay != nil {
min = r.delay.Min
max = r.delay.Max
}
span := max - min
if max < min {
@@ -226,9 +231,26 @@ func (h *Handler) blockDelay(rule *FinalRule) time.Duration {
return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second
}
func (r *FinalRule) log(ctx context.Context, msg ...interface{}) {
level := log.Severity_Info
if r.logLevel != nil {
level = *r.logLevel
}
switch level {
case log.Severity_Debug:
errors.LogDebug(ctx, msg...)
case log.Severity_Info:
errors.LogInfo(ctx, msg...)
case log.Severity_Warning:
errors.LogWarning(ctx, msg...)
case log.Severity_Error:
errors.LogError(ctx, msg...)
}
}
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error {
delay := h.blockDelay(rule)
errors.LogInfo(ctx, "blocked target: ", *dest, ", blackholing connection for ", delay)
delay := rule.blockDuration()
rule.log(ctx, "target blocked by a finalrule: ", *dest, ", blackholing connection for ", delay)
defer common.Close(output)
done := make(chan struct{})
go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy
@@ -240,7 +262,7 @@ func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Wr
case <-time.After(delay):
common.Interrupt(input)
common.Interrupt(output)
errors.LogInfo(ctx, "closed blackholed connection to blocked target: ", *dest)
rule.log(ctx, "closed blackholed connection to blocked target: ", *dest)
}
return nil
}
+17 -12
View File
@@ -4,7 +4,7 @@ TUN interface support bridges the gap between network layer 3 and layer 7, intro
This functionality is targeted to assist applications/end devices that don't have proxy support, or can't run external applications (like Smart TV's). Making it possible to run Xray proxy right on network edge devices (routers) with support to route raw network traffic. \
Primary targets are Linux based router devices. Like most popular OpenWRT option. \
Support for Windows, macOS, Android and iOS is also implemented (see below).
Support for Windows, macOS, FreeBSD, Android and iOS is also implemented (see below).
## PLEASE READ FOLLOWING CAREFULLY
@@ -25,6 +25,8 @@ Examples of how to achieve this on a simple Linux system (Ubuntu with systemd-ne
Packets are handled by Xray-core's own lightweight TCP/IP stack, which replaced gVisor (XTLS/Xray-core#7130).
On Linux, as on Android, the TUN can also be a file descriptor handed over through the environment variable `xray.tun.fd` (or `XRAY_TUN_FD`), e.g. for lightweight or unprivileged setups.
With `autoSystemRoutingTable`, Xray's own connections are kept out of the TUN through `autoOutboundsInterface` (then `"auto"` by default): each of their sockets is bound to another interface, the one named there, or with `"auto"` the one of the default route (Android needs the name). Linux and Android bind with `SO_BINDTODEVICE`, Windows with `IP_UNICAST_IF` and `IPV6_UNICAST_IF`, macOS and iOS with `IP_BOUND_IF` and `IPV6_BOUND_IF`, and FreeBSD switches them to another routing table (see [FreeBSD SUPPORT](#freebsd-support)). Connections to loopback addresses, TCP and UDP, stay unbound. If a socket cannot be bound, the connection fails rather than leave unbound, where it could loop back into the TUN (XTLS/Xray-core#7173).
### SYSTEM DNS ON LINUX AND FREEBSD (`autoSystemDnsToGateway`)
@@ -221,23 +223,26 @@ To make it start, wintun.dll specific for your Windows/arch must be present next
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused.
With IPv6 disabled system-wide (the `DisabledComponents` registry value), the adapter has no IPv6, and the TUN starts with IPv4 only, unless `gateway` or `autoSystemRoutingTable` has IPv6 entries, which then keep it from starting.
With IPv6 turned off by the `DisabledComponents` registry value (0x10 set, as in 0xFF), errors setting up IPv6 for `gateway`, `dns` and `autoSystemRoutingTable`, clearing the IPv6 DNS servers when `dns` has none included, are only logged. Otherwise, they keep the TUN from starting.
When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops.
When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops. Xray's own lookups through the system's DNS servers, like those of the `localhost` DNS server with `autoOutboundsInterface`, skip them, unless another interface uses them as well, as they would lead back into the TUN.
With `autoSystemWfpBlockLeak`, which needs `autoSystemRoutingTable` (the config is rejected otherwise), Xray also adds Windows Filtering Platform filters that keep traffic of every program but Xray itself from leaving outside the TUN, each kind chosen by a value in the list, e.g. `"autoSystemWfpBlockLeak": ["dns", "misconfigtun"]`:
- `"tcp/<port>"`, `"udp/<port>"`: connections to that TCP or UDP port only go through the TUN, e.g. `"tcp/853"`.
- `"windnsclient"`: Windows' DNS Client service cannot connect outside the TUN at all, except for name resolution on the local network (LLMNR, mDNS). On Windows 11 and Server 2022 and later, it may send name queries over HTTPS or TLS, to any port. Earlier versions only query port 53, so there it does nothing.
- `"dns"`: stands for `"udp/53"`, `"tcp/53"`, `"windnsclient"`, `"tcp/853"` (DNS over TLS) and `"udp/853"` (DNS over QUIC). Windows keeps sending name queries to the DNS servers of the other interfaces as well, out through those interfaces whatever the routes say, and other programs reach a resolver on the local network (e.g. `192.168.1.1` handed out by DHCP) through its more specific LAN route instead of the TUN. Keeping the system's DNS inside the TUN like this, with `"dns"`, `"udp/53"`, `"tcp/53"` or `"windnsclient"`, needs `dns` (the config is rejected otherwise). The `dns` servers then have to lie within `gateway` or `autoSystemRoutingTable` (a warning is logged otherwise), and DNS servers that should be reached directly belong in Xray's own `dns` settings.
- `"misconfigtun"`: an IP version without routes in `autoSystemRoutingTable`, IPv4 or IPv6, is blocked entirely, in both directions, as it would bypass the TUN. Only loopback and what Windows itself needs on the local link (DHCP, and for IPv6 neighbor and multicast listener discovery) remain allowed. An address of that version in `gateway` is not needed: without one, Windows gives the TUN link-local addresses itself, an IPv6 one at once and an IPv4 one from `169.254.0.0/16` after some seconds (until then, IPv4 routed to the TUN is unreachable), and what is routed to the TUN goes through it with those.
Setting `autoSystemWfpBlockLeak` to at least `["dns", "misconfigtun"]` is recommended, to block DNS leaks and the traffic of an IP version without routes. It needs `autoSystemRoutingTable` (the config is rejected otherwise), and adds Windows Filtering Platform filters that let traffic of every program but Xray itself leave only through the TUN, each kind chosen by a value:
- `"dns"`: stands for `"53"`, `"853"` (DNS over TLS and QUIC) and `"windnsclient"`. Windows also queries the DNS servers of the other interfaces, through those interfaces whatever the routes say, and other programs reach a resolver on the local network (e.g. `192.168.1.1` from DHCP) through its more specific route.
- `"windnsclient"`: Windows' DNS Client service, except for name resolution on the local network (LLMNR, mDNS). Since Windows 11 and Server 2022, it may query over HTTPS or TLS, to any port; earlier versions only query port 53, so there it does nothing.
- `"tcp"`, `"udp"`: that protocol, to all ports, or with `/<port>` or `/<low>-<high>` (1 to 65535) to some, e.g. `"tcp/853"` or `"udp/10-20"`. The ports alone stand for both, e.g. `"53"` or `"10-20"`.
- `"icmp"`: ICMP and ICMPv6, e.g. `ping`.
- `"misconfigtun"`: an IP version without routes in `autoSystemRoutingTable`, which would bypass the TUN. With IPv6 turned off by `DisabledComponents`, it covers IPv6 whatever the routes, as IPv6 setup errors are then only logged, and IPv6 still works until the reboot that applies the value.
- `"all"`: everything, in both directions. Access to the local network then breaks unless it is routed into the TUN as well, and so do incoming connections to other programs, other VPNs, and virtual machines whose NAT runs on the host.
- `"allexceptlan"`: like `"all"`, but traffic to and from the local network stays allowed, e.g. for printers or casting to a TV: private, link-local, multicast and broadcast addresses (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `224.0.0.0/4`, `255.255.255.255`, `fc00::/7`, `fe80::/10`, `ff00::/8`), not global IPv6 ones. It includes `"dns"`, and the other values apply there as well. `"all"` overrides it.
With the filters in place, Xray's own connections out also get past Windows Firewall's block rules (other firewalls may still block them), while connections to Xray's inbounds stay subject to them.
A CIDR in front limits a value to its addresses, an IPv6 one in brackets, e.g. `"8.8.8.8/32:all"`, `"1.1.1.0/24:53"` or `"[::/0]:all"` (IPv6 only). It limits what the value stands for or includes as well: `"0.0.0.0/0:allexceptlan"`, for instance, leaves DNS over IPv6 open.
Names that Xray resolves through the system resolver, such as an outbound's server address given as a domain with the default `AsIs` domain strategy, would be looked up by Windows on Xray's behalf, and those queries would then go into the TUN too. While DNS is restricted this way and `autoOutboundsInterface` is in use (the default with `autoSystemRoutingTable`), Xray therefore resolves them itself, with its own queries to the DNS servers of the other interfaces. That bypasses Windows' DNS cache, and its name resolution on the local network (LLMNR, mDNS): a server address given as a domain is looked up again for every connection, and a DNS server that does not answer delays each lookup. Having Xray's own `dns` resolve it, through the outbound's `sockopt.domainStrategy`, avoids that. The `localhost` DNS server queries the same servers whenever `autoOutboundsInterface` is in use. Both skip the TUN's own DNS servers, unless another interface uses them as well: queried from Xray itself, they would lead back into it, or nowhere.
Loopback, DHCP, DHCPv6 and IPv6 neighbor discovery always stay allowed. Xray's own connections out also get past Windows Firewall's block rules, while connections to its inbounds stay subject to them. If the filters cannot be added, Xray does not start; they are removed when it exits. `"dns"` leaves name resolution on the local network (LLMNR, mDNS, NetBIOS) alone; `"all"` or `"udp"`, for instance, block it as well.
If the filters cannot be added, Xray does not start. They are removed when Xray exits. Not covered is name resolution on the local network (LLMNR, mDNS, NetBIOS), except over an IP version that is blocked.
Keeping the system's DNS inside the TUN, with `"all"`, `"allexceptlan"`, `"dns"`, `"windnsclient"`, or anything covering TCP or UDP port 53, even to some addresses only, needs `dns` (the config is rejected otherwise), whose servers have to lie within `gateway` or `autoSystemRoutingTable`, or be loopback addresses like `127.0.0.1` (a warning is logged otherwise); DNS servers to be reached directly belong in Xray's own `dns` settings. With `autoOutboundsInterface`, names that Xray would look up through the system, e.g. an outbound's server address with the default `AsIs` domain strategy, are then resolved by Xray itself, from the DNS servers of the other interfaces, as Windows would send those queries into the TUN. That bypasses Windows' DNS cache, so such a name is looked up for every connection; resolving it with Xray's own `dns`, through the outbound's `sockopt.domainStrategy`, avoids that.
`autoSystemWfpBlockLeak` (Windows only) is empty by default, as the filters break some setups: with `"dns"`, a local DNS resolver other programs use (e.g. on `127.0.0.1:53`), the DNS of another VPN on its own interface, virtual machines whose NAT resolves names on the host, or signing in to a captive portal; with `"misconfigtun"`, IPv4 or IPv6 on the local network while no route of that version leads to the TUN. Without the filters, DNS may leak as described above. To keep an IP version out of the TUN on purpose while still blocking DNS leaks, use only `["dns"]`.
`autoSystemWfpBlockLeak` is empty by default, as the filters break some setups: with `"dns"`, a local DNS resolver that queries through another interface, the DNS of another VPN, virtual machines whose NAT resolves names on the host, and captive portals; with `"misconfigtun"`, IPv4 or IPv6 on the local network while not routed into the TUN.
`autoOutboundsInterface` (the default with `autoSystemRoutingTable`) keeps Xray's own connections out of the TUN by binding them to another interface, which Windows only honors while that interface has weak host send and forwarding off for the IP versions routed to the TUN. Otherwise, Windows sends them into the TUN, from that interface's address, and they stall. While the TUN runs, Xray therefore turns weak host send off on that interface, and on again when it stops or another interface takes over. Forwarding cannot be turned off this way, as Mobile Hotspot and Internet Connection Sharing need it, so a warning is logged while it is on. Having the hotspot share the TUN instead of that interface (Settings, Mobile hotspot, Share my internet connection from) moves forwarding to the TUN, where it does no harm, and sends the hotspot's devices through Xray as well.
+63 -23
View File
@@ -23,6 +23,7 @@ import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/transport/internet"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
"golang.zx2c4.com/wintun"
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
)
@@ -98,6 +99,19 @@ func open(name, desc string) (*wintun.Adapter, error) {
return nil, err
}
// ipv6Off tells whether DisabledComponents turns IPv6 off on the non-tunnel
// interfaces (0x10, as 0xFF does), the TUN among them. Windows applies it at
// boot only.
func ipv6Off() bool {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters`, registry.QUERY_VALUE)
if err != nil {
return false
}
defer key.Close()
value, _, err := key.GetIntegerValue("DisabledComponents")
return err == nil && value&0x10 != 0
}
func (t *WindowsTun) Start() (err error) {
var address4, address6 bool
addresses := make([]netip.Prefix, 0, len(t.options.Gateway))
@@ -139,6 +153,17 @@ func (t *WindowsTun) Start() (err error) {
routesData = append(routesData, &r)
}
// With IPv6 off by DisabledComponents, setting it up may fail, clearing
// its DNS servers too, which is then only logged.
off6 := ipv6Off()
ignored := func(family winipcfg.AddressFamily, err error) bool {
if family != windows.AF_INET6 || !off6 {
return false
}
errors.LogErrorInner(context.Background(), err, "[tun] ignored, as DisabledComponents turns IPv6 off")
return true
}
var retryTimes int
var firstErr error
startOver:
@@ -155,6 +180,9 @@ startOver:
err = t.luid.SetRoutesForFamily(family, routesData)
if err != nil {
firstErr = errors.New("unable to set routes").Base(err)
if ignored(family, firstErr) {
continue
}
if err == windows.ERROR_NOT_FOUND {
goto startOver
}
@@ -165,6 +193,9 @@ startOver:
err = t.luid.SetIPAddressesForFamily(family, addresses)
if err != nil {
firstErr = errors.New("unable to set ips").Base(err)
if ignored(family, firstErr) {
continue
}
if err == windows.ERROR_NOT_FOUND {
goto startOver
}
@@ -173,9 +204,7 @@ startOver:
}
ipif, err := t.luid.IPInterface(family)
if err != nil {
// With IPv6 disabled system-wide (DisabledComponents), the adapter has no
// IPv6 interface at all. Skip the family unless the config asks for it.
if err == windows.ERROR_NOT_FOUND && family == windows.AF_INET6 && !address6 && !route6 {
if ignored(family, errors.New("unable to get the interface").Base(err)) {
continue
}
return err
@@ -194,6 +223,9 @@ startOver:
err = ipif.Set()
if err != nil {
firstErr = errors.New("unable to set metric and MTU").Base(err)
if ignored(family, firstErr) {
continue
}
if err == windows.ERROR_NOT_FOUND {
goto startOver
}
@@ -202,6 +234,9 @@ startOver:
err = t.luid.SetDNS(family, dns, nil)
if err != nil {
firstErr = errors.New("unable to set DNS").Base(err)
if ignored(family, firstErr) {
continue
}
if err == windows.ERROR_NOT_FOUND {
goto startOver
}
@@ -247,18 +282,25 @@ startOver:
}
// With autoSystemWfpBlockLeak, once the system routes lead to the TUN,
// keep connections to the ports given ("dns" stands for those of DNS),
// Windows' DNS Client service, and an IP version no route of which leads
// to the TUN ("misconfigtun"), from leaving through the other interfaces.
// Addresses do not matter: without one of a version in gateway, Windows
// gives the TUN a link-local one.
// keep the protocols and ports given ("dns" stands for those of DNS),
// Windows' DNS Client service, an IP version no route of which leads to
// the TUN ("misconfigtun"), or everything ("all", or "allexceptlan" but
// for the local network), to the addresses of a CIDR or to all, from
// leaving through the other interfaces. The TUN's own addresses do not
// matter: without one of a version in gateway, Windows gives it a
// link-local one.
leaks, err := ExpandWfpBlockLeak(t.options.AutoSystemWfpBlockLeak)
if err != nil {
return err
}
block := newLeakFilters(leaks, route4, route6)
// With IPv6 off by DisabledComponents, IPv6 setup failures are only logged,
// and IPv6 still works until the reboot that applies it. So "misconfigtun"
// then blocks IPv6 outside the TUN whatever the routes.
block := newLeakFilters(leaks, route4, route6 && !off6)
if route4 || route6 {
if slices.Contains(leaks, "windnsclient") && !block.dnsClient {
dnsClient := func(l leak) bool { return l.name == "windnsclient" }
if slices.ContainsFunc(block, dnsClient) && !dnsClientUsesAnyPort() {
block = slices.DeleteFunc(block, dnsClient)
errors.LogInfo(context.Background(), "[tun] windnsclient skipped: before Windows 11 and Server 2022, the DNS Client service only queries port 53")
}
if block.systemDNS() && len(dns) == 0 {
@@ -271,19 +313,17 @@ startOver:
return errors.New("unable to block ", blocked, " outside the TUN (remove autoSystemWfpBlockLeak to run without)").Base(err)
}
errors.LogInfo(context.Background(), "[tun] blocked outside the TUN: ", blocked)
if block.systemDNS() {
covered := slices.Clone(addresses)
for _, route := range routesData {
covered = append(covered, route.Destination)
}
for _, server := range dnsOutsideTUN(dns, covered) {
errors.LogWarning(context.Background(), "[tun] DNS server ", server, " is in neither gateway nor autoSystemRoutingTable, so queries to it cannot go through the TUN and are blocked")
}
// With updater, the dialer controllers bind Xray's own sockets
// to the physical interface.
if updater != nil {
t.resolver = resolveOnOwn()
}
covered := slices.Clone(addresses)
for _, route := range routesData {
covered = append(covered, route.Destination)
}
for _, server := range dnsOutsideTUN(dns, covered, block) {
errors.LogWarning(context.Background(), "[tun] DNS server ", server, " is in neither gateway nor autoSystemRoutingTable, so queries to it cannot go through the TUN and are blocked")
}
// With updater, the dialer controllers bind Xray's own sockets to the
// physical interface.
if block.systemDNS() && updater != nil {
t.resolver = resolveOnOwn()
}
}
if len(dns) > 0 || route4 || route6 {
+325 -158
View File
@@ -3,6 +3,7 @@
package tun
import (
"encoding/binary"
"net/netip"
"os"
"runtime"
@@ -37,15 +38,19 @@ const (
fwpmSessionFlagDynamic = 1 // FWPM_SESSION_FLAG_DYNAMIC
fwpmFilterFlagClearActionRight = 8 // FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT
fwpUint8 = 1 // FWP_UINT8
fwpUint16 = 2 // FWP_UINT16
fwpUint32 = 3 // FWP_UINT32
fwpUint64 = 4 // FWP_UINT64
fwpByteArray16Type = 11 // FWP_BYTE_ARRAY16_TYPE
fwpByteBlobType = 12 // FWP_BYTE_BLOB_TYPE
fwpSecurityDescriptorType = 14 // FWP_SECURITY_DESCRIPTOR_TYPE
fwpUint8 = 1 // FWP_UINT8
fwpUint16 = 2 // FWP_UINT16
fwpUint32 = 3 // FWP_UINT32
fwpUint64 = 4 // FWP_UINT64
fwpByteArray16Type = 11 // FWP_BYTE_ARRAY16_TYPE
fwpByteBlobType = 12 // FWP_BYTE_BLOB_TYPE
fwpSecurityDescriptorType = 14 // FWP_SECURITY_DESCRIPTOR_TYPE
fwpV4AddrMask = 0x100 // FWP_V4_ADDR_MASK
fwpV6AddrMask = 0x101 // FWP_V6_ADDR_MASK
fwpRangeType = 0x102 // FWP_RANGE_TYPE
fwpMatchEqual = 0 // FWP_MATCH_EQUAL
fwpMatchRange = 5 // FWP_MATCH_RANGE
fwpMatchFlagsAllSet = 6 // FWP_MATCH_FLAGS_ALL_SET
fwpConditionFlagIsLoopback = 1 // FWP_CONDITION_FLAG_IS_LOOPBACK
@@ -94,6 +99,37 @@ type fwpValue0 struct {
value uintptr
}
// fwpRange0 is FWP_RANGE0, which an FWP_RANGE_TYPE condition points to.
type fwpRange0 struct {
low, high fwpValue0
}
// fwpV4AddrAndMask is FWP_V4_ADDR_AND_MASK, in host byte order.
type fwpV4AddrAndMask struct {
addr, mask uint32
}
// fwpV6AddrAndMask is FWP_V6_ADDR_AND_MASK.
type fwpV6AddrAndMask struct {
addr [16]byte
prefixLength uint8
}
// lanPrefixes are what "allexceptlan" leaves to the local network: private
// and link-local addresses, and multicast and broadcast, which discovery on
// it uses.
var lanPrefixes = []netip.Prefix{
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("255.255.255.255/32"),
netip.MustParsePrefix("fc00::/7"),
netip.MustParsePrefix("fe80::/10"),
netip.MustParsePrefix("ff00::/8"),
}
type fwpmDisplayData0 struct {
name *uint16
description *uint16
@@ -171,27 +207,36 @@ func condition(field *windows.GUID, typ uint32, value uintptr) fwpmFilterConditi
}
}
// leakFilters is what blockLeaks keeps from leaving outside the TUN.
type leakFilters struct {
ports []leakPort // connections to these ports
dnsClient bool // Windows' DNS Client service
ipv4, ipv6 bool // an IP version altogether
}
// leakFilters are the values of autoSystemWfpBlockLeak that blockLeaks keeps
// from leaving outside the TUN.
type leakFilters []leak
// newLeakFilters turns expanded autoSystemWfpBlockLeak values into the filters
// for a TUN that the routes of route4 (IPv4) and route6 (IPv6) lead to.
// for a TUN that the routes of route4 (IPv4) and route6 (IPv6) lead to, which
// leave "misconfigtun" over the IP versions without such routes only.
func newLeakFilters(leaks []string, route4, route6 bool) leakFilters {
var block leakFilters
for _, leak := range leaks {
switch leak {
case "windnsclient":
block.dnsClient = dnsClientUsesAnyPort()
case "misconfigtun":
block.ipv4, block.ipv6 = !route4, !route6
default:
if port, ok := parseLeakPort(leak); ok {
block.ports = append(block.ports, port)
for _, value := range leaks {
l, ok := parseLeak(value)
if !ok {
continue
}
if l.name == "misconfigtun" {
unrouted4, unrouted6 := !route4, !route6
if l.prefix.IsValid() {
unrouted4, unrouted6 = unrouted4 && l.prefix.Addr().Is4(), unrouted6 && l.prefix.Addr().Is6()
}
switch {
case !unrouted4 && !unrouted6:
continue
case !l.prefix.IsValid() && !unrouted4:
l.prefix = allAddresses(true)
case !l.prefix.IsValid() && !unrouted6:
l.prefix = allAddresses(false)
}
}
if !slices.Contains(block, l) {
block = append(block, l)
}
}
return block
@@ -199,24 +244,69 @@ func newLeakFilters(leaks []string, route4, route6 bool) leakFilters {
// String lists what block keeps inside the TUN, or is empty for nothing.
func (block leakFilters) String() string {
var blocked []string
for _, port := range block.ports {
blocked = append(blocked, port.String())
values := make([]string, len(block))
for i, l := range block {
values[i] = l.String()
}
for _, b := range []struct {
on bool
what string
}{{block.dnsClient, "windnsclient"}, {block.ipv4, "IPv4"}, {block.ipv6, "IPv6"}} {
if b.on {
blocked = append(blocked, b.what)
}
}
return strings.Join(blocked, ", ")
return strings.Join(values, ", ")
}
// systemDNS tells whether block keeps the system's DNS inside the TUN.
// systemDNS tells whether block keeps the system's DNS inside the TUN, to at
// least some addresses: port 53, the DNS Client service, or everything ("all"),
// though not everything but the local network ("allexceptlan"), where a
// resolver like the router's may be.
func (block leakFilters) systemDNS() bool {
return block.dnsClient || slices.ContainsFunc(block.ports, func(port leakPort) bool { return port.port == 53 })
return slices.ContainsFunc(block, leak.blocksDNS)
}
// prefixes returns the CIDRs of the values of block named name over an IP
// version.
func (block leakFilters) prefixes(name string, ipv6 bool) []netip.Prefix {
var prefixes []netip.Prefix
for _, l := range block {
if prefix, ok := l.over(ipv6); ok && l.name == name {
prefixes = append(prefixes, prefix)
}
}
return prefixes
}
// over returns the CIDR of l over an IP version, all its addresses for l
// without one, or false for l over the other IP version only.
func (l leak) over(ipv6 bool) (netip.Prefix, bool) {
if !l.prefix.IsValid() {
return allAddresses(ipv6), true
}
return l.prefix, l.prefix.Addr().Is6() == ipv6
}
// allAddresses is the CIDR of all addresses of an IP version.
func allAddresses(ipv6 bool) netip.Prefix {
if ipv6 {
return netip.PrefixFrom(netip.IPv6Unspecified(), 0)
}
return netip.PrefixFrom(netip.IPv4Unspecified(), 0)
}
// lanWithin returns the parts of lanPrefixes that lie in any of prefixes: two
// prefixes either share no address, or one holds the other.
func lanWithin(prefixes ...netip.Prefix) []netip.Prefix {
var parts []netip.Prefix
for _, lan := range lanPrefixes {
for _, prefix := range prefixes {
if !prefix.Overlaps(lan) {
continue
}
part := lan
if prefix.Bits() > lan.Bits() {
part = prefix
}
if !slices.Contains(parts, part) {
parts = append(parts, part)
}
}
}
return parts
}
// dnsClientUsesAnyPort tells whether Windows' DNS Client service may send its
@@ -229,31 +319,49 @@ func dnsClientUsesAnyPort() bool {
return build >= 20348
}
// The weights of the filters of blockLeaks, the heaviest matching one of which
// decides.
const (
weightAllExceptLAN uint8 = iota // block "allexceptlan"
weightLAN // permit its local network
weightDNSClient // block "windnsclient"
weightLocalLink // permit its mDNS and LLMNR on the local network
weightBlock // block the other values
weightPermit // permit what always stays allowed, and the TUN
weightXray // permit Xray
)
// blockLeaks keeps traffic from leaving through interfaces other than tun,
// for every program but Xray itself, whose outbounds (DNS included) use the
// other interfaces on purpose:
// other interfaces on purpose, as the values of block say, each to the
// addresses of its CIDR, or to all:
//
// - ports: connections to these TCP or UDP ports may only go through the
// TUN, those of DNS (53), DNS over TLS (TCP 853) and DNS over QUIC (UDP
// 853) with "dns". Windows sends a name query to the DNS servers of all
// interfaces, not only to those of the TUN: to the first server of each
// interface, then to all of them when no answer arrives within a second or
// two. It sends the queries for the servers of an interface out through
// that interface, whatever the routes say, and other programs reach an
// on-link resolver, like 192.168.1.1 from DHCP, through its LAN route,
// which is more specific than the TUN's default route.
// - dnsClient: since Windows 11 and Server 2022, Windows may also send its
// queries over HTTPS or TLS, to any port, so its DNS Client service may not
// connect outside the TUN at all, except for name resolution on the local
// link (mDNS, LLMNR).
// - ipv4, ipv6: no IPv4, or no IPv6, at all, in either direction, for a TUN
// that no route of it leads to, except loopback and what Windows itself
// needs on the local link (DHCP, and for IPv6 neighbor and multicast
// listener discovery), none of which can leave it. The TUN carries what
// is routed to it even without an address of that IP version in gateway:
// Windows gives it link-local ones itself, an IPv6 one at once, an IPv4
// one from 169.254.0.0/16 after some seconds (until then, IPv4 routed to
// the TUN is unreachable).
// - Protocols and ports: connections of these, TCP or UDP to some or all
// ports, or ICMP, may only go through the TUN, those of DNS (53), DNS
// over TLS (TCP 853) and DNS over QUIC (UDP 853) with "dns". Windows
// sends a name query to the DNS servers of all interfaces, not only to
// those of the TUN: to the first server of each interface, then to all
// of them when no answer arrives within a second or two. It sends the
// queries for the servers of an interface out through that interface,
// whatever the routes say, and other programs reach an on-link resolver,
// like 192.168.1.1 from DHCP, through its LAN route, which is more
// specific than the TUN's default route.
// - "windnsclient": since Windows 11 and Server 2022, Windows may also send
// its queries over HTTPS or TLS, to any port, so its DNS Client service
// may not connect outside the TUN at all, except for name resolution on
// the local network (mDNS, LLMNR).
// - "all", and "misconfigtun" over an IP version no route of which leads to
// the TUN: nothing at all outside the TUN, in either direction. The TUN
// carries what is routed to it even without an address of that IP
// version in gateway: Windows gives it link-local ones itself, an IPv6
// one at once, an IPv4 one from 169.254.0.0/16 after some seconds (until
// then, IPv4 routed to the TUN is unreachable).
// - "allexceptlan": the same, but to and from the local network.
//
// The other values still apply to what "allexceptlan" and "windnsclient" leave
// open on the local network. Whatever is blocked, loopback, which cannot leave
// the system, and what Windows itself needs on the local link stay allowed:
// DHCP, and for IPv6 neighbor and multicast listener discovery.
//
// The filters live in a dynamic WFP session: closing the returned engine handle
// with closeWFPEngine deletes them, and so does Windows when the process dies.
@@ -354,33 +462,149 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
onTUN := func(field *windows.GUID) fwpmFilterCondition0 {
return condition(field, fwpUint64, uintptr(unsafe.Pointer(tunLUID)))
}
// remote matches the remote addresses in any of prefixes, all of one IP
// version: conditions on the same field match when any of them does. With
// all addresses among them, no condition is needed.
remote := func(prefixes ...netip.Prefix) []fwpmFilterCondition0 {
if slices.ContainsFunc(prefixes, func(prefix netip.Prefix) bool { return prefix.Bits() == 0 }) {
return nil
}
var conditions []fwpmFilterCondition0
for _, prefix := range prefixes {
var value uintptr
typ := uint32(fwpV4AddrMask)
if prefix.Addr().Is6() {
addr := &fwpV6AddrAndMask{addr: prefix.Addr().As16(), prefixLength: uint8(prefix.Bits())}
pinner.Pin(addr) // the condition only holds it as uintptr
value, typ = uintptr(unsafe.Pointer(addr)), fwpV6AddrMask
} else {
a := prefix.Addr().As4()
addr := &fwpV4AddrAndMask{addr: binary.BigEndian.Uint32(a[:]), mask: ^uint32(0) << (32 - prefix.Bits())}
pinner.Pin(addr) // the condition only holds it as uintptr
value = uintptr(unsafe.Pointer(addr))
}
conditions = append(conditions, condition(&fwpmConditionIPRemoteAddress, typ, value))
}
return conditions
}
// toPorts matches the ports of traffic, if not all of them.
toPorts := func(traffic leak) []fwpmFilterCondition0 {
switch {
case traffic.low == 0:
return nil
case traffic.low == traffic.high:
return []fwpmFilterCondition0{condition(&fwpmConditionIPRemotePort, fwpUint16, uintptr(traffic.low))}
}
ports := &fwpRange0{
low: fwpValue0{typ: fwpUint16, value: uintptr(traffic.low)},
high: fwpValue0{typ: fwpUint16, value: uintptr(traffic.high)},
}
pinner.Pin(ports) // the condition only holds it as uintptr
return []fwpmFilterCondition0{{
fieldKey: fwpmConditionIPRemotePort,
matchType: fwpMatchRange,
conditionValue: fwpValue0{typ: fwpRangeType, value: uintptr(unsafe.Pointer(ports))},
}}
}
// What stays allowed whatever is blocked, in both directions: replies to
// a connection accepted from outside would leave through the physical
// link as well.
type permit struct {
name string
conditions []fwpmFilterCondition0
}
loopback := permit{"loopback", []fwpmFilterCondition0{{
fieldKey: fwpmConditionFlags,
matchType: fwpMatchFlagsAllSet,
conditionValue: fwpValue0{typ: fwpUint32, value: fwpConditionFlagIsLoopback},
}}}
// DHCP keeps the addresses of the other interfaces, which Xray's own
// connections use.
dhcp := permit{"DHCP", []fwpmFilterCondition0{
condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_UDP),
condition(&fwpmConditionIPLocalPort, fwpUint16, 68),
condition(&fwpmConditionIPRemotePort, fwpUint16, 67),
}}
// Neighbor and multicast listener discovery, ICMPv6 130-137 and 143,
// whose type and code sit where the local and remote port are.
discovery := permit{"IPv6 neighbor and multicast listener discovery", []fwpmFilterCondition0{condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_ICMPV6)}}
for _, typ := range []uintptr{130, 131, 132, 133, 134, 135, 136, 137, 143} {
discovery.conditions = append(discovery.conditions, condition(&fwpmConditionIPLocalPort, fwpUint16, typ))
}
discovery.conditions = append(discovery.conditions, condition(&fwpmConditionIPRemotePort, fwpUint16, 0))
dhcpv6 := []fwpmFilterCondition0{
condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_UDP),
condition(&fwpmConditionIPLocalPort, fwpUint16, 546),
condition(&fwpmConditionIPRemotePort, fwpUint16, 547),
}
// The DHCPv6 client sends to the servers' multicast address, and they
// answer from their own.
dhcpv6Out := permit{"DHCPv6", slices.Concat(dhcpv6, []fwpmFilterCondition0{condition(&fwpmConditionIPRemoteAddress, fwpByteArray16Type, uintptr(unsafe.Pointer(&ipv6AllDHCPv6Servers)))})}
dhcpv6In := permit{"DHCPv6", dhcpv6}
for _, layer := range []struct {
key *windows.GUID
selfFlags uint32
via *windows.GUID // the interface that has to be the TUN as well
ipv6 bool
permits []permit
}{
{&fwpmLayerALEAuthConnectV4, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface},
{&fwpmLayerALEAuthRecvAcceptV4, 0, &fwpmConditionIPArrivalInterface},
{&fwpmLayerALEAuthConnectV6, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface},
{&fwpmLayerALEAuthRecvAcceptV6, 0, &fwpmConditionIPArrivalInterface},
{&fwpmLayerALEAuthConnectV4, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface, false, []permit{loopback, dhcp}},
{&fwpmLayerALEAuthRecvAcceptV4, 0, &fwpmConditionIPArrivalInterface, false, []permit{loopback, dhcp}},
{&fwpmLayerALEAuthConnectV6, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface, true, []permit{loopback, discovery, dhcpv6Out}},
{&fwpmLayerALEAuthRecvAcceptV6, 0, &fwpmConditionIPArrivalInterface, true, []permit{loopback, discovery, dhcpv6In}},
} {
if err := add(layer.key, "permit Xray", layer.selfFlags, fwpActionPermit, 4, self); err != nil {
throughTUN := permit{"through the TUN", []fwpmFilterCondition0{onTUN(&fwpmConditionIPLocalInterface), onTUN(layer.via)}}
if err := add(layer.key, "permit Xray", layer.selfFlags, fwpActionPermit, weightXray, self); err != nil {
return err
}
for _, port := range block.ports {
protocol := uintptr(windows.IPPROTO_UDP)
if port.tcp {
protocol = windows.IPPROTO_TCP
}
toPort := []fwpmFilterCondition0{
condition(&fwpmConditionIPProtocol, fwpUint8, protocol),
condition(&fwpmConditionIPRemotePort, fwpUint16, uintptr(port.port)),
}
throughTUN := slices.Concat(toPort, []fwpmFilterCondition0{onTUN(&fwpmConditionIPLocalInterface), onTUN(layer.via)})
if err := add(layer.key, "permit "+port.String()+" through the TUN", 0, fwpActionPermit, 3, throughTUN...); err != nil {
for _, p := range append(layer.permits, throughTUN) {
if err := add(layer.key, "permit "+p.name, 0, fwpActionPermit, weightPermit, p.conditions...); err != nil {
return err
}
if err := add(layer.key, "block "+port.String(), 0, fwpActionBlock, 2, toPort...); err != nil {
}
for _, l := range block {
prefix, ok := l.over(layer.ipv6)
if !ok {
continue // for the other IP version only
}
var protocols []uintptr
switch l.name {
case "tcp":
protocols = []uintptr{windows.IPPROTO_TCP}
case "udp":
protocols = []uintptr{windows.IPPROTO_UDP}
case "":
protocols = []uintptr{windows.IPPROTO_TCP, windows.IPPROTO_UDP}
case "icmp":
protocols = []uintptr{windows.IPPROTO_ICMP}
if layer.ipv6 {
protocols = []uintptr{windows.IPPROTO_ICMPV6}
}
case "all", "misconfigtun":
// every protocol
default:
continue // "allexceptlan" and "windnsclient" have filters of their own
}
var matches []fwpmFilterCondition0
for _, protocol := range protocols {
matches = append(matches, condition(&fwpmConditionIPProtocol, fwpUint8, protocol))
}
matches = slices.Concat(matches, toPorts(l), remote(prefix))
if err := add(layer.key, "block "+l.String(), 0, fwpActionBlock, weightBlock, matches...); err != nil {
return err
}
}
if allExceptLAN := block.prefixes("allexceptlan", layer.ipv6); len(allExceptLAN) > 0 {
// Lighter than the other values, which so still apply on the
// local network, DNS with "allexceptlan" among them.
if lan := lanWithin(allExceptLAN...); len(lan) > 0 {
if err := add(layer.key, "permit the local network", 0, fwpActionPermit, weightLAN, remote(lan...)...); err != nil {
return err
}
}
if err := add(layer.key, "block allexceptlan", 0, fwpActionBlock, weightAllExceptLAN, remote(allExceptLAN...)...); err != nil {
return err
}
}
@@ -389,12 +613,11 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
// Since Windows 11 and Server 2022, the DNS Client service may also send
// the queries for an interface's servers over HTTPS or TLS, out through
// that interface and to any port. So there it may only connect through
// the TUN, except for mDNS and LLMNR, which stay on the local link (over
// an IP version only while it is not blocked altogether). Like Windows
// the TUN, except for mDNS and LLMNR on the local network. Like Windows
// Firewall's rules for it, the filters recognize the service by its SID,
// which Windows puts in the token of its process: the security descriptor
// grants that SID the right to match (FWP_ACTRL_MATCH_FILTER, CC in SDDL).
if block.dnsClient {
if slices.ContainsFunc(block, func(l leak) bool { return l.name == "windnsclient" }) {
sd, err := windows.SecurityDescriptorFromString("O:SYG:SYD:(A;;CCRC;;;" + dnsClientSID + ")")
if err != nil {
return err
@@ -405,85 +628,20 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
// Conditions on the same field match when any of them does.
mdnsLLMNR := []fwpmFilterCondition0{dnsClient, condition(&fwpmConditionIPRemotePort, fwpUint16, 5353), condition(&fwpmConditionIPRemotePort, fwpUint16, 5355)}
for _, layer := range []struct {
key *windows.GUID
localLink bool
key *windows.GUID
ipv6 bool
}{
{&fwpmLayerALEAuthConnectV4, !block.ipv4},
{&fwpmLayerALEAuthConnectV6, !block.ipv6},
{&fwpmLayerALEAuthConnectV4, false},
{&fwpmLayerALEAuthConnectV6, true},
} {
if err := add(layer.key, "permit the DNS Client service through the TUN", 0, fwpActionPermit, 3, dnsClient, onTUN(&fwpmConditionIPLocalInterface), onTUN(&fwpmConditionIPNexthopInterface)); err != nil {
prefixes := block.prefixes("windnsclient", layer.ipv6)
if len(prefixes) == 0 {
continue
}
if err := add(layer.key, "permit the DNS Client service's mDNS and LLMNR", 0, fwpActionPermit, weightLocalLink, slices.Concat(mdnsLLMNR, remote(lanWithin(allAddresses(layer.ipv6))...))...); err != nil {
return err
}
if layer.localLink {
if err := add(layer.key, "permit the DNS Client service's mDNS and LLMNR", 0, fwpActionPermit, 3, mdnsLLMNR...); err != nil {
return err
}
}
if err := add(layer.key, "block the DNS Client service", 0, fwpActionBlock, 2, dnsClient); err != nil {
return err
}
}
}
// Both directions: replies to a connection accepted from outside would
// leave through the physical link as well.
loopback := fwpmFilterCondition0{
fieldKey: fwpmConditionFlags,
matchType: fwpMatchFlagsAllSet,
conditionValue: fwpValue0{typ: fwpUint32, value: fwpConditionFlagIsLoopback},
}
if block.ipv4 {
// DHCP keeps the addresses of the other interfaces, which Xray's own
// connections use.
dhcp := []fwpmFilterCondition0{
condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_UDP),
condition(&fwpmConditionIPLocalPort, fwpUint16, 68),
condition(&fwpmConditionIPRemotePort, fwpUint16, 67),
}
for _, layer := range []*windows.GUID{&fwpmLayerALEAuthConnectV4, &fwpmLayerALEAuthRecvAcceptV4} {
if err := add(layer, "permit IPv4 loopback", 0, fwpActionPermit, 1, loopback); err != nil {
return err
}
if err := add(layer, "permit DHCP", 0, fwpActionPermit, 1, dhcp...); err != nil {
return err
}
if err := add(layer, "block IPv4", 0, fwpActionBlock, 0); err != nil {
return err
}
}
}
if block.ipv6 {
// Neighbor and multicast listener discovery, ICMPv6 130-137 and 143,
// whose type and code sit where the local and remote port are.
discovery := []fwpmFilterCondition0{condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_ICMPV6)}
for _, typ := range []uintptr{130, 131, 132, 133, 134, 135, 136, 137, 143} {
discovery = append(discovery, condition(&fwpmConditionIPLocalPort, fwpUint16, typ))
}
discovery = append(discovery, condition(&fwpmConditionIPRemotePort, fwpUint16, 0))
dhcpv6 := []fwpmFilterCondition0{
condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_UDP),
condition(&fwpmConditionIPLocalPort, fwpUint16, 546),
condition(&fwpmConditionIPRemotePort, fwpUint16, 547),
}
for _, direction := range []struct {
layer *windows.GUID
dhcpv6 []fwpmFilterCondition0
}{
// The client sends to the servers' multicast address, and they
// answer from their own.
{&fwpmLayerALEAuthConnectV6, slices.Concat(dhcpv6, []fwpmFilterCondition0{condition(&fwpmConditionIPRemoteAddress, fwpByteArray16Type, uintptr(unsafe.Pointer(&ipv6AllDHCPv6Servers)))})},
{&fwpmLayerALEAuthRecvAcceptV6, dhcpv6},
} {
if err := add(direction.layer, "permit IPv6 loopback", 0, fwpActionPermit, 1, loopback); err != nil {
return err
}
if err := add(direction.layer, "permit IPv6 neighbor and multicast listener discovery", 0, fwpActionPermit, 1, discovery...); err != nil {
return err
}
if err := add(direction.layer, "permit DHCPv6", 0, fwpActionPermit, 1, direction.dhcpv6...); err != nil {
return err
}
if err := add(direction.layer, "block IPv6", 0, fwpActionBlock, 0); err != nil {
if err := add(layer.key, "block the DNS Client service", 0, fwpActionBlock, weightDNSClient, slices.Concat([]fwpmFilterCondition0{dnsClient}, remote(prefixes...))...); err != nil {
return err
}
}
@@ -510,13 +668,22 @@ func addFilter(engine windows.Handle, sublayer, layer *windows.GUID, name string
return nil
}
// dnsOutsideTUN returns the servers outside all of prefixes, the TUN's own
// subnets and routes: queries to them cannot go through the TUN.
func dnsOutsideTUN(servers []netip.Addr, prefixes []netip.Prefix) []netip.Addr {
// dnsOutsideTUN returns the servers whose queries block blocks: those outside
// all of prefixes, the TUN's own subnets and routes, as queries to them cannot
// go through the TUN, and inside the CIDR of a value that keeps DNS inside the
// TUN, or of "misconfigtun". Loopback ones, local resolvers, are not among
// them, as loopback stays allowed.
func dnsOutsideTUN(servers []netip.Addr, prefixes []netip.Prefix, block leakFilters) []netip.Addr {
var outside []netip.Addr
for _, server := range servers {
server = server.Unmap()
if !slices.ContainsFunc(prefixes, func(p netip.Prefix) bool { return p.Contains(server) }) {
if server.IsLoopback() || slices.ContainsFunc(prefixes, func(p netip.Prefix) bool { return p.Contains(server) }) {
continue
}
if slices.ContainsFunc(block, func(l leak) bool {
prefix, ok := l.over(server.Is6())
return ok && prefix.Contains(server) && (l.blocksDNS() || l.name == "misconfigtun")
}) {
outside = append(outside, server)
}
}
+134 -25
View File
@@ -40,6 +40,21 @@ func TestWFPStructLayout(t *testing.T) {
[]uintptr{unsafe.Sizeof(value), unsafe.Offsetof(value.value)},
[]uintptr{16, 8}, []uintptr{8, 4})
var ports fwpRange0
check("FWP_RANGE0",
[]uintptr{unsafe.Sizeof(ports), unsafe.Offsetof(ports.high)},
[]uintptr{32, 16}, []uintptr{16, 8})
var v4 fwpV4AddrAndMask
check("FWP_V4_ADDR_AND_MASK",
[]uintptr{unsafe.Sizeof(v4), unsafe.Offsetof(v4.mask)},
[]uintptr{8, 4}, []uintptr{8, 4})
var v6 fwpV6AddrAndMask
check("FWP_V6_ADDR_AND_MASK",
[]uintptr{unsafe.Sizeof(v6), unsafe.Offsetof(v6.prefixLength)},
[]uintptr{17, 16}, []uintptr{17, 16})
var display fwpmDisplayData0
check("FWPM_DISPLAY_DATA0",
[]uintptr{unsafe.Sizeof(display), unsafe.Offsetof(display.description)},
@@ -114,35 +129,101 @@ func TestLeakFiltersAccepted(t *testing.T) {
if err != nil {
t.Fatal(err)
}
leaks, err := ExpandWfpBlockLeak([]string{"dns", "misconfigtun", "tcp/443"})
if err != nil {
t.Fatal(err)
}
block := newLeakFilters(leaks, false, false)
block.dnsClient = true // whatever the Windows version
if err := addLeakFilters(engine, loopback, block); err != nil {
skipUnlessElevated(err)
// Each with a sublayer of its own.
for _, c := range []struct {
values []string
route4, route6 bool
}{
{[]string{"dns", "misconfigtun", "all", "tcp/443", "udp/1000-2000", "tcp", "icmp", "10-20", "1-65535"}, false, false},
// CIDRs, and the local network's addresses.
{[]string{"1.1.1.0/24:tcp/80", "[2001:db8::/32]:udp/5000-6000", "[::/0]:icmp", "8.8.8.8/32:all", "[2000::/3]:misconfigtun", "9.9.9.9/32:dns"}, true, false},
{[]string{"allexceptlan", "udp/1000-2000", "icmp", "192.168.1.5/32:all"}, true, false},
{[]string{"0.0.0.0/0:allexceptlan", "[::/0]:all", "[::/0]:windnsclient", "1.0.0.0/8:windnsclient"}, true, true},
{[]string{"[::/0]:allexceptlan", "0.0.0.0/0:misconfigtun", "10.0.0.0/8:allexceptlan", "1.0.0.0/8:allexceptlan"}, false, true},
} {
leaks, err := ExpandWfpBlockLeak(c.values)
if err != nil {
t.Fatal(err)
}
if err := addLeakFilters(engine, loopback, newLeakFilters(leaks, c.route4, c.route6)); err != nil {
skipUnlessElevated(err)
}
}
}
func TestNewLeakFilters(t *testing.T) {
leaks, err := ExpandWfpBlockLeak([]string{"dns", "misconfigtun"})
if err != nil {
t.Fatal(err)
for _, c := range []struct {
values []string
route4, route6 bool
blocked string
systemDNS bool
}{
{[]string{"dns", "misconfigtun"}, true, false, "53, 853, windnsclient, [::/0]:misconfigtun", true},
{[]string{"tcp/853", "udp/853", "misconfigtun"}, true, true, "tcp/853, udp/853", false},
{[]string{"all"}, true, true, "all", true},
{[]string{"all", "misconfigtun"}, true, true, "all", true},
{[]string{"misconfigtun"}, true, false, "[::/0]:misconfigtun", false},
{[]string{"misconfigtun"}, false, true, "0.0.0.0/0:misconfigtun", false},
{[]string{"misconfigtun"}, false, false, "misconfigtun", false},
{[]string{"tcp/10-20", "udp", "icmp"}, true, true, "tcp/10-20, udp, icmp", true},
{[]string{"tcp/54-60", "icmp", "54-60"}, true, true, "tcp/54-60, icmp, 54-60", false},
{[]string{"allexceptlan"}, true, true, "allexceptlan, 53, 853, windnsclient", true},
{[]string{"allexceptlan", "all"}, true, true, "allexceptlan, 53, 853, windnsclient, all", true},
{[]string{"misconfigtun", "allexceptlan"}, true, false, "[::/0]:misconfigtun, allexceptlan, 53, 853, windnsclient", true},
// Limited to the addresses of a CIDR.
{[]string{"0.0.0.0/0:TCP/10-20", "[::/0]:udp", "0.0.0.0/0:icmp"}, true, true, "0.0.0.0/0:tcp/10-20, [::/0]:udp, 0.0.0.0/0:icmp", true},
{[]string{"[::/0]:tcp/54-60", "[::/0]:icmp"}, true, true, "[::/0]:tcp/54-60, [::/0]:icmp", false},
{[]string{"0.0.0.0/0:windnsclient"}, true, true, "0.0.0.0/0:windnsclient", true},
{[]string{"1.1.1.0/24:53"}, true, true, "1.1.1.0/24:53", true},
{[]string{"[::/0]:all"}, true, false, "[::/0]:all", true},
{[]string{"0.0.0.0/0:allexceptlan", "[::/0]:all"}, true, true, "0.0.0.0/0:allexceptlan, 0.0.0.0/0:53, 0.0.0.0/0:853, 0.0.0.0/0:windnsclient, [::/0]:all", true},
{[]string{"0.0.0.0/0:misconfigtun"}, true, false, "", false},
{[]string{"[::/0]:misconfigtun"}, true, false, "[::/0]:misconfigtun", false},
{[]string{"[2000::/3]:misconfigtun", "1.0.0.0/8:misconfigtun"}, true, false, "[2000::/3]:misconfigtun", false},
{[]string{"misconfigtun", "[::/0]:misconfigtun"}, true, false, "[::/0]:misconfigtun", false},
{[]string{"0.0.0.0/0:misconfigtun", "[::/0]:allexceptlan"}, false, true, "0.0.0.0/0:misconfigtun, [::/0]:allexceptlan, [::/0]:53, [::/0]:853, [::/0]:windnsclient", true},
} {
leaks, err := ExpandWfpBlockLeak(c.values)
if err != nil {
t.Fatal(err)
}
block := newLeakFilters(leaks, c.route4, c.route6)
if got := block.String(); got != c.blocked {
t.Errorf("%v: String() = %q, want %q", c.values, got, c.blocked)
}
if got := block.systemDNS(); got != c.systemDNS {
t.Errorf("%v: systemDNS() = %v", c.values, got)
}
}
block := newLeakFilters(leaks, true, false)
want := "udp/53, tcp/53, tcp/853, udp/853, IPv6"
if dnsClientUsesAnyPort() {
want = "udp/53, tcp/53, tcp/853, udp/853, windnsclient, IPv6"
// Without the port 53 values "allexceptlan" brings along, a resolver on
// the local network, like the router's, stays reachable.
if (leakFilters{{name: "allexceptlan"}}).systemDNS() {
t.Error("systemDNS() = true with the local network open")
}
if got := block.String(); got != want {
t.Errorf("String() = %q, want %q", got, want)
}
func TestLanWithin(t *testing.T) {
prefixes := func(cidrs ...string) []netip.Prefix {
var prefixes []netip.Prefix
for _, cidr := range cidrs {
prefixes = append(prefixes, netip.MustParsePrefix(cidr))
}
return prefixes
}
if !block.systemDNS() {
t.Error("systemDNS() = false with dns")
}
if block := newLeakFilters([]string{"tcp/853", "udp/853", "misconfigtun"}, true, true); block.String() != "tcp/853, udp/853" || block.systemDNS() {
t.Errorf("tcp/853, udp/853: %q, systemDNS() = %v", block.String(), block.systemDNS())
for _, c := range []struct {
within, lan []netip.Prefix
}{
{nil, nil},
{prefixes("0.0.0.0/0"), prefixes("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "224.0.0.0/4", "255.255.255.255/32")},
{prefixes("::/0"), prefixes("fc00::/7", "fe80::/10", "ff00::/8")},
{prefixes("1.0.0.0/8", "10.1.0.0/16"), prefixes("10.1.0.0/16")},
{prefixes("192.0.0.0/2"), prefixes("192.168.0.0/16", "224.0.0.0/4", "255.255.255.255/32")},
{prefixes("2000::/3", "fe80::/64", "fe80::/10"), prefixes("fe80::/64", "fe80::/10")},
{prefixes("8.8.8.8/32", "2001:db8::/32"), nil},
} {
if got := lanWithin(c.within...); !slices.Equal(got, c.lan) {
t.Errorf("%v: got %v, want %v", c.within, got, c.lan)
}
}
}
@@ -167,10 +248,38 @@ func TestDNSOutsideTUN(t *testing.T) {
netip.MustParseAddr("::ffff:203.0.113.54"),
netip.MustParseAddr("8.8.8.8"),
netip.MustParseAddr("2001:db8::53"),
// Local resolvers, reachable over loopback whatever is blocked.
netip.MustParseAddr("127.0.0.1"),
netip.MustParseAddr("::ffff:127.0.0.53"),
netip.MustParseAddr("::1"),
}
want := []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("2001:db8::53")}
if got := dnsOutsideTUN(servers, prefixes); !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
// Only to the addresses of their CIDRs, if any, and "misconfigtun" over
// an IP version without routes to the TUN blocks DNS as well.
for _, c := range []struct {
values []string
route4, route6 bool
want []string
}{
{[]string{"dns"}, true, true, []string{"8.8.8.8", "2001:db8::53"}},
{[]string{"0.0.0.0/0:53"}, true, true, []string{"8.8.8.8"}},
{[]string{"8.8.8.0/24:windnsclient", "[2001:db8::/32]:tcp/853"}, true, true, []string{"8.8.8.8"}},
{[]string{"[2001:db8::53/128]:all", "9.9.9.9/32:53"}, true, true, []string{"2001:db8::53"}},
{[]string{"misconfigtun"}, true, false, []string{"2001:db8::53"}},
{[]string{"misconfigtun"}, true, true, nil},
{[]string{"tcp/853", "udp/5353", "icmp", "10.0.0.0/8:all"}, true, true, nil},
{[]string{"[::/0]:allexceptlan"}, true, true, []string{"2001:db8::53"}},
} {
leaks, err := ExpandWfpBlockLeak(c.values)
if err != nil {
t.Fatal(err)
}
var want []netip.Addr
for _, server := range c.want {
want = append(want, netip.MustParseAddr(server))
}
if got := dnsOutsideTUN(servers, prefixes, newLeakFilters(leaks, c.route4, c.route6)); !slices.Equal(got, want) {
t.Errorf("%v: got %v, want %v", c.values, got, want)
}
}
}
+126 -45
View File
@@ -1,6 +1,7 @@
package tun
import (
"net/netip"
"slices"
"strconv"
"strings"
@@ -8,72 +9,152 @@ import (
"github.com/xtls/xray-core/common/errors"
)
// dnsLeaks is what "dns" in autoSystemWfpBlockLeak stands for: DNS over UDP and
// TCP, Windows' DNS Client service, which may also use other protocols and
// ports, DNS over TLS, and DNS over QUIC.
var dnsLeaks = []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}
// dnsLeaks is what "dns" in autoSystemWfpBlockLeak stands for: DNS over TCP
// and UDP, DNS over TLS and QUIC, and Windows' DNS Client service, which may
// also use other protocols and ports.
var dnsLeaks = []string{"53", "853", "windnsclient"}
// leakPort is a "tcp/<port>" or "udp/<port>" value of autoSystemWfpBlockLeak:
// connections to that port may only go through the TUN.
type leakPort struct {
tcp bool
port uint16
// leak is a value of autoSystemWfpBlockLeak: "dns", "windnsclient",
// "misconfigtun", "all", "allexceptlan", "icmp", or "tcp" or "udp", the latter
// two with "/<port>" or "/<low>-<high>" for some ports only, such as "tcp/853"
// or "udp/10-20", or such ports alone for TCP and UDP, such as "53". A CIDR in
// front limits any of them to its addresses, an IPv6 one in brackets, such as
// "1.1.1.0/24:53" or "[::/0]:all".
type leak struct {
prefix netip.Prefix // all addresses of both IP versions if not valid
name string // empty for TCP and UDP to some ports
low, high uint16 // the ports of TCP and UDP, both 0 for all
}
func (p leakPort) String() string {
if p.tcp {
return "tcp/" + strconv.Itoa(int(p.port))
func (l leak) String() string {
s := l.name
if l.low != 0 {
if s != "" {
s += "/"
}
s += strconv.Itoa(int(l.low))
if l.high != l.low {
s += "-" + strconv.Itoa(int(l.high))
}
}
switch {
case !l.prefix.IsValid():
return s
case l.prefix.Addr().Is6():
return "[" + l.prefix.String() + "]:" + s
default:
return l.prefix.String() + ":" + s
}
return "udp/" + strconv.Itoa(int(p.port))
}
// parseLeakPort parses a lower case "tcp/<port>" or "udp/<port>" value.
func parseLeakPort(value string) (leakPort, bool) {
protocol, port, ok := strings.Cut(value, "/")
if !ok || protocol != "tcp" && protocol != "udp" {
return leakPort{}, false
// covers tells whether l includes connections of protocol, "tcp" or "udp", to
// port, to at least some addresses.
func (l leak) covers(protocol string, port uint16) bool {
switch l.name {
case "all":
return true
case "", protocol:
return l.low == 0 || l.low <= port && port <= l.high
}
n, err := strconv.ParseUint(port, 10, 16)
if err != nil || n == 0 {
return leakPort{}, false
return false
}
// blocksDNS tells whether l keeps the system's DNS, TCP or UDP port 53 or
// Windows' DNS Client service, inside the TUN, to at least some addresses.
func (l leak) blocksDNS() bool {
return l.name == "windnsclient" || l.covers("udp", 53) || l.covers("tcp", 53)
}
// parseLeak parses a lower case value of autoSystemWfpBlockLeak. Ports go from
// 1 to 65535, low not above high, and "tcp/1-65535" stands for all of them, as
// does "tcp".
func parseLeak(value string) (leak, bool) {
var l leak
cidr, rest, hasCIDR := strings.Cut(value, ":")
ipv6 := strings.HasPrefix(value, "[")
if ipv6 {
cidr, rest, hasCIDR = strings.Cut(value[1:], "]:")
}
return leakPort{tcp: protocol == "tcp", port: uint16(n)}, true
if hasCIDR {
// IPv4-mapped IPv6 ones would not match: Windows checks such
// connections as IPv4.
prefix, err := netip.ParsePrefix(cidr)
if err != nil || prefix.Addr().Is6() != ipv6 || prefix.Addr().Is4In6() {
return leak{}, false
}
l.prefix, value = prefix.Masked(), rest
}
name, ports, hasPorts := strings.Cut(value, "/")
switch name {
case "tcp", "udp":
l.name = name
if !hasPorts {
return l, true
}
case "dns", "windnsclient", "misconfigtun", "all", "allexceptlan", "icmp":
l.name = name
return l, !hasPorts
default:
if hasPorts {
return leak{}, false
}
ports = name // for TCP and UDP
}
lowText, highText, isRange := strings.Cut(ports, "-")
low, err := strconv.ParseUint(lowText, 10, 16)
if err != nil || low == 0 {
return leak{}, false
}
high := low
if isRange {
if high, err = strconv.ParseUint(highText, 10, 16); err != nil || high < low {
return leak{}, false
}
}
if l.name == "" || low != 1 || high != 65535 {
l.low, l.high = uint16(low), uint16(high)
}
return l, true
}
// ExpandWfpBlockLeak checks the values of autoSystemWfpBlockLeak and returns
// them in lower case, in order and without duplicates, with "dns" replaced by
// what it stands for.
// them in lower case, in order and each once, with "dns" replaced by what it
// stands for, "allexceptlan" followed by that, CIDRs masked, and ports written
// the same way, "tcp/1-65535" as "tcp" say.
func ExpandWfpBlockLeak(values []string) ([]string, error) {
var leaks []string
add := func(leak string) {
if !slices.Contains(leaks, leak) {
leaks = append(leaks, leak)
var expanded []string
add := func(l leak) {
if value := l.String(); !slices.Contains(expanded, value) {
expanded = append(expanded, value)
}
}
for _, value := range values {
switch value = strings.ToLower(value); value {
case "dns":
for _, leak := range dnsLeaks {
add(leak)
l, ok := parseLeak(strings.ToLower(value))
if !ok {
return nil, errors.New("unknown autoSystemWfpBlockLeak value: ", value)
}
if l.name != "dns" {
add(l)
}
// The local network is no way out for DNS with "allexceptlan", as a
// resolver there, like the router, would forward outside the TUN.
if l.name == "dns" || l.name == "allexceptlan" {
for _, dnsLeak := range dnsLeaks {
dns, _ := parseLeak(dnsLeak)
dns.prefix = l.prefix
add(dns)
}
case "windnsclient", "misconfigtun":
add(value)
default:
port, ok := parseLeakPort(value)
if !ok {
return nil, errors.New("unknown autoSystemWfpBlockLeak value: ", value)
}
add(port.String())
}
}
return leaks, nil
return expanded, nil
}
// BlocksSystemDNS tells whether expanded autoSystemWfpBlockLeak values keep the
// system's DNS (port 53, or Windows' DNS Client service) inside the TUN, which
// then needs DNS servers of its own.
// system's DNS (TCP or UDP port 53, or Windows' DNS Client service) inside the
// TUN, to at least some addresses, which then needs DNS servers of its own.
func BlocksSystemDNS(leaks []string) bool {
return slices.ContainsFunc(leaks, func(leak string) bool {
return leak == "udp/53" || leak == "tcp/53" || leak == "windnsclient"
return slices.ContainsFunc(leaks, func(value string) bool {
l, _ := parseLeak(value)
return l.blocksDNS()
})
}
+86 -4
View File
@@ -12,13 +12,39 @@ func TestExpandWfpBlockLeak(t *testing.T) {
systemDNS bool
}{
{nil, nil, false},
{[]string{"dns"}, []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}, true},
{[]string{"DNS", "MisconfigTUN"}, []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853", "misconfigtun"}, true},
{[]string{"tcp/853", "dns", "TCP/0853"}, []string{"tcp/853", "udp/53", "tcp/53", "windnsclient", "udp/853"}, true},
{[]string{"dns"}, []string{"53", "853", "windnsclient"}, true},
{[]string{"DNS", "MisconfigTUN"}, []string{"53", "853", "windnsclient", "misconfigtun"}, true},
{[]string{"tcp/853", "dns", "TCP/0853"}, []string{"tcp/853", "53", "853", "windnsclient"}, true},
{[]string{"tcp/853", "udp/853", "misconfigtun"}, []string{"tcp/853", "udp/853", "misconfigtun"}, false},
{[]string{"udp/65535", "tcp/1"}, []string{"udp/65535", "tcp/1"}, false},
{[]string{"tcp/53"}, []string{"tcp/53"}, true},
{[]string{"windnsclient"}, []string{"windnsclient"}, true},
{[]string{"ALL"}, []string{"all"}, true},
{[]string{"tcp", "TCP", "UDP"}, []string{"tcp", "udp"}, true},
{[]string{"tcp/1-65535", "udp/1-65535"}, []string{"tcp", "udp"}, true},
{[]string{"udp/10-20", "udp/53-53", "tcp/50-60"}, []string{"udp/10-20", "udp/53", "tcp/50-60"}, true},
{[]string{"tcp/54-60", "udp/1-52"}, []string{"tcp/54-60", "udp/1-52"}, false},
{[]string{"ICMP", "icmp"}, []string{"icmp"}, false},
{[]string{"AllExceptLAN"}, []string{"allexceptlan", "53", "853", "windnsclient"}, true},
{[]string{"dns", "allexceptlan", "all"}, []string{"53", "853", "windnsclient", "allexceptlan", "all"}, true},
// Ports alone, for TCP and UDP.
{[]string{"53"}, []string{"53"}, true},
{[]string{"10-20", "0053", "853-853", "53"}, []string{"10-20", "53", "853"}, true},
{[]string{"54-60", "1-52", "65535"}, []string{"54-60", "1-52", "65535"}, false},
{[]string{"1-65535"}, []string{"1-65535"}, true},
{[]string{"853", "tcp/853"}, []string{"853", "tcp/853"}, false},
// Limited to the addresses of a CIDR.
{[]string{"1.1.1.0/24:53"}, []string{"1.1.1.0/24:53"}, true},
{[]string{"1.1.1.1/24:TCP/853", "[2001:DB8::1/32]:udp/10-20", "[::/0]:ICMP"}, []string{"1.1.1.0/24:tcp/853", "[2001:db8::/32]:udp/10-20", "[::/0]:icmp"}, false},
{[]string{"0.0.0.0/0:dns"}, []string{"0.0.0.0/0:53", "0.0.0.0/0:853", "0.0.0.0/0:windnsclient"}, true},
{[]string{"[::/0]:all"}, []string{"[::/0]:all"}, true},
{[]string{"10.0.0.1/32:windnsclient"}, []string{"10.0.0.1/32:windnsclient"}, true},
{[]string{"[2000::/3]:misconfigtun"}, []string{"[2000::/3]:misconfigtun"}, false},
{[]string{"1.1.1.0/24:tcp/1-65535", "1.1.1.0/24:udp/53-53"}, []string{"1.1.1.0/24:tcp", "1.1.1.0/24:udp/53"}, true},
{[]string{"1.1.1.0/24:20-30", "[::/0]:10-10"}, []string{"1.1.1.0/24:20-30", "[::/0]:10"}, false},
{[]string{"0.0.0.0/0:allexceptlan", "[::/0]:all"}, []string{"0.0.0.0/0:allexceptlan", "0.0.0.0/0:53", "0.0.0.0/0:853", "0.0.0.0/0:windnsclient", "[::/0]:all"}, true},
{[]string{"1.1.1.1/32:53", "1.1.1.1/32:0053", "1.1.1.1/24:53", "1.1.1.0/24:53", "53"}, []string{"1.1.1.1/32:53", "1.1.1.0/24:53", "53"}, true},
{[]string{"1.2.3.4/0:icmp", "[::1/0]:icmp", "icmp"}, []string{"0.0.0.0/0:icmp", "[::/0]:icmp", "icmp"}, false},
} {
leaks, err := ExpandWfpBlockLeak(c.values)
if err != nil {
@@ -32,9 +58,65 @@ func TestExpandWfpBlockLeak(t *testing.T) {
t.Errorf("%v: BlocksSystemDNS() = %v", c.values, got)
}
}
for _, value := range []string{"", "ip", "tcp", "tcp/", "tcp/0", "udp/65536", "tcp/-1", "tcp/+53", "tcp/53/1", "udp/abc", "icmp/1", "tcp:53", " dns"} {
for _, value := range []string{
"", "ip", "tcp/", "udp/65536", "tcp/-1", "tcp/+53", "tcp/53/1", "udp/abc", "icmp/0", "icmp/8", "tcp:53", " dns",
"tcp/0-10", "tcp/20-10", "tcp/5-", "tcp/-5", "tcp/1-2-3", "tcp/1-65536", "udp/ 53", "all/0", "dns/53", "windnsclient/53",
"tcp/0", "udp/0", "tcp/00", "udp/0-0", "udp/65535-1",
// Ports alone.
"0", "00", "65536", "0-10", "20-10", "5-", "-5", "-", "1-2-3", "1-65536", "+53", " 53", "53 ", "53/1", "53/tcp", "0x35",
// IP versions are CIDRs now.
"ipv4", "ipv6", "ipv4:udp", "ipv6:all", "ipv4:dns", "tcpv4", "udpv6", "icmpv4", "tcp4", "dnsv4",
// CIDRs, IPv6 ones in brackets, but neither single addresses nor
// CIDRs on their own.
"1.1.1.0/24", "[2001:db8::/32]", "1.1.1.0/24:", "[::/0]:", ":udp", "[]:udp", "[:udp", "[::/0]udp",
"1.1.1.1:53", "[::1]:53", "[2001:db8::1]:tcp/53", "2001:db8::/32:53", "::/0:all", "[1.1.1.0/24]:53",
"[2001:db8::]/32:53", "1.1.1.0/33:53", "[::/129]:53", "1.1.1.0/24:1.1.1.0/24:53", "[::/0]:[::/0]:53",
"1.1.1.0/24 :53", "1.1.1.0/24: 53", " 1.1.1.0/24:53", "1.1.1.0/24::53", "[fe80::%1/64]:53", "geoip:cn:53",
"1.1.1.0/24:udp/0", "[::/0]:icmp/8", "1.1.1.0/24:dns/53", "[::/0]:20-10", "1.1.1.0/24:ipv4:53", "1.1.1.0/24:geoip",
"[::ffff:1.1.1.0/120]:53", "[::ffff:0:0/96]:all",
} {
if _, err := ExpandWfpBlockLeak([]string{value}); err == nil {
t.Errorf("%q was accepted", value)
}
}
}
func TestLeakCovers(t *testing.T) {
for _, c := range []struct {
value string
protocol string
port uint16
covers bool
}{
{"tcp", "tcp", 1, true},
{"tcp", "udp", 53, false},
{"udp/53", "udp", 53, true},
{"udp/53", "udp", 54, false},
{"tcp/10-20", "tcp", 10, true},
{"tcp/10-20", "tcp", 20, true},
{"tcp/10-20", "tcp", 21, false},
{"tcp/10-20", "tcp", 9, false},
{"53", "udp", 53, true},
{"53", "tcp", 53, true},
{"10-20", "tcp", 15, true},
{"10-20", "udp", 21, false},
{"1.1.1.0/24:udp/53", "udp", 53, true},
{"[::/0]:tcp", "tcp", 443, true},
{"[2001:db8::/32]:53", "tcp", 53, true},
{"0.0.0.0/0:icmp", "udp", 53, false},
{"all", "udp", 53, true},
{"1.1.1.1/32:all", "tcp", 1, true},
{"allexceptlan", "udp", 53, false},
{"misconfigtun", "udp", 53, false},
{"windnsclient", "udp", 53, false},
} {
l, ok := parseLeak(c.value)
if !ok {
t.Errorf("%q was not parsed", c.value)
continue
}
if got := l.covers(c.protocol, c.port); got != c.covers {
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
}
}
}
+6 -2
View File
@@ -17,7 +17,7 @@ import (
type bind struct {
ctx context.Context
resolveFunc func(host string) (net.IP, error)
resolveFunc func(ctx context.Context, host string) (net.IP, error)
listenFunc func(ctx context.Context) (net.PacketConn, error)
downFunc func() error
reserved []byte
@@ -143,7 +143,11 @@ func (b *bind) ParseEndpoint(s string) (conn.Endpoint, error) {
if port < 0 || port > 65535 {
return nil, errors.New("invalid port " + sport)
}
ip, err := b.resolveFunc(host)
// up sets the connection's context right before it hands over the endpoint
b.mu.Lock()
ctx := b.ctx
b.mu.Unlock()
ip, err := b.resolveFunc(ctx, host)
if err != nil {
return nil, err
}
+24 -3
View File
@@ -323,12 +323,12 @@ func (h *Handler) up(ctx context.Context) error {
return h.dev.Up()
}
func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig) func(host string) (net.IP, error) {
return func(host string) (net.IP, error) {
func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig) func(ctx context.Context, host string) (net.IP, error) {
return func(ctx context.Context, host string) (net.IP, error) {
if ip := net.ParseIP(host); ip != nil {
return ip, nil
}
ips, _, err := d.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
ips, err := lookupIPContext(ctx, d, host)
if err != nil {
return nil, err
}
@@ -368,6 +368,27 @@ func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig)
}
}
func lookupIPContext(ctx context.Context, d dns.Client, host string) ([]net.IP, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
type result struct {
ips []net.IP
err error
}
done := make(chan result, 1)
go func() {
ips, _, err := d.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
done <- result{ips, err}
}()
select {
case r := <-done:
return r.ips, r.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
type UDPConnClient struct {
net.PacketConn
Dest *net.UDPAddr
-1
View File
@@ -1,5 +1,4 @@
//go:build coverage
// +build coverage
package scenarios
-1
View File
@@ -1,5 +1,4 @@
//go:build !coverage
// +build !coverage
package scenarios
+8 -8
View File
@@ -661,7 +661,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
wg.Wait()
}
// A blocked connection must be closed after blockDelay even while the client keeps it open and sends nothing.
// A blocked connection must close after finalRules.delay even while the client keeps it open and sends nothing.
func TestVlessBlockDelay(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
@@ -671,7 +671,7 @@ func TestVlessBlockDelay(t *testing.T) {
defer tcpServer.Close()
for _, delay := range []uint64{0, 1} {
t.Run(fmt.Sprint("blockDelay=", delay), func(t *testing.T) {
t.Run(fmt.Sprint("delay=", delay), func(t *testing.T) {
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
@@ -697,8 +697,8 @@ func TestVlessBlockDelay(t *testing.T) {
ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{
{
Action: freedom.RuleAction_Block,
BlockDelay: &freedom.Range{Min: delay, Max: delay},
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{Min: delay, Max: delay},
},
},
}),
@@ -726,15 +726,15 @@ func TestVlessBlockDelay(t *testing.T) {
Port: dest.Port,
}, &encoding.Addons{}))
blockDelay := time.Duration(delay) * time.Second
common.Must(conn.SetReadDeadline(time.Now().Add(blockDelay + 5*time.Second)))
blockDuration := time.Duration(delay) * time.Second
common.Must(conn.SetReadDeadline(time.Now().Add(blockDuration + 5*time.Second)))
_, err = io.Copy(io.Discard, conn)
elapsed := time.Since(start)
if err, ok := err.(net.Error); ok && err.Timeout() {
t.Fatalf("connection is still open after %v", elapsed)
}
if elapsed < blockDelay {
t.Fatalf("connection is closed after %v, before blockDelay", elapsed)
if elapsed < blockDuration {
t.Fatalf("connection is closed after %v, before finalRules.delay", elapsed)
}
})
}
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package internet
@@ -1,5 +1,4 @@
//go:build !amd64
// +build !amd64
package original
+2 -1
View File
@@ -6,6 +6,7 @@ import (
goerrors "errors"
"io"
mrand "math/rand"
stdnet "net"
"net/netip"
"sync"
"time"
@@ -164,7 +165,7 @@ func (c *udpHopConn) recv(conn net.PacketConn) {
n, addr, err := conn.ReadFrom(p)
if err != nil {
pool.Put(p[:cap(p)])
if c.closed() {
if c.closed() || goerrors.Is(err, stdnet.ErrClosed) {
return
}
var netErr net.Error
+9 -2
View File
@@ -108,8 +108,15 @@ func NewDomain(domain string, lenLimit int, labelLimit int, types []uint16, edns
return nil, err
}
ascii = strings.Trim(ascii, ".")
name, err := dnsmessage.NewName(domain + ".")
if ascii == "" {
return nil, errors.New("empty domain")
}
for _, label := range strings.Split(ascii, ".") {
if len(label) == 0 || len(label) > 63 {
return nil, errors.New("invalid domain")
}
}
name, err := dnsmessage.NewName(ascii + ".")
if err != nil {
return nil, err
}
+104 -57
View File
@@ -1,11 +1,11 @@
package xdns
import (
"encoding/binary"
"errors"
"context"
"io"
"sync"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
@@ -14,11 +14,9 @@ type TCPResolver struct {
dest net.Destination
dialer *finalmask.Dialer
conn net.Conn
tcpAddr *net.TCPAddr
udpAddr *net.UDPAddr
readCh chan []byte
sendCh chan []byte
closeCh chan struct{}
wg sync.WaitGroup
mu sync.Mutex
@@ -33,12 +31,10 @@ func NewTCPResolver(config *ResolverProto, dialer *finalmask.Dialer) (Resolver,
dest: dest,
dialer: dialer,
readCh: make(chan []byte),
sendCh: make(chan []byte),
closeCh: make(chan struct{}),
}
if err := r.dial(); err != nil {
r.Close()
return nil, err
}
go r.run(config.Worker)
return r, nil
}
@@ -51,60 +47,113 @@ func (r *TCPResolver) closed() bool {
}
}
func (r *TCPResolver) dial() error {
if r.closed() {
return errors.New("closed")
func (r *TCPResolver) setaddr(addr net.Addr) {
r.mu.Lock()
defer r.mu.Unlock()
switch v := addr.(type) {
case *net.TCPAddr:
r.udpAddr = &net.UDPAddr{IP: v.IP, Port: v.Port}
case *net.UDPAddr:
r.udpAddr = v
default:
panic(v)
}
if r.conn != nil {
return nil
}
func (r *TCPResolver) read(reader io.Reader, p []byte) (l int, err error) {
if _, err := io.ReadFull(reader, p[:2]); err != nil {
return 0, err
}
conn, err := r.dialer.DialTCP(r.dest)
l = int(p[0])<<8 | int(p[1])
if l == 0 || l > 4096 {
return 0, errors.New("err resp len ", l)
}
if _, err = io.ReadFull(reader, p[:l]); err != nil {
return 0, err
}
return l, nil
}
func (r *TCPResolver) do(conn *net.Conn, buf *[4096 + 2]byte, p []byte) error {
var err error
if *conn == nil {
*conn, err = r.dialer.DialTCP(r.dest)
if err != nil {
*conn = nil
return err
}
r.setaddr((*conn).RemoteAddr())
}
c := *conn
l := len(p)
buf[0] = byte(l >> 8)
buf[1] = byte(l)
copy(buf[2:], p)
_, err = c.Write(buf[:2+len(p)])
if err != nil {
c.Close()
*conn = nil
return err
}
r.conn = conn
r.tcpAddr = conn.RemoteAddr().(*net.TCPAddr)
r.udpAddr = &net.UDPAddr{IP: r.tcpAddr.IP, Port: r.tcpAddr.Port}
r.wg.Add(1)
go r.recv(conn)
b := pool4K.Get().([]byte)
l, err = r.read(c, b)
if err != nil {
c.Close()
*conn = nil
pool4K.Put(b[:cap(b)])
return err
}
select {
case <-r.closeCh:
pool4K.Put(b[:cap(b)])
case r.readCh <- b[:l]:
}
return nil
}
func (r *TCPResolver) recv(conn net.Conn) {
func (r *TCPResolver) worker() {
defer r.wg.Done()
var buf [4096]byte
var conn net.Conn
defer func() {
if conn != nil {
_ = conn.Close()
}
}()
var buf [4096 + 2]byte
var p []byte
for {
_, err := io.ReadFull(conn, buf[:2])
if err != nil {
break
}
n := binary.BigEndian.Uint16(buf[:2])
if n == 0 || n > 4096 {
io.CopyN(io.Discard, conn, int64(n))
continue
}
_, err = io.ReadFull(conn, buf[:n])
if err != nil {
break
}
p := pool4K.Get().([]byte)
copy(p, buf[:n])
select {
case <-r.closeCh:
pool4K.Put(p[:cap(p)])
case r.readCh <- p[:n]:
return
default:
select {
case <-r.closeCh:
return
case p = <-r.sendCh:
}
}
if err := r.do(&conn, &buf, p); err != nil {
errors.LogErrorInner(context.Background(), err, "do err")
}
}
}
r.mu.Lock()
defer r.mu.Unlock()
_ = conn.Close()
r.conn = nil
func (r *TCPResolver) run(worker int32) {
for range worker {
r.wg.Add(1)
go r.worker()
}
r.wg.Wait()
close(r.readCh)
// close(r.sendCh)
}
func (r *TCPResolver) Addr() *net.UDPAddr {
r.mu.Lock()
defer r.mu.Unlock()
return r.udpAddr
}
@@ -119,27 +168,25 @@ func (r *TCPResolver) Read(p []byte) (n int, err error) {
}
func (r *TCPResolver) Send(p []byte) {
r.mu.Lock()
defer r.mu.Unlock()
if r.dial() != nil {
select {
case <-r.closeCh:
return
default:
b := make([]byte, len(p))
copy(b, p)
select {
case <-r.closeCh:
return
case r.sendCh <- b:
}
}
_ = binary.Write(r.conn, binary.BigEndian, len(p))
_, _ = r.conn.Write(p)
}
func (r *TCPResolver) Close() {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed() {
r.mu.Unlock()
return
}
close(r.closeCh)
conn := r.conn
r.mu.Unlock()
if conn != nil {
_ = conn.Close()
}
r.wg.Wait()
close(r.readCh)
}
+22 -3
View File
@@ -41,14 +41,17 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string) (*clientConn, error) {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, padding []*Padding) (*clientConn, error) {
if len(rsaPublicKey) == 0 {
return nil, fmt.Errorf("empty rsa public key")
}
if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles")
}
paddingSchedule, err := newClientPaddingSchedule2612()
if len(password) > MaxLegacyPasswordLength {
return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
}
paddingSchedule, err := newPaddingSchedule(padding, true)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
@@ -195,6 +198,22 @@ func (c *clientConn) handshake() error {
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
// Set Compression is not compressed itself and must be handled before the
// packet that follows it, which already uses the compressed framing.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer, int32(threshold))
}
pkt, err = readPacket(c.reader)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
}
if pkt.packetID == 0x00 {
var reason String
if readErr := pkt.readFields(&reason); readErr != nil {
@@ -217,7 +236,7 @@ func (c *clientConn) handshake() error {
if err != nil {
return fmt.Errorf("write login acknowledged: %w", err)
}
if err = runPaddingSchedule(c.reader, c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
return fmt.Errorf("run startup padding: %w", err)
}
@@ -0,0 +1,194 @@
// Minecraft compression framing, negotiated by the login Set Compression packet.
package xmc
import (
"bytes"
"compress/zlib"
"fmt"
"io"
)
const (
// Packet Length is a VarInt, so one frame cannot exceed 2^21-1 bytes.
maxCompressedFrameLength = (1 << 21) - 1
// Vanilla caps serverbound uncompressed packet bodies at 2^23 bytes.
maxUncompressedFrameBody = 1 << 23
)
// compressionReader converts the post-Set Compression framing
// (Packet Length, Data Length, optional zlib body) back into the plain
// (VarInt body length, body) frame that readPacket expects.
//
// A zero Data Length means the body was sent uncompressed, which vanilla
// servers accept even when the body exceeds the negotiated threshold.
type compressionReader struct {
r io.Reader
frame bytes.Buffer
}
func newCompressionReader(r io.Reader) io.Reader {
return &compressionReader{r: r}
}
func (c *compressionReader) Read(p []byte) (int, error) {
if c.frame.Len() == 0 {
if err := c.readFrame(); err != nil {
return 0, err
}
}
return c.frame.Read(p)
}
func (c *compressionReader) readFrame() error {
packetLength, _, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed packet length: %w", err)
}
if packetLength < 1 || int(packetLength) > maxCompressedFrameLength {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
dataLength, dataLengthSize, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed data length: %w", err)
}
if dataLength < 0 || int(dataLength) > maxUncompressedFrameBody {
return fmt.Errorf("read compressed packet: bad uncompressed length: %d", dataLength)
}
payloadLength := int(packetLength) - dataLengthSize
if payloadLength < 0 {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
payload := make([]byte, payloadLength)
if _, err := io.ReadFull(c.r, payload); err != nil {
return fmt.Errorf("read compressed packet data: %w", err)
}
body := payload
if dataLength > 0 {
zr, err := zlib.NewReader(bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("open compressed packet: %w", err)
}
body = make([]byte, int(dataLength))
_, readErr := io.ReadFull(zr, body)
closeErr := zr.Close()
if readErr != nil {
return fmt.Errorf("decompress packet: %w", readErr)
}
if closeErr != nil {
return fmt.Errorf("close decompressor: %w", closeErr)
}
}
if len(body) < 1 {
return fmt.Errorf("read compressed packet: empty body")
}
var frame bytes.Buffer
frame.Grow(varintSize(Varint(len(body))) + len(body))
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(body)
c.frame = frame
return nil
}
// compressionWriter converts a plain frame (VarInt body length, body) into the
// post-Set Compression framing. Frames are buffered until complete, because a
// caller may split one frame across several Write calls.
type compressionWriter struct {
w io.Writer
threshold int32
pending []byte
}
func newCompressionWriter(w io.Writer, threshold int32) io.Writer {
return &compressionWriter{w: w, threshold: threshold}
}
func (c *compressionWriter) Write(p []byte) (int, error) {
c.pending = append(c.pending, p...)
for {
body, ok, err := c.nextFrame()
if err != nil {
return 0, err
}
if !ok {
return len(p), nil
}
if err := c.writeFrame(body); err != nil {
return 0, err
}
}
}
// nextFrame returns one complete frame body from the pending bytes. It only
// waits for more bytes while the length prefix or the body is still
// incomplete; a complete but invalid prefix is an error.
func (c *compressionWriter) nextFrame() ([]byte, bool, error) {
limit := len(c.pending)
if limit > 5 {
limit = 5
}
bodyLength, prefixLength, err := readVarintWithLength(bytes.NewReader(c.pending[:limit]))
if err != nil {
if len(c.pending) < 5 {
return nil, false, nil
}
return nil, false, fmt.Errorf("read frame length: %w", err)
}
if bodyLength < 1 {
return nil, false, fmt.Errorf("read frame: bad length: %d", bodyLength)
}
end := prefixLength + int(bodyLength)
if end > len(c.pending) {
return nil, false, nil
}
// The body stays valid after the reslice: appends only write past the
// remaining pending length and writeFrame consumes it immediately.
body := c.pending[prefixLength:end]
c.pending = c.pending[end:]
return body, true, nil
}
func (c *compressionWriter) writeFrame(body []byte) error {
if len(body) >= int(c.threshold) {
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
_ = zw.Close()
return fmt.Errorf("compress packet: %w", err)
}
if err := zw.Close(); err != nil {
return fmt.Errorf("close compressor: %w", err)
}
var frame bytes.Buffer
packetLength := varintSize(Varint(len(body))) + compressed.Len()
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(compressed.Bytes())
return writeFull(c.w, frame.Bytes())
}
var frame bytes.Buffer
frame.Grow(varintSize(Varint(1+len(body))) + 1 + len(body))
frameLength := Varint(1 + len(body))
if err := frameLength.writeTo(&frame); err != nil {
return err
}
frame.WriteByte(0)
frame.Write(body)
return writeFull(c.w, frame.Bytes())
}
@@ -0,0 +1,220 @@
package xmc
import (
"bytes"
"crypto/rand"
"errors"
"io"
"testing"
)
func plainFrame(body []byte) []byte {
frame := make([]byte, 0, 5+len(body))
length := Varint(len(body))
var buf bytes.Buffer
_ = length.writeTo(&buf)
frame = append(frame, buf.Bytes()...)
return append(frame, body...)
}
type wireFrame struct {
packetLength int
dataLength int
payload []byte
}
func readWireFrame(t *testing.T, r *bytes.Reader) wireFrame {
t.Helper()
packetLength, _, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read packet length: %v", err)
}
dataLength, dataLengthSize, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read data length: %v", err)
}
payload := make([]byte, int(packetLength)-dataLengthSize)
if _, err := io.ReadFull(r, payload); err != nil {
t.Fatalf("read payload: %v", err)
}
return wireFrame{packetLength: int(packetLength), dataLength: int(dataLength), payload: payload}
}
func randomBody(t *testing.T, size int) []byte {
t.Helper()
body := make([]byte, size)
if _, err := rand.Read(body); err != nil {
t.Fatalf("random body: %v", err)
}
return body
}
func TestCompressionWriterThreshold(t *testing.T) {
for _, threshold := range []int32{0, 1, 256, 65536} {
for _, size := range []int{1, 10, 255, 256, 257, 65535, 65536} {
body := bytes.Repeat([]byte{0}, size)
var wire bytes.Buffer
w := newCompressionWriter(&wire, threshold)
if _, err := w.Write(plainFrame(body)); err != nil {
t.Fatalf("threshold %d size %d: write: %v", threshold, size, err)
}
frame := readWireFrame(t, bytes.NewReader(wire.Bytes()))
wantCompressed := int32(size) >= threshold
if wantCompressed && frame.dataLength != size {
t.Fatalf("threshold %d size %d: want compressed data length %d, got %d", threshold, size, size, frame.dataLength)
}
if !wantCompressed {
if frame.dataLength != 0 {
t.Fatalf("threshold %d size %d: want uncompressed frame, got data length %d", threshold, size, frame.dataLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("threshold %d size %d: uncompressed payload mismatch", threshold, size)
}
if frame.packetLength != 1+size {
t.Fatalf("threshold %d size %d: packet length %d", threshold, size, frame.packetLength)
}
}
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("threshold %d size %d: decode: %v", threshold, size, err)
}
if !bytes.Equal(decoded, body) {
t.Fatalf("threshold %d size %d: round trip mismatch", threshold, size)
}
}
}
}
func TestCompressionRoundTripChunked(t *testing.T) {
cases := [][]byte{
[]byte("hello"),
randomBody(t, 255),
randomBody(t, 24*1024),
randomBody(t, 64*1024),
bytes.Repeat([]byte("xmc"), 8*1024),
}
for _, threshold := range []int32{0, 256, 65536} {
var wire bytes.Buffer
w := newCompressionWriter(&wire, threshold)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("threshold %d: chunked write: %v", threshold, err)
}
frame = frame[n:]
}
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("threshold %d frame %d: decode: %v", threshold, i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("threshold %d frame %d: mismatch (%d vs %d bytes)", threshold, i, len(got), len(want))
}
}
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("threshold %d: expected EOF after the last frame, got %v", threshold, err)
}
}
}
func TestCompressionMultipleFramesOneWrite(t *testing.T) {
var plain []byte
bodies := [][]byte{[]byte("a"), randomBody(t, 1024), randomBody(t, 300)}
for _, body := range bodies {
plain = append(plain, plainFrame(body)...)
}
var wire bytes.Buffer
w := newCompressionWriter(&wire, 256)
if _, err := w.Write(plain); err != nil {
t.Fatalf("write: %v", err)
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range bodies {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch", i)
}
}
}
// Vanilla servers accept uncompressed packets even when the body exceeds the
// negotiated threshold, which is what lets padding frames keep their wire size.
func TestCompressionReaderUncompressedOverThreshold(t *testing.T) {
body := randomBody(t, 64*1024)
var wire bytes.Buffer
length := Varint(1 + len(body))
if err := length.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.WriteByte(0)
wire.Write(body)
got, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("decode: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatal("payload mismatch")
}
}
func TestCompressionReaderErrors(t *testing.T) {
// Compressed packet with a bogus body.
var badZlib bytes.Buffer
length := Varint(1 + 10)
_ = length.writeTo(&badZlib)
dataLength := Varint(64)
_ = dataLength.writeTo(&badZlib)
badZlib.Write(bytes.Repeat([]byte{0xff}, 10))
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(badZlib.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an invalid zlib body")
}
// Uncompressed length beyond the vanilla limit.
var tooLong bytes.Buffer
length = Varint(1 + 4)
_ = length.writeTo(&tooLong)
dataLength = Varint(maxUncompressedFrameBody + 1)
_ = dataLength.writeTo(&tooLong)
tooLong.Write([]byte{1, 2, 3, 4})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(tooLong.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an oversized uncompressed length")
}
// Truncated payload.
var truncated bytes.Buffer
length = Varint(1 + 100)
_ = length.writeTo(&truncated)
var zero Varint
_ = zero.writeTo(&truncated)
truncated.Write([]byte{1, 2, 3})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(truncated.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for a truncated payload")
}
}
func TestCompressionWriterInvalidFrameLength(t *testing.T) {
var wire bytes.Buffer
w := newCompressionWriter(&wire, 256)
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for an invalid frame length prefix")
}
}
+71 -2
View File
@@ -2,17 +2,28 @@ package xmc
import (
"fmt"
"math"
"time"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
// maxPaddingDelayMilliseconds keeps the millisecond value convertible to a
// time.Duration on every platform.
const maxPaddingDelayMilliseconds = int64(math.MaxInt64 / int64(time.Millisecond))
// MaxLegacyPasswordLength is the longest pre-shared password the login can
// carry. The verify token (4 random bytes) and the password travel together in
// one RSA-1024 PKCS#1 v1.5 block, which holds at most 128-11 bytes.
const MaxLegacyPasswordLength = 128 - 11 - 4
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
profiles, err := profilesFromConfig(c.Profiles)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname)
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, c.Paddings)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -25,10 +36,68 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey)
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, c.Paddings)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
return cc, nil
}
// ValidatePadding checks custom startup turns without selecting a built-in preset.
func (c *Config) ValidatePadding() error {
_, err := paddingScheduleFromConfig(c.Paddings)
return err
}
func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
if len(paddings) == 0 {
return nil, nil
}
schedule := make([]paddingTurn, len(paddings))
for i, turn := range paddings {
if turn == nil || turn.LengthMin < 1 || turn.LengthMax < turn.LengthMin || turn.LengthMax > maxPaddingTurnLength {
return nil, fmt.Errorf("invalid padding length range at turn %d", i)
}
if turn.DelayMin < 0 || turn.DelayMax < turn.DelayMin {
return nil, fmt.Errorf("invalid padding delay range %d-%d at turn %d (must be non-negative and ordered)", turn.DelayMin, turn.DelayMax, i)
}
if turn.DelayMax > maxPaddingDelayMilliseconds {
return nil, fmt.Errorf("padding delay range %d-%d at turn %d is too large", turn.DelayMin, turn.DelayMax, i)
}
var direction paddingDirection
switch turn.Direction {
case 1:
direction = paddingClientToServer
case 2:
direction = paddingServerToClient
default:
return nil, fmt.Errorf("invalid padding direction %d at turn %d (1=client-to-server, 2=server-to-client)", turn.Direction, i)
}
schedule[i] = paddingTurn{
direction: direction,
minLength: int(turn.LengthMin),
maxLength: int(turn.LengthMax),
delay: paddingDelayRange{
min: time.Duration(turn.DelayMin) * time.Millisecond,
max: time.Duration(turn.DelayMax) * time.Millisecond,
},
}
}
// The first turn includes the two-byte Login Acknowledged packet.
if err := validatePaddingSchedule(schedule, 2); err != nil {
return nil, err
}
return schedule, nil
}
func newPaddingSchedule(paddings []*Padding, isClient bool) ([]paddingTurn, error) {
schedule, err := paddingScheduleFromConfig(paddings)
if err != nil || schedule != nil {
return schedule, err
}
if isClient {
return newClientPaddingSchedule2612()
}
return newServerPaddingSchedule2612()
}
+109 -9
View File
@@ -99,6 +99,8 @@ type Config struct {
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"`
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"`
// Startup padding turns. Empty uses the built-in preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -168,6 +170,93 @@ func (x *Config) GetProfiles() []*Profile {
return nil
}
func (x *Config) GetPaddings() []*Padding {
if x != nil {
return x.Paddings
}
return nil
}
type Padding struct {
state protoimpl.MessageState `protogen:"open.v1"`
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
LengthMax int64 `protobuf:"varint,2,opt,name=length_max,json=lengthMax,proto3" json:"length_max,omitempty"`
// 1 = client to server, 2 = server to client
Direction int32 `protobuf:"varint,3,opt,name=direction,proto3" json:"direction,omitempty"`
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
DelayMin int64 `protobuf:"varint,4,opt,name=delay_min,json=delayMin,proto3" json:"delay_min,omitempty"`
DelayMax int64 `protobuf:"varint,5,opt,name=delay_max,json=delayMax,proto3" json:"delay_max,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Padding) Reset() {
*x = Padding{}
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Padding) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Padding) ProtoMessage() {}
func (x *Padding) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Padding.ProtoReflect.Descriptor instead.
func (*Padding) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2}
}
func (x *Padding) GetLengthMin() int64 {
if x != nil {
return x.LengthMin
}
return 0
}
func (x *Padding) GetLengthMax() int64 {
if x != nil {
return x.LengthMax
}
return 0
}
func (x *Padding) GetDirection() int32 {
if x != nil {
return x.Direction
}
return 0
}
func (x *Padding) GetDelayMin() int64 {
if x != nil {
return x.DelayMin
}
return 0
}
func (x *Padding) GetDelayMax() int64 {
if x != nil {
return x.DelayMax
}
return 0
}
var File_transport_internet_finalmask_xmc_config_proto protoreflect.FileDescriptor
const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
@@ -177,14 +266,23 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xe0\x01\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xac\x02\n" +
"\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
"\x0ersa_public_key\x18\t \x01(\fR\frsaPublicKey\x12\x1a\n" +
"\bhostname\x18\n" +
" \x01(\tR\bhostname\x12J\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofilesJ\x04\b\x02\x10\x03B\x91\x01\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddingsJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\aPadding\x12\x1d\n" +
"\n" +
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
"\n" +
"length_max\x18\x02 \x01(\x03R\tlengthMax\x12\x1c\n" +
"\tdirection\x18\x03 \x01(\x05R\tdirection\x12\x1b\n" +
"\tdelay_min\x18\x04 \x01(\x03R\bdelayMin\x12\x1b\n" +
"\tdelay_max\x18\x05 \x01(\x03R\bdelayMaxB\x91\x01\n" +
")com.xray.transport.internet.finalmask.xmcP\x01Z:github.com/xtls/xray-core/transport/internet/finalmask/xmc\xaa\x02%Xray.Transport.Internet.Finalmask.XMCb\x06proto3"
var (
@@ -199,18 +297,20 @@ func file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP() []byte {
return file_transport_internet_finalmask_xmc_config_proto_rawDescData
}
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
(*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config
(*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding
}
var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{
0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
2, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_transport_internet_finalmask_xmc_config_proto_init() }
@@ -224,7 +324,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
@@ -23,4 +23,18 @@ message Config {
bytes rsa_public_key = 9;
string hostname = 10;
repeated Profile profiles = 11;
// Startup padding turns. Empty uses the built-in preset.
repeated Padding paddings = 12;
}
message Padding {
int64 length_min = 1;
int64 length_max = 2;
// 1 = client to server, 2 = server to client
int32 direction = 3;
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
int64 delay_min = 4;
int64 delay_max = 5;
}
@@ -0,0 +1,23 @@
package xmc
import (
"net"
"strings"
"testing"
)
func TestClientRejectsLongLegacyPassword(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
profiles := []loginProfile{{Username: "TestUser"}}
publicKey := []byte{0x01}
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
}
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil); err == nil {
t.Fatal("expected the long password to be rejected")
}
}
@@ -1,81 +0,0 @@
package xmc
import (
"net"
"sync"
"testing"
"time"
)
func TestConnectionDeadlinesRestoreCallerValues(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
recording := &deadlineRecordingConn{Conn: client}
deadlines := newConnectionDeadlines(recording)
callerDeadline := time.Now().Add(10 * time.Minute)
if err := deadlines.setDeadline(callerDeadline); err != nil {
t.Fatal(err)
}
if err := deadlines.beginHandshake(); err != nil {
t.Fatal(err)
}
read, write := recording.currentDeadlines()
if !read.Before(callerDeadline) || !write.Before(callerDeadline) {
t.Fatalf("handshake deadlines = %s/%s, caller = %s", read, write, callerDeadline)
}
shortReadDeadline := time.Now().Add(time.Second)
if err := deadlines.setReadDeadline(shortReadDeadline); err != nil {
t.Fatal(err)
}
read, _ = recording.currentDeadlines()
if !read.Equal(shortReadDeadline) {
t.Fatalf("read deadline = %s, want %s", read, shortReadDeadline)
}
if err := deadlines.endHandshake(); err != nil {
t.Fatal(err)
}
read, write = recording.currentDeadlines()
if !read.Equal(shortReadDeadline) || !write.Equal(callerDeadline) {
t.Fatalf("restored deadlines = %s/%s, want %s/%s", read, write, shortReadDeadline, callerDeadline)
}
}
type deadlineRecordingConn struct {
net.Conn
mu sync.Mutex
read time.Time
write time.Time
}
func (c *deadlineRecordingConn) SetDeadline(t time.Time) error {
c.mu.Lock()
c.read = t
c.write = t
c.mu.Unlock()
return c.Conn.SetDeadline(t)
}
func (c *deadlineRecordingConn) SetReadDeadline(t time.Time) error {
c.mu.Lock()
c.read = t
c.mu.Unlock()
return c.Conn.SetReadDeadline(t)
}
func (c *deadlineRecordingConn) SetWriteDeadline(t time.Time) error {
c.mu.Lock()
c.write = t
c.mu.Unlock()
return c.Conn.SetWriteDeadline(t)
}
func (c *deadlineRecordingConn) currentDeadlines() (time.Time, time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
return c.read, c.write
}
@@ -1,58 +0,0 @@
package xmc
import (
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"testing"
)
func TestDeriveRSAKey(t *testing.T) {
password := "my-very-secret-password-12345"
key1, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key: %v", err)
}
err = key1.Validate()
if err != nil {
t.Fatalf("key is not valid RSA key: %v", err)
}
key2, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key second time: %v", err)
}
// Verify determinism
if key1.D.Cmp(key2.D) != 0 || key1.N.Cmp(key2.N) != 0 {
t.Errorf("derived keys are not identical for the same password")
}
// Verify different passwords yield different keys
keyDifferent, err := DeriveRSAKey(password + "-different")
if err != nil {
t.Fatalf("failed to derive different key: %v", err)
}
if key1.D.Cmp(keyDifferent.D) == 0 || key1.N.Cmp(keyDifferent.N) == 0 {
t.Errorf("derived keys are identical for different passwords")
}
}
func TestDeriveRSAKeyGoldenPrivateKey(t *testing.T) {
const password = "deterministic-rsa-key-golden"
const wantPKCS1DERHash = "3a8c4ad56a6fb42dab73c4d5fc3af754460a2db1441edc0970cbc7f4e0798d2f"
key, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key: %v", err)
}
gotHash := sha256.Sum256(x509.MarshalPKCS1PrivateKey(key))
got := hex.EncodeToString(gotHash[:])
if got != wantPKCS1DERHash {
t.Fatalf("derived private key changed\nwant sha256: %s\n got sha256: %s", wantPKCS1DERHash, got)
}
}
@@ -1,390 +0,0 @@
package xmc
import (
"bytes"
"crypto/sha256"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"testing"
"time"
)
func deriveTestRSAKey(t *testing.T, password string) ([]byte, []byte) {
t.Helper()
key, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive rsa key: %v", err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatalf("failed to marshal public key: %v", err)
}
return x509.MarshalPKCS1PrivateKey(key), publicKey
}
func testLoginProfile(username string) loginProfile {
profile := loginProfile{
Username: username,
TexturesValue: strings.Repeat("texture-value-", 40),
TexturesSignature: strings.Repeat("texture-signature-", 24),
}
digest := sha256.Sum256([]byte(username))
copy(profile.UUID[:], digest[:16])
profile.UUID[6] = (profile.UUID[6] & 0x0f) | 0x40
profile.UUID[8] = (profile.UUID[8] & 0x3f) | 0x80
return profile
}
func TestHandshakeSuccess(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
password := "super-secure-shared-key-12345"
profiles := []loginProfile{testLoginProfile("test_user")}
privateKey, publicKey := deriveTestRSAKey(t, password)
go func() {
rawConn, err := ln.Accept()
if err != nil {
return
}
defer rawConn.Close()
server, err := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
if err != nil {
t.Errorf("failed to wrap server: %v", err)
return
}
buf := make([]byte, 1024)
n, err := server.Read(buf)
if err != nil {
t.Errorf("server read error: %v", err)
return
}
if !bytes.Equal(buf[:n], []byte("hello server")) {
t.Errorf("unexpected payload from client: %s", string(buf[:n]))
return
}
_, err = server.Write([]byte("hello client"))
if err != nil {
t.Errorf("server write error: %v", err)
return
}
}()
clientRaw, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer clientRaw.Close()
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatalf("failed to create client: %v", err)
}
_, err = client.Write([]byte("hello server"))
if err != nil {
t.Fatalf("client write error: %v", err)
}
buf := make([]byte, 1024)
n, err := client.Read(buf)
if err != nil {
t.Fatalf("client read error: %v", err)
}
if !bytes.Equal(buf[:n], []byte("hello client")) {
t.Errorf("unexpected payload from server: %s", string(buf[:n]))
}
}
func TestHandshakePasswordMismatch(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
clientPassword := "client-secret-123"
serverPassword := "server-secret-456"
profiles := []loginProfile{testLoginProfile("test_user")}
serverPrivateKey, serverPublicKey := deriveTestRSAKey(t, serverPassword)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
rawConn, err := ln.Accept()
if err != nil {
return
}
defer rawConn.Close()
server, err := wrapConnServer(rawConn, profiles, serverPassword, serverPrivateKey, serverPublicKey)
if err != nil {
// Wrapping is synchronous and shouldn't fail initially simply because key derivation works with any string
t.Logf("wrapped server: %v", err)
}
// When client sends data, handshake happens and should fail
buf := make([]byte, 1024)
_, err = server.Read(buf)
if err == nil {
t.Errorf("expected handshake to fail due to password mismatch, but it succeeded")
} else {
t.Logf("server read failed as expected: %v", err)
}
}()
clientRaw, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer clientRaw.Close()
client, err := newClientConn(clientRaw, profiles, clientPassword, serverPublicKey, "localhost")
if err != nil {
t.Fatalf("failed to create client: %v", err)
}
err = client.handshake()
if err == nil {
t.Fatal("expected client handshake to fail due to password mismatch")
}
wg.Wait()
// Check if we lost connection or received error
t.Log("Handshake mismatch tested")
}
func TestHandshakeNetPipeWithKeepAlive(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
const password = "net-pipe-shared-key"
profiles := []loginProfile{testLoginProfile("pipe_user")}
privateKey, publicKey := deriveTestRSAKey(t, password)
serverDone := make(chan error, 1)
go func() {
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey)
if err != nil {
serverDone <- err
return
}
request := make([]byte, len("hello server"))
if _, err = io.ReadFull(server, request); err != nil {
serverDone <- fmt.Errorf("read request: %w", err)
return
}
if string(request) != "hello server" {
serverDone <- fmt.Errorf("unexpected request: %q", request)
return
}
followupDone := make(chan error, 1)
go func() {
followup := make([]byte, len("after keepalive"))
_, readErr := io.ReadFull(server, followup)
if readErr == nil && string(followup) != "after keepalive" {
readErr = fmt.Errorf("unexpected followup: %q", followup)
}
followupDone <- readErr
}()
if err = server.packet.writeKeepAlive(Long(42)); err != nil {
serverDone <- fmt.Errorf("write keep-alive: %w", err)
return
}
if _, err = server.Write([]byte("hello client")); err != nil {
serverDone <- fmt.Errorf("write response: %w", err)
return
}
serverDone <- <-followupDone
}()
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if _, err = client.Write([]byte("hello server")); err != nil {
t.Fatalf("write request: %v", err)
}
response := make([]byte, len("hello client"))
if _, err = io.ReadFull(client, response); err != nil {
t.Fatalf("read response: %v", err)
}
if string(response) != "hello client" {
t.Fatalf("unexpected response: %q", response)
}
if _, err = client.Write([]byte("after keepalive")); err != nil {
t.Fatalf("write followup: %v", err)
}
select {
case err = <-serverDone:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("net.Pipe handshake timed out")
}
}
func TestStatusQueryUnaffected(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
const password = "status-shared-key"
profiles := []loginProfile{testLoginProfile("status_user")}
privateKey, publicKey := deriveTestRSAKey(t, password)
serverDone := make(chan error, 1)
go func() {
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey)
if err == nil {
err = server.handshake()
}
serverDone <- err
}()
protocolVersion := Varint(775)
serverAddress := String("localhost")
serverPort := UnsignedShort(25565)
nextState := Varint(1)
if err := writePacket(clientRaw, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState); err != nil {
t.Fatal(err)
}
if err := writePacket(clientRaw, 0x00); err != nil {
t.Fatal(err)
}
response, err := readPacket(clientRaw)
if err != nil {
t.Fatal(err)
}
if response.packetID != 0x00 {
t.Fatalf("status packet id = %d", response.packetID)
}
var responseJSON String
if err = response.readFields(&responseJSON); err != nil {
t.Fatal(err)
}
if string(responseJSON) != statusResponse {
t.Fatalf("status response = %q", responseJSON)
}
payload := Long(0x0102030405060708)
if err = writePacket(clientRaw, 0x01, &payload); err != nil {
t.Fatal(err)
}
pong, err := readPacket(clientRaw)
if err != nil {
t.Fatal(err)
}
var receivedPayload Long
if pong.packetID != 0x01 {
t.Fatalf("pong packet id = %d", pong.packetID)
}
if err = pong.readFields(&receivedPayload); err != nil {
t.Fatal(err)
}
if receivedPayload != payload {
t.Fatalf("pong payload = %x", receivedPayload)
}
select {
case err = <-serverDone:
if err == nil || !strings.Contains(err.Error(), "ping") {
t.Fatalf("server error = %v", err)
}
case <-time.After(time.Second):
t.Fatal("status handshake timed out")
}
}
func TestClientHandshakeHonorsCallerDeadline(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
const password = "deadline-shared-key"
profiles := []loginProfile{testLoginProfile("deadline_user")}
_, publicKey := deriveTestRSAKey(t, password)
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if err = client.SetDeadline(time.Now().Add(30 * time.Millisecond)); err != nil {
t.Fatal(err)
}
started := time.Now()
_, err = client.Write([]byte("blocked"))
var netErr net.Error
if !errors.As(err, &netErr) || !netErr.Timeout() {
t.Fatalf("error = %v, want network timeout", err)
}
if elapsed := time.Since(started); elapsed > 500*time.Millisecond {
t.Fatalf("caller deadline took %s", elapsed)
}
}
func TestClientCloseInterruptsHandshake(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer serverRaw.Close()
const password = "close-shared-key"
profiles := []loginProfile{testLoginProfile("close_user")}
_, publicKey := deriveTestRSAKey(t, password)
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
_, writeErr := client.Write([]byte("blocked"))
done <- writeErr
}()
time.Sleep(20 * time.Millisecond)
if err = client.Close(); err != nil {
t.Fatal(err)
}
select {
case err = <-done:
if err == nil {
t.Fatal("handshake unexpectedly succeeded after close")
}
case <-time.After(time.Second):
t.Fatal("close did not interrupt handshake")
}
}
func TestValidateLoginAcknowledgedPacketRejectsData(t *testing.T) {
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03}); err != nil {
t.Fatalf("valid login acknowledged packet: %v", err)
}
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03, data: []byte{0x00}}); err == nil {
t.Fatal("login acknowledged packet with trailing data was accepted")
}
}
@@ -1,102 +0,0 @@
package xmc
import (
"bytes"
"io"
"net"
"testing"
)
func TestPacketStreamUsesPlainFraming(t *testing.T) {
payload := []byte("hello")
var wire bytes.Buffer
stream := newPacketStream(bytes.NewReader(nil), &wire, true)
written, err := stream.Write(payload)
if err != nil {
t.Fatalf("write payload: %v", err)
}
if written != len(payload) {
t.Fatalf("written = %d, want %d", written, len(payload))
}
wantOutbound := []byte{0x0f, 0x02, 0x08, 'x', 'm', 'c', ':', 'd', 'a', 't', 'a', 'h', 'e', 'l', 'l', 'o'}
if !bytes.Equal(wire.Bytes(), wantOutbound) {
t.Fatalf("wire frame = %x, want %x", wire.Bytes(), wantOutbound)
}
wantInbound := append([]byte(nil), wantOutbound...)
wantInbound[1] = configurationClientboundCustomPayload
reader := newPacketStream(bytes.NewReader(wantInbound), io.Discard, true)
got := make([]byte, len(payload))
if _, err = io.ReadFull(reader, got); err != nil {
t.Fatalf("read payload: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("payload = %q, want %q", got, payload)
}
}
func TestPacketStreamRoundTrip(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
const password = "packet-stream-shared-key"
privateKey, publicKey := deriveTestRSAKey(t, password)
profiles := []loginProfile{testLoginProfile("packet_user")}
clientPayload := bytes.Repeat([]byte("client-payload-"), 5000)
serverPayload := bytes.Repeat([]byte("server-payload-"), 5000)
serverDone := make(chan error, 1)
go func() {
rawConn, acceptErr := ln.Accept()
if acceptErr != nil {
serverDone <- acceptErr
return
}
defer rawConn.Close()
server, wrapErr := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
if wrapErr != nil {
serverDone <- wrapErr
return
}
got := make([]byte, len(clientPayload))
if _, readErr := io.ReadFull(server, got); readErr != nil {
serverDone <- readErr
return
}
if !bytes.Equal(got, clientPayload) {
serverDone <- io.ErrUnexpectedEOF
return
}
_, writeErr := server.Write(serverPayload)
serverDone <- writeErr
}()
rawClient, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
defer rawClient.Close()
client, err := newClientConn(rawClient, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if _, err = client.Write(clientPayload); err != nil {
t.Fatalf("write payload: %v", err)
}
got := make([]byte, len(serverPayload))
if _, err = io.ReadFull(client, got); err != nil {
t.Fatalf("read payload: %v", err)
}
if !bytes.Equal(got, serverPayload) {
t.Fatal("server payload mismatch")
}
if err = <-serverDone; err != nil {
t.Fatalf("server: %v", err)
}
}
+126 -87
View File
@@ -1,7 +1,6 @@
package xmc
import (
"bytes"
"crypto/rand"
"fmt"
"io"
@@ -18,8 +17,21 @@ const (
paddingBufferLength = 16 * 1024
maxPaddingChunkLength = 48 * 1024
maxPaddingTurnLength = 8 * 1024 * 1024
// Frame padding carries the startup padding in ordinary Minecraft custom
// payload packets so that a vanilla server can parse the whole connection
// without taking the pipeline over. The channel is deliberately different
// from the packet stream channel: both ends drop unknown payloads.
paddingFrameChannel = "xmc:pad"
// Serverbound custom payload data is capped at 32767 bytes by
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
maxPaddingFrameDataLength = 32767
// Length varint, packet id, channel length varint and the channel itself.
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
)
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
type paddingVariant struct {
chunks []int
delays []paddingDelayRange
@@ -34,6 +46,7 @@ type paddingTurn struct {
direction paddingDirection
minLength int
maxLength int
delay paddingDelayRange // pause after this turn, including the last one
variants []paddingVariant
startDelay paddingDelayRange
chunkDelay paddingDelayRange
@@ -44,27 +57,40 @@ type paddingTurn struct {
sendVariants []int
}
func runPaddingSchedule(reader io.Reader, writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
return runPaddingScheduleWithSleep(writer, isClient, firstTurnPrefixLength, schedule, time.Sleep)
}
func runPaddingScheduleWithSleep(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration)) error {
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
return err
}
var writeBuffer []byte
for i, turn := range schedule {
prefixLength := 0
if i == 0 {
prefixLength = firstTurnPrefixLength
}
localSends := isClient == (turn.direction == paddingClientToServer)
if localSends {
if err := writePaddingTurnWithBuffer(writer, turn, prefixLength, time.Sleep, &writeBuffer); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
if isClient != (turn.direction == paddingClientToServer) {
// Padding is ordinary Minecraft traffic, so the peer's turns are
// never consumed here: they stay in the stream and are dropped as
// unknown packets by whoever reads it next. Both endpoints still
// apply the same minimum pause, including after the last turn.
if turn.delay.min > 0 {
sleep(turn.delay.min)
}
continue
}
if err := readPaddingTurn(reader, turn, prefixLength); err != nil {
return fmt.Errorf("read padding turn %d: %w", i, err)
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
}
delay, err := randomPaddingDelay(turn.delay)
if err != nil {
return fmt.Errorf("select padding turn %d delay: %w", i, err)
}
if delay > 0 {
sleep(delay)
}
}
return nil
@@ -91,6 +117,9 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
if err := validatePaddingDelayRange(turn.chunkDelay); err != nil {
return fmt.Errorf("padding turn %d has an invalid chunk delay: %w", i, err)
}
if err := validatePaddingDelayRange(turn.delay); err != nil {
return fmt.Errorf("padding turn %d has an invalid inter-turn delay: %w", i, err)
}
if turn.writeChunkMinLength < 0 || turn.writeChunkLength < turn.writeChunkMinLength || turn.writeChunkLength > maxPaddingChunkLength {
return fmt.Errorf("padding turn %d has an invalid write chunk range: %d-%d", i, turn.writeChunkMinLength, turn.writeChunkLength)
}
@@ -121,25 +150,27 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
}
}
}
if i > 0 && turn.direction == schedule[i-1].direction {
return fmt.Errorf("padding turns %d and %d have the same direction", i-1, i)
}
}
return nil
}
func writePaddingTurn(w io.Writer, turn paddingTurn, prefixLength int) error {
return writePaddingTurnWithSleep(w, turn, prefixLength, time.Sleep)
// paddingFramePacketID returns the configuration-state custom payload packet id
// used by the side that sends the padding bytes; both values come from the
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
func paddingFramePacketID(isClient bool) int {
if isClient {
return configurationServerboundCustomPayload
}
return configurationClientboundCustomPayload
}
func writePaddingTurnWithSleep(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration)) error {
return writePaddingTurnWithBuffer(w, turn, prefixLength, sleep, nil)
}
func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), reusableBuffer *[]byte) error {
// writePaddingTurnFrames writes one padding turn as a sequence of valid
// Minecraft custom payload frames. Only the framing is native: payload bodies
// stay zero-filled, so the captured traffic shape is kept.
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), packetID int) (int, error) {
startDelay, err := randomPaddingDelay(turn.startDelay)
if err != nil {
return fmt.Errorf("select padding start delay: %w", err)
return 0, fmt.Errorf("select padding start delay: %w", err)
}
if startDelay > 0 {
sleep(startDelay)
@@ -147,17 +178,11 @@ func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int,
targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength)
if err != nil {
return err
return 0, err
}
recordLength := targetLength - prefixLength
if recordLength < 1 {
return fmt.Errorf("target length %d leaves an invalid record length %d", targetLength, recordLength)
}
encodedLength := Varint(recordLength)
var header bytes.Buffer
if err = encodedLength.writeTo(&header); err != nil {
return fmt.Errorf("write padding header: %w", err)
payloadLength := targetLength - prefixLength
if payloadLength < 1 {
return 0, fmt.Errorf("target length %d leaves an invalid padding payload of %d bytes", targetLength, payloadLength)
}
if len(chunks) == 0 {
writeChunkLength := turn.writeChunkLength
@@ -166,89 +191,103 @@ func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int,
} else if turn.writeChunkMinLength > 0 {
writeChunkLength, err = randomPaddingTarget(turn.writeChunkMinLength, writeChunkLength)
if err != nil {
return fmt.Errorf("select padding write chunk length: %w", err)
return 0, fmt.Errorf("select padding write chunk length: %w", err)
}
}
chunks = defaultPaddingChunks(recordLength, writeChunkLength)
chunks = defaultPaddingChunks(payloadLength, writeChunkLength)
delays = make([]paddingDelayRange, len(chunks))
for i := 1; i < len(delays); i++ {
delays[i] = turn.chunkDelay
}
}
if chunks[0] < header.Len() {
return fmt.Errorf("first padding chunk %d is shorter than header %d", chunks[0], header.Len())
}
maxChunkLength := 0
for _, chunkLength := range chunks {
if chunkLength < 1 || chunkLength > maxPaddingChunkLength {
return fmt.Errorf("invalid padding chunk length: %d", chunkLength)
}
maxChunkLength = max(maxChunkLength, chunkLength)
}
var buffer []byte
if reusableBuffer == nil {
buffer = make([]byte, maxChunkLength)
} else {
if cap(*reusableBuffer) < maxChunkLength {
*reusableBuffer = make([]byte, maxChunkLength)
}
buffer = (*reusableBuffer)[:maxChunkLength]
clear(buffer)
}
copy(buffer, header.Bytes())
zeros := make([]byte, maxPaddingFrameDataLength)
channel := String(paddingFrameChannel)
written := 0
for i, chunkLength := range chunks {
if i < len(delays) {
delay, delayErr := randomPaddingDelay(delays[i])
if delayErr != nil {
return fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
return written, fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
}
if delay > 0 {
sleep(delay)
}
}
if err = writeFull(w, buffer[:chunkLength]); err != nil {
return fmt.Errorf("write padding chunk %d: %w", i, err)
frameLengths, planErr := paddingFramePlan(chunkLength)
if planErr != nil {
return written, planErr
}
written += chunkLength
if i == 0 {
clear(buffer[:header.Len()])
for _, frameLength := range frameLengths {
dataLength, ok := paddingFrameDataLength(frameLength)
if !ok {
return written, fmt.Errorf("unframed padding length %d", frameLength)
}
payload := RestBytes(zeros[:dataLength])
if err = writePacket(w, packetID, &channel, &payload); err != nil {
return written, fmt.Errorf("write padding frame: %w", err)
}
written += frameLength
}
}
if written != recordLength {
return fmt.Errorf("padding chunks total %d, want %d", written, recordLength)
}
return nil
return written, nil
}
func readPaddingTurn(r io.Reader, turn paddingTurn, prefixLength int) error {
encodedLength, headerLength, err := readVarintWithLength(r)
if err != nil {
return fmt.Errorf("read padding header: %w", err)
}
recordLength := int(encodedLength)
if recordLength < headerLength || recordLength > maxPaddingTurnLength {
return fmt.Errorf("invalid padding record length: %d", recordLength)
}
totalLength := prefixLength + recordLength
if !paddingTurnAcceptsLength(turn, totalLength) {
if len(turn.variants) > 0 {
return fmt.Errorf("padding turn length %d is not an allowed variant", totalLength)
}
return fmt.Errorf("padding turn length %d is outside %d-%d", totalLength, turn.minLength, turn.maxLength)
}
// paddingFrameLength is the wire size of a custom payload frame whose payload
// body is dataLength bytes long.
func paddingFrameLength(dataLength int) int {
bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength
return varintSize(Varint(bodyLength)) + bodyLength
}
var buffer [paddingBufferLength]byte
remaining := recordLength - headerLength
for remaining > 0 {
chunkLength := min(remaining, len(buffer))
if _, err := io.ReadFull(r, buffer[:chunkLength]); err != nil {
return fmt.Errorf("read padding body: %w", err)
// paddingFrameDataLength is the payload body that makes a frame exactly
// frameLength bytes long. Some lengths are unreachable because the length
// varint grows in steps.
func paddingFrameDataLength(frameLength int) (int, bool) {
for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ {
dataLength := frameLength - overhead
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
continue
}
if paddingFrameLength(dataLength) == frameLength {
return dataLength, true
}
remaining -= chunkLength
}
return nil
return 0, false
}
// paddingFramePlan splits length bytes into reachable frame sizes. The result is
// exact whenever a partition exists; a length below the smallest frame (the
// captured 2-byte turns) is rounded up to that frame.
func paddingFramePlan(length int) ([]int, error) {
if length <= 0 {
return nil, nil
}
if length < paddingFrameOverhead {
return []int{paddingFrameOverhead}, nil
}
frameLengths := make([]int, 0, length/paddingBufferLength+1)
for remaining := length; remaining > 0; {
candidate := min(remaining, maxPaddingFrameLength)
picked := 0
for ; candidate >= paddingFrameOverhead; candidate-- {
if _, ok := paddingFrameDataLength(candidate); !ok {
continue
}
rest := remaining - candidate
if rest > 0 && rest < paddingFrameOverhead {
continue
}
picked = candidate
break
}
if picked == 0 {
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
}
frameLengths = append(frameLengths, picked)
remaining -= picked
}
return frameLengths, nil
}
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
@@ -0,0 +1,137 @@
package xmc
import (
"bytes"
"testing"
"time"
)
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
frameLength := paddingFrameLength(dataLength)
got, ok := paddingFrameDataLength(frameLength)
if !ok || got != dataLength {
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
}
}
}
func TestPaddingFramePlanTotals(t *testing.T) {
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
for _, length := range lengths {
plan, err := paddingFramePlan(length)
if err != nil {
t.Fatalf("plan %d: %v", length, err)
}
total := 0
for _, frameLength := range plan {
if _, ok := paddingFrameDataLength(frameLength); !ok {
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
}
if frameLength > maxPaddingFrameLength {
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
}
total += frameLength
}
if total != length {
t.Fatalf("plan %d totals %d", length, total)
}
}
}
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
plan, err := paddingFramePlan(2)
if err != nil {
t.Fatal(err)
}
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
t.Fatalf("short turn plan = %v", plan)
}
}
func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
turns := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
}
for i, turn := range turns {
var buffer bytes.Buffer
written, err := writePaddingTurnFrames(&buffer, turn, 0, func(time.Duration) {}, configurationServerboundCustomPayload)
if err != nil {
t.Fatalf("turn %d: %v", i, err)
}
if written != buffer.Len() {
t.Fatalf("turn %d wrote %d bytes, buffer has %d", i, written, buffer.Len())
}
target := turn.minLength
if written < target {
t.Fatalf("turn %d wrote %d bytes, want at least %d", i, written, target)
}
reader := bytes.NewReader(buffer.Bytes())
frames := 0
for reader.Len() > 0 {
packet, err := readPacket(reader)
if err != nil {
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
}
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
}
_, ok, err := parseCustomPayload(packet)
if err != nil {
t.Fatalf("turn %d frame %d: %v", i, frames, err)
}
if ok {
t.Fatalf("turn %d frame %d uses the packet stream channel", i, frames)
}
if len(packet.data) == 0 {
t.Fatalf("turn %d frame %d has no channel", i, frames)
}
frames++
}
}
}
func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
{direction: paddingServerToClient, minLength: 64, maxLength: 64},
{direction: paddingClientToServer, minLength: 25, maxLength: 25},
}
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, schedule); err != nil {
t.Fatal(err)
}
reader := bytes.NewReader(out.Bytes())
total := 0
for reader.Len() > 0 {
before := reader.Len()
packet, err := readPacket(reader)
if err != nil {
t.Fatalf("padding stream is not a valid packet stream: %v", err)
}
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
}
total += before - reader.Len()
}
// Turn 0 carries the 2 byte Login Acknowledged prefix, turn 1 is the peer's.
want := 44 - 2 + 25
if total != want {
t.Fatalf("padding stream carries %d payload bytes, want %d", total, want)
}
}
func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
}
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule); err == nil {
t.Fatal("expected an error for a prefixed server-to-client first turn")
}
}
@@ -1,618 +0,0 @@
package xmc
import (
"bytes"
"errors"
"io"
"net"
"strconv"
"strings"
"testing"
"time"
)
func TestPaddingTurnReachesFinalTargetLength(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 128, maxLength: 128}
const prefixLength = 3
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, prefixLength); err != nil {
t.Fatal(err)
}
if got := prefixLength + encoded.Len(); got != turn.minLength {
t.Fatalf("total turn length = %d, want %d", got, turn.minLength)
}
encodedReader := bytes.NewReader(encoded.Bytes())
var recordLength Varint
if err := recordLength.readFrom(encodedReader); err != nil {
t.Fatal(err)
}
if got := int(recordLength); got != encoded.Len() {
t.Fatalf("record length = %d, encoded = %d", got, encoded.Len())
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, prefixLength); err != nil {
t.Fatal(err)
}
}
func TestPaddingTurnSupportsThreeByteTarget(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if got := encoded.Len(); got != 3 {
t.Fatalf("padding length = %d, want 3", got)
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
func TestPaddingTurnVarintBoundaries(t *testing.T) {
for _, targetLength := range []int{127, 128, 16383, 16384} {
t.Run(strconv.Itoa(targetLength), func(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: targetLength, maxLength: targetLength}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() != targetLength {
t.Fatalf("padding length = %d, want %d", encoded.Len(), targetLength)
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
})
}
}
func TestPaddingTurnRandomRange(t *testing.T) {
turn := paddingTurn{direction: paddingServerToClient, minLength: 127, maxLength: 129}
seen := make(map[int]bool)
for range 100 {
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() < turn.minLength || encoded.Len() > turn.maxLength {
t.Fatalf("padding length = %d", encoded.Len())
}
seen[encoded.Len()] = true
}
if len(seen) < 2 {
t.Fatalf("padding range did not vary: %v", seen)
}
}
func TestPaddingTurnUsesRestrictedSendRange(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 3,
maxLength: 100,
sendMinLength: 90,
sendMaxLength: 100,
}
seen := make(map[int]bool)
for range 100 {
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() < turn.sendMinLength || encoded.Len() > turn.sendMaxLength {
t.Fatalf("padding length = %d", encoded.Len())
}
seen[encoded.Len()] = true
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
if len(seen) < 2 {
t.Fatalf("restricted send range did not vary: %v", seen)
}
}
func TestPaddingScheduleSynchronizesDirections(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 33, maxLength: 33},
{direction: paddingServerToClient, minLength: 4097, maxLength: 4097},
{direction: paddingClientToServer, minLength: 16385, maxLength: 16385},
}
serverDone := make(chan error, 1)
go func() {
serverDone <- runPaddingSchedule(server, server, false, 3, schedule)
}()
if err := runPaddingSchedule(client, client, true, 3, schedule); err != nil {
t.Fatal(err)
}
select {
case err := <-serverDone:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("server padding schedule did not complete")
}
}
func TestReadPaddingTurnHandlesFragmentedInput(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 1024, maxLength: 1024}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if err := readPaddingTurn(&oneByteReader{reader: bytes.NewReader(encoded.Bytes())}, turn, 0); err != nil {
t.Fatal(err)
}
}
func TestReadPaddingTurnRejectsInvalidLength(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 96}
data := encodePaddingLength(t, 63)
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "outside") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnRejectsNonCanonicalHeader(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
err := readPaddingTurn(bytes.NewReader([]byte{0x83, 0x00, 0x00}), turn, 0)
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnRejectsTruncatedBody(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
data := encodePaddingLength(t, 64)
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "body") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnHonorsConnectionTimeout(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
if err := server.SetReadDeadline(time.Now().Add(20 * time.Millisecond)); err != nil {
t.Fatal(err)
}
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
err := readPaddingTurn(server, turn, 0)
var netErr net.Error
if !errors.As(err, &netErr) || !netErr.Timeout() {
t.Fatalf("error = %v, want network timeout", err)
}
}
func TestValidatePaddingSchedule(t *testing.T) {
tests := []struct {
name string
schedule []paddingTurn
prefix int
}{
{name: "empty"},
{name: "bad direction", schedule: []paddingTurn{{direction: 99, minLength: 4, maxLength: 4}}},
{name: "too small", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 0, maxLength: 4}}},
{name: "reversed range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 7}}},
{name: "wrong first direction", prefix: 3, schedule: []paddingTurn{{direction: paddingServerToClient, minLength: 8, maxLength: 8}}},
{name: "prefix leaves no header", prefix: 8, schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
{name: "same direction", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}, {direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
{name: "range with variants", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, variants: []paddingVariant{paddingVariantFromChunks(8)}}}},
{name: "empty variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{}}}}},
{name: "bad chunk", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(maxPaddingChunkLength + 1)}}}},
{
name: "delay mismatch",
schedule: []paddingTurn{{
direction: paddingClientToServer,
variants: []paddingVariant{{
chunks: []int{4, 4},
delays: []paddingDelayRange{{min: time.Millisecond, max: time.Millisecond}},
}},
}},
},
{name: "reversed start delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, startDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
{name: "reversed generated chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
{name: "oversized generated chunk", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkLength: maxPaddingChunkLength + 1}}},
{name: "reversed generated chunk range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkMinLength: 9, writeChunkLength: 8}}},
{name: "variant with generated chunks", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, writeChunkLength: 8}}},
{name: "send range outside accepted range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 16, sendMinLength: 7, sendMaxLength: 12}}},
{name: "variant with send range", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendMinLength: 8, sendMaxLength: 8}}},
{name: "negative chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{chunks: []int{8}, delays: []paddingDelayRange{{min: -time.Millisecond}}}}}}},
{name: "bad send variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendVariants: []int{1}}}},
{name: "prefix splits chunk", prefix: 3, schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8, 4)}}}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := validatePaddingSchedule(test.schedule, test.prefix); err == nil {
t.Fatal("expected invalid padding schedule")
}
})
}
}
func TestPaddingSchedule2612MatchesCapturedTemplates(t *testing.T) {
wantDirections := []paddingDirection{
paddingClientToServer,
paddingServerToClient,
paddingClientToServer,
paddingServerToClient,
paddingClientToServer,
paddingServerToClient,
}
wantLengths := [][]int{
{44},
{72},
{25},
{41172},
{2},
{7464, 8267, 8790, 8153, 7375, 7347, 8184, 6633, 7670, 8241, 7857, 7254, 8407, 8283, 6804, 8177, 8177, 7929, 8296, 8177},
}
if len(paddingSchedule2612) != len(wantDirections)+33 {
t.Fatalf("padding schedule has %d turns, want %d", len(paddingSchedule2612), len(wantDirections)+33)
}
for i, turn := range paddingSchedule2612[:len(wantDirections)] {
if turn.direction != wantDirections[i] {
t.Fatalf("padding turn %d direction = %d, want %d", i, turn.direction, wantDirections[i])
}
if len(turn.variants) != len(wantLengths[i]) {
t.Fatalf("padding turn %d has %d variants, want %d", i, len(turn.variants), len(wantLengths[i]))
}
for j, variant := range turn.variants {
if got := paddingVariantLength(variant); got != wantLengths[i][j] {
t.Fatalf("padding turn %d variant %d length = %d, want %d", i, j, got, wantLengths[i][j])
}
}
}
wantPlayBounds := [][2]int{
{6, 883},
{346, 58638},
{6, 887},
{388, 61077},
{2, 50},
{575, 65584},
{6, 45},
{86, 63563},
{2, 44},
{42, 51983},
{2, 851},
{309, 25083},
{2, 19},
{74, 63885},
{8, 24},
{30, 66128},
{2, 19},
{26, 35818},
{6, 19},
{35, 59407},
{6, 19},
{37, 65328},
{2, 19},
{26, 60622},
{6, 19},
{11, 60808},
{8, 43},
{55, 62027},
{2, 19},
{427, 65622},
{5, 19},
{35, 59401},
{6, 19},
}
for i, want := range wantPlayBounds {
turn := paddingSchedule2612[len(wantDirections)+i]
wantDirection := paddingClientToServer
if i%2 == 1 {
wantDirection = paddingServerToClient
}
if turn.direction != wantDirection {
t.Fatalf("play turn %d direction = %d, want %d", i, turn.direction, wantDirection)
}
if turn.minLength != want[0] || turn.maxLength != want[1] {
t.Fatalf("play turn %d bounds = %d-%d, want %d-%d", i, turn.minLength, turn.maxLength, want[0], want[1])
}
if len(turn.variants) != 0 {
t.Fatalf("play turn %d unexpectedly has captured variants", i)
}
}
if got := len(paddingSchedule2612[3].variants[0].chunks); got != 30 {
t.Fatalf("registry turn chunks = %d, want 30", got)
}
minimumPlayStart := maxPaddingTurnLength
maximumPlayStart := 0
for _, variant := range paddingSchedule2612[5].variants {
length := paddingVariantLength(variant)
minimumPlayStart = min(minimumPlayStart, length)
maximumPlayStart = max(maximumPlayStart, length)
if variant.chunks[0] != 4941 {
t.Fatalf("play start first chunk = %d, want 4941", variant.chunks[0])
}
}
if minimumPlayStart != 6633 || maximumPlayStart != 8790 {
t.Fatalf("play start bounds = %d-%d, want 6633-8790", minimumPlayStart, maximumPlayStart)
}
if err := validatePaddingSchedule(paddingSchedule2612, 2); err != nil {
t.Fatalf("captured schedule is invalid: %v", err)
}
serverSchedule, err := newServerPaddingSchedule2612()
if err != nil {
t.Fatal(err)
}
if err = validatePaddingSchedule(serverSchedule, 2); err != nil {
t.Fatalf("server schedule is invalid: %v", err)
}
for i, branches := range serverPlayBranches2612 {
turn := serverSchedule[len(startupPaddingSchedule2612)+1+i*2]
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
if got != branches.small && got != branches.large {
t.Fatalf("server play turn %d send range = %v, want %v or %v", i, got, branches.small, branches.large)
}
}
for range 20 {
clientSchedule, clientErr := newClientPaddingSchedule2612()
if clientErr != nil {
t.Fatal(clientErr)
}
if clientErr = validatePaddingSchedule(clientSchedule, 2); clientErr != nil {
t.Fatalf("client schedule is invalid: %v", clientErr)
}
burstCount := 0
for _, burst := range clientPlayBursts2612 {
turn := clientSchedule[len(startupPaddingSchedule2612)+burst.playIndex]
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
switch got {
case burst.regular:
case burst.burst:
burstCount++
default:
t.Fatalf("client play turn %d send range = %v", burst.playIndex, got)
}
}
if burstCount != 1 {
t.Fatalf("client schedule has %d initialization bursts, want 1", burstCount)
}
}
for variantIndex := range paddingSchedule2612[3].variants {
turn := paddingSchedule2612[3]
turn.sendVariants = []int{variantIndex}
var encoded bytes.Buffer
if err = writePaddingTurnWithSleep(&encoded, turn, 0, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
if err = readPaddingTurn(bytes.NewReader(encoded.Bytes()), paddingSchedule2612[3], 0); err != nil {
t.Fatalf("registry variant %d was rejected: %v", variantIndex, err)
}
}
}
func TestPaddingVariantPreservesWriteBoundaries(t *testing.T) {
tests := []struct {
name string
turn paddingTurn
prefix int
want []int
}{
{name: "login acknowledged turn", turn: paddingSchedule2612[0], prefix: 2, want: []int{26, 16}},
{name: "server response turn", turn: paddingSchedule2612[1], want: []int{26, 21, 25}},
{name: "single packet turn", turn: paddingSchedule2612[2], want: []int{25}},
{name: "fixed registry profile", turn: paddingSchedule2612[3], want: paddingSchedule2612[3].variants[0].chunks},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, test.turn, test.prefix, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
if len(writer.writes) != len(test.want) {
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
}
for i := range test.want {
if writer.writes[i] != test.want[i] {
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
}
}
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), test.turn, test.prefix); err != nil {
t.Fatal(err)
}
})
}
}
func TestPaddingVariantAppliesPacing(t *testing.T) {
turn := paddingTurn{
direction: paddingClientToServer,
startDelay: paddingDelayRange{min: 3 * time.Millisecond, max: 3 * time.Millisecond},
variants: []paddingVariant{{
chunks: []int{3, 5, 7},
delays: []paddingDelayRange{
{},
{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
{min: 4 * time.Millisecond, max: 4 * time.Millisecond},
},
}},
}
var slept []time.Duration
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 3, func(delay time.Duration) {
slept = append(slept, delay)
}); err != nil {
t.Fatal(err)
}
want := []time.Duration{3 * time.Millisecond, 2 * time.Millisecond, 4 * time.Millisecond}
if len(slept) != len(want) {
t.Fatalf("delays = %v, want %v", slept, want)
}
for i := range want {
if slept[i] != want[i] {
t.Fatalf("delays = %v, want %v", slept, want)
}
}
}
func TestGeneratedPaddingChunksApplyPacing(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 100,
maxLength: 100,
writeChunkLength: 32,
chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
}
var slept []time.Duration
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(delay time.Duration) {
slept = append(slept, delay)
}); err != nil {
t.Fatal(err)
}
wantWrites := []int{32, 32, 32, 4}
if !slicesEqual(writer.writes, wantWrites) {
t.Fatalf("writes = %v, want %v", writer.writes, wantWrites)
}
wantSleeps := []time.Duration{2 * time.Millisecond, 2 * time.Millisecond, 2 * time.Millisecond}
if !slicesEqual(slept, wantSleeps) {
t.Fatalf("delays = %v, want %v", slept, wantSleeps)
}
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
func TestGeneratedPaddingChunkLengthIsRandomized(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 100,
maxLength: 100,
writeChunkMinLength: 16,
writeChunkLength: 32,
}
seen := make(map[int]bool)
for range 100 {
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
firstWrite := writer.writes[0]
if firstWrite < turn.writeChunkMinLength || firstWrite > turn.writeChunkLength {
t.Fatalf("first write = %d", firstWrite)
}
seen[firstWrite] = true
}
if len(seen) < 2 {
t.Fatalf("generated write chunk length did not vary: %v", seen)
}
}
func TestPaddingDelayRangeIsRandomized(t *testing.T) {
delayRange := millisecondRange(25, 40)
seen := make(map[time.Duration]bool)
for range 100 {
delay, err := randomPaddingDelay(delayRange)
if err != nil {
t.Fatal(err)
}
if delay < delayRange.min || delay > delayRange.max {
t.Fatalf("delay = %s, want %s-%s", delay, delayRange.min, delayRange.max)
}
seen[delay] = true
}
if len(seen) < 2 {
t.Fatalf("padding delay did not vary: %v", seen)
}
}
func TestPaddingSchedule2612UsesCoarseTimingBands(t *testing.T) {
assertDelayRange(t, "turn 3 to 4", paddingSchedule2612[3].startDelay, 20*time.Millisecond, 50*time.Millisecond)
assertDelayRange(t, "turn 5 to 6", paddingSchedule2612[5].startDelay, 35*time.Millisecond, 50*time.Millisecond)
assertDelayRange(t, "first play client turn", paddingSchedule2612[6].startDelay, time.Millisecond, 30*time.Millisecond)
assertDelayRange(t, "first play server turn", paddingSchedule2612[7].startDelay, time.Millisecond, 45*time.Millisecond)
assertDelayRange(t, "play server chunk pacing", paddingSchedule2612[7].chunkDelay, time.Millisecond, 4*time.Millisecond)
if paddingSchedule2612[6].writeChunkLength != 1024 {
t.Fatalf("play client write chunk = %d, want 1024", paddingSchedule2612[6].writeChunkLength)
}
if paddingSchedule2612[7].writeChunkLength != maxPaddingChunkLength {
t.Fatalf("play server write chunk = %d, want %d", paddingSchedule2612[7].writeChunkLength, maxPaddingChunkLength)
}
if paddingSchedule2612[7].writeChunkMinLength != 32*1024 {
t.Fatalf("play server minimum write chunk = %d, want %d", paddingSchedule2612[7].writeChunkMinLength, 32*1024)
}
for i, variant := range paddingSchedule2612[3].variants {
minimum, maximum := paddingVariantDelayBounds(variant)
if minimum != 45*time.Millisecond || maximum != 65*time.Millisecond {
t.Fatalf("turn 4 variant %d duration = %s-%s, want 45ms-65ms", i, minimum, maximum)
}
}
for i, variant := range paddingSchedule2612[5].variants {
minimum, maximum := paddingVariantDelayBounds(variant)
if minimum != 10*time.Millisecond || maximum != 25*time.Millisecond {
t.Fatalf("turn 6 variant %d duration = %s-%s, want 10ms-25ms", i, minimum, maximum)
}
}
}
func assertDelayRange(t *testing.T, name string, got paddingDelayRange, minimum, maximum time.Duration) {
t.Helper()
if got.min != minimum || got.max != maximum {
t.Fatalf("%s delay = %s-%s, want %s-%s", name, got.min, got.max, minimum, maximum)
}
}
func paddingVariantDelayBounds(variant paddingVariant) (time.Duration, time.Duration) {
var minimum time.Duration
var maximum time.Duration
for _, delay := range variant.delays {
minimum += delay.min
maximum += delay.max
}
return minimum, maximum
}
func slicesEqual[T comparable](left, right []T) bool {
if len(left) != len(right) {
return false
}
for i := range left {
if left[i] != right[i] {
return false
}
}
return true
}
func encodePaddingLength(t *testing.T, length int) []byte {
t.Helper()
var encoded bytes.Buffer
value := Varint(length)
if err := value.writeTo(&encoded); err != nil {
t.Fatal(err)
}
return encoded.Bytes()
}
type oneByteReader struct {
reader io.Reader
}
func (r *oneByteReader) Read(p []byte) (int, error) {
if len(p) > 1 {
p = p[:1]
}
return r.reader.Read(p)
}
type recordingWriter struct {
bytes.Buffer
writes []int
}
func (w *recordingWriter) Write(p []byte) (int, error) {
w.writes = append(w.writes, len(p))
return w.Buffer.Write(p)
}
@@ -1,33 +0,0 @@
package xmc
import (
"bytes"
"testing"
)
func TestProfilesFromConfigRejectsEmpty(t *testing.T) {
if _, err := profilesFromConfig(nil); err == nil {
t.Fatal("expected empty profiles error")
}
}
func TestProfilesFromConfig(t *testing.T) {
uuid := bytes.Repeat([]byte{0x2a}, 16)
profiles, err := profilesFromConfig([]*Profile{
{
Username: "SignedUser",
Uuid: uuid,
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
},
})
if err != nil {
t.Fatalf("build explicit profile: %v", err)
}
if len(profiles) != 1 || profiles[0].Username != "SignedUser" {
t.Fatalf("unexpected profile: %+v", profiles)
}
if profiles[0].TexturesValue != "textures-value" || profiles[0].TexturesSignature != "textures-signature" {
t.Fatalf("textures were not preserved: %+v", profiles[0])
}
}
+5 -1
View File
@@ -8,7 +8,11 @@ import (
)
const (
maxPacketDataLength = 32 * 1024
// Clientbound custom payloads are allowed up to 1 MiB by vanilla, and a
// vanilla configuration state can send large registry data packets. This is
// only an upper bound for decoding; the XMC payload stream keeps its own,
// much smaller, chunk size.
maxPacketDataLength = 1024 * 1024
maxPacketBodyLength = maxPacketDataLength + 5
)
@@ -1,56 +0,0 @@
package xmc
import (
"bytes"
"strings"
"testing"
)
func TestReadPacketDoesNotConsumeFollowingPacket(t *testing.T) {
data := []byte{0x01, 0x80, 0x01, 0x00}
r := bytes.NewReader(data)
if _, err := readPacket(r); err == nil {
t.Fatal("expected truncated packet ID to fail")
}
pkt, err := readPacket(r)
if err != nil {
t.Fatalf("read following packet: %v", err)
}
if pkt.packetID != 0 {
t.Fatalf("packet ID = %d", pkt.packetID)
}
}
func TestPacketWithLengthReportsWireBytes(t *testing.T) {
var wire bytes.Buffer
written, err := writePacketWithLength(&wire, 0x03)
if err != nil {
t.Fatal(err)
}
if written != 2 || !bytes.Equal(wire.Bytes(), []byte{0x01, 0x03}) {
t.Fatalf("wire = %x, length = %d", wire.Bytes(), written)
}
packet, read, err := readPacketWithLength(bytes.NewReader(wire.Bytes()))
if err != nil {
t.Fatal(err)
}
if packet.packetID != 0x03 || read != written {
t.Fatalf("packet ID = %d, read = %d, written = %d", packet.packetID, read, written)
}
}
func TestReadPacketRejectsNonCanonicalLengthVarint(t *testing.T) {
_, _, err := readPacketWithLength(bytes.NewReader([]byte{0x81, 0x00, 0x03}))
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
t.Fatalf("error = %v", err)
}
}
func TestVarintRejectsOversizedFifthByte(t *testing.T) {
var value Varint
err := value.readFrom(bytes.NewReader([]byte{0xff, 0xff, 0xff, 0xff, 0x1f}))
if err == nil || !strings.Contains(err.Error(), "too large") {
t.Fatalf("error = %v", err)
}
}
+3 -3
View File
@@ -245,7 +245,7 @@ func (c *serverConn) handshake() error {
if err = validateLoginAcknowledgedPacket(pkt); err != nil {
return err
}
if err = runPaddingSchedule(c.reader, c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
return fmt.Errorf("run startup padding: %w", err)
}
@@ -328,7 +328,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
return c.deadlines.setWriteDeadline(t)
}
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte) (*serverConn, error) {
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, padding []*Padding) (*serverConn, error) {
if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles")
}
@@ -342,7 +342,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
if err != nil {
return nil, fmt.Errorf("parse rsa private key: %w", err)
}
paddingSchedule, err := newServerPaddingSchedule2612()
paddingSchedule, err := newPaddingSchedule(padding, false)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
@@ -1,81 +0,0 @@
package xmc
import (
"bytes"
"io"
"testing"
)
type dataAndEOFReader struct {
data []byte
}
func (r *dataAndEOFReader) Read(p []byte) (int, error) {
if len(r.data) == 0 {
return 0, io.EOF
}
n := copy(p, r.data)
r.data = r.data[n:]
return n, io.EOF
}
type shortWriter struct {
bytes.Buffer
}
func (w *shortWriter) Write(p []byte) (int, error) {
if len(p) > 1 {
p = p[:len(p)/2]
}
return w.Buffer.Write(p)
}
func TestCryptoReaderPreservesDataReturnedWithEOF(t *testing.T) {
secret := []byte("0123456789abcdef")
plaintext := []byte("payload returned with EOF")
var encrypted bytes.Buffer
writer, err := newCryptoWriter(&encrypted, secret)
if err != nil {
t.Fatal(err)
}
if _, err = writer.Write(plaintext); err != nil {
t.Fatal(err)
}
reader, err := newCryptoReader(&dataAndEOFReader{data: encrypted.Bytes()}, secret)
if err != nil {
t.Fatal(err)
}
got := make([]byte, len(plaintext))
n, err := reader.Read(got)
if err == nil || n != len(plaintext) {
t.Fatalf("Read = %d, %v", n, err)
}
if !bytes.Equal(got[:n], plaintext) {
t.Fatalf("plaintext = %q", got[:n])
}
}
func TestCryptoWriterHandlesShortWrites(t *testing.T) {
secret := []byte("0123456789abcdef")
plaintext := bytes.Repeat([]byte("short-write"), 100)
var dst shortWriter
writer, err := newCryptoWriter(&dst, secret)
if err != nil {
t.Fatal(err)
}
if n, err := writer.Write(plaintext); err != nil || n != len(plaintext) {
t.Fatalf("Write = %d, %v", n, err)
}
reader, err := newCryptoReader(bytes.NewReader(dst.Bytes()), secret)
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, plaintext) {
t.Fatal("decrypted payload mismatch")
}
}
+7 -3
View File
@@ -197,7 +197,8 @@ func (c *client) dial(ctx context.Context) error {
}
// udp, _ := strconv.ParseBool(resp.Header.Get(ResponseHeaderUDPEnabled))
down, _ := strconv.ParseUint(resp.Header.Get(CommonHeaderCCRX), 10, 64)
remote_rx, _ := strconv.ParseUint(resp.Header.Get(CommonHeaderCCRX), 10, 64)
tx := quicParams.BrutalUp
errors.LogDebug(context.Background(), "ECHAccepted ", conn.ConnectionState().TLS.ECHAccepted)
switch quicParams.Congestion {
@@ -205,10 +206,13 @@ func (c *client) dial(ctx context.Context) error {
case "bbr":
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
case "", "brutal":
if quicParams.BrutalUp == 0 || down == 0 {
if tx == 0 {
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
} else {
congestion.UseBrutal(conn, min(quicParams.BrutalUp, down), quicParams.BrutalDisableLossCompensation)
if remote_rx > 0 {
tx = min(tx, remote_rx)
}
congestion.UseBrutal(conn, tx, quicParams.BrutalDisableLossCompensation)
}
case "force-brutal":
congestion.UseBrutal(conn, quicParams.BrutalUp, quicParams.BrutalDisableLossCompensation)
+7 -3
View File
@@ -55,7 +55,8 @@ func (h *httpHandler) AuthHTTP(w http.ResponseWriter, r *http.Request) bool {
}
auth := r.Header.Get(RequestHeaderAuth)
down, _ := strconv.ParseUint(r.Header.Get(CommonHeaderCCRX), 10, 64)
remote_rx, _ := strconv.ParseUint(r.Header.Get(CommonHeaderCCRX), 10, 64)
tx := h.quicParams.BrutalUp
var user *protocol.MemoryUser
var ok bool
@@ -76,10 +77,13 @@ func (h *httpHandler) AuthHTTP(w http.ResponseWriter, r *http.Request) bool {
case "bbr":
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
case "", "brutal":
if quicParams.BrutalUp == 0 || down == 0 {
if remote_rx == 0 {
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
} else {
congestion.UseBrutal(conn, min(quicParams.BrutalUp, down), quicParams.BrutalDisableLossCompensation)
if tx > 0 {
remote_rx = min(remote_rx, tx)
}
congestion.UseBrutal(conn, remote_rx, quicParams.BrutalDisableLossCompensation)
}
case "force-brutal":
congestion.UseBrutal(conn, quicParams.BrutalUp, quicParams.BrutalDisableLossCompensation)
-1
View File
@@ -1,5 +1,4 @@
//go:build openbsd
// +build openbsd
package internet
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build js || netbsd || solaris
// +build js netbsd solaris
//go:build !windows && !darwin && !linux && !freebsd && !openbsd
package internet
-1
View File
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin
package tcp
@@ -1,5 +1,4 @@
//go:build freebsd
// +build freebsd
package tcp
-1
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package tcp
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package tcp_test
-1
View File
@@ -1,5 +1,4 @@
//go:build !linux && !freebsd && !darwin
// +build !linux,!freebsd,!darwin
package tcp
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package tls
-1
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package tls
+1
View File
@@ -275,6 +275,7 @@ var ModernFingerprints = map[string]*utls.ClientHelloID{
"hellochrome_120": &utls.HelloChrome_120,
"hellochrome_131": &utls.HelloChrome_131,
"hellochrome_133": &utls.HelloChrome_133,
"hellochrome_155": &utls.HelloChrome_155,
"helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14,
"helloedge_106": &utls.HelloEdge_106,
-1
View File
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin
package udp
-1
View File
@@ -1,5 +1,4 @@
//go:build freebsd
// +build freebsd
package udp
-1
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package udp
-1
View File
@@ -1,5 +1,4 @@
//go:build openbsd
// +build openbsd
package udp
@@ -1,5 +1,4 @@
//go:build openbsd
// +build openbsd
package udp
-1
View File
@@ -1,5 +1,4 @@
//go:build !linux && !freebsd && !darwin && !openbsd
// +build !linux,!freebsd,!darwin,!openbsd
package udp
+42 -5
View File
@@ -433,14 +433,22 @@ func (b *doneBody) Close() error {
return err
}
// a connection that has not answered yet is given this long before its
// timeouts retire it, so that a dial or handshake is not cut short again
var stalledGrace = 12 * time.Second
// sessionTransport sends the requests of one session over a connection of
// XMUX, and over another once that one has no requests or time left
type sessionTransport struct {
pool *connPool
mu sync.Mutex
client *splithttp.XmuxClient
closed bool
mu sync.Mutex
client *splithttp.XmuxClient
closed bool
slowAt, retiredAt time.Time
movedAt time.Time
takenAt time.Time
served bool
}
func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
@@ -450,7 +458,7 @@ func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return nil, errSessionClosed
}
client := t.client
if client == nil || client.LeftRequests.Add(-1) < 0 || !client.UnreusableAt.IsZero() && time.Now().After(client.UnreusableAt) {
if client == nil || client.XmuxConn.IsClosed() || client.LeftRequests.Add(-1) < 0 || !client.UnreusableAt.IsZero() && time.Now().After(client.UnreusableAt) {
t.pool.mu.Lock()
t.client = t.pool.xmux.GetXmuxClient(r.Context())
t.pool.mu.Unlock()
@@ -458,8 +466,10 @@ func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
t.client.LeftRequests.Add(-1)
if client != nil {
client.DoneRunning()
t.movedAt = time.Now()
}
client = t.client
t.takenAt, t.served = time.Now(), false
}
// counted under mu, or another request of the session that moves on could
// close the connection before this one is sent
@@ -468,7 +478,34 @@ func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
conn.inflight++
conn.mu.Unlock()
t.mu.Unlock()
return conn.roundTrip(r)
resp, err := conn.roundTrip(r)
if err == nil {
t.mu.Lock()
if t.client == client {
t.served = true
}
t.mu.Unlock()
}
return resp, err
}
func (t *sessionTransport) stalled(began time.Time) {
t.mu.Lock()
defer t.mu.Unlock()
if began.Before(t.movedAt) {
return
}
now := time.Now()
if !t.served && now.Sub(t.takenAt) < stalledGrace {
return
}
slow := now.Sub(t.slowAt) < 3*time.Second
t.slowAt = now
if !slow || t.client == nil || now.Sub(t.retiredAt) < 2*time.Second {
return
}
t.retiredAt = now
t.client.XmuxConn.(*poolConn).Close()
}
func (t *sessionTransport) Close() {
+154
View File
@@ -987,3 +987,157 @@ func TestDriveXmuxOverH3(t *testing.T) {
}
waitFor(t, "the first connection of XMUX to close", func() bool { return server.closed.Load() == 1 })
}
type stallConn struct{}
func (stallConn) RoundTrip(r *http.Request) (*http.Response, error) {
<-r.Context().Done()
return nil, r.Context().Err()
}
type okConn struct{}
func (okConn) RoundTrip(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"id":"file-1"}`)),
}, nil
}
func TestSessionRetiresStalledConn(t *testing.T) {
oldGrace := stalledGrace
stalledGrace = 0
t.Cleanup(func() { stalledGrace = oldGrace })
made := atomic.Int32{}
transport := &sessionTransport{pool: newConnPool(nil, func(connCtx context.Context) *http.Client {
if made.Add(1) == 1 {
return &http.Client{Transport: stallConn{}}
}
return &http.Client{Transport: okConn{}}
})}
storage := &driveStorage{
driveShared: &driveShared{
token: "token",
tokenExpiry: time.Now().Add(time.Hour),
backoff: time.Millisecond,
},
client: &http.Client{Transport: transport},
inflight: make(chan struct{}, 1),
reserved: make(chan struct{}, 1),
}
ctx := context.WithValue(context.Background(), attemptKey{}, 100*time.Millisecond)
code, body, err := storage.do(ctx, http.MethodPost, "http://drive.invalid/files", "", nil)
if err != nil {
t.Fatalf("the first request over a stalled connection: %v", err)
}
if code != http.StatusOK || string(body) != `{"id":"file-1"}` {
t.Fatalf("the stalled connection gave %d %q", code, body)
}
if n := made.Load(); n != 2 {
t.Fatalf("a stalled connection took %d connections, want it retired and one made after it", n)
}
if _, _, err := storage.do(ctx, http.MethodPost, "http://drive.invalid/files", "", nil); err != nil {
t.Fatalf("the request after the retirement: %v", err)
}
if n := made.Load(); n != 2 {
t.Fatalf("%d connections were made, want the healthy one kept", n)
}
}
func TestSessionIgnoresStallOfRetiredConn(t *testing.T) {
var made atomic.Int32
transport := &sessionTransport{pool: newConnPool(nil, func(connCtx context.Context) *http.Client {
made.Add(1)
return &http.Client{Transport: okConn{}}
})}
send := func() {
req, err := http.NewRequest(http.MethodGet, "http://drive.invalid/files", nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
}
send()
old := time.Now()
time.Sleep(2 * time.Millisecond)
transport.stalled(old)
transport.stalled(old)
send()
if n := made.Load(); n != 2 {
t.Fatalf("a stalled connection took %d connections, want it retired and one made after it", n)
}
transport.mu.Lock()
transport.slowAt, transport.retiredAt = time.Time{}, time.Time{}
transport.mu.Unlock()
transport.stalled(old)
transport.stalled(old)
send()
if n := made.Load(); n != 2 {
t.Fatalf("the stall of a retired connection took the healthy one too, %d connections", n)
}
time.Sleep(2 * time.Millisecond)
fresh := time.Now()
transport.stalled(fresh)
transport.stalled(fresh)
send()
if n := made.Load(); n != 3 {
t.Fatalf("a stall of the current connection made %d connections, want it retired", n)
}
}
func TestSessionSparesFreshConn(t *testing.T) {
transport := &sessionTransport{pool: newConnPool(nil, func(connCtx context.Context) *http.Client {
return &http.Client{Transport: okConn{}}
})}
send := func() {
req, err := http.NewRequest(http.MethodGet, "http://drive.invalid/files", nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
}
current := func() *poolConn {
transport.mu.Lock()
defer transport.mu.Unlock()
return transport.client.XmuxConn.(*poolConn)
}
send()
conn := current()
transport.mu.Lock()
transport.takenAt, transport.served = time.Now(), false
transport.mu.Unlock()
transport.stalled(time.Now())
transport.stalled(time.Now())
if conn.IsClosed() {
t.Fatal("a fresh connection was retired before its grace period ended")
}
transport.mu.Lock()
transport.takenAt = time.Now().Add(-stalledGrace - time.Second)
transport.mu.Unlock()
transport.stalled(time.Now())
transport.stalled(time.Now())
if !conn.IsClosed() {
t.Fatal("a fresh connection older than its grace period was not retired")
}
send()
conn = current()
transport.mu.Lock()
transport.takenAt, transport.served = time.Now(), true
transport.slowAt, transport.retiredAt = time.Time{}, time.Time{}
transport.mu.Unlock()
transport.stalled(time.Now())
transport.stalled(time.Now())
if !conn.IsClosed() {
t.Fatal("a connection that had answered was not retired")
}
}
+2 -2
View File
@@ -47,12 +47,12 @@ func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix strin
}
}
func newSlotConn(ctx context.Context, store slotStore, write, read slotTable, p params, onClose func()) *Conn {
func newSlotConn(ctx context.Context, store slotStore, write, read slotTable, p params, first []byte, onClose func()) *Conn {
ctx, cancel := context.WithCancel(ctx)
return &Conn{
cancel: cancel,
writer: newSlotWriter(ctx, store, write, p),
reader: newSlotReader(ctx, store, read, p),
reader: newSlotReader(ctx, store, read, p, first),
onClose: onClose,
}
}

Some files were not shown because too many files have changed in this diff Show More