| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/hex" |
| 7 | "errors" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/netip" |
| 11 | "sync" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/miekg/dns" |
| 15 | ) |
| 16 | |
| 17 | const ( |
| 18 | GateClosed = "closed" |
| 19 | GateChecking = "checking" |
| 20 | GateOpen = "open" |
| 21 | GateLease = 90 * time.Second |
| 22 | DiagnosticHost = "198.18.0.254" |
| 23 | DiagnosticAddress = "198.18.0.254:80" |
| 24 | ) |
| 25 | |
| 26 | var ErrGateClosed = errors.New("Cage 外网未放行,请在工作台完成关键检查") |
| 27 | |
| 28 | type GateCounters struct { |
| 29 | TCPDenied uint64 `json:"tcp_denied"` |
| 30 | UDPDenied uint64 `json:"udp_denied"` |
| 31 | IPv6Denied uint64 `json:"ipv6_denied"` |
| 32 | PrivateDenied uint64 `json:"private_denied"` |
| 33 | DNSDenied uint64 `json:"dns_denied"` |
| 34 | ProbeTCP uint64 `json:"probe_tcp"` |
| 35 | ProbeDNS uint64 `json:"probe_dns"` |
| 36 | FaultTCP uint64 `json:"fault_tcp"` |
| 37 | FaultDNS uint64 `json:"fault_dns"` |
| 38 | } |
| 39 | |
| 40 | type GateStatus struct { |
| 41 | IPv6LinkProbeCheck string `json:"ipv6_link_probe_check,omitempty"` |
| 42 | Epoch uint64 `json:"epoch"` |
| 43 | PolicyVerified bool `json:"policy_verified"` |
| 44 | Policy string `json:"policy"` |
| 45 | RunID string `json:"run_id"` |
| 46 | CheckID string `json:"check_id,omitempty"` |
| 47 | CheckStartedAt time.Time `json:"check_started_at,omitempty"` |
| 48 | Configuration string `json:"configuration"` |
| 49 | Mode string `json:"mode"` |
| 50 | Fault bool `json:"fault"` |
| 51 | Until time.Time `json:"until"` |
| 52 | Reason string `json:"reason,omitempty"` |
| 53 | Counters GateCounters `json:"counters"` |
| 54 | Connections int `json:"connections"` |
| 55 | Report *SafetyReport `json:"report,omitempty"` |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | type EgressGate struct { |
| 62 | config Config |
| 63 | mu sync.Mutex |
| 64 | raw, diagnostic, failedDiagnostic *Egress |
| 65 | state GateStatus |
| 66 | epoch uint64 |
| 67 | epochContext context.Context |
| 68 | cancel context.CancelFunc |
| 69 | timer *time.Timer |
| 70 | connections map[*gateConn]struct{} |
| 71 | probeRequests int |
| 72 | } |
| 73 | |
| 74 | func NewEgressGate(cfg Config) (*EgressGate, error) { |
| 75 | raw, err := NewEgress(cfg) |
| 76 | if err != nil { |
| 77 | return nil, err |
| 78 | } |
| 79 | diagnostic, err := NewEgress(cfg) |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | failed, err := NewEgress(cfg) |
| 84 | if err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | failed.connect = unavailableProxy{} |
| 88 | diagnostic.client.Transport.(*http.Transport).DisableKeepAlives = true |
| 89 | failed.client.Transport.(*http.Transport).DisableKeepAlives = true |
| 90 | ctx, cancel := context.WithCancel(context.Background()) |
| 91 | var id [16]byte |
| 92 | if _, err = rand.Read(id[:]); err != nil { |
| 93 | cancel() |
| 94 | return nil, err |
| 95 | } |
| 96 | g := &EgressGate{config: cfg, raw: raw, diagnostic: diagnostic, failedDiagnostic: failed, |
| 97 | epochContext: ctx, cancel: cancel, connections: make(map[*gateConn]struct{}), |
| 98 | state: GateStatus{Policy: SafetyPolicyVersion, RunID: hex.EncodeToString(id[:]), Configuration: cfg.Fingerprint(), Mode: GateClosed, Reason: "等待关键检查"}} |
| 99 | |
| 100 | |
| 101 | raw.client.Transport.(*http.Transport).DialContext = g.dialDNS |
| 102 | return g, nil |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | func (g *EgressGate) SyncProxyRevision(cfg Config) error { |
| 108 | g.mu.Lock() |
| 109 | before, after := g.config, cfg |
| 110 | before.ProxyRevision, after.ProxyRevision = "", "" |
| 111 | if before != after || cfg.ProxyRevision == "" { |
| 112 | g.mu.Unlock() |
| 113 | return errors.New("出口地址或环境设置变化需要重启环境") |
| 114 | } |
| 115 | connections := g.transitionLocked(GateClosed, false, "代理节点已变更,等待重新检查") |
| 116 | g.config = cfg |
| 117 | g.state.Configuration = cfg.Fingerprint() |
| 118 | g.state.Report = nil |
| 119 | g.mu.Unlock() |
| 120 | closeGateConnections(connections) |
| 121 | return nil |
| 122 | } |
| 123 | |
| 124 | func (g *EgressGate) Status() GateStatus { |
| 125 | g.mu.Lock() |
| 126 | defer g.mu.Unlock() |
| 127 | s := g.state |
| 128 | s.Epoch = g.epoch |
| 129 | s.PolicyVerified = g.raw.Allows("tcp", netip.MustParseAddrPort("1.1.1.1:443")) && |
| 130 | !g.raw.Allows("udp", netip.MustParseAddrPort("1.1.1.1:3478")) && |
| 131 | !g.raw.Allows("icmp", netip.MustParseAddrPort("1.1.1.1:1")) && |
| 132 | !g.raw.Allows("tcp", netip.MustParseAddrPort("[2606:4700:4700::1111]:443")) && |
| 133 | !g.raw.Allows("tcp", netip.MustParseAddrPort("127.0.0.1:17777")) |
| 134 | if s.Mode != GateClosed && !time.Now().Before(s.Until) { |
| 135 | s.Mode = GateClosed |
| 136 | s.Reason = "检查或监测授权已到期" |
| 137 | } |
| 138 | s.Connections = len(g.connections) |
| 139 | if s.Report != nil { |
| 140 | r := *s.Report |
| 141 | r.Checks = append([]SafetyCheck(nil), r.Checks...) |
| 142 | s.Report = &r |
| 143 | } |
| 144 | return s |
| 145 | } |
| 146 | |
| 147 | func (g *EgressGate) validLocked(epoch uint64) bool { |
| 148 | return g.epoch == epoch && g.state.Mode != GateClosed && time.Now().Before(g.state.Until) |
| 149 | } |
| 150 | |
| 151 | func (g *EgressGate) armLocked(duration time.Duration) { |
| 152 | g.armUntilLocked(time.Now().Add(duration)) |
| 153 | } |
| 154 | |
| 155 | func (g *EgressGate) armUntilLocked(until time.Time) { |
| 156 | if g.timer != nil { |
| 157 | g.timer.Stop() |
| 158 | } |
| 159 | g.state.Until = until |
| 160 | epoch := g.epoch |
| 161 | g.timer = time.AfterFunc(time.Until(until), func() { |
| 162 | g.mu.Lock() |
| 163 | if epoch != g.epoch || time.Now().Before(g.state.Until) { |
| 164 | g.mu.Unlock() |
| 165 | return |
| 166 | } |
| 167 | connections := g.transitionLocked(GateClosed, false, "检查或监测授权已到期") |
| 168 | g.mu.Unlock() |
| 169 | closeGateConnections(connections) |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | |
| 174 | |
| 175 | func (g *EgressGate) transitionLocked(mode string, fault bool, reason string) []*gateConn { |
| 176 | g.cancel() |
| 177 | if g.timer != nil { |
| 178 | g.timer.Stop() |
| 179 | } |
| 180 | g.epoch++ |
| 181 | g.epochContext, g.cancel = context.WithCancel(context.Background()) |
| 182 | g.state.Mode, g.state.Fault, g.state.Reason = mode, fault, reason |
| 183 | g.state.Until = time.Time{} |
| 184 | if mode == GateClosed { |
| 185 | g.state.CheckID = "" |
| 186 | } |
| 187 | connections := make([]*gateConn, 0, len(g.connections)) |
| 188 | for c := range g.connections { |
| 189 | connections = append(connections, c) |
| 190 | } |
| 191 | g.connections = make(map[*gateConn]struct{}) |
| 192 | return connections |
| 193 | } |
| 194 | |
| 195 | func closeGateConnections(connections []*gateConn) { |
| 196 | for _, c := range connections { |
| 197 | _ = c.Close() |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func (g *EgressGate) Close(reason string) { |
| 202 | g.mu.Lock() |
| 203 | connections := g.transitionLocked(GateClosed, false, reason) |
| 204 | g.mu.Unlock() |
| 205 | closeGateConnections(connections) |
| 206 | } |
| 207 | |
| 208 | func (g *EgressGate) BeginCheck() error { |
| 209 | var id [16]byte |
| 210 | if _, err := rand.Read(id[:]); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | g.mu.Lock() |
| 214 | connections := g.transitionLocked(GateChecking, false, "关键检查进行中") |
| 215 | g.state.CheckID = hex.EncodeToString(id[:]) |
| 216 | g.state.IPv6LinkProbeCheck = "" |
| 217 | g.state.CheckStartedAt = time.Now() |
| 218 | g.probeRequests = 0 |
| 219 | g.armLocked(3 * time.Minute) |
| 220 | g.mu.Unlock() |
| 221 | closeGateConnections(connections) |
| 222 | return nil |
| 223 | } |
| 224 | |
| 225 | func (g *EgressGate) SetFault(fault bool) error { |
| 226 | g.mu.Lock() |
| 227 | if g.state.Mode != GateChecking || !g.validLocked(g.epoch) { |
| 228 | g.mu.Unlock() |
| 229 | return ErrGateClosed |
| 230 | } |
| 231 | until := g.state.Until |
| 232 | connections := g.transitionLocked(GateChecking, fault, "关键检查进行中") |
| 233 | g.armUntilLocked(until) |
| 234 | g.mu.Unlock() |
| 235 | closeGateConnections(connections) |
| 236 | return nil |
| 237 | } |
| 238 | |
| 239 | func (g *EgressGate) Grant(report SafetyReport) error { |
| 240 | g.mu.Lock() |
| 241 | if g.state.Mode != GateChecking || !g.validLocked(g.epoch) || report.CheckID != g.state.CheckID || report.CreatedAt.Before(g.state.CheckStartedAt) { |
| 242 | g.mu.Unlock() |
| 243 | return errors.New("检测会话已失效,请重新检测") |
| 244 | } |
| 245 | if err := report.Authorizes(g.state.RunID, g.state.Configuration, time.Now()); err != nil { |
| 246 | g.mu.Unlock() |
| 247 | return err |
| 248 | } |
| 249 | connections := g.transitionLocked(GateOpen, false, "") |
| 250 | g.state.CheckID = "" |
| 251 | report.Checks = append([]SafetyCheck(nil), report.Checks...) |
| 252 | g.state.Report = &report |
| 253 | g.armReportLeaseLocked(report) |
| 254 | g.mu.Unlock() |
| 255 | closeGateConnections(connections) |
| 256 | return nil |
| 257 | } |
| 258 | |
| 259 | func (g *EgressGate) Renew(reportID string) error { |
| 260 | g.mu.Lock() |
| 261 | defer g.mu.Unlock() |
| 262 | if g.state.Mode != GateOpen || !g.validLocked(g.epoch) || g.state.Report == nil || g.state.Report.ID != reportID { |
| 263 | return ErrGateClosed |
| 264 | } |
| 265 | if err := g.state.Report.Authorizes(g.state.RunID, g.state.Configuration, time.Now()); err != nil { |
| 266 | return err |
| 267 | } |
| 268 | g.armReportLeaseLocked(*g.state.Report) |
| 269 | return nil |
| 270 | } |
| 271 | |
| 272 | func (g *EgressGate) armReportLeaseLocked(report SafetyReport) { |
| 273 | until := time.Now().Add(GateLease) |
| 274 | if expiry := report.CreatedAt.Add(SafetyReportLifetime); expiry.Before(until) { |
| 275 | until = expiry |
| 276 | } |
| 277 | g.armUntilLocked(until) |
| 278 | } |
| 279 | |
| 280 | func (g *EgressGate) Allows(network string, dst netip.AddrPort) bool { |
| 281 | g.mu.Lock() |
| 282 | defer g.mu.Unlock() |
| 283 | active := g.validLocked(g.epoch) |
| 284 | if active && g.state.Mode == GateChecking && network == "tcp" && dst.String() == DiagnosticAddress { |
| 285 | return true |
| 286 | } |
| 287 | public := g.raw.Allows(network, dst) |
| 288 | if active && g.state.Mode == GateOpen && public { |
| 289 | return true |
| 290 | } |
| 291 | switch network { |
| 292 | case "tcp": |
| 293 | g.state.Counters.TCPDenied++ |
| 294 | case "udp": |
| 295 | g.state.Counters.UDPDenied++ |
| 296 | } |
| 297 | if dst.Addr().Is6() { |
| 298 | g.state.Counters.IPv6Denied++ |
| 299 | } |
| 300 | if !g.raw.public.Allows("tcp", dst) { |
| 301 | g.state.Counters.PrivateDenied++ |
| 302 | } |
| 303 | return false |
| 304 | } |
| 305 | |
| 306 | func (g *EgressGate) operation(ctx context.Context, diagnostic bool) (context.Context, func(), uint64, error) { |
| 307 | g.mu.Lock() |
| 308 | defer g.mu.Unlock() |
| 309 | if !g.validLocked(g.epoch) || (!diagnostic && g.state.Mode != GateOpen) || (diagnostic && g.state.Mode != GateChecking) { |
| 310 | return nil, nil, 0, ErrGateClosed |
| 311 | } |
| 312 | child, cancel := context.WithCancel(ctx) |
| 313 | stop := context.AfterFunc(g.epochContext, cancel) |
| 314 | return child, func() { stop(); cancel() }, g.epoch, nil |
| 315 | } |
| 316 | |
| 317 | func (g *EgressGate) track(c net.Conn, epoch uint64) (net.Conn, error) { |
| 318 | g.mu.Lock() |
| 319 | if !g.validLocked(epoch) || len(g.connections) >= 1024 { |
| 320 | g.mu.Unlock() |
| 321 | _ = c.SetDeadline(time.Now()) |
| 322 | _ = c.Close() |
| 323 | return nil, ErrGateClosed |
| 324 | } |
| 325 | wrapped := &gateConn{Conn: c, gate: g, epoch: epoch} |
| 326 | g.connections[wrapped] = struct{}{} |
| 327 | g.mu.Unlock() |
| 328 | return wrapped, nil |
| 329 | } |
| 330 | |
| 331 | func (g *EgressGate) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { |
| 332 | dst, err := netip.ParseAddrPort(addr) |
| 333 | if err != nil || (network != "tcp" && network != "tcp4" && network != "tcp6") { |
| 334 | return nil, ErrGateClosed |
| 335 | } |
| 336 | if addr == DiagnosticAddress { |
| 337 | return g.dialDiagnostic(ctx) |
| 338 | } |
| 339 | if !g.raw.Allows("tcp", dst) { |
| 340 | return nil, ErrGateClosed |
| 341 | } |
| 342 | return g.dialDNS(ctx, network, addr) |
| 343 | } |
| 344 | |
| 345 | |
| 346 | func (g *EgressGate) dialDNS(ctx context.Context, network, addr string) (net.Conn, error) { |
| 347 | ctx, done, epoch, err := g.operation(ctx, false) |
| 348 | if err != nil { |
| 349 | return nil, err |
| 350 | } |
| 351 | defer done() |
| 352 | c, err := g.raw.DialContext(ctx, network, addr) |
| 353 | if err != nil { |
| 354 | return nil, err |
| 355 | } |
| 356 | return g.track(c, epoch) |
| 357 | } |
| 358 | |
| 359 | func (g *EgressGate) ExchangeDNS(ctx context.Context, query *dns.Msg) (*dns.Msg, error) { |
| 360 | ctx, done, epoch, err := g.operation(ctx, false) |
| 361 | if err != nil { |
| 362 | g.mu.Lock() |
| 363 | g.state.Counters.DNSDenied++ |
| 364 | g.mu.Unlock() |
| 365 | return nil, err |
| 366 | } |
| 367 | defer done() |
| 368 | r, err := g.raw.ExchangeDNS(ctx, query) |
| 369 | g.mu.Lock() |
| 370 | valid := g.validLocked(epoch) |
| 371 | g.mu.Unlock() |
| 372 | if !valid { |
| 373 | return nil, ErrGateClosed |
| 374 | } |
| 375 | return r, err |
| 376 | } |
| 377 | |
| 378 | type gateConn struct { |
| 379 | net.Conn |
| 380 | gate *EgressGate |
| 381 | epoch uint64 |
| 382 | once sync.Once |
| 383 | } |
| 384 | |
| 385 | func (c *gateConn) valid() bool { |
| 386 | c.gate.mu.Lock() |
| 387 | defer c.gate.mu.Unlock() |
| 388 | return c.gate.validLocked(c.epoch) |
| 389 | } |
| 390 | func (c *gateConn) Read(b []byte) (int, error) { |
| 391 | if !c.valid() { |
| 392 | _ = c.Close() |
| 393 | return 0, ErrGateClosed |
| 394 | } |
| 395 | return c.Conn.Read(b) |
| 396 | } |
| 397 | func (c *gateConn) Write(b []byte) (int, error) { |
| 398 | if !c.valid() { |
| 399 | _ = c.Close() |
| 400 | return 0, ErrGateClosed |
| 401 | } |
| 402 | return c.Conn.Write(b) |
| 403 | } |
| 404 | func (c *gateConn) Close() error { |
| 405 | var err error |
| 406 | c.once.Do(func() { |
| 407 | _ = c.Conn.SetDeadline(time.Now()) |
| 408 | err = c.Conn.Close() |
| 409 | c.gate.mu.Lock() |
| 410 | delete(c.gate.connections, c) |
| 411 | c.gate.mu.Unlock() |
| 412 | }) |
| 413 | return err |
| 414 | } |
| 415 | |
| 416 | type unavailableProxy struct{} |
| 417 | |
| 418 | func (unavailableProxy) Dial(string, string) (net.Conn, error) { |
| 419 | return nil, errors.New("proxy outage drill") |
| 420 | } |
| 421 | func (unavailableProxy) DialContext(context.Context, string, string) (net.Conn, error) { |
| 422 | return nil, errors.New("proxy outage drill") |
| 423 | } |