package egress import ( "bufio" "bytes" "context" "io" "net" "net/http" "net/netip" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "golang.org/x/sys/unix" ) const ( MaxHeaders = 8 * 1024 MaxTunnels = 16 ConnectTimeout = 15 * time.Second IdleTimeout = 60 * time.Second NamespaceSocket = "/egress/proxy.sock" RelayAddress = "127.0.0.1:18080" ProxyURL = "http://127.0.0.1:18080" ) type dependencies struct { lookup func(context.Context, string) ([]netip.Addr, error) dial func(context.Context, string, string) (net.Conn, error) connect, idle time.Duration } func defaults() dependencies { return dependencies{ lookup: func(ctx context.Context, host string) ([]netip.Addr, error) { return net.DefaultResolver.LookupNetIP(ctx, "ip", host) }, dial: (&net.Dialer{}).DialContext, connect: ConnectTimeout, idle: IdleTimeout, } } type Proxy struct { denials atomic.Uint64 listener net.Listener directory *os.File path string hosts map[string]bool deps dependencies ctx context.Context cancel context.CancelFunc done chan struct{} once sync.Once mu sync.Mutex closed bool clients map[net.Conn]struct{} upstreams map[net.Conn]struct{} wg sync.WaitGroup } // Open requires an existing private, symlink-free directory owned by the runner. // It creates no TCP listener. Each attempt must have a different directory. func Open(ctx context.Context, dir string, policy Policy) (*Proxy, error) { return open(ctx, dir, policy, defaults()) } func open(ctx context.Context, dir string, policy Policy, d dependencies) (*Proxy, error) { if _, e := policy.Hash(); e != nil { return nil, e } if e := ctx.Err(); e != nil { return nil, e } if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { return nil, errPolicy } fd, e := openDirNoLinks(dir) if e != nil { return nil, e } directory := os.NewFile(uintptr(fd), dir) defer func() { if directory != nil { directory.Close() } }() var st unix.Stat_t if e = unix.Fstat(fd, &st); e != nil { return nil, e } if st.Mode&0777 != 0700 || st.Uid != uint32(os.Geteuid()) { return nil, errPolicy } path := filepath.Join(dir, "proxy.sock") // Bind and chmod through the verified directory. Keep its descriptor until // listener.Close unlinks the socket, even if the directory has been renamed. bindPath := "/proc/self/fd/" + strconv.Itoa(fd) + "/proxy.sock" ln, e := net.Listen("unix", bindPath) if e != nil { return nil, e } if e = os.Chmod(bindPath, 0600); e != nil { ln.Close() return nil, e } ctx, cancel := context.WithCancel(ctx) p := &Proxy{listener: ln, directory: directory, path: path, hosts: map[string]bool{}, deps: d, ctx: ctx, cancel: cancel, done: make(chan struct{}), clients: map[net.Conn]struct{}{}, upstreams: map[net.Conn]struct{}{}} directory = nil for _, h := range policy.Hosts { p.hosts[h] = true } p.wg.Add(1) go p.serve() go func() { select { case <-ctx.Done(): p.shutdown() case <-p.done: } }() return p, nil } func (p *Proxy) Denials() uint64 { return p.denials.Load() } func (p *Proxy) SocketPath() string { return p.path } // Done closes on endpoint loss, cancellation or Close. Owners stop the attempt. func (p *Proxy) Done() <-chan struct{} { return p.done } func (p *Proxy) shutdown() { p.once.Do(func() { p.mu.Lock() p.closed = true p.cancel() p.listener.Close() p.directory.Close() for c := range p.clients { c.Close() } for c := range p.upstreams { c.Close() } p.mu.Unlock() close(p.done) }) } func (p *Proxy) Close() error { p.shutdown(); p.wg.Wait(); return nil } func (p *Proxy) active() int { p.mu.Lock(); defer p.mu.Unlock(); return len(p.clients) } func (p *Proxy) serve() { defer p.wg.Done() defer p.shutdown() for { c, e := p.listener.Accept() if e != nil { return } p.mu.Lock() if p.closed || len(p.clients) >= MaxTunnels { p.mu.Unlock() c.Close() continue } p.clients[c] = struct{}{} p.wg.Add(1) p.mu.Unlock() go func() { defer p.wg.Done() defer func() { c.Close(); p.mu.Lock(); delete(p.clients, c); p.mu.Unlock() }() p.handle(c) }() } } // Read exactly one bounded CONNECT header. No HTTP request is forwarded to the // destination. Framing headers and queued requests are rejected before dialing. func authority(r *bufio.Reader) (string, error) { data := make([]byte, 0, MaxHeaders) for len(data) < MaxHeaders { b, e := r.ReadByte() if e != nil { return "", e } data = append(data, b) if bytes.HasSuffix(data, []byte("\r\n\r\n")) { break } } if !bytes.HasSuffix(data, []byte("\r\n\r\n")) || r.Buffered() != 0 { return "", errPolicy } lines := strings.Split(string(data), "\r\n") first := strings.Split(lines[0], " ") if len(first) != 3 || first[0] != "CONNECT" || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") { return "", errPolicy } host, port, e := net.SplitHostPort(first[1]) if e != nil || port != "443" || !hostname(host) { return "", errPolicy } seen := map[string]bool{} for _, line := range lines[1 : len(lines)-2] { key, value, ok := strings.Cut(line, ":") key = strings.ToLower(key) if !ok || seen[key] { return "", errPolicy } seen[key] = true switch key { case "host": // The authority itself, or (Node's fetch) its host alone, // which names the default port 443. if v := strings.TrimSpace(value); v != first[1] && v != host { return "", errPolicy } case "user-agent", "proxy-connection", "connection": default: return "", errPolicy } } req, e := http.ReadRequest(bufio.NewReader(bytes.NewReader(data))) if e != nil { return "", errPolicy } req.Body.Close() return host, nil } func (p *Proxy) handle(c net.Conn) { c.SetDeadline(time.Now().Add(p.deps.connect)) r := bufio.NewReaderSize(c, MaxHeaders+1) host, e := authority(r) if e != nil || !p.hosts[host] { p.denials.Add(1) io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n") return } ctx, cancel := context.WithTimeout(p.ctx, p.deps.connect) defer cancel() if upstreamOverride != nil { if to, ok := upstreamOverride(host); ok { p.tunnelTo(ctx, c, to) return } } addresses, e := p.deps.lookup(ctx, host) if e != nil || len(addresses) == 0 { io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n") return } // Reject the whole answer if any address is unsafe. Never resolve again in Dial. for _, a := range addresses { if !publicAddress(a) { p.denials.Add(1) io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n") return } } upstream, e := p.deps.dial(ctx, "tcp", net.JoinHostPort(addresses[0].Unmap().String(), "443")) if e != nil { io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n") return } defer upstream.Close() p.mu.Lock() if p.closed { p.mu.Unlock() return } p.upstreams[upstream] = struct{}{} p.mu.Unlock() defer func() { p.mu.Lock(); delete(p.upstreams, upstream); p.mu.Unlock() }() if _, e = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n"); e != nil { return } Tunnel(c, upstream, p.deps.idle) } // upstreamOverride is nil in every build but a test build // (proxy_testbuild.go), where it sends an allowed host's tunnels to a fake // provider on a loopback address instead of resolving the host. var upstreamOverride func(host string) (string, bool) // tunnelTo carries a test build's tunnel to a loopback upstream. func (p *Proxy) tunnelTo(ctx context.Context, c net.Conn, to string) { upstream, e := p.deps.dial(ctx, "tcp", to) if e != nil { io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n") return } defer upstream.Close() if _, e = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n"); e != nil { return } Tunnel(c, upstream, p.deps.idle) } // Tunnel copies opaque TLS bytes. Traffic in either direction renews the idle // deadline for both sockets; closing either side releases both copying goroutines. func Tunnel(a, b net.Conn, idle time.Duration) { touch := func() { deadline := time.Now().Add(idle); a.SetDeadline(deadline); b.SetDeadline(deadline) } touch() copyTo := func(dst, src net.Conn) { buffer := make([]byte, 32*1024) for { n, e := src.Read(buffer) if n > 0 { touch() if _, writeErr := dst.Write(buffer[:n]); writeErr != nil { return } } if e != nil { return } } } done := make(chan struct{}) go func() { defer close(done); copyTo(a, b); a.Close(); b.Close() }() copyTo(b, a) a.Close() b.Close() <-done }