1
0

outbound_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package link
  2. import (
  3. "encoding/base64"
  4. "net/url"
  5. "strings"
  6. "testing"
  7. )
  8. func TestParseVmessLink(t *testing.T) {
  9. // vmess:// + base64 of:
  10. // {"v":"2","ps":"test","add":"1.2.3.4","port":443,"id":"uuid","aid":"0","net":"ws","type":"","host":"ex.com","path":"/","tls":"tls"}
  11. link := "vmess://eyJ2IjoiMiIsInBzIjoidGVzdCIsImFkZCI6IjEuMi4zLjQiLCJwb3J0Ijo0NDMsImlkIjoidXVpZCIsImFpZCI6IjAiLCJuZXQiOiJ3cyIsInR5cGUiOiIiLCJob3N0IjoiZXguY29tIiwicGF0aCI6Ii8iLCJ0bHMiOiJ0bHMifQ=="
  12. res, err := ParseLink(link)
  13. if err != nil {
  14. t.Fatalf("parse vmess: %v", err)
  15. }
  16. if res.Outbound["protocol"] != "vmess" {
  17. t.Errorf("expected vmess protocol, got %v", res.Outbound["protocol"])
  18. }
  19. if res.Outbound["tag"] != "test" {
  20. t.Errorf("expected tag 'test', got %v", res.Outbound["tag"])
  21. }
  22. }
  23. func TestParseVlessLink(t *testing.T) {
  24. link := "vless://[email protected]:443?type=ws&security=tls&path=/&host=ex.com#node1"
  25. res, err := ParseLink(link)
  26. if err != nil {
  27. t.Fatalf("parse vless: %v", err)
  28. }
  29. if res.Outbound["protocol"] != "vless" {
  30. t.Fatalf("bad protocol")
  31. }
  32. if res.Outbound["tag"] != "node1" {
  33. t.Errorf("tag mismatch: %v", res.Outbound["tag"])
  34. }
  35. }
  36. func TestParseVlessLink_FinalMaskQuicParamsSanitized(t *testing.T) {
  37. fm := url.QueryEscape(`{"mask":"dtls","quicParams":{"keepAlivePeriod":"10s","maxIdleTimeout":"30","initStreamReceiveWindow":524288,"maxIncomingStreams":true,"brutalUp":"100 mbps"}}`)
  38. res, err := ParseLink("vless://[email protected]:443?type=tcp&security=none&fm=" + fm + "#node1")
  39. if err != nil {
  40. t.Fatalf("parse vless with fm: %v", err)
  41. }
  42. stream, ok := res.Outbound["streamSettings"].(map[string]any)
  43. if !ok {
  44. t.Fatalf("missing streamSettings: %v", res.Outbound)
  45. }
  46. finalmask, ok := stream["finalmask"].(map[string]any)
  47. if !ok {
  48. t.Fatalf("missing finalmask: %v", stream)
  49. }
  50. if finalmask["mask"] != "dtls" {
  51. t.Errorf("mask changed: %v", finalmask["mask"])
  52. }
  53. qp, ok := finalmask["quicParams"].(map[string]any)
  54. if !ok {
  55. t.Fatalf("missing quicParams: %v", finalmask)
  56. }
  57. if got := qp["keepAlivePeriod"]; got != int64(10) {
  58. t.Errorf("keepAlivePeriod: expected 10, got %v (%T)", got, got)
  59. }
  60. if got := qp["maxIdleTimeout"]; got != int64(30) {
  61. t.Errorf("maxIdleTimeout: expected 30, got %v (%T)", got, got)
  62. }
  63. if got := qp["initStreamReceiveWindow"]; got != int64(524288) {
  64. t.Errorf("initStreamReceiveWindow: expected 524288, got %v (%T)", got, got)
  65. }
  66. if _, exists := qp["maxIncomingStreams"]; exists {
  67. t.Errorf("maxIncomingStreams should be dropped, got %v", qp["maxIncomingStreams"])
  68. }
  69. if got := qp["brutalUp"]; got != "100 mbps" {
  70. t.Errorf("brutalUp should stay a string, got %v (%T)", got, got)
  71. }
  72. }
  73. func TestSanitizeFinalMaskQuicParams_ClampsAndRejects(t *testing.T) {
  74. cases := []struct {
  75. name string
  76. key string
  77. in any
  78. want any
  79. }{
  80. {"infinite string dropped", "keepAlivePeriod", "inf", nil},
  81. {"nan string dropped", "keepAlivePeriod", "NaN", nil},
  82. {"negative dropped", "maxStreamReceiveWindow", float64(-5), nil},
  83. {"negative duration dropped", "keepAlivePeriod", "-10s", nil},
  84. {"absurd magnitude dropped", "initConnectionReceiveWindow", float64(1e30), nil},
  85. {"keepAlive clamped up", "keepAlivePeriod", "1s", int64(2)},
  86. {"keepAlive clamped down", "keepAlivePeriod", "90s", int64(60)},
  87. {"idle clamped up", "maxIdleTimeout", float64(1), int64(4)},
  88. {"idle clamped down", "maxIdleTimeout", "10m", int64(120)},
  89. {"streams clamped up", "maxIncomingStreams", float64(4), int64(8)},
  90. {"zero means unset and survives", "maxIdleTimeout", float64(0), int64(0)},
  91. {"window passes through", "initStreamReceiveWindow", float64(524288), int64(524288)},
  92. }
  93. for _, c := range cases {
  94. t.Run(c.name, func(t *testing.T) {
  95. parsed := map[string]any{"quicParams": map[string]any{c.key: c.in}}
  96. sanitizeFinalMaskQuicParams(parsed)
  97. qp := parsed["quicParams"].(map[string]any)
  98. got, exists := qp[c.key]
  99. if c.want == nil {
  100. if exists {
  101. t.Fatalf("%s: expected key dropped, got %v (%T)", c.key, got, got)
  102. }
  103. return
  104. }
  105. if !exists || got != c.want {
  106. t.Fatalf("%s: expected %v, got %v (%T)", c.key, c.want, got, got)
  107. }
  108. })
  109. }
  110. }
  111. func salamanderPassword(t *testing.T, res *ParseResult) (string, bool) {
  112. t.Helper()
  113. stream, ok := res.Outbound["streamSettings"].(map[string]any)
  114. if !ok {
  115. t.Fatalf("missing streamSettings: %v", res.Outbound)
  116. }
  117. finalmask, ok := stream["finalmask"].(map[string]any)
  118. if !ok {
  119. return "", false
  120. }
  121. udp, ok := finalmask["udp"].([]any)
  122. if !ok {
  123. return "", false
  124. }
  125. for _, m := range udp {
  126. mask, _ := m.(map[string]any)
  127. if mask == nil || mask["type"] != "salamander" {
  128. continue
  129. }
  130. settings, _ := mask["settings"].(map[string]any)
  131. pw, _ := settings["password"].(string)
  132. return pw, true
  133. }
  134. return "", false
  135. }
  136. func finalmaskUDP(t *testing.T, res *ParseResult) []any {
  137. t.Helper()
  138. stream, _ := res.Outbound["streamSettings"].(map[string]any)
  139. finalmask, _ := stream["finalmask"].(map[string]any)
  140. udp, _ := finalmask["udp"].([]any)
  141. return udp
  142. }
  143. func hopPorts(t *testing.T, res *ParseResult) (string, bool) {
  144. t.Helper()
  145. stream, _ := res.Outbound["streamSettings"].(map[string]any)
  146. finalmask, _ := stream["finalmask"].(map[string]any)
  147. quicParams, _ := finalmask["quicParams"].(map[string]any)
  148. udpHop, ok := quicParams["udpHop"].(map[string]any)
  149. if !ok {
  150. return "", false
  151. }
  152. ports, _ := udpHop["ports"].(string)
  153. return ports, true
  154. }
  155. func TestParseHysteria2_Obfs(t *testing.T) {
  156. cases := []struct {
  157. name string
  158. query string
  159. wantPw string
  160. wantSet bool
  161. }{
  162. {"standard", "obfs=salamander&obfs-password=s3cr3t", "s3cr3t", true},
  163. {"snake-case alias", "obfs=salamander&obfs_password=aliaspw", "aliaspw", true},
  164. {"camel-case alias", "obfs=salamander&obfsPassword=camelpw", "camelpw", true},
  165. {"case-insensitive type", "obfs=Salamander&obfs-password=mixed", "mixed", true},
  166. {"no obfs", "sni=ex.com", "", false},
  167. {"obfs without password", "obfs=salamander", "", false},
  168. {"unknown obfs type", "obfs=random&obfs-password=x", "", false},
  169. }
  170. for _, c := range cases {
  171. t.Run(c.name, func(t *testing.T) {
  172. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&" + c.query + "#node")
  173. if err != nil {
  174. t.Fatalf("parse hysteria2: %v", err)
  175. }
  176. if res.Outbound["protocol"] != "hysteria" {
  177. t.Fatalf("bad protocol: %v", res.Outbound["protocol"])
  178. }
  179. pw, ok := salamanderPassword(t, res)
  180. if ok != c.wantSet {
  181. t.Fatalf("salamander mask present = %v, want %v (stream: %v)", ok, c.wantSet, res.Outbound["streamSettings"])
  182. }
  183. if pw != c.wantPw {
  184. t.Errorf("salamander password: got %q, want %q", pw, c.wantPw)
  185. }
  186. })
  187. }
  188. }
  189. func TestParseHysteria2_ObfsFinalMaskPrecedence(t *testing.T) {
  190. cases := []struct {
  191. name string
  192. fm string
  193. obfsPw string
  194. wantPw string
  195. wantUDPLen int
  196. }{
  197. {
  198. name: "fm password wins over obfs",
  199. fm: `{"udp":[{"type":"salamander","settings":{"password":"fromfm"}}]}`,
  200. obfsPw: "fromobfs",
  201. wantPw: "fromfm",
  202. wantUDPLen: 1,
  203. },
  204. {
  205. name: "obfs fills password-less fm mask",
  206. fm: `{"udp":[{"type":"salamander","settings":{}}]}`,
  207. obfsPw: "fromobfs",
  208. wantPw: "fromobfs",
  209. wantUDPLen: 1,
  210. },
  211. {
  212. name: "obfs appends alongside a non-salamander mask",
  213. fm: `{"udp":[{"type":"mkcp-legacy","settings":{"header":"srtp"}}]}`,
  214. obfsPw: "fromobfs",
  215. wantPw: "fromobfs",
  216. wantUDPLen: 2,
  217. },
  218. }
  219. for _, c := range cases {
  220. t.Run(c.name, func(t *testing.T) {
  221. link := "hysteria2://[email protected]:443?security=tls&fm=" + url.QueryEscape(c.fm) +
  222. "&obfs=salamander&obfs-password=" + c.obfsPw + "#node"
  223. res, err := ParseLink(link)
  224. if err != nil {
  225. t.Fatalf("parse hysteria2: %v", err)
  226. }
  227. pw, ok := salamanderPassword(t, res)
  228. if !ok {
  229. t.Fatalf("salamander mask missing: %v", res.Outbound["streamSettings"])
  230. }
  231. if pw != c.wantPw {
  232. t.Errorf("salamander password: got %q, want %q", pw, c.wantPw)
  233. }
  234. if udp := finalmaskUDP(t, res); len(udp) != c.wantUDPLen {
  235. t.Errorf("udp mask count: got %d, want %d (%v)", len(udp), c.wantUDPLen, udp)
  236. }
  237. })
  238. }
  239. }
  240. func TestParseHysteria2_Mport(t *testing.T) {
  241. cases := []struct {
  242. name string
  243. query string
  244. wantPorts string
  245. wantHop bool
  246. }{
  247. {"standard mport", "mport=20000-50000", "20000-50000", true},
  248. {"no mport", "sni=ex.com", "", false},
  249. {
  250. name: "fm udpHop wins over mport",
  251. query: "mport=1-2&fm=" + url.QueryEscape(`{"quicParams":{"udpHop":{"ports":"30000-40000","interval":"7-9"}}}`),
  252. wantPorts: "30000-40000",
  253. wantHop: true,
  254. },
  255. }
  256. for _, c := range cases {
  257. t.Run(c.name, func(t *testing.T) {
  258. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&" + c.query + "#node")
  259. if err != nil {
  260. t.Fatalf("parse hysteria2: %v", err)
  261. }
  262. ports, ok := hopPorts(t, res)
  263. if ok != c.wantHop {
  264. t.Fatalf("udpHop present = %v, want %v (stream: %v)", ok, c.wantHop, res.Outbound["streamSettings"])
  265. }
  266. if ports != c.wantPorts {
  267. t.Errorf("hop ports: got %q, want %q", ports, c.wantPorts)
  268. }
  269. })
  270. }
  271. }
  272. func TestParseShadowsocks(t *testing.T) {
  273. modernUser := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:secretpass"))
  274. legacyBody := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:[email protected]:8388"))
  275. cases := []struct {
  276. name string
  277. link string
  278. host string
  279. port int
  280. method string
  281. pass string
  282. }{
  283. {
  284. name: "modern",
  285. link: "ss://" + modernUser + "@1.2.3.4:8388#node",
  286. host: "1.2.3.4",
  287. port: 8388,
  288. method: "aes-256-gcm",
  289. pass: "secretpass",
  290. },
  291. {
  292. name: "modern with plugin query",
  293. link: "ss://" + modernUser + "@1.2.3.4:8388?plugin=v2ray-plugin#node",
  294. host: "1.2.3.4",
  295. port: 8388,
  296. method: "aes-256-gcm",
  297. pass: "secretpass",
  298. },
  299. {
  300. name: "modern sip002 slash query",
  301. link: "ss://" + modernUser + "@1.2.3.4:8388/?plugin=obfs-local%3Bobfs%3Dhttp#node",
  302. host: "1.2.3.4",
  303. port: 8388,
  304. method: "aes-256-gcm",
  305. pass: "secretpass",
  306. },
  307. {
  308. name: "legacy",
  309. link: "ss://" + legacyBody + "#node",
  310. host: "1.2.3.4",
  311. port: 8388,
  312. method: "aes-256-gcm",
  313. pass: "secretpass",
  314. },
  315. {
  316. name: "base64url userinfo with plugin and trailing slash",
  317. link: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:pa+ss/word")) + "@1.2.3.4:8388/?plugin=obfs-local%3Bobfs%3Dhttp#node",
  318. host: "1.2.3.4",
  319. port: 8388,
  320. method: "aes-128-gcm",
  321. pass: "pa+ss/word",
  322. },
  323. {
  324. name: "sip022 percent-encoded userinfo",
  325. link: "ss://2022-blake3-aes-256-gcm:YctPZ6U7xPPcU%2Bgp3u%2B0tx%2FtRizJN9K8y%2BuKlW2qjlI%[email protected]:8888#Example3",
  326. host: "example.com",
  327. port: 8888,
  328. method: "2022-blake3-aes-256-gcm",
  329. pass: "YctPZ6U7xPPcU+gp3u+0tx/tRizJN9K8y+uKlW2qjlI=",
  330. },
  331. {
  332. name: "sip022 dual-key password with type query preserves inner colon",
  333. link: "ss://2022-blake3-aes-256-gcm:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%3D:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB%[email protected]:9999?type=tcp#node",
  334. host: "1.2.3.4",
  335. port: 9999,
  336. method: "2022-blake3-aes-256-gcm",
  337. pass: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
  338. },
  339. }
  340. for _, c := range cases {
  341. t.Run(c.name, func(t *testing.T) {
  342. res, err := ParseLink(c.link)
  343. if err != nil {
  344. t.Fatalf("parse ss: %v", err)
  345. }
  346. if res.Outbound["protocol"] != "shadowsocks" {
  347. t.Fatalf("protocol = %v, want shadowsocks", res.Outbound["protocol"])
  348. }
  349. srv := res.Outbound["settings"].(map[string]any)["servers"].([]any)[0].(map[string]any)
  350. if srv["address"] != c.host {
  351. t.Errorf("address = %v, want %v", srv["address"], c.host)
  352. }
  353. if srv["port"] != c.port {
  354. t.Errorf("port = %v, want %v", srv["port"], c.port)
  355. }
  356. if srv["method"] != c.method {
  357. t.Errorf("method = %v, want %v", srv["method"], c.method)
  358. }
  359. if srv["password"] != c.pass {
  360. t.Errorf("password = %v, want %v", srv["password"], c.pass)
  361. }
  362. })
  363. }
  364. }
  365. func TestParseShadowsocksBadPort(t *testing.T) {
  366. user := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:secretpass"))
  367. cases := map[string]string{
  368. "modern": "ss://" + user + "@1.2.3.4:notaport#node",
  369. "legacy": "ss://" + base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:[email protected]:notaport")) + "#node",
  370. }
  371. for name, link := range cases {
  372. t.Run(name, func(t *testing.T) {
  373. if _, err := ParseLink(link); err == nil {
  374. t.Errorf("expected parse error for non-numeric port, got nil")
  375. }
  376. })
  377. }
  378. }
  379. func TestParseSubscriptionBody_Base64(t *testing.T) {
  380. // base64 of the two joined links:
  381. // vless://u@h:443?type=tcp#A\nvless://u2@h2:443?type=tcp#B
  382. b64 := "dmxlc3M6Ly91QGg6NDQzP3R5cGU9dGNwI0EKdmxlc3M6Ly91MkBoMjo0NDM/dHlwZT10Y3AjQg=="
  383. obs, ids, err := ParseSubscriptionBody([]byte(b64))
  384. if err != nil {
  385. t.Fatalf("parse sub body: %v", err)
  386. }
  387. if len(obs) != 2 {
  388. t.Fatalf("expected 2 outbounds, got %d", len(obs))
  389. }
  390. if !strings.HasPrefix(ids[0], "vless:") || !strings.HasPrefix(ids[1], "vless:") {
  391. t.Errorf("bad identities: %v", ids)
  392. }
  393. }
  394. func TestSlugAndSuggest(t *testing.T) {
  395. if SlugRemark("Hello World!") != "hello-world" {
  396. t.Errorf("slug failed")
  397. }
  398. tag := SuggestTag("hk-", " SG 01 !! ", 0)
  399. if tag != "hk-sg-01" {
  400. t.Errorf("suggest tag got %q", tag)
  401. }
  402. // Non-ASCII letters/digits are preserved rather than stripped.
  403. if got := SlugRemark("Москва 🇷🇺 01"); got != "москва-01" {
  404. t.Errorf("unicode slug got %q", got)
  405. }
  406. if got := SuggestTag("ru-", "Сервер 2", 0); got != "ru-сервер-2" {
  407. t.Errorf("unicode suggest tag got %q", got)
  408. }
  409. }