feat(masque): SPEC 021 — MASQUE CONNECT-IP outbound (Cloudflare WARP)
CONNECT-IP (RFC 9484) outbound tunnelling whole IP packets over HTTP/3 and HTTP/2, targeting Cloudflare WARP. One `type: masque` outbound with a `profile` field (cloudflare default | standard) and `network` (h3 | h2). - transport/masque/connectip: vendored connect-ip-go (client subset) ported onto sagernet/quic-go — no second quic-go, no external dependency. - transport/masque: cloudflare/standard profiles (ECDSA pubkey pinning), h3 ConnectTunnel (Extended CONNECT cf-connect-ip + advertiseDefaultRoute), and h2 capsule-DATAGRAM over stdlib net/http (no http fork needed). - protocol/masque: adapter.Outbound reusing transport/wireguard gVisor stackDevice via NewDevice(System:false); lazy tunnel + two IP pumps; DialContext/ListenPacket/Close. - constant/option/include wiring (with_quic + with_gvisor); graceful ErrGVisorNotIncluded without gvisor. Key material (ECDSA priv/pub, ip/ipv6) is taken ready from config — WARP device registration is done client-side (Dart), out of core scope. Unit-tested (profiles, TLS pinning, EC key round-trip, capsule round-trip, IPv4 checksum vector, prefix parsing, config decode via registry). NOT yet device-verified against live WARP (needs real key material). Refs: SPEC 021, SagerNet/sing-box#4000
This commit is contained in:
1 parent
dbd219027c
commit
0f41d00ac6
21 files changed
+2615
-9
No files matched your search
@@ -0,0 +1,332 @@
|
||||
# SPEC 021 — MASQUE outbound (CONNECT-IP over HTTP/3 + HTTP/2), профиль Cloudflare WARP
|
||||
|
||||
**Статус:** РЕАЛИЗОВАН (h3+h2, cloudflare+standard), НЕ device-verified на живом WARP
|
||||
**Ветка:** `lx-spec021-masque`
|
||||
**Тег типа:** `masque` (`C.TypeMASQUE`)
|
||||
**Build-tag:** `with_quic` + `with_gvisor` (userspace-стек)
|
||||
|
||||
---
|
||||
|
||||
## Зачем
|
||||
|
||||
Нужен outbound, умеющий подключаться к **Cloudflare WARP по MASQUE**. MASQUE у Cloudflare — это
|
||||
**CONNECT-IP (RFC 9484)**, а НЕ CONNECT-UDP (RFC 9298): туннелируются целые IP-пакеты, не UDP-датаграммы.
|
||||
Сервер отдаёт нам поток IP-пакетов, поверх которого мы поднимаем userspace-стек (как WireGuard-endpoint)
|
||||
и раздаём приложениям через `DialContext`/`ListenPacket`.
|
||||
|
||||
Референс — реализация mihomo (`transport/masque`, `adapter/outbound/masque.go`, ветка `Alpha`), которая
|
||||
в свою очередь порт от `Diniboy1123/usque` + `connect-ip-go`. **Портируем логику**, адаптируя импорты на
|
||||
наш форк (`sagernet/quic-go/http3`, наш `transport/wireguard` gVisor-стек), НЕ тянем чужой WARP-заточенный
|
||||
`connect-ip-go` в go.mod — вкапываем его в `transport/masque/` как lx-owned код.
|
||||
|
||||
Это отвечает на давний запрос апстрима — [SagerNet/sing-box#4000](https://github.com/SagerNet/sing-box/issues/4000)
|
||||
(«MASQUE по образцу WireGuard endpoint»).
|
||||
|
||||
## Не путать
|
||||
|
||||
- НЕ RFC 9298 (CONNECT-UDP). Здесь **CONNECT-IP** (RFC 9484), IP-пакеты.
|
||||
- `transport/wireguard/masque_awg.go` — ЭТО ДРУГОЕ (SPEC 009, AWG-обфускация I1 «masquerade»).
|
||||
Случайное совпадение имени. К этому спеку отношения не имеет.
|
||||
|
||||
---
|
||||
|
||||
## Дизайн-решения (закрыты с заказчиком)
|
||||
|
||||
1. **Один outbound `type: masque`**, режим переключается полем `profile`, а не отдельными протоколами
|
||||
(паттерн `tuic.udp_relay_mode`). Значения: `cloudflare` (дефолт, цель) | `standard` (чистый RFC 9484, задел).
|
||||
2. **Транспорты в v1: `h3` И `h2` сразу.** `h3` = CONNECT-IP over QUIC (основной путь WARP);
|
||||
`h2` = CONNECT-IP over HTTP/2 (для сетей, где режут QUIC/UDP). `h3-l4proxy` — НЕ в scope v1 (см. §Не в scope).
|
||||
3. **`connect-ip-go` вкопировать** в `transport/masque/` (lx-owned, ~500 строк), не внешней зависимостью.
|
||||
4. **Регистрация в WARP — вне ядра.** Клиент ПРИНИМАЕТ готовый ключевой материал из конфига
|
||||
(`private_key`/`public_key`/`ip`/`ipv6`). Регистрацию устройства (генерация ECDSA, WARP API) делает
|
||||
вызывающая сторона (Dart/LxBox). См. §Ключевой материал.
|
||||
5. **userspace-стек — переиспользуем наш `transport/wireguard.stackDevice`** (gVisor), НЕ тянем
|
||||
`sing-wireguard` как mihomo. `stackDevice` уже даёт ровно нужный контракт (см. §Стек).
|
||||
|
||||
---
|
||||
|
||||
## Конфиг
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "masque",
|
||||
"tag": "warp",
|
||||
|
||||
"server": "162.159.198.1", // WARP endpoint IP (или host)
|
||||
"server_port": 443,
|
||||
|
||||
"profile": "cloudflare", // "cloudflare" (дефолт) | "standard"
|
||||
"network": "h3", // "h3" (дефолт) | "h2"
|
||||
|
||||
// --- ключевой материал (обязателен для cloudflare) ---
|
||||
"private_key": "<base64>", // x509 EC private key (DER), ParseECPrivateKey
|
||||
"public_key": "<base64>", // PKIX public key (DER) endpoint'а, ParsePKIXPublicKey → *ecdsa.PublicKey
|
||||
"ip": "172.16.0.2/32", // локальный IPv4 внутри туннеля (/32 если без маски)
|
||||
"ipv6": "2606:4700:110:...::/128",
|
||||
|
||||
// --- опционально ---
|
||||
"uri": "https://cloudflareaccess.com", // CONNECT-IP URI-шаблон; дефолт зависит от profile
|
||||
"sni": "", // дефолт: consumer-masque.cloudflareclient.com (cloudflare)
|
||||
"mtu": 1280, // дефолт 1280
|
||||
"skip_cert_verify": false, // отключить pinning на public_key (debug)
|
||||
|
||||
// --- congestion (как tuic/hysteria) ---
|
||||
"congestion_control": "", // "", "cubic", "bbr", ...
|
||||
"cwnd": 0,
|
||||
|
||||
// стандартные:
|
||||
"network_list": ["tcp","udp"], // NetworkList
|
||||
...DialerOptions
|
||||
}
|
||||
```
|
||||
|
||||
### Поля
|
||||
|
||||
| Поле | Тип | Дефолт | Профиль | Смысл |
|
||||
|---|---|---|---|---|
|
||||
| `profile` | string | `cloudflare` | — | набор поведения (см. §Профили) |
|
||||
| `network` | string | `h3` | оба | `h3` = QUIC, `h2` = HTTP/2 |
|
||||
| `private_key` | string(b64) | — | cloudflare (обяз.) | EC private key, DER → `x509.ParseECPrivateKey` |
|
||||
| `public_key` | string(b64) | — | cloudflare (обяз.) | endpoint PKIX pubkey, `x509.ParsePKIXPublicKey` |
|
||||
| `ip` | string(CIDR) | — | обяз. (хотя бы один из ip/ipv6) | локальный IPv4 туннеля |
|
||||
| `ipv6` | string(CIDR) | — | обяз. (хотя бы один) | локальный IPv6 туннеля |
|
||||
| `uri` | string | по профилю | оба | CONNECT-IP URI-шаблон |
|
||||
| `sni` | string | по профилю | оба | TLS SNI (для WARP != endpoint host) |
|
||||
| `mtu` | int | 1280 | оба | MTU userspace-стека |
|
||||
| `skip_cert_verify` | bool | false | cloudflare | отключить pubkey-pinning |
|
||||
| `congestion_control`, `cwnd` | | | h3 | как tuic |
|
||||
|
||||
**Валидация fail-fast при старте:**
|
||||
- `profile == cloudflare`: `private_key`, `public_key` обязательны и парсятся (иначе ошибка конфига).
|
||||
- Хотя бы одно из `ip`/`ipv6` задано и парсится в CIDR.
|
||||
- `network ∈ {h3, h2}`.
|
||||
- `network == h2` + `profile == standard` → пока ошибка «not implemented» (h2 в v1 только для cloudflare,
|
||||
т.к. capsule-over-h2 завязан на cf-поведение; RFC-h2 — задел).
|
||||
|
||||
---
|
||||
|
||||
## Профили (что переключает `profile`)
|
||||
|
||||
Профиль влияет ТОЛЬКО на 4 точки; всё остальное (QUIC/http3, capsule/datagram, стек, насосы) — общее.
|
||||
|
||||
| Точка | `cloudflare` | `standard` (RFC 9484) |
|
||||
|---|---|---|
|
||||
| `:protocol` (Extended CONNECT) | `cf-connect-ip` | `connect-ip` |
|
||||
| Extended CONNECT settings | **игнорировать** отсутствие (`ignoreExtendedConnect=true`) — WARP их не шлёт (нарушает RFC) | требовать `EnableExtendedConnect` |
|
||||
| Доп. заголовки | h3: `User-Agent: ""`; h2: `cf-connect-proto: cf-connect-ip`, `pq-enabled: false` | нет |
|
||||
| TLS-проверка | pinning на `public_key` (ECDSA equal), `InsecureSkipVerify` + `VerifyConnection` | обычная цепочка по `sni` |
|
||||
| дефолт `uri` | `https://cloudflareaccess.com` | нет дефолта (обязателен) |
|
||||
| дефолт `sni` | `consumer-masque.cloudflareclient.com` | = server host |
|
||||
|
||||
В коде — одна структура `profile` с полями/функциями, выбирается в `NewOutbound` по `options.Profile`.
|
||||
|
||||
---
|
||||
|
||||
## Файлы и точки интеграции
|
||||
|
||||
```
|
||||
constant/proxy.go
|
||||
+ TypeMASQUE = "masque" // рядом с TypeTUIC (стр. ~25) + в displayName switch
|
||||
|
||||
option/masque.go (НОВЫЙ)
|
||||
+ type MASQUEOutboundOptions struct { ... } // DialerOptions + ServerOptions + поля выше
|
||||
|
||||
protocol/masque/ (НОВЫЙ пакет)
|
||||
outbound.go — adapter.Outbound: NewOutbound, DialContext, ListenPacket, Close,
|
||||
run()/насосы, resolve, RegisterOutbound
|
||||
device.go — тонкая обёртка над transport/wireguard.stackDevice (или прямое исп.)
|
||||
|
||||
transport/masque/ (НОВЫЙ пакет — вкопанный connect-ip-go + клиент)
|
||||
client_h3.go — ConnectTunnel: http3.Transport{EnableDatagrams} → NewClientConn →
|
||||
OpenRequestStream → SendRequestHeader(Extended CONNECT) → ReadResponse
|
||||
client_h2.go — ConnectTunnelH2: http.Transport (h2c) → CONNECT → capsule DATAGRAM в теле
|
||||
connectip.go — порт connect-ip-go: IpConn (ReadPacket/WritePacket), capsule-парсинг,
|
||||
TTL/checksum, AdvertiseRoute (h3)
|
||||
profile.go — cloudflareProfile / standardProfile, PrepareTLSConfig (pinning), GenerateCert
|
||||
const.go — ConnectSNI, ConnectURI, capsule type constants
|
||||
|
||||
include/quic.go
|
||||
+ masque.RegisterOutbound(registry) в registerQUICOutbounds() // под with_quic
|
||||
+ import _ protocol/masque
|
||||
```
|
||||
|
||||
**Фабрика/registry не трогаем** — регистрация идёт через `outbound.Register[MASQUEOutboundOptions]`.
|
||||
|
||||
### adapter.Outbound (что реализуем)
|
||||
|
||||
`adapter/outbound.go:16` — интерфейс минимален: `Type/Tag/Network/Dependencies` + `N.Dialer`.
|
||||
Реально пишем:
|
||||
- `DialContext(ctx, network, dest) (net.Conn, error)` — TCP через userspace-стек
|
||||
- `ListenPacket(ctx, dest) (net.PacketConn, error)` — UDP через userspace-стек
|
||||
- `Network() []string` — из `network_list` (tcp/udp)
|
||||
- `Close()` — рвёт туннель, гасит стек
|
||||
- lazy `run(ctx)` — поднимает туннель+стек+насосы при первом дайле (как mihomo `run()` с sync.Once-паттерном)
|
||||
|
||||
---
|
||||
|
||||
## Стек (userspace gVisor) — переиспользование
|
||||
|
||||
Наш `transport/wireguard/device_stack.go` `stackDevice` (build `with_gvisor`) уже даёт ровно нужный контракт:
|
||||
- `newStackDevice(DeviceOptions{Address: prefixes, MTU})` — gVisor-стек с локальными IP
|
||||
- `Read(bufs, sizes, offset)` — вынимает исходящий IP-пакет (приложение → сеть) ⇒ пихаем в туннель
|
||||
- `Write(bufs, offset)` — вкидывает входящий IP-пакет (сеть → приложение)
|
||||
- `DialContext` / `ListenPacket` — наружу для adapter.Outbound
|
||||
- `Inet4Address()` / `Inet6Address()` — локальные IP
|
||||
|
||||
WG-специфика (`SetDevice`, `Events`, wg `bind`) для MASQUE НЕ нужна — просто не вызываем.
|
||||
**Решение по переиспользованию (выбрать при имплементации):**
|
||||
- (A) вызвать `newStackDevice` напрямую из `protocol/masque` — но это внутренний символ пакета `wireguard`.
|
||||
Тогда экспортировать конструктор (`NewStackDevice`) или вынести stackDevice в общий пакет.
|
||||
- (B) не трогать wireguard, сделать свой тонкий gVisor-стек в `protocol/masque/device.go` (копия ~200 строк).
|
||||
|
||||
Рекомендация: **(A) экспортировать `NewStackDevice`** из `transport/wireguard` (минимальный diff, один
|
||||
источник gVisor-стека, меньше дублирования). Проверить, что экспорт не тянет лишних WG-зависимостей в сборку
|
||||
без WG. Fallback — (B).
|
||||
|
||||
---
|
||||
|
||||
## Поток данных (h3)
|
||||
|
||||
```
|
||||
NewOutbound: разобрать ключи, prefixes, profile, quicConfig{EnableDatagrams,InitialPacketSize:1242,KeepAlive:30s}
|
||||
run() (lazy, sync.Once-паттерн):
|
||||
1. stackDevice = NewStackDevice(prefixes, mtu); stackDevice.Start()
|
||||
2. pc, quicConn = DialQuic(server, tlsConfig(profile), quicConfig) // через наш dialer
|
||||
3. tr, ipConn = ConnectTunnel(quicConn, uri, profile) // Extended CONNECT + AdvertiseRoute
|
||||
4. насос TX: for { stackDevice.Read(bufs,sizes) → ipConn.WritePacket(pkt) [→ icmp? → stackDevice.Write] }
|
||||
5. насос RX: for { ipConn.ReadPacket() → stackDevice.Write(pkt) }
|
||||
DialContext/ListenPacket: run(); затем stackDevice.DialContext/ListenPacket(dest)
|
||||
Close: cancel → ipConn.Close, tr.Close, pc.Close, stackDevice.Close
|
||||
```
|
||||
|
||||
`ConnectTunnel` (h3): `tr.NewClientConn(quicConn)` → `OpenRequestStream` → `SendRequestHeader`
|
||||
(`:method CONNECT`, `:protocol cf-connect-ip`, `Capsule-Protocol: ?1`, cf-заголовки) → `ReadResponse`
|
||||
(status 2xx) → `connectip.NewProxiedConn(rstr)`; затем `AdvertiseRoute(0.0.0.0/0, ::/0)`.
|
||||
При `ignoreExtendedConnect` НЕ падать, если `settings.EnableExtendedConnect == false`.
|
||||
|
||||
## Поток данных (h2)
|
||||
|
||||
`ConnectTunnelH2`: наш http-форк `Transport` c `DialTLSContext` (TCP dial → tls.Client с tlsConfig, ALPN `h2`,
|
||||
h2c для запрета fallback на HTTP/1.1) → `MethodConnect` с телом-pipe → capsule DATAGRAM (`type 0` + varint len)
|
||||
пишутся в тело запроса, читаются из тела ответа. `IpConn` тот же интерфейс (ReadPacket/WritePacket),
|
||||
внутри — `h2DatagramStream` (см. mihomo `client_h2.go`). TTL/checksum-декремент делает клиент (composeDatagram).
|
||||
|
||||
**Зависимость h2:** нужен http-форк, поддерживающий `Protocols.SetUnencryptedHTTP2` / `HTTP2Config`
|
||||
(mihomo использует `metacubex/http`). ⚠️ **Проверить при имплементации**, умеет ли наш стек (stdlib `net/http`
|
||||
или форк) h2c-режим с masked-tls-conn (см. golang/go#79293). Если нет — h2 требует вкапывания http-форка
|
||||
ИЛИ ручного h2-framing. Это риск объёма для h2 (см. §Риски).
|
||||
|
||||
---
|
||||
|
||||
## Ключевой материал (контракт с Dart/LxBox)
|
||||
|
||||
Регистрацию WARP делает вызывающая сторона (воспроизводимо на Dart, ядро не нужно):
|
||||
1. Сгенерировать **ECDSA P-256** keypair.
|
||||
2. WARP registration API (`api.cloudflareclient.com`) → назначенные `ip`/`ipv6`, endpoint `public_key`.
|
||||
3. Сериализовать: `private_key` = base64(DER `x509.MarshalECPrivateKey`),
|
||||
`public_key` = base64(DER `x509.MarshalPKIXPublicKey` от `*ecdsa.PublicKey`).
|
||||
|
||||
Ядро только парсит (`ParseECPrivateKey` / `ParsePKIXPublicKey`) и пинит. **Формат байт матчить точно** —
|
||||
несовпадение DER-кодировки = ошибка парсинга при старте. Тест-вектор согласовать с Dart-стороной (§Тест-план).
|
||||
|
||||
---
|
||||
|
||||
## Совместимость / сборка
|
||||
|
||||
- Только под `with_quic` + `with_gvisor`. В минимальных сборках отсутствует (как tuic/hysteria).
|
||||
- **LX_TAGS**: `masque` попадает в сборки, где есть `with_quic`+`with_gvisor` (desktop/CLI — да; AAR — проверить,
|
||||
gVisor обычно включён т.к. WG-endpoint его требует). Свериться с [[desktop-keeps-clash-api-aar-drops]] логикой тегов.
|
||||
- go.mod: **новых внешних зависимостей нет** (connect-ip-go вкопан). Если h2 потребует http-форк — это
|
||||
единственная возможная новая зависимость, решить отдельно (см. §Риски).
|
||||
|
||||
---
|
||||
|
||||
## Тест-план
|
||||
|
||||
Юнит (без сети):
|
||||
- `option/masque_test.go` — парсинг конфига, дефолты по профилю, fail-fast валидация (нет ключей → ошибка;
|
||||
плохой CIDR → ошибка; `network` вне множества → ошибка).
|
||||
- `transport/masque` — парсинг ключей (тест-вектор DER, согласованный с Dart); capsule DATAGRAM
|
||||
encode/decode (h2 path); TTL-декремент + IPv4-checksum пересчёт (известные векторы).
|
||||
- профиль-матрица: cloudflare vs standard дают правильный `:protocol` и набор заголовков.
|
||||
|
||||
Интеграция (live, стенд):
|
||||
- реальный WARP endpoint + реальный ключевой материал (из Dart-регистрации):
|
||||
- `network: h3` — TCP (curl ifconfig.me через outbound → видим WARP-IP) + UDP (DNS/QUIC через outbound).
|
||||
- `network: h2` — то же, там где h3 режется.
|
||||
- reachability-матрица как в SPEC 020: dial успех, данные ходят в обе стороны, Close чистый (нет goroutine-leak).
|
||||
- негатив: неверный `public_key` → login failed (ожидаемая ошибка `tls: access denied`); неверный `ip` → нет данных.
|
||||
|
||||
Записать РЕЗУЛЬТАТЫ в `SPECS/021-.../TEST_PLAN.md` §RESULTS с указанием endpoint/даты/сборки
|
||||
(конвенция форка — стендовые замеры в спеке).
|
||||
|
||||
---
|
||||
|
||||
## Фазы
|
||||
|
||||
- **Ф1 (h3, cloudflare):** constant + option + профили + client_h3 + connectip + stackDevice-reuse + outbound +
|
||||
регистрация. Цель: живое TCP+UDP через WARP по QUIC. ← основная ценность.
|
||||
- **Ф2 (h2):** client_h2 + capsule-over-h2 (+ решение по http-форку). Цель: WARP там, где режут QUIC.
|
||||
- **Ф3 (standard/RFC, задел):** `connect-ip`/строгий Extended CONNECT/обычный TLS. НЕ вылизываем в v1.
|
||||
|
||||
---
|
||||
|
||||
## Что НЕ в scope
|
||||
|
||||
- **CONNECT-UDP (RFC 9298)** — здесь только CONNECT-IP. Отдельный спек, если понадобится generic UDP-прокси.
|
||||
- **h3-l4proxy** (mihomo `network: h3-l4proxy`, L4 CONNECT/TCP-стрим поверх, только TCP) — фаза позже.
|
||||
- **inbound / MASQUE-сервер** — только клиент-outbound.
|
||||
- **регистрация устройства в WARP** — вне ядра (Dart/LxBox).
|
||||
- **PQC** (`pq-enabled: true`) — cf-поле фиксируем в false.
|
||||
- **IP flow forwarding** (URI-шаблон с переменными host/port) — mihomo его тоже не поддерживает (`Varnames > 0` → ошибка).
|
||||
|
||||
---
|
||||
|
||||
## Риски / открытые вопросы
|
||||
|
||||
1. **h2 требует h2c-режима** с masked tls.Conn — стандартный `net/http` это не умеет чисто
|
||||
(golang/go#79293). Возможные пути: (а) вкопать нужную часть http-форка, (б) ручной h2-framing поверх
|
||||
tls.Conn, (в) отложить h2 в Ф2 и решить по факту. Влияет на объём — уточнить в начале Ф2.
|
||||
2. **Экспорт `NewStackDevice`** из `transport/wireguard` — убедиться, что не тянет WG-код в masque-only сборку
|
||||
и не ломает существующие тесты WG-endpoint.
|
||||
3. **DER-формат ключей** — согласовать байт-в-байт тест-вектор с Dart до Ф1-интеграции, иначе живой тест
|
||||
упадёт на парсинге.
|
||||
4. **Cloudflare non-RFC quirks** могут дрейфовать (WARP меняет протокол) — привязываемся к текущему поведению
|
||||
mihomo Alpha; зафиксировать версию/коммит mihomo как референс в TEST_PLAN.
|
||||
|
||||
## Результаты реализации (что реально легло)
|
||||
|
||||
Файлы:
|
||||
- `transport/masque/connectip/` — вкопанный connect-ip-go (connectip.go, capsule.go, iprange.go,
|
||||
checksum.go, icmp.go) на `sagernet/quic-go`. Порт = смена импортов + `min` builtin (выкинут minmax.go),
|
||||
без httpsfv/uritemplate (URI парсим `net/url`, capsule-header хардкод `?1`). Отброшены proxy/request/
|
||||
client (серверная сторона + RFC-strict Dial). Компилируется без build-тегов.
|
||||
- `transport/masque/` — `profile.go` (cloudflare/standard + PrepareTLSConfig pinning + генерация client
|
||||
cert), `masque.go` (ConnectTunnelH3 + IpConn), `request.go` (Extended CONNECT + advertiseDefaultRoute),
|
||||
`client_h2.go` (capsule DATAGRAM поверх stdlib net/http CONNECT-pipe).
|
||||
- `protocol/masque/outbound.go` — adapter.Outbound: lazy run(), два насоса, DialContext/ListenPacket/Close.
|
||||
- `option/masque.go`, `constant/proxy.go` (TypeMASQUE + displayName), `include/quic.go` (+quic_stub.go).
|
||||
|
||||
Отклонения от плана спека:
|
||||
- **Экспорт `NewStackDevice` НЕ понадобился.** `transport/wireguard.NewDevice(DeviceOptions{Address,MTU})`
|
||||
уже экспортирован и при `System:false` даёт gVisor `stackDevice` с Read/Write (raw IP) + DialContext/
|
||||
ListenPacket + Start/Close. `SetDevice` — no-op для stackDevice, WG-device не нужен. Риск №2 снят.
|
||||
- **h2 БЕЗ http-форка.** Риск №1 снят: stdlib Go 1.25 `net/http` (Protocols.SetHTTP2 + DialTLSContext)
|
||||
тянет обычный CONNECT со стриминговым телом-pipe; capsule DATAGRAM (type 0) framing ручной поверх
|
||||
`quicvarint`. Не используем `NewClientConn`/`Reserve` (это была причина форка у mihomo). НОВЫХ внешних
|
||||
зависимостей нет; `golang.org/x/net` (icmp/ipv4/ipv6) и `x/exp` уже в go.mod.
|
||||
- Без gvisor `NewDevice(System:false)` вернёт `ErrGVisorNotIncluded` при первом дайле (graceful, не паника).
|
||||
|
||||
Проверки: `go build` (with_quic+with_gvisor+with_wireguard и stub-путь без quic), `go vet`, `gofmt -l`
|
||||
чисто. Юнит-тесты зелёные: profile-матрица, TLS-pinning, EC-ключи round-trip, capsule round-trip
|
||||
(route/address), IPv4-checksum (вектор 0xb861), parsePrefixes, decode `type:masque` через include-registry.
|
||||
**НЕ проверено на живом WARP** — нужен реальный ключевой материал из Dart-регистрации (риск №3, §Тест-план).
|
||||
|
||||
## Референс
|
||||
|
||||
- mihomo `Alpha`: `transport/masque/{masque.go,client_h2.go,l4proxy.go}`, `adapter/outbound/masque.go`
|
||||
(порт от `Diniboy1123/usque` + `connect-ip-go`; изучены в разведке).
|
||||
- RFC 9484 (CONNECT-IP), RFC 9298 (CONNECT-UDP, для контраста), RFC 9297 (HTTP Datagrams).
|
||||
- Наш форк: `transport/wireguard/device_stack.go` (stackDevice), `sagernet/quic-go/http3`
|
||||
(OpenRequestStream/SendDatagram/capsule), `include/quic.go`.
|
||||
- Апстрим-запрос: SagerNet/sing-box#4000.
|
||||
@@ -24,6 +24,7 @@ const (
|
||||
TypeVLESS = "vless"
|
||||
TypeTUIC = "tuic"
|
||||
TypeHysteria2 = "hysteria2"
|
||||
TypeMASQUE = "masque"
|
||||
TypeTailscale = "tailscale"
|
||||
TypeCloudflared = "cloudflared"
|
||||
TypeDERP = "derp"
|
||||
@@ -114,6 +115,8 @@ func ProxyDisplayName(proxyType string) string {
|
||||
return "TUIC"
|
||||
case TypeHysteria2:
|
||||
return "Hysteria2"
|
||||
case TypeMASQUE:
|
||||
return "MASQUE"
|
||||
case TypeAnyTLS:
|
||||
return "AnyTLS"
|
||||
case TypeTailscale:
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/sagernet/sing-box/dns/transport/quic"
|
||||
"github.com/sagernet/sing-box/protocol/hysteria"
|
||||
"github.com/sagernet/sing-box/protocol/hysteria2"
|
||||
"github.com/sagernet/sing-box/protocol/masque"
|
||||
_ "github.com/sagernet/sing-box/protocol/naive/quic"
|
||||
"github.com/sagernet/sing-box/protocol/tuic"
|
||||
_ "github.com/sagernet/sing-box/transport/v2rayquic"
|
||||
@@ -25,6 +26,7 @@ func registerQUICOutbounds(registry *outbound.Registry) {
|
||||
hysteria.RegisterOutbound(registry)
|
||||
tuic.RegisterOutbound(registry)
|
||||
hysteria2.RegisterOutbound(registry)
|
||||
masque.RegisterOutbound(registry)
|
||||
}
|
||||
|
||||
func registerQUICTransports(registry *dns.TransportRegistry) {
|
||||
|
||||
@@ -60,6 +60,9 @@ func registerQUICOutbounds(registry *outbound.Registry) {
|
||||
outbound.Register[option.Hysteria2OutboundOptions](registry, C.TypeHysteria2, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2OutboundOptions) (adapter.Outbound, error) {
|
||||
return nil, C.ErrQUICNotIncluded
|
||||
})
|
||||
outbound.Register[option.MASQUEOutboundOptions](registry, C.TypeMASQUE, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.MASQUEOutboundOptions) (adapter.Outbound, error) {
|
||||
return nil, C.ErrQUICNotIncluded
|
||||
})
|
||||
}
|
||||
|
||||
func registerQUICTransports(registry *dns.TransportRegistry) {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package option
|
||||
|
||||
// MASQUEOutboundOptions configures a MASQUE (CONNECT-IP / RFC 9484) outbound,
|
||||
// primarily for Cloudflare WARP. See SPEC 021.
|
||||
type MASQUEOutboundOptions struct {
|
||||
DialerOptions
|
||||
ServerOptions
|
||||
|
||||
// Profile selects behaviour: "cloudflare" (default) or "standard" (RFC 9484).
|
||||
Profile string `json:"profile,omitempty"`
|
||||
// Network selects the transport: "h3" (QUIC, default) or "h2" (HTTP/2).
|
||||
Network string `json:"network,omitempty"`
|
||||
|
||||
// Key material (required for the cloudflare profile). Base64-encoded DER:
|
||||
// PrivateKey via x509.ParseECPrivateKey, PublicKey via x509.ParsePKIXPublicKey.
|
||||
PrivateKey string `json:"private_key,omitempty"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
|
||||
// Local tunnel addresses. At least one of IP/IPv6 is required. A bare
|
||||
// address without a mask is treated as /32 (v4) or /128 (v6).
|
||||
IP string `json:"ip,omitempty"`
|
||||
IPv6 string `json:"ipv6,omitempty"`
|
||||
|
||||
// URI is the CONNECT-IP request URI template. Defaults per profile.
|
||||
URI string `json:"uri,omitempty"`
|
||||
// SNI overrides the TLS server name. Defaults per profile.
|
||||
SNI string `json:"sni,omitempty"`
|
||||
// MTU of the userspace stack. Defaults to 1280.
|
||||
MTU uint32 `json:"mtu,omitempty"`
|
||||
// SkipCertVerify disables public-key pinning (debug only).
|
||||
SkipCertVerify bool `json:"skip_cert_verify,omitempty"`
|
||||
|
||||
CongestionControl string `json:"congestion_control,omitempty"`
|
||||
|
||||
NetworkList NetworkList `json:"network_list,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/quic-go"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
"github.com/sagernet/sing-box/common/dialer"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/transport/masque"
|
||||
"github.com/sagernet/sing-box/transport/wireguard"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
func RegisterOutbound(registry *outbound.Registry) {
|
||||
outbound.Register[option.MASQUEOutboundOptions](registry, C.TypeMASQUE, NewOutbound)
|
||||
}
|
||||
|
||||
const defaultMTU uint32 = 1280
|
||||
|
||||
type Outbound struct {
|
||||
outbound.Adapter
|
||||
ctx context.Context
|
||||
logger logger.ContextLogger
|
||||
dialer N.Dialer
|
||||
profile masque.Profile
|
||||
|
||||
server M.Socksaddr
|
||||
uri string
|
||||
network string // "h3" | "h2"
|
||||
mtu uint32
|
||||
prefixes []netip.Prefix
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
|
||||
// lazily-started tunnel state
|
||||
runMu sync.Mutex
|
||||
running bool
|
||||
device wireguard.Device
|
||||
closer io.Closer
|
||||
ipConn masque.IpConn
|
||||
runCtx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.MASQUEOutboundOptions) (adapter.Outbound, error) {
|
||||
profile, err := masque.ParseProfile(options.Profile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
network := options.Network
|
||||
if network == "" {
|
||||
network = "h3"
|
||||
}
|
||||
if network != "h3" && network != "h2" {
|
||||
return nil, E.New("masque: invalid network: ", network, " (expected h3 or h2)")
|
||||
}
|
||||
if network == "h2" && options.Profile == "standard" {
|
||||
return nil, E.New("masque: network h2 is not implemented for the standard profile")
|
||||
}
|
||||
|
||||
prefixes, err := parsePrefixes(options.IP, options.IPv6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var privKey *ecdsa.PrivateKey
|
||||
var pubKey *ecdsa.PublicKey
|
||||
if profile.PinPublicKey {
|
||||
if options.PrivateKey == "" || options.PublicKey == "" {
|
||||
return nil, E.New("masque: private_key and public_key are required for the cloudflare profile")
|
||||
}
|
||||
}
|
||||
if options.PrivateKey != "" {
|
||||
privKey, err = parseECPrivateKey(options.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse private_key")
|
||||
}
|
||||
}
|
||||
if options.PublicKey != "" {
|
||||
pubKey, err = parseECPublicKey(options.PublicKey)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse public_key")
|
||||
}
|
||||
}
|
||||
|
||||
uri := options.URI
|
||||
if uri == "" {
|
||||
uri = profile.DefaultURI
|
||||
}
|
||||
if uri == "" {
|
||||
return nil, E.New("masque: uri is required for the standard profile")
|
||||
}
|
||||
|
||||
sni := options.SNI
|
||||
if sni == "" {
|
||||
sni = profile.DefaultSNI
|
||||
}
|
||||
if sni == "" {
|
||||
sni = options.Server
|
||||
}
|
||||
|
||||
tlsConfig, err := masque.PrepareTLSConfig(profile, privKey, pubKey, sni, options.SkipCertVerify)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mtu := options.MTU
|
||||
if mtu == 0 {
|
||||
mtu = defaultMTU
|
||||
}
|
||||
|
||||
outboundDialer, err := dialer.New(ctx, options.DialerOptions, options.ServerIsDomain())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
quicConfig := &quic.Config{
|
||||
EnableDatagrams: true,
|
||||
InitialPacketSize: 1242,
|
||||
KeepAlivePeriod: 30 * time.Second,
|
||||
}
|
||||
|
||||
networkList := options.NetworkList.Build()
|
||||
|
||||
return &Outbound{
|
||||
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeMASQUE, tag, networkList, options.DialerOptions),
|
||||
ctx: ctx,
|
||||
logger: logger,
|
||||
dialer: outboundDialer,
|
||||
profile: profile,
|
||||
server: options.ServerOptions.Build(),
|
||||
uri: uri,
|
||||
network: network,
|
||||
mtu: mtu,
|
||||
prefixes: prefixes,
|
||||
tlsConfig: tlsConfig,
|
||||
quicConfig: quicConfig,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// run lazily establishes the tunnel and userspace stack on first dial.
|
||||
func (o *Outbound) run(ctx context.Context) error {
|
||||
o.runMu.Lock()
|
||||
defer o.runMu.Unlock()
|
||||
if o.running {
|
||||
return nil
|
||||
}
|
||||
|
||||
device, err := wireguard.NewDevice(wireguard.DeviceOptions{
|
||||
Context: o.ctx,
|
||||
Logger: o.logger,
|
||||
MTU: o.mtu,
|
||||
Address: o.prefixes,
|
||||
})
|
||||
if err != nil {
|
||||
return E.Cause(err, "create userspace stack")
|
||||
}
|
||||
if err = device.Start(); err != nil {
|
||||
return E.Cause(err, "start userspace stack")
|
||||
}
|
||||
|
||||
var closer io.Closer
|
||||
var ipConn masque.IpConn
|
||||
switch o.network {
|
||||
case "h2":
|
||||
closer, ipConn, err = o.connectH2(ctx)
|
||||
default:
|
||||
closer, ipConn, err = o.connectH3(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
_ = device.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
runCtx, cancel := context.WithCancel(o.ctx)
|
||||
o.device = device
|
||||
o.closer = closer
|
||||
o.ipConn = ipConn
|
||||
o.runCtx = runCtx
|
||||
o.cancel = cancel
|
||||
o.running = true
|
||||
|
||||
go o.pumpToTunnel(runCtx, device, ipConn)
|
||||
go o.pumpFromTunnel(runCtx, device, ipConn)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Outbound) connectH3(ctx context.Context) (io.Closer, masque.IpConn, error) {
|
||||
udpConn, err := o.dialer.DialContext(ctx, N.NetworkUDP, o.server)
|
||||
if err != nil {
|
||||
return nil, nil, E.Cause(err, "dial udp")
|
||||
}
|
||||
quicConn, err := quic.DialEarly(ctx, bufio.NewUnbindPacketConn(udpConn), udpConn.RemoteAddr(), o.tlsConfig, o.quicConfig)
|
||||
if err != nil {
|
||||
_ = udpConn.Close()
|
||||
return nil, nil, E.Cause(err, "dial quic")
|
||||
}
|
||||
tr, ipConn, err := masque.ConnectTunnelH3(ctx, o.profile, quicConn, o.uri)
|
||||
if err != nil {
|
||||
_ = udpConn.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return &h3Closer{transport: tr, rawConn: udpConn}, ipConn, nil
|
||||
}
|
||||
|
||||
func (o *Outbound) connectH2(ctx context.Context) (io.Closer, masque.IpConn, error) {
|
||||
protocols := new(http.Protocols)
|
||||
protocols.SetHTTP2(true)
|
||||
transport := &http.Transport{
|
||||
Protocols: protocols,
|
||||
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
c, err := o.dialer.DialContext(ctx, N.NetworkTCP, o.server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tls.Client(c, o.tlsConfig)
|
||||
if err = tlsConn.HandshakeContext(ctx); err != nil {
|
||||
_ = c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
},
|
||||
}
|
||||
return masque.ConnectTunnelH2(ctx, o.profile, transport, o.uri)
|
||||
}
|
||||
|
||||
// pumpToTunnel reads outgoing IP packets from the userspace stack and writes
|
||||
// them into the MASQUE tunnel.
|
||||
func (o *Outbound) pumpToTunnel(ctx context.Context, device wireguard.Device, ipConn masque.IpConn) {
|
||||
defer o.cancel()
|
||||
batch := device.BatchSize()
|
||||
bufs := make([][]byte, batch)
|
||||
sizes := make([]int, batch)
|
||||
for i := range bufs {
|
||||
bufs[i] = make([]byte, int(o.mtu)+80)
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
count, err := device.Read(bufs, sizes, 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for i := 0; i < count; i++ {
|
||||
icmp, werr := ipConn.WritePacket(bufs[i][:sizes[i]])
|
||||
if werr != nil {
|
||||
return
|
||||
}
|
||||
if len(icmp) > 0 {
|
||||
_, _ = device.Write([][]byte{icmp}, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pumpFromTunnel reads incoming IP packets from the MASQUE tunnel and injects
|
||||
// them into the userspace stack.
|
||||
func (o *Outbound) pumpFromTunnel(ctx context.Context, device wireguard.Device, ipConn masque.IpConn) {
|
||||
defer o.cancel()
|
||||
for ctx.Err() == nil {
|
||||
packet, err := ipConn.ReadPacket()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = device.Write([][]byte{packet}, 0); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
if err := o.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o.device.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (o *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
if err := o.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o.device.ListenPacket(ctx, destination)
|
||||
}
|
||||
|
||||
func (o *Outbound) Close() error {
|
||||
o.runMu.Lock()
|
||||
defer o.runMu.Unlock()
|
||||
if !o.running {
|
||||
return nil
|
||||
}
|
||||
o.running = false
|
||||
if o.cancel != nil {
|
||||
o.cancel()
|
||||
}
|
||||
if o.ipConn != nil {
|
||||
_ = o.ipConn.Close()
|
||||
}
|
||||
if o.closer != nil {
|
||||
_ = o.closer.Close()
|
||||
}
|
||||
if o.device != nil {
|
||||
_ = o.device.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type h3Closer struct {
|
||||
transport io.Closer
|
||||
rawConn net.Conn
|
||||
}
|
||||
|
||||
func (c *h3Closer) Close() error {
|
||||
if c.transport != nil {
|
||||
_ = c.transport.Close()
|
||||
}
|
||||
if c.rawConn != nil {
|
||||
_ = c.rawConn.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parsePrefixes(ip, ipv6 string) ([]netip.Prefix, error) {
|
||||
prefixes := make([]netip.Prefix, 0, 2)
|
||||
if ip != "" {
|
||||
if !strings.Contains(ip, "/") {
|
||||
ip += "/32"
|
||||
}
|
||||
prefix, err := netip.ParsePrefix(ip)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse ip")
|
||||
}
|
||||
prefixes = append(prefixes, prefix)
|
||||
}
|
||||
if ipv6 != "" {
|
||||
if !strings.Contains(ipv6, "/") {
|
||||
ipv6 += "/128"
|
||||
}
|
||||
prefix, err := netip.ParsePrefix(ipv6)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse ipv6")
|
||||
}
|
||||
prefixes = append(prefixes, prefix)
|
||||
}
|
||||
if len(prefixes) == 0 {
|
||||
return nil, E.New("masque: at least one of ip/ipv6 is required")
|
||||
}
|
||||
return prefixes, nil
|
||||
}
|
||||
|
||||
func parseECPrivateKey(b64 string) (*ecdsa.PrivateKey, error) {
|
||||
der, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x509.ParseECPrivateKey(der)
|
||||
}
|
||||
|
||||
func parseECPublicKey(b64 string) (*ecdsa.PublicKey, error) {
|
||||
der, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub, err := x509.ParsePKIXPublicKey(der)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ecPub, ok := pub.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, E.New("public_key is not an ECDSA key")
|
||||
}
|
||||
return ecPub, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParsePrefixes(t *testing.T) {
|
||||
t.Parallel()
|
||||
// bare v4 → /32, bare v6 → /128
|
||||
prefixes, err := parsePrefixes("172.16.0.2", "2606:4700::1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(prefixes) != 2 {
|
||||
t.Fatalf("expected 2 prefixes, got %d", len(prefixes))
|
||||
}
|
||||
if prefixes[0].String() != "172.16.0.2/32" {
|
||||
t.Fatalf("v4 = %s", prefixes[0])
|
||||
}
|
||||
if prefixes[1].String() != "2606:4700::1/128" {
|
||||
t.Fatalf("v6 = %s", prefixes[1])
|
||||
}
|
||||
|
||||
// explicit mask preserved
|
||||
prefixes, err = parsePrefixes("10.0.0.0/24", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prefixes[0].String() != "10.0.0.0/24" {
|
||||
t.Fatalf("masked v4 = %s", prefixes[0])
|
||||
}
|
||||
|
||||
// none → error
|
||||
if _, err = parsePrefixes("", ""); err == nil {
|
||||
t.Fatal("expected error when no address given")
|
||||
}
|
||||
|
||||
// bad → error
|
||||
if _, err = parsePrefixes("not-an-ip", ""); err == nil {
|
||||
t.Fatal("expected error for malformed ip")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseECKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
privDER, err := x509.MarshalECPrivateKey(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pubDER, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
gotPriv, err := parseECPrivateKey(base64.StdEncoding.EncodeToString(privDER))
|
||||
if err != nil {
|
||||
t.Fatalf("parse private: %v", err)
|
||||
}
|
||||
if !gotPriv.Equal(priv) {
|
||||
t.Fatal("round-tripped private key mismatch")
|
||||
}
|
||||
|
||||
gotPub, err := parseECPublicKey(base64.StdEncoding.EncodeToString(pubDER))
|
||||
if err != nil {
|
||||
t.Fatalf("parse public: %v", err)
|
||||
}
|
||||
if !gotPub.Equal(&priv.PublicKey) {
|
||||
t.Fatal("round-tripped public key mismatch")
|
||||
}
|
||||
|
||||
// garbage base64 → error
|
||||
if _, err = parseECPrivateKey("!!!!"); err == nil {
|
||||
t.Fatal("expected error for bad base64")
|
||||
}
|
||||
// valid base64 but not an EC key → error
|
||||
if _, err = parseECPublicKey(base64.StdEncoding.EncodeToString([]byte("nope"))); err == nil {
|
||||
t.Fatal("expected error for non-key DER")
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -11,7 +11,7 @@ require (
|
||||
github.com/docker/go-connections v0.5.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/sagernet/quic-go v0.59.0-sing-box-mod.4
|
||||
github.com/sagernet/sing v0.8.11-0.20260514110501-905ad103a4df
|
||||
github.com/sagernet/sing v0.8.12-0.20260701111927-87e1e819f10a
|
||||
github.com/sagernet/sing-quic v0.6.2-0.20260525051024-9467ede27fb7
|
||||
github.com/sagernet/sing-shadowsocks v0.2.8
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.1
|
||||
@@ -140,10 +140,10 @@ require (
|
||||
github.com/sagernet/gvisor v0.0.0-20250822052253-5558536cf237 // indirect
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect
|
||||
github.com/sagernet/nftables v0.3.0-mod.2 // indirect
|
||||
github.com/sagernet/sing-cloudflared v0.1.1-0.20260620151903-a1d6358fe953 // indirect
|
||||
github.com/sagernet/sing-cloudflared v0.1.1 // indirect
|
||||
github.com/sagernet/sing-mux v0.3.5 // indirect
|
||||
github.com/sagernet/sing-shadowtls v0.2.1 // indirect
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260620141852-d8bba3691575 // indirect
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260629021427-b3c6babbd353 // indirect
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260616101517-efb91521eddb // indirect
|
||||
github.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1 // indirect
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1 // indirect
|
||||
|
||||
+6
-6
@@ -277,10 +277,10 @@ github.com/sagernet/nftables v0.3.0-mod.2 h1:ck2KMU02OxL1eDFgGaWYglMDpoOZ7OHzxje
|
||||
github.com/sagernet/nftables v0.3.0-mod.2/go.mod h1:8kslHG4VvYNihcco+i6uxIX7qbT8A56T0y5q7U44ZaQ=
|
||||
github.com/sagernet/quic-go v0.59.0-sing-box-mod.4 h1:6qvrUW79S+CrPwWz6cMePXohgjHoKxLo3c+MDhNwc3o=
|
||||
github.com/sagernet/quic-go v0.59.0-sing-box-mod.4/go.mod h1:OqILvS182CyOol5zNNo6bguvOGgXzV459+chpRaUC+4=
|
||||
github.com/sagernet/sing v0.8.11-0.20260514110501-905ad103a4df h1:zSDw1g1JhIEqE/XPC3hW1wMdFPzbVgVJZiV86FAJoNQ=
|
||||
github.com/sagernet/sing v0.8.11-0.20260514110501-905ad103a4df/go.mod h1:olXxWQNqRW/l2Q6JI3b2Qmz8iQnIFlOeeH8bx6JhgUA=
|
||||
github.com/sagernet/sing-cloudflared v0.1.1-0.20260620151903-a1d6358fe953 h1:bqZWzc7mVO+V6Z07PAwav1TnlAlNltr/e1J2z8sZn4o=
|
||||
github.com/sagernet/sing-cloudflared v0.1.1-0.20260620151903-a1d6358fe953/go.mod h1:bH2NKX+NpDTY1Zkxfboxw6MXB/ZywaNLmrDJYgKMJ2Y=
|
||||
github.com/sagernet/sing v0.8.12-0.20260701111927-87e1e819f10a h1:MCid6UN8a7WZWziqlWbLRFOt2jsfNZ7HRYEbP+MxX0U=
|
||||
github.com/sagernet/sing v0.8.12-0.20260701111927-87e1e819f10a/go.mod h1:olXxWQNqRW/l2Q6JI3b2Qmz8iQnIFlOeeH8bx6JhgUA=
|
||||
github.com/sagernet/sing-cloudflared v0.1.1 h1:By29ZWMJl8QU6UcC5pmBv803rYigAoSmzhDFOZc3h18=
|
||||
github.com/sagernet/sing-cloudflared v0.1.1/go.mod h1:bH2NKX+NpDTY1Zkxfboxw6MXB/ZywaNLmrDJYgKMJ2Y=
|
||||
github.com/sagernet/sing-mux v0.3.5 h1:RHnhVEc+SFqkrK4xMygYjDwwLhzp2Bj3lztSukONfhI=
|
||||
github.com/sagernet/sing-mux v0.3.5/go.mod h1:QvlKMyNBNrQoyX4x+gq028uPbLM2XeRpWtDsWBJbFSk=
|
||||
github.com/sagernet/sing-quic v0.6.2-0.20260525051024-9467ede27fb7 h1:hFLPJ21uNZSbRnzhOKz4Zv0b4F93mpDorWyN93BeRcM=
|
||||
@@ -291,8 +291,8 @@ github.com/sagernet/sing-shadowsocks2 v0.2.1 h1:dWV9OXCeFPuYGHb6IRqlSptVnSzOelnq
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.1/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=
|
||||
github.com/sagernet/sing-shadowtls v0.2.1 h1:ZiHZdnEnP+YS73NMsxiZmIFCwNd0M4k7PkGCKNXhbaM=
|
||||
github.com/sagernet/sing-shadowtls v0.2.1/go.mod h1:sWqKnGlMipCHaGsw1sTTlimyUpgzP4WP3pjhCsYt9oA=
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260620141852-d8bba3691575 h1:0K8un73LZ6xOkeX6OQjH9HcKilwMJyZ9sURnsp8tn5U=
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260620141852-d8bba3691575/go.mod h1:QvarqUtHfj1ULaRR+6kZOS/OoCE+pYGq67A5tyIy+dQ=
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260629021427-b3c6babbd353 h1:HA0TGrBQSFfvcoVXL1DxzF+i8pmaGOGb33jdReB7L4s=
|
||||
github.com/sagernet/sing-tun v0.8.12-0.20260629021427-b3c6babbd353/go.mod h1:QvarqUtHfj1ULaRR+6kZOS/OoCE+pYGq67A5tyIy+dQ=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260616101517-efb91521eddb h1:KEMbfexD4DvrQGYWwx6r+AwH9Veh8z6cnBZmtCS2G+0=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260616101517-efb91521eddb/go.mod h1:D4CnJX3MNAAANhbQUxfIRgBdnvlTEaV7h6ojedcs+pw=
|
||||
github.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1 h1:aSwUNYUkVyVvdmBSufR8/nRFonwJeKSIROxHcm5br9o=
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/sing-box/include"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func masqueTestKeys(t *testing.T) (privB64, pubB64 string) {
|
||||
t.Helper()
|
||||
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
privDER, err := x509.MarshalECPrivateKey(priv)
|
||||
require.NoError(t, err)
|
||||
pubDER, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
require.NoError(t, err)
|
||||
return base64.StdEncoding.EncodeToString(privDER), base64.StdEncoding.EncodeToString(pubDER)
|
||||
}
|
||||
|
||||
// TestMASQUEOptionDecode verifies the option type is registered and a valid
|
||||
// cloudflare config decodes through the outbound registry.
|
||||
func TestMASQUEOptionDecode(t *testing.T) {
|
||||
priv, pub := masqueTestKeys(t)
|
||||
config := `{
|
||||
"outbounds": [
|
||||
{
|
||||
"type": "masque",
|
||||
"tag": "warp",
|
||||
"server": "162.159.198.1",
|
||||
"server_port": 443,
|
||||
"profile": "cloudflare",
|
||||
"network": "h3",
|
||||
"private_key": "` + priv + `",
|
||||
"public_key": "` + pub + `",
|
||||
"ip": "172.16.0.2/32",
|
||||
"ipv6": "2606:4700:110::/128"
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
ctx := include.Context(context.Background())
|
||||
var options option.Options
|
||||
err := json.UnmarshalContext(ctx, []byte(config), &options)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, options.Outbounds, 1)
|
||||
require.Equal(t, "masque", options.Outbounds[0].Type)
|
||||
|
||||
masqueOpts, ok := options.Outbounds[0].Options.(*option.MASQUEOutboundOptions)
|
||||
require.True(t, ok, "outbound options must decode to *MASQUEOutboundOptions")
|
||||
require.Equal(t, "cloudflare", masqueOpts.Profile)
|
||||
require.Equal(t, "h3", masqueOpts.Network)
|
||||
require.Equal(t, priv, masqueOpts.PrivateKey)
|
||||
require.Equal(t, "172.16.0.2/32", masqueOpts.IP)
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package masque
|
||||
|
||||
// HTTP/2 CONNECT-IP path. Adapted from mihomo's transport/masque/client_h2.go
|
||||
// (itself from Diniboy1123/connect-ip-go), ported to the stdlib net/http.
|
||||
//
|
||||
// Unlike HTTP/3, HTTP/2 has no native datagrams: proxied IP packets are carried
|
||||
// as HTTP capsule DATAGRAM frames (type 0) inside the bodies of a single
|
||||
// long-lived CONNECT request/response pair. TTL/checksum handling mirrors the
|
||||
// HTTP/3 path.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/quic-go/quicvarint"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
const h2DatagramCapsuleType uint64 = 0
|
||||
|
||||
const (
|
||||
ipv4HeaderLen = 20
|
||||
ipv6HeaderLen = 40
|
||||
)
|
||||
|
||||
// ConnectTunnelH2 establishes a CONNECT-IP tunnel over HTTP/2.
|
||||
func ConnectTunnelH2(ctx context.Context, profile Profile, transport *http.Transport, connectURI string) (io.Closer, IpConn, error) {
|
||||
header := http.Header{
|
||||
"User-Agent": []string{""},
|
||||
}
|
||||
if profile.H2ConnectProto != "" {
|
||||
header.Set("cf-connect-proto", profile.H2ConnectProto)
|
||||
// PQC not supported.
|
||||
header.Set("pq-enabled", "false")
|
||||
}
|
||||
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
ipConn, statusOK, err := dialH2(ctx, client, connectURI, header)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "tls: access denied") {
|
||||
return nil, nil, E.New("masque: login failed — verify the TLS key/cert is enrolled with Cloudflare Access")
|
||||
}
|
||||
return nil, nil, E.Cause(err, "masque: dial connect-ip over HTTP/2")
|
||||
}
|
||||
if !statusOK {
|
||||
_ = ipConn.Close()
|
||||
return nil, nil, E.New("masque: connect-ip over HTTP/2 rejected")
|
||||
}
|
||||
|
||||
return closerFunc(transport.CloseIdleConnections), ipConn, nil
|
||||
}
|
||||
|
||||
type closerFunc func()
|
||||
|
||||
func (f closerFunc) Close() error { f(); return nil }
|
||||
|
||||
func dialH2(ctx context.Context, client *http.Client, connectURI string, header http.Header) (*h2IpConn, bool, error) {
|
||||
u, err := url.Parse(connectURI)
|
||||
if err != nil {
|
||||
return nil, false, E.Cause(err, "parse connect uri")
|
||||
}
|
||||
|
||||
// reqCtx must be independent of ctx: cancelling ctx would otherwise tear
|
||||
// down the whole HTTP/2 connection instead of just this stream.
|
||||
reqCtx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodConnect, u.String(), pr)
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, false, E.Cause(err, "create request")
|
||||
}
|
||||
req.Host = authorityFromURL(u)
|
||||
req.ContentLength = -1
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
|
||||
// Bridge cancellation for the duration of the round trip only.
|
||||
stop := context.AfterFunc(ctx, cancel)
|
||||
rsp, err := client.Do(req)
|
||||
stop()
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, false, E.Cause(err, "send request")
|
||||
}
|
||||
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
_ = rsp.Body.Close()
|
||||
return nil, false, E.New("connect-ip: server responded with ", rsp.StatusCode)
|
||||
}
|
||||
|
||||
stream := &h2DatagramStream{
|
||||
requestBody: pw,
|
||||
responseBody: rsp.Body,
|
||||
cancel: cancel,
|
||||
}
|
||||
return &h2IpConn{str: stream, closeChan: make(chan struct{})}, true, nil
|
||||
}
|
||||
|
||||
func authorityFromURL(u *url.URL) string {
|
||||
if u.Port() != "" {
|
||||
return u.Host
|
||||
}
|
||||
host := u.Hostname()
|
||||
if host == "" {
|
||||
return u.Host
|
||||
}
|
||||
return host + ":443"
|
||||
}
|
||||
|
||||
type h2IpConn struct {
|
||||
str *h2DatagramStream
|
||||
|
||||
mu sync.Mutex
|
||||
closeChan chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (c *h2IpConn) ReadPacket() (b []byte, err error) {
|
||||
start:
|
||||
data, err := c.str.ReceiveDatagram()
|
||||
if err != nil {
|
||||
// h2 mode has no recoverable errors; closing lets the read loop exit.
|
||||
defer func() { _ = c.Close() }()
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := validateProxiedPacket(data); err != nil {
|
||||
goto start
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) WritePacket(b []byte) (icmp []byte, err error) {
|
||||
data, err := composeH2Datagram(b)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
if data == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err := c.str.SendDatagram(data); err != nil {
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) Close() error {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = io.ErrClosedPipe
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return c.str.Close()
|
||||
}
|
||||
|
||||
func validateProxiedPacket(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return E.New("connect-ip: empty packet")
|
||||
}
|
||||
switch v := ipVersion(data); v {
|
||||
default:
|
||||
return E.New("connect-ip: unknown IP version: ", v)
|
||||
case 4:
|
||||
if len(data) < ipv4HeaderLen {
|
||||
return E.New("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
case 6:
|
||||
if len(data) < ipv6HeaderLen {
|
||||
return E.New("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func composeH2Datagram(b []byte) ([]byte, error) {
|
||||
if len(b) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
switch v := ipVersion(b); v {
|
||||
default:
|
||||
return nil, E.New("connect-ip: unknown IP version: ", v)
|
||||
case 4:
|
||||
if len(b) < ipv4HeaderLen {
|
||||
return nil, E.New("connect-ip: IPv4 packet too short")
|
||||
}
|
||||
ttl := b[8]
|
||||
if ttl <= 1 {
|
||||
return nil, E.New("connect-ip: datagram TTL too small")
|
||||
}
|
||||
b[8]--
|
||||
binary.BigEndian.PutUint16(b[10:12], ipv4Checksum(b[:ipv4HeaderLen]))
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderLen {
|
||||
return nil, E.New("connect-ip: IPv6 packet too short")
|
||||
}
|
||||
hopLimit := b[7]
|
||||
if hopLimit <= 1 {
|
||||
return nil, E.New("connect-ip: datagram Hop Limit too small")
|
||||
}
|
||||
b[7]--
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func ipVersion(b []byte) uint8 { return b[0] >> 4 }
|
||||
|
||||
func ipv4Checksum(header []byte) uint16 {
|
||||
var sum uint32
|
||||
for i := 0; i < ipv4HeaderLen; i += 2 {
|
||||
if i == 10 {
|
||||
continue
|
||||
}
|
||||
sum += uint32(binary.BigEndian.Uint16(header[i : i+2]))
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
|
||||
// h2DatagramStream carries capsule DATAGRAM frames over the CONNECT body pipes.
|
||||
type h2DatagramStream struct {
|
||||
requestBody *io.PipeWriter
|
||||
responseBody io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
|
||||
readMu sync.Mutex
|
||||
writeMu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) ReceiveDatagram() ([]byte, error) {
|
||||
s.readMu.Lock()
|
||||
defer s.readMu.Unlock()
|
||||
|
||||
reader := quicvarint.NewReader(s.responseBody)
|
||||
for {
|
||||
capsuleType, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payloadLen, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := make([]byte, payloadLen)
|
||||
if _, err = io.ReadFull(reader, payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capsuleType != h2DatagramCapsuleType {
|
||||
continue
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) SendDatagram(data []byte) error {
|
||||
frame := make([]byte, 0, quicvarint.Len(h2DatagramCapsuleType)+quicvarint.Len(uint64(len(data)))+len(data))
|
||||
frame = quicvarint.Append(frame, h2DatagramCapsuleType)
|
||||
frame = quicvarint.Append(frame, uint64(len(data)))
|
||||
frame = append(frame, data...)
|
||||
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if _, err := s.requestBody.Write(frame); err != nil {
|
||||
return E.Cause(err, "send datagram capsule")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) Close() error {
|
||||
_ = s.requestBody.Close()
|
||||
err := s.responseBody.Close()
|
||||
s.cancel()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package connectip
|
||||
|
||||
// Vendored from connect-ip-go (MIT). Address/route capsules of RFC 9484,
|
||||
// ported onto sagernet/quic-go. See connectip.go header for provenance.
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
"github.com/sagernet/quic-go/quicvarint"
|
||||
)
|
||||
|
||||
const (
|
||||
capsuleTypeAddressAssign http3.CapsuleType = 1
|
||||
capsuleTypeAddressRequest http3.CapsuleType = 2
|
||||
capsuleTypeRouteAdvertisement http3.CapsuleType = 3
|
||||
)
|
||||
|
||||
type addressAssignCapsule struct {
|
||||
AssignedAddresses []AssignedAddress
|
||||
}
|
||||
|
||||
// AssignedAddress represents an Assigned Address within an ADDRESS_ASSIGN capsule.
|
||||
type AssignedAddress struct {
|
||||
RequestID uint64
|
||||
IPPrefix netip.Prefix
|
||||
}
|
||||
|
||||
func (a AssignedAddress) len() int {
|
||||
return quicvarint.Len(a.RequestID) + 1 + a.IPPrefix.Addr().BitLen()/8 + 1
|
||||
}
|
||||
|
||||
type addressRequestCapsule struct {
|
||||
RequestedAddresses []RequestedAddress
|
||||
}
|
||||
|
||||
// RequestedAddress represents a Requested Address within an ADDRESS_REQUEST capsule.
|
||||
type RequestedAddress struct {
|
||||
RequestID uint64
|
||||
IPPrefix netip.Prefix
|
||||
}
|
||||
|
||||
func (r RequestedAddress) len() int {
|
||||
return quicvarint.Len(r.RequestID) + 1 + r.IPPrefix.Addr().BitLen()/8 + 1
|
||||
}
|
||||
|
||||
func parseAddressAssignCapsule(r io.Reader) (*addressAssignCapsule, error) {
|
||||
var assignedAddresses []AssignedAddress
|
||||
for {
|
||||
requestID, prefix, err := parseAddress(r)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
assignedAddresses = append(assignedAddresses, AssignedAddress{RequestID: requestID, IPPrefix: prefix})
|
||||
}
|
||||
return &addressAssignCapsule{AssignedAddresses: assignedAddresses}, nil
|
||||
}
|
||||
|
||||
func (c *addressAssignCapsule) append(b []byte) []byte {
|
||||
totalLen := 0
|
||||
for _, addr := range c.AssignedAddresses {
|
||||
totalLen += addr.len()
|
||||
}
|
||||
|
||||
b = quicvarint.Append(b, uint64(capsuleTypeAddressAssign))
|
||||
b = quicvarint.Append(b, uint64(totalLen))
|
||||
|
||||
for _, addr := range c.AssignedAddresses {
|
||||
b = quicvarint.Append(b, addr.RequestID)
|
||||
if addr.IPPrefix.Addr().Is4() {
|
||||
b = append(b, 4)
|
||||
} else {
|
||||
b = append(b, 6)
|
||||
}
|
||||
b = append(b, addr.IPPrefix.Addr().AsSlice()...)
|
||||
b = append(b, byte(addr.IPPrefix.Bits()))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func parseAddressRequestCapsule(r io.Reader) (*addressRequestCapsule, error) {
|
||||
var requestedAddresses []RequestedAddress
|
||||
for {
|
||||
requestID, prefix, err := parseAddress(r)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
requestedAddresses = append(requestedAddresses, RequestedAddress{RequestID: requestID, IPPrefix: prefix})
|
||||
}
|
||||
return &addressRequestCapsule{RequestedAddresses: requestedAddresses}, nil
|
||||
}
|
||||
|
||||
func (c *addressRequestCapsule) append(b []byte) []byte {
|
||||
var totalLen int
|
||||
for _, addr := range c.RequestedAddresses {
|
||||
totalLen += addr.len()
|
||||
}
|
||||
|
||||
b = quicvarint.Append(b, uint64(capsuleTypeAddressRequest))
|
||||
b = quicvarint.Append(b, uint64(totalLen))
|
||||
|
||||
for _, addr := range c.RequestedAddresses {
|
||||
b = quicvarint.Append(b, addr.RequestID)
|
||||
if addr.IPPrefix.Addr().Is4() {
|
||||
b = append(b, 4)
|
||||
} else {
|
||||
b = append(b, 6)
|
||||
}
|
||||
b = append(b, addr.IPPrefix.Addr().AsSlice()...)
|
||||
b = append(b, byte(addr.IPPrefix.Bits()))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func parseAddress(r io.Reader) (requestID uint64, prefix netip.Prefix, _ error) {
|
||||
vr := quicvarint.NewReader(r)
|
||||
requestID, err := quicvarint.Read(vr)
|
||||
if err != nil {
|
||||
return 0, netip.Prefix{}, err
|
||||
}
|
||||
ipVer, err := vr.ReadByte()
|
||||
if err != nil {
|
||||
return 0, netip.Prefix{}, err
|
||||
}
|
||||
var ip netip.Addr
|
||||
switch ipVer {
|
||||
case 4:
|
||||
var v4 [4]byte
|
||||
if _, err := io.ReadFull(r, v4[:]); err != nil {
|
||||
return 0, netip.Prefix{}, err
|
||||
}
|
||||
ip = netip.AddrFrom4(v4)
|
||||
case 6:
|
||||
var v6 [16]byte
|
||||
if _, err := io.ReadFull(r, v6[:]); err != nil {
|
||||
return 0, netip.Prefix{}, err
|
||||
}
|
||||
ip = netip.AddrFrom16(v6)
|
||||
default:
|
||||
return 0, netip.Prefix{}, fmt.Errorf("invalid IP version: %d", ipVer)
|
||||
}
|
||||
prefixLen, err := vr.ReadByte()
|
||||
if err != nil {
|
||||
return 0, netip.Prefix{}, err
|
||||
}
|
||||
if int(prefixLen) > ip.BitLen() {
|
||||
return 0, netip.Prefix{}, fmt.Errorf("prefix length %d exceeds IP address length (%d)", prefixLen, ip.BitLen())
|
||||
}
|
||||
prefix = netip.PrefixFrom(ip, int(prefixLen))
|
||||
if prefix != prefix.Masked() {
|
||||
return 0, netip.Prefix{}, errors.New("lower bits not covered by prefix length are not all zero")
|
||||
}
|
||||
return requestID, prefix, nil
|
||||
}
|
||||
|
||||
type routeAdvertisementCapsule struct {
|
||||
IPAddressRanges []IPRoute
|
||||
}
|
||||
|
||||
// IPRoute represents an IP Address Range advertised in a ROUTE_ADVERTISEMENT capsule.
|
||||
type IPRoute struct {
|
||||
StartIP netip.Addr
|
||||
EndIP netip.Addr
|
||||
// IPProtocol is the Internet Protocol Number for traffic that can be sent to
|
||||
// this range. If 0, all protocols are allowed.
|
||||
IPProtocol uint8
|
||||
}
|
||||
|
||||
func (r IPRoute) len() int { return 1 + r.StartIP.BitLen()/8 + r.EndIP.BitLen()/8 + 1 }
|
||||
|
||||
// Prefixes returns the prefixes that this IP address range covers.
|
||||
func (r IPRoute) Prefixes() []netip.Prefix { return rangeToPrefixes(r.StartIP, r.EndIP) }
|
||||
|
||||
func parseRouteAdvertisementCapsule(r io.Reader) (*routeAdvertisementCapsule, error) {
|
||||
var ranges []IPRoute
|
||||
for {
|
||||
ipRange, err := parseIPAddressRange(r)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
ranges = append(ranges, ipRange)
|
||||
}
|
||||
return &routeAdvertisementCapsule{IPAddressRanges: ranges}, nil
|
||||
}
|
||||
|
||||
func (c *routeAdvertisementCapsule) append(b []byte) []byte {
|
||||
var totalLen int
|
||||
for _, ipRange := range c.IPAddressRanges {
|
||||
totalLen += ipRange.len()
|
||||
}
|
||||
|
||||
b = quicvarint.Append(b, uint64(capsuleTypeRouteAdvertisement))
|
||||
b = quicvarint.Append(b, uint64(totalLen))
|
||||
|
||||
for _, ipRange := range c.IPAddressRanges {
|
||||
if ipRange.StartIP.Is4() {
|
||||
b = append(b, 4)
|
||||
} else {
|
||||
b = append(b, 6)
|
||||
}
|
||||
b = append(b, ipRange.StartIP.AsSlice()...)
|
||||
b = append(b, ipRange.EndIP.AsSlice()...)
|
||||
b = append(b, ipRange.IPProtocol)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func parseIPAddressRange(r io.Reader) (IPRoute, error) {
|
||||
var ipVer uint8
|
||||
if err := binary.Read(r, binary.LittleEndian, &ipVer); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
|
||||
var startIP, endIP netip.Addr
|
||||
switch ipVer {
|
||||
case 4:
|
||||
var start, end [4]byte
|
||||
if _, err := io.ReadFull(r, start[:]); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, end[:]); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
startIP = netip.AddrFrom4(start)
|
||||
endIP = netip.AddrFrom4(end)
|
||||
case 6:
|
||||
var start, end [16]byte
|
||||
if _, err := io.ReadFull(r, start[:]); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, end[:]); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
startIP = netip.AddrFrom16(start)
|
||||
endIP = netip.AddrFrom16(end)
|
||||
default:
|
||||
return IPRoute{}, fmt.Errorf("invalid IP version: %d", ipVer)
|
||||
}
|
||||
|
||||
if startIP.Compare(endIP) > 0 {
|
||||
return IPRoute{}, errors.New("start IP is greater than end IP")
|
||||
}
|
||||
|
||||
var ipProtocol uint8
|
||||
if err := binary.Read(r, binary.LittleEndian, &ipProtocol); err != nil {
|
||||
return IPRoute{}, err
|
||||
}
|
||||
return IPRoute{StartIP: startIP, EndIP: endIP, IPProtocol: ipProtocol}, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package connectip
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
"github.com/sagernet/quic-go/quicvarint"
|
||||
)
|
||||
|
||||
func TestRouteAdvertisementRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
orig := &routeAdvertisementCapsule{IPAddressRanges: []IPRoute{
|
||||
{
|
||||
StartIP: netip.AddrFrom4([4]byte{}),
|
||||
EndIP: netip.AddrFrom4([4]byte{255, 255, 255, 255}),
|
||||
IPProtocol: 0,
|
||||
},
|
||||
}}
|
||||
|
||||
encoded := orig.append(nil)
|
||||
|
||||
r := quicvarint.NewReader(bytes.NewReader(encoded))
|
||||
typ, body, err := http3.ParseCapsule(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if typ != capsuleTypeRouteAdvertisement {
|
||||
t.Fatalf("wrong capsule type: %d", typ)
|
||||
}
|
||||
parsed, err := parseRouteAdvertisementCapsule(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(parsed.IPAddressRanges) != 1 {
|
||||
t.Fatalf("expected 1 range, got %d", len(parsed.IPAddressRanges))
|
||||
}
|
||||
got := parsed.IPAddressRanges[0]
|
||||
if got.StartIP != orig.IPAddressRanges[0].StartIP || got.EndIP != orig.IPAddressRanges[0].EndIP {
|
||||
t.Fatalf("range mismatch: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressAssignRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
orig := &addressAssignCapsule{AssignedAddresses: []AssignedAddress{
|
||||
{RequestID: 0, IPPrefix: netip.MustParsePrefix("172.16.0.2/32")},
|
||||
{RequestID: 1, IPPrefix: netip.MustParsePrefix("2606:4700::/128")},
|
||||
}}
|
||||
encoded := orig.append(nil)
|
||||
|
||||
r := quicvarint.NewReader(bytes.NewReader(encoded))
|
||||
typ, body, err := http3.ParseCapsule(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if typ != capsuleTypeAddressAssign {
|
||||
t.Fatalf("wrong capsule type: %d", typ)
|
||||
}
|
||||
parsed, err := parseAddressAssignCapsule(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(parsed.AssignedAddresses) != 2 {
|
||||
t.Fatalf("expected 2 addresses, got %d", len(parsed.AssignedAddresses))
|
||||
}
|
||||
if parsed.AssignedAddresses[0].IPPrefix != orig.AssignedAddresses[0].IPPrefix {
|
||||
t.Fatalf("v4 prefix mismatch: %v", parsed.AssignedAddresses[0].IPPrefix)
|
||||
}
|
||||
if parsed.AssignedAddresses[1].IPPrefix != orig.AssignedAddresses[1].IPPrefix {
|
||||
t.Fatalf("v6 prefix mismatch: %v", parsed.AssignedAddresses[1].IPPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPv4Checksum(t *testing.T) {
|
||||
t.Parallel()
|
||||
// A well-formed IPv4 header (from RFC examples): checksum field zeroed.
|
||||
header := [20]byte{
|
||||
0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00,
|
||||
0x40, 0x11, 0x00, 0x00, 0xc0, 0xa8, 0x00, 0x01,
|
||||
0xc0, 0xa8, 0x00, 0xc7,
|
||||
}
|
||||
got := calculateIPv4Checksum(header)
|
||||
if got != 0xb861 {
|
||||
t.Fatalf("checksum = %#x, want 0xb861", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package connectip
|
||||
|
||||
// Vendored from connect-ip-go (MIT). IPv4 header checksum recomputation used
|
||||
// after TTL decrement.
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
|
||||
"golang.org/x/net/ipv4"
|
||||
)
|
||||
|
||||
func calculateIPv4Checksum(header [ipv4.HeaderLen]byte) uint16 {
|
||||
var sum uint32
|
||||
for i := 0; i < len(header); i += 2 {
|
||||
if i == 10 {
|
||||
continue // skip checksum field
|
||||
}
|
||||
sum += uint32(binary.BigEndian.Uint16(header[i : i+2]))
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
// Package connectip is a vendored, lx-adapted subset of connect-ip-go
|
||||
// (CONNECT-IP / RFC 9484 client side), ported onto the sagernet/quic-go fork.
|
||||
//
|
||||
// Upstream: https://github.com/metacubex/connect-ip-go (which in turn forked
|
||||
// github.com/quic-go/connect-ip-go). We vendor it here (SPEC 021) instead of
|
||||
// adding an external dependency, because the upstream fork is pinned to
|
||||
// github.com/metacubex/quic-go and would pull a second, incompatible quic-go
|
||||
// into the build (sing-box uses github.com/sagernet/quic-go).
|
||||
//
|
||||
// Only the client-facing pieces are kept: the proxied Conn (IP packets over
|
||||
// HTTP Datagrams + Capsule Protocol), route/address capsules, IPv4 checksum
|
||||
// recomputation and the ICMP "packet too big" helper. The server/proxy side
|
||||
// (proxy.go, request.go) and the RFC-strict Dial (client.go) are intentionally
|
||||
// dropped — the dialing (with Cloudflare quirks) lives in transport/masque.
|
||||
//
|
||||
// License: MIT (connect-ip-go). See SPEC 021 for the porting notes.
|
||||
package connectip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/quic-go"
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
"github.com/sagernet/quic-go/quicvarint"
|
||||
|
||||
"golang.org/x/exp/slices"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
// contextIDZero is the QUIC varint encoding of context ID 0, which prefixes
|
||||
// every proxied IP datagram (RFC 9484 §6).
|
||||
var contextIDZero = quicvarint.Append(nil, 0)
|
||||
|
||||
type CloseError struct {
|
||||
Remote bool
|
||||
}
|
||||
|
||||
func (e *CloseError) Error() string { return net.ErrClosed.Error() }
|
||||
func (e *CloseError) Is(target error) bool { return target == net.ErrClosed }
|
||||
|
||||
type appendable interface{ append([]byte) []byte }
|
||||
|
||||
type writeCapsule struct {
|
||||
capsule appendable
|
||||
result chan error
|
||||
}
|
||||
|
||||
const (
|
||||
ipProtoICMP = 1
|
||||
ipProtoICMPv6 = 58
|
||||
)
|
||||
|
||||
// Http3Stream is the minimal stream surface the proxied Conn needs. Both
|
||||
// *http3.Stream and *http3.RequestStream satisfy it.
|
||||
type Http3Stream interface {
|
||||
io.ReadWriteCloser
|
||||
ReceiveDatagram(context.Context) ([]byte, error)
|
||||
SendDatagram([]byte) error
|
||||
CancelRead(quic.StreamErrorCode)
|
||||
}
|
||||
|
||||
var (
|
||||
_ Http3Stream = &http3.Stream{}
|
||||
_ Http3Stream = &http3.RequestStream{}
|
||||
)
|
||||
|
||||
// If a packet is too large to fit into a QUIC datagram, we send an ICMP Packet
|
||||
// Too Big packet. On IPv6, the minimum MTU of a link is 1280 bytes.
|
||||
const minMTU = 1280
|
||||
|
||||
// Conn is a connection that proxies IP packets over HTTP/3.
|
||||
type Conn struct {
|
||||
str Http3Stream
|
||||
writes chan writeCapsule
|
||||
|
||||
assignedAddressNotify chan struct{}
|
||||
availableRoutesNotify chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
peerAddresses []netip.Prefix
|
||||
localRoutes []IPRoute
|
||||
assignedAddresses []netip.Prefix
|
||||
availableRoutes []IPRoute
|
||||
|
||||
closeChan chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// NewProxiedConn wraps an already-established CONNECT-IP request stream.
|
||||
func NewProxiedConn(str Http3Stream) *Conn {
|
||||
c := &Conn{
|
||||
str: str,
|
||||
writes: make(chan writeCapsule),
|
||||
assignedAddressNotify: make(chan struct{}, 1),
|
||||
availableRoutesNotify: make(chan struct{}, 1),
|
||||
closeChan: make(chan struct{}),
|
||||
}
|
||||
go func() {
|
||||
if err := c.readFromStream(); err != nil {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = &CloseError{Remote: true}
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
if err := c.writeToStream(); err != nil {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = &CloseError{Remote: true}
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
return c
|
||||
}
|
||||
|
||||
// AdvertiseRoute informs the peer about available routes. Only the routes from
|
||||
// the most recent call are active.
|
||||
func (c *Conn) AdvertiseRoute(ctx context.Context, routes []IPRoute) error {
|
||||
for _, route := range routes {
|
||||
if route.StartIP.Compare(route.EndIP) == 1 {
|
||||
return fmt.Errorf("invalid route advertising start_ip: %s larger than %s", route.StartIP, route.EndIP)
|
||||
}
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.localRoutes = slices.Clone(routes)
|
||||
c.mu.Unlock()
|
||||
return c.sendCapsule(ctx, &routeAdvertisementCapsule{IPAddressRanges: routes})
|
||||
}
|
||||
|
||||
// AssignAddresses assigns address prefixes to the peer. Only the addresses from
|
||||
// the most recent call are active.
|
||||
func (c *Conn) AssignAddresses(ctx context.Context, prefixes []netip.Prefix) error {
|
||||
c.mu.Lock()
|
||||
c.peerAddresses = slices.Clone(prefixes)
|
||||
c.mu.Unlock()
|
||||
capsule := &addressAssignCapsule{AssignedAddresses: make([]AssignedAddress, 0, len(prefixes))}
|
||||
for _, p := range prefixes {
|
||||
capsule.AssignedAddresses = append(capsule.AssignedAddresses, AssignedAddress{IPPrefix: p})
|
||||
}
|
||||
return c.sendCapsule(ctx, capsule)
|
||||
}
|
||||
|
||||
func (c *Conn) sendCapsule(ctx context.Context, capsule appendable) error {
|
||||
res := make(chan error, 1)
|
||||
select {
|
||||
case c.writes <- writeCapsule{capsule: capsule, result: res}:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-res:
|
||||
return err
|
||||
}
|
||||
case <-c.closeChan:
|
||||
return c.closeErr
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// LocalPrefixes returns the prefixes the peer currently assigned. The peer can
|
||||
// change the assignment at any time, so call this in a loop if you care.
|
||||
func (c *Conn) LocalPrefixes(ctx context.Context) ([]netip.Prefix, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
case <-c.assignedAddressNotify:
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.assignedAddresses, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Routes returns the routes the peer currently advertised.
|
||||
func (c *Conn) Routes(ctx context.Context) ([]IPRoute, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
case <-c.availableRoutesNotify:
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.availableRoutes, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) readFromStream() error {
|
||||
defer c.str.Close()
|
||||
r := quicvarint.NewReader(c.str)
|
||||
for {
|
||||
t, cr, err := http3.ParseCapsule(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch t {
|
||||
case capsuleTypeAddressAssign:
|
||||
capsule, err := parseAddressAssignCapsule(cr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prefixes := make([]netip.Prefix, 0, len(capsule.AssignedAddresses))
|
||||
for _, assigned := range capsule.AssignedAddresses {
|
||||
prefixes = append(prefixes, assigned.IPPrefix)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.assignedAddresses = prefixes
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case c.assignedAddressNotify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
case capsuleTypeAddressRequest:
|
||||
if _, err := parseAddressRequestCapsule(cr); err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("connect-ip: address request not yet supported")
|
||||
case capsuleTypeRouteAdvertisement:
|
||||
capsule, err := parseRouteAdvertisementCapsule(cr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.availableRoutes = capsule.IPAddressRanges
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case c.availableRoutesNotify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown capsule type: %d", t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) writeToStream() error {
|
||||
buf := make([]byte, 0, 1024)
|
||||
for {
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return c.closeErr
|
||||
case req, ok := <-c.writes:
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
buf = req.capsule.append(buf[:0])
|
||||
_, err := c.str.Write(buf)
|
||||
req.result <- err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPacket reads a single proxied IP packet from the tunnel.
|
||||
func (c *Conn) ReadPacket() (b []byte, err error) {
|
||||
start:
|
||||
data, err := c.str.ReceiveDatagram(context.Background())
|
||||
if err != nil {
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
contextID, n, err := quicvarint.Parse(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect-ip: malformed datagram: %w", err)
|
||||
}
|
||||
if contextID != 0 {
|
||||
// We only support proxying of IP payloads (context ID 0).
|
||||
goto start
|
||||
}
|
||||
if err := c.handleIncomingProxiedPacket(data[n:]); err != nil {
|
||||
goto start
|
||||
}
|
||||
return data[n:], nil
|
||||
}
|
||||
|
||||
func (c *Conn) handleIncomingProxiedPacket(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return errors.New("connect-ip: empty packet")
|
||||
}
|
||||
var src, dst netip.Addr
|
||||
var ipProto uint8
|
||||
switch v := ipVersion(data); v {
|
||||
default:
|
||||
return fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(data) < ipv4.HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
src = netip.AddrFrom4([4]byte(data[12:16]))
|
||||
dst = netip.AddrFrom4([4]byte(data[16:20]))
|
||||
ipProto = data[9]
|
||||
case 6:
|
||||
if len(data) < ipv6.HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
src = netip.AddrFrom16([16]byte(data[8:24]))
|
||||
dst = netip.AddrFrom16([16]byte(data[24:40]))
|
||||
ipProto = data[6]
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
assignedAddresses := c.assignedAddresses
|
||||
localRoutes := c.localRoutes
|
||||
peerAddresses := c.peerAddresses
|
||||
c.mu.Unlock()
|
||||
|
||||
if peerAddresses != nil {
|
||||
if !slices.ContainsFunc(peerAddresses, func(p netip.Prefix) bool { return p.Contains(src) }) {
|
||||
return fmt.Errorf("connect-ip: datagram source address not allowed: %s", src)
|
||||
}
|
||||
}
|
||||
|
||||
var isAllowedDst bool
|
||||
if len(assignedAddresses) > 0 {
|
||||
isAllowedDst = slices.ContainsFunc(assignedAddresses, func(p netip.Prefix) bool { return p.Contains(dst) })
|
||||
}
|
||||
if !isAllowedDst {
|
||||
isAllowedDst = slices.ContainsFunc(localRoutes, func(r IPRoute) bool {
|
||||
if r.StartIP.Compare(dst) > 0 || dst.Compare(r.EndIP) > 0 {
|
||||
return false
|
||||
}
|
||||
if (ipVersion(data) == 4 && ipProto == ipProtoICMP) || (ipVersion(data) == 6 && ipProto == ipProtoICMPv6) {
|
||||
return true
|
||||
}
|
||||
return r.IPProtocol == 0 || r.IPProtocol == ipProto
|
||||
})
|
||||
}
|
||||
if !isAllowedDst {
|
||||
return fmt.Errorf("connect-ip: datagram destination address / protocol not allowed: %s (protocol: %d)", dst, ipProto)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WritePacket writes an IP packet to the stream. If the packet is too large it
|
||||
// returns an ICMP "packet too big" reply the caller should feed back locally.
|
||||
func (c *Conn) WritePacket(b []byte) (icmp []byte, err error) {
|
||||
data, err := c.composeDatagram(b)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
if data == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err := c.str.SendDatagram(data); err != nil {
|
||||
var errDTL *quic.DatagramTooLargeError
|
||||
if errors.As(err, &errDTL) {
|
||||
icmpPacket, cerr := composeICMPTooLargePacket(b, minMTU)
|
||||
if cerr != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return icmpPacket, nil
|
||||
}
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *Conn) composeDatagram(b []byte) ([]byte, error) {
|
||||
if len(b) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
switch v := ipVersion(b); v {
|
||||
default:
|
||||
return nil, fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(b) < ipv4.HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv4 packet too short")
|
||||
}
|
||||
ttl := b[8]
|
||||
if ttl <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram TTL too small: %d", ttl)
|
||||
}
|
||||
b[8]-- // decrement TTL
|
||||
binary.BigEndian.PutUint16(b[10:12], calculateIPv4Checksum(([ipv4.HeaderLen]byte)(b[:ipv4.HeaderLen])))
|
||||
case 6:
|
||||
if len(b) < ipv6.HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv6 packet too short")
|
||||
}
|
||||
hopLimit := b[7]
|
||||
if hopLimit <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram Hop Limit too small: %d", hopLimit)
|
||||
}
|
||||
b[7]-- // decrement Hop Limit
|
||||
}
|
||||
data := make([]byte, 0, len(contextIDZero)+len(b))
|
||||
data = append(data, contextIDZero...)
|
||||
data = append(data, b...)
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Close tears down the tunnel.
|
||||
func (c *Conn) Close() error {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = &CloseError{Remote: false}
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
c.str.CancelRead(quic.StreamErrorCode(http3.ErrCodeNoError))
|
||||
return c.str.Close()
|
||||
}
|
||||
|
||||
func ipVersion(b []byte) uint8 { return b[0] >> 4 }
|
||||
@@ -0,0 +1,78 @@
|
||||
package connectip
|
||||
|
||||
// Vendored from connect-ip-go (MIT). Builds an ICMP "packet too big" reply when
|
||||
// an outgoing IP packet exceeds the tunnel's datagram size.
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
func composeICMPTooLargePacket(b []byte, mtu int) ([]byte, error) {
|
||||
if len(b) == 0 {
|
||||
return nil, errors.New("connect-ip: empty packet")
|
||||
}
|
||||
|
||||
var icmpMessage *icmp.Message
|
||||
var psh []byte
|
||||
switch v := ipVersion(b); v {
|
||||
case 4:
|
||||
if len(b) < ipv4.HeaderLen {
|
||||
return nil, errors.New("connect-ip: IPv4 packet too short")
|
||||
}
|
||||
icmpMessage = &icmp.Message{
|
||||
Type: ipv4.ICMPTypeDestinationUnreachable,
|
||||
Code: 4, // Fragmentation Needed and Don't Fragment was Set
|
||||
Body: &icmp.PacketTooBig{
|
||||
MTU: mtu,
|
||||
Data: b[:min(len(b), ipv4.HeaderLen+8)],
|
||||
},
|
||||
}
|
||||
case 6:
|
||||
if len(b) < ipv6.HeaderLen {
|
||||
return nil, errors.New("connect-ip: IPv6 packet too short")
|
||||
}
|
||||
icmpMessage = &icmp.Message{
|
||||
Type: ipv6.ICMPTypePacketTooBig,
|
||||
Body: &icmp.PacketTooBig{
|
||||
MTU: mtu,
|
||||
Data: b[:min(len(b), 1232)],
|
||||
},
|
||||
}
|
||||
psh = icmp.IPv6PseudoHeader(b[24:40], b[8:24])
|
||||
default:
|
||||
return nil, fmt.Errorf("connect-ip: unknown IP version: %d", v)
|
||||
}
|
||||
|
||||
icmpBytes, err := icmpMessage.Marshal(psh)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect-ip: failed to marshal ICMP message: %w", err)
|
||||
}
|
||||
|
||||
if ipVersion(b) == 4 {
|
||||
var header [ipv4.HeaderLen]byte
|
||||
header[0] = 4<<4 | ipv4.HeaderLen>>2 // Version and IHL
|
||||
ipLen := ipv4.HeaderLen + len(icmpBytes)
|
||||
binary.BigEndian.PutUint16(header[2:4], uint16(ipLen)) // Total Length
|
||||
header[8] = 64 // TTL
|
||||
header[9] = 1 // Protocol (ICMP)
|
||||
copy(header[12:16], b[16:20]) // Source IP (swapped)
|
||||
copy(header[16:20], b[12:16]) // Dest IP (swapped)
|
||||
binary.BigEndian.PutUint16(header[10:12], calculateIPv4Checksum(header))
|
||||
return append(header[:], icmpBytes...), nil
|
||||
}
|
||||
|
||||
var header [ipv6.HeaderLen]byte
|
||||
header[0] = 6 << 4 // Version 6
|
||||
binary.BigEndian.PutUint16(header[4:6], uint16(len(icmpBytes))) // Payload Length
|
||||
header[6] = 58 // Next Header (ICMPv6)
|
||||
header[7] = 64 // Hop Limit
|
||||
copy(header[8:24], b[24:40]) // Source IP (swapped)
|
||||
copy(header[24:40], b[8:24]) // Dest IP (swapped)
|
||||
return append(header[:], icmpBytes...), nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package connectip
|
||||
|
||||
// Vendored from connect-ip-go (MIT). IP range → CIDR prefix expansion.
|
||||
|
||||
import "net/netip"
|
||||
|
||||
// rangeToPrefixes converts an IP range defined by start and end addresses into a
|
||||
// slice of CIDR prefixes that exactly cover the range. It assumes start and end
|
||||
// are the same IP version and start <= end.
|
||||
func rangeToPrefixes(start, end netip.Addr) []netip.Prefix {
|
||||
var prefixes []netip.Prefix
|
||||
for current := start; current.Compare(end) <= 0; {
|
||||
prefix := findLargestPrefix(current, end)
|
||||
prefixes = append(prefixes, prefix)
|
||||
|
||||
lastIP := lastIPInPrefix(prefix)
|
||||
if lastIP.Compare(end) >= 0 {
|
||||
break
|
||||
}
|
||||
current = lastIP.Next()
|
||||
}
|
||||
return prefixes
|
||||
}
|
||||
|
||||
func findLargestPrefix(start, end netip.Addr) netip.Prefix {
|
||||
if start == end {
|
||||
return netip.PrefixFrom(start, start.BitLen())
|
||||
}
|
||||
|
||||
var prefixLen int
|
||||
for prefixLen = start.BitLen(); prefixLen > 0; prefixLen-- {
|
||||
prefix := netip.PrefixFrom(start, prefixLen-1)
|
||||
if lastIPInPrefix(prefix).Compare(end) > 0 || !isAligned(start, prefixLen-1) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return netip.PrefixFrom(start, prefixLen)
|
||||
}
|
||||
|
||||
func lastIPInPrefix(prefix netip.Prefix) netip.Addr {
|
||||
addr := prefix.Addr()
|
||||
bits := addr.As16()
|
||||
|
||||
hostBits := addr.BitLen() - prefix.Bits()
|
||||
|
||||
for i := len(bits) - 1; i >= 0 && hostBits > 0; i-- {
|
||||
bitsInThisByte := min(8, hostBits)
|
||||
mask := byte((1 << bitsInThisByte) - 1)
|
||||
bits[i] |= mask
|
||||
hostBits -= bitsInThisByte
|
||||
}
|
||||
|
||||
if addr.Is4() {
|
||||
return netip.AddrFrom4([4]byte(bits[12:16]))
|
||||
}
|
||||
return netip.AddrFrom16(bits)
|
||||
}
|
||||
|
||||
func isAligned(addr netip.Addr, prefixLen int) bool {
|
||||
bits := addr.As16()
|
||||
|
||||
hostBits := addr.BitLen() - prefixLen
|
||||
for i := len(bits) - 1; i >= 0 && hostBits > 0; i-- {
|
||||
bitsInThisByte := min(8, hostBits)
|
||||
mask := byte((1 << bitsInThisByte) - 1)
|
||||
if bits[i]&mask != 0 {
|
||||
return false
|
||||
}
|
||||
hostBits -= bitsInThisByte
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Package masque implements a CONNECT-IP (RFC 9484) client for MASQUE
|
||||
// outbounds, primarily targeting Cloudflare WARP. It carries whole IP packets
|
||||
// over an HTTP/3 (or HTTP/2) tunnel using HTTP Datagrams and the Capsule
|
||||
// Protocol.
|
||||
//
|
||||
// This is NOT CONNECT-UDP (RFC 9298). See SPEC 021.
|
||||
//
|
||||
// The CONNECT-IP wire logic is vendored under ./connectip (ported from
|
||||
// connect-ip-go). This file holds the dialing that layers the profile quirks
|
||||
// (Cloudflare vs standard) on top.
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
|
||||
"github.com/sagernet/quic-go"
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
"github.com/sagernet/sing-box/transport/masque/connectip"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
// IpConn is the transport-agnostic surface the outbound pumps IP packets
|
||||
// through. Both the HTTP/3 connectip.Conn and the HTTP/2 shim satisfy it.
|
||||
type IpConn interface {
|
||||
ReadPacket() (b []byte, err error)
|
||||
WritePacket(b []byte) (icmp []byte, err error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// ConnectTunnelH3 establishes a CONNECT-IP tunnel over an existing HTTP/3
|
||||
// (QUIC) connection and advertises a default route so all traffic is tunnelled.
|
||||
// It returns the http3 transport (for lifetime management) and the IP conn.
|
||||
func ConnectTunnelH3(ctx context.Context, profile Profile, quicConn *quic.Conn, connectURI string) (*http3.Transport, IpConn, error) {
|
||||
tr := &http3.Transport{
|
||||
EnableDatagrams: true,
|
||||
AdditionalSettings: map[uint64]uint64{
|
||||
// The official client still advertises the deprecated
|
||||
// SETTINGS_H3_DATAGRAM_00 (0x276); WARP expects it.
|
||||
0x276: 1,
|
||||
},
|
||||
DisableCompression: true,
|
||||
}
|
||||
|
||||
hconn := tr.NewClientConn(quicConn)
|
||||
|
||||
ipConn, rsp, err := dialCONNECTIP(ctx, profile, hconn, connectURI)
|
||||
if err != nil {
|
||||
_ = tr.Close()
|
||||
if err.Error() == "CRYPTO_ERROR 0x131 (remote): tls: access denied" {
|
||||
return nil, nil, E.New("masque: login failed — verify the TLS key/cert is enrolled with Cloudflare Access")
|
||||
}
|
||||
return nil, nil, E.Cause(err, "masque: dial connect-ip")
|
||||
}
|
||||
|
||||
if err = advertiseDefaultRoute(ctx, ipConn); err != nil {
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if rsp.StatusCode != 200 {
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
return nil, nil, E.New("masque: connect-ip rejected: ", rsp.Status)
|
||||
}
|
||||
|
||||
return tr, ipConn, nil
|
||||
}
|
||||
|
||||
// dialCONNECTIP sends the Extended CONNECT request and wraps the request stream
|
||||
// into a proxied IP connection.
|
||||
func dialCONNECTIP(ctx context.Context, profile Profile, conn *http3.ClientConn, connectURI string) (*connectip.Conn, *responseInfo, error) {
|
||||
u, err := url.Parse(connectURI)
|
||||
if err != nil {
|
||||
return nil, nil, E.Cause(err, "parse connect uri")
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, context.Cause(ctx)
|
||||
case <-conn.Context().Done():
|
||||
return nil, nil, context.Cause(conn.Context())
|
||||
case <-conn.ReceivedSettings():
|
||||
}
|
||||
settings := conn.Settings()
|
||||
if !profile.IgnoreExtendedConnect && !settings.EnableExtendedConnect {
|
||||
return nil, nil, E.New("connect-ip: server didn't enable Extended CONNECT")
|
||||
}
|
||||
if !settings.EnableDatagrams {
|
||||
return nil, nil, E.New("connect-ip: server didn't enable datagrams")
|
||||
}
|
||||
|
||||
rstr, err := conn.OpenRequestStream(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, E.Cause(err, "open request stream")
|
||||
}
|
||||
|
||||
req := buildConnectIPRequest(profile, u)
|
||||
if err = rstr.SendRequestHeader(req); err != nil {
|
||||
return nil, nil, E.Cause(err, "send request header")
|
||||
}
|
||||
rsp, err := rstr.ReadResponse()
|
||||
if err != nil {
|
||||
return nil, nil, E.Cause(err, "read response")
|
||||
}
|
||||
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
|
||||
return nil, &responseInfo{StatusCode: rsp.StatusCode, Status: rsp.Status}, E.New("connect-ip: server responded with ", rsp.StatusCode)
|
||||
}
|
||||
return connectip.NewProxiedConn(rstr), &responseInfo{StatusCode: rsp.StatusCode, Status: rsp.Status}, nil
|
||||
}
|
||||
|
||||
type responseInfo struct {
|
||||
StatusCode int
|
||||
Status string
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"math/big"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
// Cloudflare WARP MASQUE defaults.
|
||||
const (
|
||||
// CloudflareConnectSNI is the SNI Cloudflare's consumer MASQUE endpoint
|
||||
// expects. It intentionally does not match the endpoint IP/host — the
|
||||
// endpoint is authenticated by pinning its public key instead.
|
||||
CloudflareConnectSNI = "consumer-masque.cloudflareclient.com"
|
||||
// CloudflareConnectURI is the default CONNECT-IP request URI for WARP.
|
||||
CloudflareConnectURI = "https://cloudflareaccess.com"
|
||||
)
|
||||
|
||||
// Profile selects the behavioural quirks of the CONNECT-IP dial. It varies four
|
||||
// things; everything else (QUIC, http3, capsule/datagram, the userspace stack)
|
||||
// is profile-independent. See SPEC 021.
|
||||
type Profile struct {
|
||||
// RequestProtocol is the :protocol value of the Extended CONNECT request.
|
||||
// Cloudflare uses "cf-connect-ip"; RFC 9484 uses "connect-ip".
|
||||
RequestProtocol string
|
||||
// IgnoreExtendedConnect skips the "server enabled Extended CONNECT" check.
|
||||
// Cloudflare WARP does not send the setting, violating the RFC, so a strict
|
||||
// client would refuse; we tolerate it for the cloudflare profile.
|
||||
IgnoreExtendedConnect bool
|
||||
// H3ConnectProto, when non-empty, is sent as the HTTP/2 "cf-connect-proto"
|
||||
// header on the h2 path (Cloudflare-specific).
|
||||
H2ConnectProto string
|
||||
// DefaultSNI / DefaultURI are used when the config leaves sni/uri empty.
|
||||
DefaultSNI string
|
||||
DefaultURI string
|
||||
// PinPublicKey enables ECDSA public-key pinning against the endpoint's
|
||||
// certificate (Cloudflare Access model) instead of normal chain validation.
|
||||
PinPublicKey bool
|
||||
}
|
||||
|
||||
// ProfileCloudflare matches Cloudflare WARP's non-RFC-compliant CONNECT-IP.
|
||||
func ProfileCloudflare() Profile {
|
||||
return Profile{
|
||||
RequestProtocol: "cf-connect-ip",
|
||||
IgnoreExtendedConnect: true,
|
||||
H2ConnectProto: "cf-connect-ip",
|
||||
DefaultSNI: CloudflareConnectSNI,
|
||||
DefaultURI: CloudflareConnectURI,
|
||||
PinPublicKey: true,
|
||||
}
|
||||
}
|
||||
|
||||
// ProfileStandard is the strict RFC 9484 profile (for a self-hosted CONNECT-IP
|
||||
// server). Kept minimal in v1 — see SPEC 021 phase 3.
|
||||
func ProfileStandard() Profile {
|
||||
return Profile{
|
||||
RequestProtocol: "connect-ip",
|
||||
IgnoreExtendedConnect: false,
|
||||
DefaultSNI: "",
|
||||
DefaultURI: "",
|
||||
PinPublicKey: false,
|
||||
}
|
||||
}
|
||||
|
||||
// ParseProfile resolves a profile name. Empty defaults to cloudflare.
|
||||
func ParseProfile(name string) (Profile, error) {
|
||||
switch name {
|
||||
case "", "cloudflare":
|
||||
return ProfileCloudflare(), nil
|
||||
case "standard":
|
||||
return ProfileStandard(), nil
|
||||
default:
|
||||
return Profile{}, E.New("masque: unknown profile: ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareTLSConfig builds the client TLS config for a given profile.
|
||||
//
|
||||
// For the cloudflare profile it pins the endpoint's ECDSA public key: SNI does
|
||||
// not match the endpoint, so normal verification is skipped (InsecureSkipVerify)
|
||||
// and VerifyConnection asserts that a presented certificate carries exactly the
|
||||
// expected public key. When insecure is true, pinning is disabled entirely.
|
||||
func PrepareTLSConfig(profile Profile, privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string, insecure bool) (*tls.Config, error) {
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: sni,
|
||||
NextProtos: []string{http3.NextProtoH3},
|
||||
}
|
||||
|
||||
if privKey != nil {
|
||||
cert, err := generateClientCert(privKey)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "generate client cert")
|
||||
}
|
||||
tlsConfig.Certificates = []tls.Certificate{{
|
||||
Certificate: cert,
|
||||
PrivateKey: privKey,
|
||||
}}
|
||||
}
|
||||
|
||||
if profile.PinPublicKey && !insecure {
|
||||
if peerPubKey == nil {
|
||||
return nil, errors.New("masque: public key required for pinning")
|
||||
}
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
tlsConfig.VerifyConnection = func(cs tls.ConnectionState) error {
|
||||
var joined error
|
||||
for _, cert := range cs.PeerCertificates {
|
||||
if err := verifyPinnedCert(cert, peerPubKey); err != nil {
|
||||
joined = errors.Join(joined, err)
|
||||
continue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if joined == nil {
|
||||
joined = errors.New("masque: no peer certificate to pin")
|
||||
}
|
||||
return joined
|
||||
}
|
||||
} else if insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
func verifyPinnedCert(cert *x509.Certificate, peerPubKey *ecdsa.PublicKey) error {
|
||||
pub, ok := cert.PublicKey.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
// We only support ECDSA endpoint keys (Cloudflare's cert type).
|
||||
return x509.ErrUnsupportedAlgorithm
|
||||
}
|
||||
if !pub.Equal(peerPubKey) {
|
||||
return errors.New("masque: remote endpoint has a different public key than pinned")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateClientCert creates a short-lived self-signed certificate wrapping the
|
||||
// client's ECDSA key, presented to the endpoint (Cloudflare Access mTLS).
|
||||
func generateClientCert(privKey *ecdsa.PrivateKey) ([][]byte, error) {
|
||||
now := time.Now()
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
NotBefore: now,
|
||||
NotAfter: now.Add(24 * time.Hour),
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &privKey.PublicKey, privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return [][]byte{der}, nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
)
|
||||
|
||||
func TestParseProfile(t *testing.T) {
|
||||
t.Parallel()
|
||||
cf, err := ParseProfile("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cf.RequestProtocol != "cf-connect-ip" || !cf.IgnoreExtendedConnect || !cf.PinPublicKey {
|
||||
t.Fatalf("empty should default to cloudflare, got %+v", cf)
|
||||
}
|
||||
if cf.DefaultSNI != CloudflareConnectSNI || cf.DefaultURI != CloudflareConnectURI {
|
||||
t.Fatalf("cloudflare defaults wrong: %+v", cf)
|
||||
}
|
||||
|
||||
std, err := ParseProfile("standard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if std.RequestProtocol != "connect-ip" || std.IgnoreExtendedConnect || std.PinPublicKey {
|
||||
t.Fatalf("standard profile wrong: %+v", std)
|
||||
}
|
||||
|
||||
if _, err = ParseProfile("bogus"); err == nil {
|
||||
t.Fatal("expected error for unknown profile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareTLSConfigPinning(t *testing.T) {
|
||||
t.Parallel()
|
||||
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := PrepareTLSConfig(ProfileCloudflare(), priv, &peer.PublicKey, "example.org", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cfg.InsecureSkipVerify {
|
||||
t.Fatal("cloudflare pinning must set InsecureSkipVerify")
|
||||
}
|
||||
if cfg.VerifyConnection == nil {
|
||||
t.Fatal("cloudflare pinning must set VerifyConnection")
|
||||
}
|
||||
if len(cfg.Certificates) != 1 {
|
||||
t.Fatal("client cert must be generated when private key provided")
|
||||
}
|
||||
if len(cfg.NextProtos) != 1 || cfg.NextProtos[0] != http3.NextProtoH3 {
|
||||
t.Fatalf("ALPN should be h3, got %v", cfg.NextProtos)
|
||||
}
|
||||
|
||||
// Standard profile: no pinning, normal verification.
|
||||
stdCfg, err := PrepareTLSConfig(ProfileStandard(), nil, nil, "example.org", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stdCfg.InsecureSkipVerify || stdCfg.VerifyConnection != nil {
|
||||
t.Fatal("standard profile must not pin")
|
||||
}
|
||||
|
||||
// Insecure disables pinning even for cloudflare.
|
||||
insecureCfg, err := PrepareTLSConfig(ProfileCloudflare(), priv, &peer.PublicKey, "example.org", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if insecureCfg.VerifyConnection != nil {
|
||||
t.Fatal("insecure must disable VerifyConnection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPinnedCert(t *testing.T) {
|
||||
t.Parallel()
|
||||
priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
other, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
|
||||
cert := &x509.Certificate{PublicKey: &priv.PublicKey}
|
||||
if err := verifyPinnedCert(cert, &priv.PublicKey); err != nil {
|
||||
t.Fatalf("matching key should verify: %v", err)
|
||||
}
|
||||
if err := verifyPinnedCert(cert, &other.PublicKey); err == nil {
|
||||
t.Fatal("mismatched key must fail")
|
||||
}
|
||||
|
||||
rsaLike := &x509.Certificate{PublicKey: "not-a-key"}
|
||||
if err := verifyPinnedCert(rsaLike, &priv.PublicKey); err == nil {
|
||||
t.Fatal("non-ECDSA key must be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
"github.com/sagernet/sing-box/transport/masque/connectip"
|
||||
)
|
||||
|
||||
// capsuleProtocolHeaderValue is the structured-field boolean true ("?1") sent in
|
||||
// the Capsule-Protocol request header (RFC 9297).
|
||||
const capsuleProtocolHeaderValue = "?1"
|
||||
|
||||
// buildConnectIPRequest constructs the Extended CONNECT request for a profile.
|
||||
func buildConnectIPRequest(profile Profile, u *url.URL) *http.Request {
|
||||
header := http.Header{
|
||||
http3.CapsuleProtocolHeader: []string{capsuleProtocolHeaderValue},
|
||||
// The official WARP client sends an empty User-Agent.
|
||||
"User-Agent": []string{""},
|
||||
}
|
||||
return &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
Proto: profile.RequestProtocol,
|
||||
Host: u.Host,
|
||||
Header: header,
|
||||
URL: u,
|
||||
}
|
||||
}
|
||||
|
||||
// advertiseDefaultRoute tells the peer we accept all IPv4/IPv6 traffic, so the
|
||||
// endpoint routes everything through the tunnel.
|
||||
func advertiseDefaultRoute(ctx context.Context, ipConn IpConn) error {
|
||||
adv, ok := ipConn.(interface {
|
||||
AdvertiseRoute(context.Context, []connectip.IPRoute) error
|
||||
})
|
||||
if !ok {
|
||||
// h2 shim doesn't do capsule route advertisement.
|
||||
return nil
|
||||
}
|
||||
return adv.AdvertiseRoute(ctx, []connectip.IPRoute{
|
||||
{
|
||||
IPProtocol: 0,
|
||||
StartIP: netip.AddrFrom4([4]byte{}),
|
||||
EndIP: netip.AddrFrom4([4]byte{255, 255, 255, 255}),
|
||||
},
|
||||
{
|
||||
IPProtocol: 0,
|
||||
StartIP: netip.AddrFrom16([16]byte{}),
|
||||
EndIP: netip.AddrFrom16([16]byte{
|
||||
255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255,
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user