1
0

reality_scan.go 14 KB

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