fix(reality): make the REALITY target check usable on a private network (#6242)

* fix(reality): make the REALITY target check usable on a private network

The probe dials through netsafe.SSRFGuardedDialContext, so a fronting service
reachable only inside the deployment (a Docker service name, a LAN address)
always failed with "blocked private/internal address": the inbound itself
works, because the guard sits in the probe path only, so the panel reported a
red verdict on a healthy configuration. Instead of a panel-wide setting that
lifts the guard for good, the guard is now lifted per probe and only after the
operator confirms the local-network warning in a modal; the verdict keeps
privateTarget set, so a passing local check stays a warning rather than a
green success.

The probe also sent the target host as SNI. Clients dial the target but send a
name from serverNames, so a fronting proxy answered with its default
certificate — a Traefik front reached as "traefik" reported "certificate is
valid for <hash>.traefik.default, not traefik" on a deployment whose clients
get a valid chain. The panel now sends the first configured serverName as SNI
and the certificate is verified against it; empty serverNames keeps the old
fallback. The reported target stays the dialled address, so a passing check no
longer rewrites the target field with the SNI host.

The result panel reports what was actually seen: the SNI used, the certificate
subject/issuer and its expiry stay visible when the chain is untrusted (with
"Not trusted" appended) instead of being replaced by that verdict alone.
Certificate names are copied into the SNI field only when the chain verified —
the names on a proxy's default certificate would otherwise become the SNI of
the next check.

The bulk/CIDR scanner keeps the guard unconditionally: honouring the opt-in
there would turn it into an internal network scanner.

* fix(reality): recover from a stale SNI and report a refused address reliably

Review follow-up on the REALITY target check.

The probe sends the stored serverNames as SNI, and the panel only wrote names
back when the whole chain verified, so switching Target while the SNI field
still held the previous target's names failed every rescan: the new target's
real names came back from the probe but were discarded with the verdict. The
certificate is now checked in two steps — chain first, then the name — and a
trusted chain presented for other names is enough for the panel to offer those
names, so the next scan passes. Picking a row in the bulk scanner replaces the
names outright, since keeping the previous target's SNI leaves a REALITY config
that cannot work.

SSRFGuardedDialContext kept the refusal only in lastErr, so on a dual-stack
name a refused private address followed by a failing public one lost the
sentinel and the panel silently skipped the confirmation. The refusal is now
tracked separately and reported alongside the last dial error.

Honouring the opt-in is logged with the target and the resolved address, since
it bypasses the SSRF guard on an authenticated endpoint. The read-only SNI row
in the result is labelled "SNI used" so it no longer collides with the SNI
field below it, and the comment blocks are back within the 2-line limit.

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
shustovTE
2026-08-18 14:47:59 +03:00
committed by GitHub
parent f75ea08ab4
commit 708a69acde
26 changed files with 294 additions and 73 deletions
+65 -33
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"slices"
@@ -12,6 +13,7 @@ import (
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
)
@@ -38,24 +40,30 @@ var defaultRealityScanCandidates = []string{
}
type RealityScanResult struct {
Target string `json:"target" example:"www.cloudflare.com:443"`
Host string `json:"host" example:"www.cloudflare.com"`
IP string `json:"ip" example:"104.16.124.96"`
Port int `json:"port" example:"443"`
Feasible bool `json:"feasible" example:"true"`
TLS13 bool `json:"tls13" example:"true"`
TLSVersion string `json:"tlsVersion" example:"1.3"`
H2 bool `json:"h2" example:"true"`
ALPN string `json:"alpn" example:"h2"`
X25519 bool `json:"x25519" example:"true"`
CurveID string `json:"curveID" example:"X25519"`
CertValid bool `json:"certValid" example:"true"`
CertSubject string `json:"certSubject" example:"cloudflare.com"`
CertIssuer string `json:"certIssuer" example:"Google Trust Services"`
NotAfter string `json:"notAfter" example:"2026-08-01T00:00:00Z"`
ServerNames []string `json:"serverNames"`
LatencyMs int `json:"latencyMs" example:"180"`
Reason string `json:"reason" example:""`
Target string `json:"target" example:"www.cloudflare.com:443"`
Host string `json:"host" example:"www.cloudflare.com"`
IP string `json:"ip" example:"104.16.124.96"`
Port int `json:"port" example:"443"`
Feasible bool `json:"feasible" example:"true"`
// PrivateTarget marks a target that resolves to a loopback/private/link-local
// address: blocked before the probe unless the caller opted in, then flagged.
PrivateTarget bool `json:"privateTarget" example:"false"`
TLS13 bool `json:"tls13" example:"true"`
TLSVersion string `json:"tlsVersion" example:"1.3"`
H2 bool `json:"h2" example:"true"`
ALPN string `json:"alpn" example:"h2"`
X25519 bool `json:"x25519" example:"true"`
CurveID string `json:"curveID" example:"X25519"`
CertValid bool `json:"certValid" example:"true"`
// CertChainValid ignores the name: a trusted chain presented for other names
// still has serverNames the panel can offer instead of the failing SNI.
CertChainValid bool `json:"certChainValid" example:"true"`
CertSubject string `json:"certSubject" example:"cloudflare.com"`
CertIssuer string `json:"certIssuer" example:"Google Trust Services"`
NotAfter string `json:"notAfter" example:"2026-08-01T00:00:00Z"`
ServerNames []string `json:"serverNames"`
LatencyMs int `json:"latencyMs" example:"180"`
Reason string `json:"reason" example:""`
}
type realityProbeTask struct {
@@ -126,6 +134,11 @@ func firstUsableName(leaf *x509.Certificate) string {
return ""
}
func leafVerifies(leaf *x509.Certificate, opts x509.VerifyOptions) bool {
_, err := leaf.Verify(opts)
return err == nil
}
func splitRealityTarget(target string) (string, int, error) {
target = strings.TrimSpace(target)
if target == "" {
@@ -170,30 +183,38 @@ func enumerateCIDR(cidr string, max int) ([]string, error) {
return ips, nil
}
func (s *ServerService) probeRealityAddr(dialHost string, port int, sni string, timeout time.Duration, xver int) *RealityScanResult {
func (s *ServerService) probeRealityAddr(dialHost string, port int, sni string, timeout time.Duration, xver int, allowPrivate bool) *RealityScanResult {
addr := net.JoinHostPort(dialHost, strconv.Itoa(port))
res := &RealityScanResult{Port: port}
if net.ParseIP(dialHost) != nil {
res.IP = dialHost
}
// Target stays the dialed address (it is what the inbound dials); Host is
// the SNI the handshake sent, which may differ for a fronting proxy.
res.Host = dialHost
res.Target = addr
if sni != "" {
res.Host = sni
res.Target = net.JoinHostPort(sni, strconv.Itoa(port))
} else {
res.Host = dialHost
res.Target = addr
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
ctx, cancel := context.WithTimeout(netsafe.ContextWithAllowPrivate(context.Background(), allowPrivate), timeout)
defer cancel()
start := time.Now()
conn, err := netsafe.SSRFGuardedDialContext(ctx, "tcp", addr)
if err != nil {
res.PrivateTarget = errors.Is(err, netsafe.ErrPrivateAddressBlocked)
res.Reason = "connection failed: " + err.Error()
return res
}
defer conn.Close()
if remote, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
res.PrivateTarget = netsafe.IsBlockedIP(remote.IP)
// The opt-in bypasses the SSRF guard, so leave an audit trail of it.
if res.PrivateTarget && allowPrivate {
logger.Infof("reality scan reached private target %s (%s) with the operator opt-in", addr, remote.IP)
}
}
_ = conn.SetDeadline(time.Now().Add(timeout))
// A REALITY inbound with xver>=1 fronts a target that speaks the PROXY
@@ -253,13 +274,18 @@ func (s *ServerService) probeRealityAddr(dialHost string, port int, sni string,
}
if verifyHost != "" {
opts := x509.VerifyOptions{DNSName: verifyHost, Intermediates: x509.NewCertPool()}
opts := x509.VerifyOptions{Intermediates: x509.NewCertPool()}
for _, c := range st.PeerCertificates[1:] {
opts.Intermediates.AddCert(c)
}
if _, verr := leaf.Verify(opts); verr == nil {
// The chain is checked without the name first: a publicly trusted
// certificate for other names still carries usable serverNames.
res.CertChainValid = leafVerifies(leaf, opts)
opts.DNSName = verifyHost
if leafVerifies(leaf, opts) {
res.CertValid = true
} else {
_, verr := leaf.Verify(opts)
res.Reason = "certificate not trusted: " + verr.Error()
}
} else {
@@ -283,16 +309,20 @@ func (s *ServerService) probeRealityAddr(dialHost string, port int, sni string,
return res
}
func (s *ServerService) probeRealityTarget(host string, port int, xver int) *RealityScanResult {
return s.probeRealityAddr(host, port, host, realityScanTimeout, xver)
}
func (s *ServerService) ScanRealityTarget(target string, xver int) (*RealityScanResult, error) {
// ScanRealityTarget probes one operator-supplied target. An empty sni falls back
// to the target host; allowPrivate lifts the SSRF guard for this probe only.
func (s *ServerService) ScanRealityTarget(target string, sni string, xver int, allowPrivate bool) (*RealityScanResult, error) {
host, port, err := splitRealityTarget(target)
if err != nil {
return nil, err
}
return s.probeRealityTarget(host, port, xver), nil
sni = strings.TrimSpace(sni)
if sni == "" {
sni = host
} else if sni, err = netsafe.NormalizeHost(sni); err != nil {
return nil, common.NewError("invalid SNI: ", err)
}
return s.probeRealityAddr(host, port, sni, realityScanTimeout, xver, allowPrivate), nil
}
func (s *ServerService) ScanRealityTargets(targetsCSV string) ([]*RealityScanResult, error) {
@@ -347,7 +377,9 @@ func (s *ServerService) ScanRealityTargets(targetsCSV string) ([]*RealityScanRes
go func(idx int, tk realityProbeTask) {
defer wg.Done()
defer func() { <-sem }()
r := s.probeRealityAddr(tk.dialHost, tk.port, tk.sni, tk.timeout, 0)
// The bulk/CIDR scanner never reaches private ranges: the opt-in
// there would turn it into an internal network scanner.
r := s.probeRealityAddr(tk.dialHost, tk.port, tk.sni, tk.timeout, 0, false)
if tk.bulk && r.TLSVersion == "" {
return
}
+2 -2
View File
@@ -78,13 +78,13 @@ func TestSplitRealityTarget(t *testing.T) {
}
func TestScanRealityTargetInputValidation(t *testing.T) {
if _, err := (&ServerService{}).ScanRealityTarget("", 0); err == nil {
if _, err := (&ServerService{}).ScanRealityTarget("", "", 0, false); err == nil {
t.Error("ScanRealityTarget(empty) expected error, got nil")
}
}
func TestScanRealityTargetBlocksPrivate(t *testing.T) {
res, err := (&ServerService{}).ScanRealityTarget("127.0.0.1:443", 0)
res, err := (&ServerService{}).ScanRealityTarget("127.0.0.1:443", "", 0, false)
if err != nil {
t.Fatalf("ScanRealityTarget(loopback) unexpected error: %v", err)
}