1
0

reality_scan.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package service
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  17. )
  18. const (
  19. realityScanTimeout = 10 * time.Second
  20. realityDiscoverTimeout = 4 * time.Second
  21. realityScanConcurrency = 32
  22. realityDiscoverMaxIPs = 256
  23. realityScanMaxTotal = 512
  24. )
  25. var defaultRealityScanCandidates = []string{
  26. "www.cloudflare.com:443",
  27. "www.microsoft.com:443",
  28. "www.amazon.com:443",
  29. "aws.amazon.com:443",
  30. "www.samsung.com:443",
  31. "www.nvidia.com:443",
  32. "www.amd.com:443",
  33. "www.intel.com:443",
  34. "www.sony.com:443",
  35. "dl.google.com:443",
  36. }
  37. type RealityScanResult struct {
  38. Target string `json:"target" example:"www.cloudflare.com:443"`
  39. Host string `json:"host" example:"www.cloudflare.com"`
  40. IP string `json:"ip" example:"104.16.124.96"`
  41. Port int `json:"port" example:"443"`
  42. Feasible bool `json:"feasible" example:"true"`
  43. // PrivateTarget marks a target that resolves to a loopback/private/link-local
  44. // address: blocked before the probe unless the caller opted in, then flagged.
  45. PrivateTarget bool `json:"privateTarget" example:"false"`
  46. TLS13 bool `json:"tls13" example:"true"`
  47. TLSVersion string `json:"tlsVersion" example:"1.3"`
  48. H2 bool `json:"h2" example:"true"`
  49. ALPN string `json:"alpn" example:"h2"`
  50. X25519 bool `json:"x25519" example:"true"`
  51. CurveID string `json:"curveID" example:"X25519"`
  52. CertValid bool `json:"certValid" example:"true"`
  53. // CertChainValid ignores the name: a trusted chain presented for other names
  54. // still has serverNames the panel can offer instead of the failing SNI.
  55. CertChainValid bool `json:"certChainValid" example:"true"`
  56. // CertChainBytes is the sum of DER lengths of the presented peer chain.
  57. // xray-core ML-DSA-65 REALITY needs >= 3500 bytes (constant lives in xray-core).
  58. CertChainBytes int `json:"certChainBytes" example:"3427"`
  59. CertSubject string `json:"certSubject" example:"cloudflare.com"`
  60. CertIssuer string `json:"certIssuer" example:"Google Trust Services"`
  61. NotAfter string `json:"notAfter" example:"2026-08-01T00:00:00Z"`
  62. ServerNames []string `json:"serverNames"`
  63. LatencyMs int `json:"latencyMs" example:"180"`
  64. Reason string `json:"reason" example:""`
  65. }
  66. type realityProbeTask struct {
  67. dialHost string
  68. port int
  69. sni string
  70. timeout time.Duration
  71. bulk bool
  72. }
  73. func tlsVersionName(v uint16) string {
  74. switch v {
  75. case tls.VersionTLS13:
  76. return "1.3"
  77. case tls.VersionTLS12:
  78. return "1.2"
  79. case tls.VersionTLS11:
  80. return "1.1"
  81. case tls.VersionTLS10:
  82. return "1.0"
  83. default:
  84. return "unknown"
  85. }
  86. }
  87. func realityCurveName(id tls.CurveID) string {
  88. switch id {
  89. case tls.X25519:
  90. return "X25519"
  91. case tls.X25519MLKEM768:
  92. return "X25519MLKEM768"
  93. case tls.CurveP256:
  94. return "P-256"
  95. case tls.CurveP384:
  96. return "P-384"
  97. case tls.CurveP521:
  98. return "P-521"
  99. case 0:
  100. return ""
  101. default:
  102. return fmt.Sprintf("0x%04x", uint16(id))
  103. }
  104. }
  105. func filterUsableSANs(dnsNames []string) []string {
  106. out := make([]string, 0, len(dnsNames))
  107. for _, n := range dnsNames {
  108. n = strings.TrimSpace(n)
  109. if n == "" || strings.HasPrefix(n, "*.") {
  110. continue
  111. }
  112. out = append(out, n)
  113. }
  114. return out
  115. }
  116. func firstUsableName(leaf *x509.Certificate) string {
  117. cn := strings.TrimSpace(leaf.Subject.CommonName)
  118. if cn != "" && !strings.HasPrefix(cn, "*.") {
  119. return cn
  120. }
  121. for _, n := range leaf.DNSNames {
  122. n = strings.TrimSpace(n)
  123. if n != "" && !strings.HasPrefix(n, "*.") {
  124. return n
  125. }
  126. }
  127. return ""
  128. }
  129. func leafVerifies(leaf *x509.Certificate, opts x509.VerifyOptions) bool {
  130. _, err := leaf.Verify(opts)
  131. return err == nil
  132. }
  133. func splitRealityTarget(target string) (string, int, error) {
  134. target = strings.TrimSpace(target)
  135. if target == "" {
  136. return "", 0, common.NewError("target is required")
  137. }
  138. host, portStr := target, "443"
  139. if h, p, err := net.SplitHostPort(target); err == nil {
  140. host, portStr = h, p
  141. }
  142. host, err := netsafe.NormalizeHost(host)
  143. if err != nil {
  144. return "", 0, common.NewError("invalid target host: ", err)
  145. }
  146. port, err := strconv.Atoi(portStr)
  147. if err != nil || port < 1 || port > 65535 {
  148. return "", 0, common.NewError("invalid target port")
  149. }
  150. return host, port, nil
  151. }
  152. func incIP(ip net.IP) {
  153. for j := len(ip) - 1; j >= 0; j-- {
  154. ip[j]++
  155. if ip[j] > 0 {
  156. break
  157. }
  158. }
  159. }
  160. func enumerateCIDR(cidr string, max int) ([]string, error) {
  161. _, ipnet, err := net.ParseCIDR(strings.TrimSpace(cidr))
  162. if err != nil {
  163. return nil, err
  164. }
  165. ips := make([]string, 0, max)
  166. for ip := ipnet.IP.Mask(ipnet.Mask); ipnet.Contains(ip); incIP(ip) {
  167. ips = append(ips, ip.String())
  168. if len(ips) >= max {
  169. break
  170. }
  171. }
  172. return ips, nil
  173. }
  174. func (s *ServerService) probeRealityAddr(dialHost string, port int, sni string, timeout time.Duration, xver int, allowPrivate bool) *RealityScanResult {
  175. addr := net.JoinHostPort(dialHost, strconv.Itoa(port))
  176. res := &RealityScanResult{Port: port}
  177. if net.ParseIP(dialHost) != nil {
  178. res.IP = dialHost
  179. }
  180. // Target stays the dialed address (it is what the inbound dials); Host is
  181. // the SNI the handshake sent, which may differ for a fronting proxy.
  182. res.Host = dialHost
  183. res.Target = addr
  184. if sni != "" {
  185. res.Host = sni
  186. }
  187. ctx, cancel := context.WithTimeout(netsafe.ContextWithAllowPrivate(context.Background(), allowPrivate), timeout)
  188. defer cancel()
  189. start := time.Now()
  190. conn, err := netsafe.SSRFGuardedDialContext(ctx, "tcp", addr)
  191. if err != nil {
  192. res.PrivateTarget = errors.Is(err, netsafe.ErrPrivateAddressBlocked)
  193. res.Reason = "connection failed: " + err.Error()
  194. return res
  195. }
  196. defer conn.Close()
  197. if remote, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  198. res.PrivateTarget = netsafe.IsBlockedIP(remote.IP)
  199. // The opt-in bypasses the SSRF guard, so leave an audit trail of it.
  200. if res.PrivateTarget && allowPrivate {
  201. logger.Infof("reality scan reached private target %s (%s) with the operator opt-in", addr, remote.IP)
  202. }
  203. }
  204. _ = conn.SetDeadline(time.Now().Add(timeout))
  205. // A REALITY inbound with xver>=1 fronts a target that speaks the PROXY
  206. // protocol (e.g. an Nginx listener with `proxy_protocol`), so the probe
  207. // must lead with a PROXY header or the target resets the connection and
  208. // the scan reports a spurious handshake failure (#6082).
  209. if xver >= 1 {
  210. if err := writeProxyProtocolHeader(conn, xver); err != nil {
  211. res.Reason = "proxy protocol write failed: " + err.Error()
  212. return res
  213. }
  214. }
  215. cfg := &tls.Config{
  216. ServerName: sni,
  217. InsecureSkipVerify: true,
  218. NextProtos: []string{"h2", "http/1.1"},
  219. CurvePreferences: []tls.CurveID{tls.X25519, tls.X25519MLKEM768},
  220. MinVersion: tls.VersionTLS12,
  221. }
  222. tlsConn := tls.Client(conn, cfg)
  223. if err := tlsConn.HandshakeContext(ctx); err != nil {
  224. res.Reason = "TLS handshake failed: " + err.Error()
  225. return res
  226. }
  227. res.LatencyMs = int(time.Since(start).Milliseconds())
  228. st := tlsConn.ConnectionState()
  229. res.TLS13 = st.Version == tls.VersionTLS13
  230. res.TLSVersion = tlsVersionName(st.Version)
  231. res.ALPN = st.NegotiatedProtocol
  232. res.H2 = st.NegotiatedProtocol == "h2"
  233. res.CurveID = realityCurveName(st.CurveID)
  234. res.X25519 = st.CurveID == tls.X25519 || st.CurveID == tls.X25519MLKEM768
  235. verifyHost := sni
  236. if len(st.PeerCertificates) > 0 {
  237. leaf := st.PeerCertificates[0]
  238. for _, cert := range st.PeerCertificates {
  239. res.CertChainBytes += len(cert.Raw)
  240. }
  241. res.CertSubject = leaf.Subject.CommonName
  242. if res.CertSubject == "" && len(leaf.DNSNames) > 0 {
  243. res.CertSubject = leaf.DNSNames[0]
  244. }
  245. if len(leaf.Issuer.Organization) > 0 {
  246. res.CertIssuer = leaf.Issuer.Organization[0]
  247. } else {
  248. res.CertIssuer = leaf.Issuer.CommonName
  249. }
  250. res.NotAfter = leaf.NotAfter.UTC().Format(time.RFC3339)
  251. res.ServerNames = filterUsableSANs(leaf.DNSNames)
  252. if sni == "" {
  253. if discovered := firstUsableName(leaf); discovered != "" {
  254. res.Host = discovered
  255. res.Target = net.JoinHostPort(discovered, strconv.Itoa(port))
  256. verifyHost = discovered
  257. }
  258. }
  259. if verifyHost != "" {
  260. opts := x509.VerifyOptions{Intermediates: x509.NewCertPool()}
  261. for _, c := range st.PeerCertificates[1:] {
  262. opts.Intermediates.AddCert(c)
  263. }
  264. // The chain is checked without the name first: a publicly trusted
  265. // certificate for other names still carries usable serverNames.
  266. res.CertChainValid = leafVerifies(leaf, opts)
  267. opts.DNSName = verifyHost
  268. if leafVerifies(leaf, opts) {
  269. res.CertValid = true
  270. } else {
  271. _, verr := leaf.Verify(opts)
  272. res.Reason = "certificate not trusted: " + verr.Error()
  273. }
  274. } else {
  275. res.Reason = "no usable domain in certificate"
  276. }
  277. } else {
  278. res.Reason = "no certificate presented"
  279. }
  280. res.Feasible = res.TLS13 && res.H2 && res.X25519 && res.CertValid
  281. if !res.Feasible && res.Reason == "" {
  282. switch {
  283. case !res.TLS13:
  284. res.Reason = "server does not negotiate TLS 1.3"
  285. case !res.H2:
  286. res.Reason = "server does not negotiate HTTP/2 (h2)"
  287. case !res.X25519:
  288. res.Reason = "server did not use X25519 key exchange"
  289. }
  290. }
  291. return res
  292. }
  293. // ScanRealityTarget probes one operator-supplied target. An empty sni falls back
  294. // to the target host; allowPrivate lifts the SSRF guard for this probe only.
  295. func (s *ServerService) ScanRealityTarget(target string, sni string, xver int, allowPrivate bool) (*RealityScanResult, error) {
  296. host, port, err := splitRealityTarget(target)
  297. if err != nil {
  298. return nil, err
  299. }
  300. sni = strings.TrimSpace(sni)
  301. if sni == "" {
  302. sni = host
  303. } else if sni, err = netsafe.NormalizeHost(sni); err != nil {
  304. return nil, common.NewError("invalid SNI: ", err)
  305. }
  306. return s.probeRealityAddr(host, port, sni, realityScanTimeout, xver, allowPrivate), nil
  307. }
  308. func (s *ServerService) ScanRealityTargets(targetsCSV string) ([]*RealityScanResult, error) {
  309. var tokens []string
  310. for raw := range strings.SplitSeq(targetsCSV, ",") {
  311. if t := strings.TrimSpace(raw); t != "" {
  312. tokens = append(tokens, t)
  313. }
  314. }
  315. if len(tokens) == 0 {
  316. tokens = append(tokens, defaultRealityScanCandidates...)
  317. }
  318. var tasks []realityProbeTask
  319. var invalid []*RealityScanResult
  320. for _, token := range tokens {
  321. if len(tasks) >= realityScanMaxTotal {
  322. break
  323. }
  324. if strings.Contains(token, "/") {
  325. ips, err := enumerateCIDR(token, realityDiscoverMaxIPs)
  326. if err != nil {
  327. invalid = append(invalid, &RealityScanResult{Target: token, Reason: "invalid CIDR: " + err.Error()})
  328. continue
  329. }
  330. for _, ip := range ips {
  331. if len(tasks) >= realityScanMaxTotal {
  332. break
  333. }
  334. tasks = append(tasks, realityProbeTask{dialHost: ip, port: 443, timeout: realityDiscoverTimeout, bulk: true})
  335. }
  336. continue
  337. }
  338. host, port, err := splitRealityTarget(token)
  339. if err != nil {
  340. invalid = append(invalid, &RealityScanResult{Target: token, Reason: err.Error()})
  341. continue
  342. }
  343. if net.ParseIP(host) != nil {
  344. tasks = append(tasks, realityProbeTask{dialHost: host, port: port, timeout: realityDiscoverTimeout})
  345. } else {
  346. tasks = append(tasks, realityProbeTask{dialHost: host, port: port, sni: host, timeout: realityScanTimeout})
  347. }
  348. }
  349. probed := make([]*RealityScanResult, len(tasks))
  350. sem := make(chan struct{}, realityScanConcurrency)
  351. var wg sync.WaitGroup
  352. for i, task := range tasks {
  353. wg.Add(1)
  354. sem <- struct{}{}
  355. go func(idx int, tk realityProbeTask) {
  356. defer wg.Done()
  357. defer func() { <-sem }()
  358. // The bulk/CIDR scanner never reaches private ranges: the opt-in
  359. // there would turn it into an internal network scanner.
  360. r := s.probeRealityAddr(tk.dialHost, tk.port, tk.sni, tk.timeout, 0, false)
  361. if tk.bulk && r.TLSVersion == "" {
  362. return
  363. }
  364. probed[idx] = r
  365. }(i, task)
  366. }
  367. wg.Wait()
  368. results := dedupRealityResults(append(probed, invalid...))
  369. sortRealityResults(results)
  370. return results, nil
  371. }
  372. func dedupRealityResults(results []*RealityScanResult) []*RealityScanResult {
  373. best := make(map[string]*RealityScanResult)
  374. order := make([]string, 0, len(results))
  375. for _, r := range results {
  376. if r == nil {
  377. continue
  378. }
  379. if ex, ok := best[r.Target]; !ok {
  380. best[r.Target] = r
  381. order = append(order, r.Target)
  382. } else if betterRealityResult(r, ex) {
  383. best[r.Target] = r
  384. }
  385. }
  386. out := make([]*RealityScanResult, 0, len(order))
  387. for _, k := range order {
  388. out = append(out, best[k])
  389. }
  390. return out
  391. }
  392. func betterRealityResult(a, b *RealityScanResult) bool {
  393. if a.Feasible != b.Feasible {
  394. return a.Feasible
  395. }
  396. return a.LatencyMs > 0 && (b.LatencyMs == 0 || a.LatencyMs < b.LatencyMs)
  397. }
  398. func sortRealityResults(results []*RealityScanResult) {
  399. slices.SortStableFunc(results, func(a, b *RealityScanResult) int {
  400. if a.Feasible != b.Feasible {
  401. if a.Feasible {
  402. return -1
  403. }
  404. return 1
  405. }
  406. return a.LatencyMs - b.LatencyMs
  407. })
  408. }
  409. // writeProxyProtocolHeader emits a PROXY protocol header describing the local
  410. // connection so a target that requires it (Nginx `proxy_protocol`, matching a
  411. // REALITY inbound's xver) accepts the probe instead of resetting it. xver 1
  412. // sends the human-readable v1 header; xver 2 sends the binary v2 header. The
  413. // addresses come from the already-dialed connection, so they are always a
  414. // consistent, real (src, dst) pair.
  415. func writeProxyProtocolHeader(conn net.Conn, xver int) error {
  416. local, lok := conn.LocalAddr().(*net.TCPAddr)
  417. remote, rok := conn.RemoteAddr().(*net.TCPAddr)
  418. if !lok || !rok {
  419. return fmt.Errorf("connection has no TCP addresses")
  420. }
  421. if xver >= 2 {
  422. return writeProxyProtocolV2(conn, local, remote)
  423. }
  424. return writeProxyProtocolV1(conn, local, remote)
  425. }
  426. func writeProxyProtocolV1(conn net.Conn, local, remote *net.TCPAddr) error {
  427. fam := "TCP4"
  428. if local.IP.To4() == nil || remote.IP.To4() == nil {
  429. fam = "TCP6"
  430. }
  431. header := fmt.Sprintf("PROXY %s %s %s %d %d\r\n", fam, local.IP.String(), remote.IP.String(), local.Port, remote.Port)
  432. _, err := conn.Write([]byte(header))
  433. return err
  434. }
  435. func writeProxyProtocolV2(conn net.Conn, local, remote *net.TCPAddr) error {
  436. buf := []byte{0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A}
  437. buf = append(buf, 0x21)
  438. src4, dst4 := local.IP.To4(), remote.IP.To4()
  439. if src4 != nil && dst4 != nil {
  440. buf = append(buf, 0x11)
  441. buf = append(buf, 0x00, 12)
  442. buf = append(buf, src4...)
  443. buf = append(buf, dst4...)
  444. buf = append(buf, byte(local.Port>>8), byte(local.Port))
  445. buf = append(buf, byte(remote.Port>>8), byte(remote.Port))
  446. } else {
  447. buf = append(buf, 0x21)
  448. buf = append(buf, 0x00, 36)
  449. buf = append(buf, local.IP.To16()...)
  450. buf = append(buf, remote.IP.To16()...)
  451. buf = append(buf, byte(local.Port>>8), byte(local.Port))
  452. buf = append(buf, byte(remote.Port>>8), byte(remote.Port))
  453. }
  454. _, err := conn.Write(buf)
  455. return err
  456. }