diff --git a/docker-compose.yml b/docker-compose.yml index 3085858..4905162 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -131,6 +131,10 @@ services: ARTEX_GATEWAY_UDP_PORT: ${ARTEX_GATEWAY_UDP_PORT:-15002} ARTEX_GATEWAY_DNS_PORT: ${ARTEX_GATEWAY_DNS_PORT:-15053} ARTEX_GATEWAY_APPLY_IPTABLES: ${ARTEX_GATEWAY_APPLY_IPTABLES:-true} + ulimits: + nofile: + soft: 65536 + hard: 65536 mem_limit: 256m pids_limit: 128 restart: unless-stopped diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go index 5ed2326..7d4827d 100644 --- a/internal/sandbox/manager.go +++ b/internal/sandbox/manager.go @@ -1192,10 +1192,7 @@ func (m *Manager) Exec(ctx context.Context, t Target, spec ExecSpec) ExecResult var pgidFile string if spec.KillOnAbort && len(cmd) > 0 { pgidFile = "/tmp/.artex-pgid-" + randomToken(8) - // Wrap in a new session (setsid) recording its PGID so timeout/cancel - // can kill the entire child process tree inside the container. - wrapped := fmt.Sprintf(`echo $$ > %q; trap 'rm -f %q' EXIT; exec "$@"`, pgidFile, pgidFile) - cmd = append([]string{"setsid", "sh", "-c", wrapped, "--"}, spec.Cmd...) + cmd = wrapPGIDCommand(pgidFile, spec.Cmd) } execID, err := m.docker.ExecCreate(runCtx, containerID, dockerExecCreateReq{ @@ -1271,10 +1268,19 @@ func (m *Manager) Exec(ctx context.Context, t Target, spec ExecSpec) ExecResult if !timedOut && ctx.Err() == nil { inspectCtx, icancel := context.WithTimeout(context.Background(), 5*time.Second) defer icancel() - if info, ierr := m.docker.ExecInspect(inspectCtx, execID); ierr == nil { - res.ExitCode = info.ExitCode - if info.ExitCode != 0 && res.Err == nil { - res.Err = fmt.Errorf("exit status %d", info.ExitCode) + if info, ierr := m.waitExecInspect(inspectCtx, execID); ierr == nil { + if info.Running { + if pgidFile != "" { + m.killProcessGroup(containerID, pgidFile) + } + if res.Err == nil { + res.Err = errors.New("sandbox exec stream closed prematurely while command was still running") + } + } else { + res.ExitCode = info.ExitCode + if info.ExitCode != 0 && res.Err == nil { + res.Err = fmt.Errorf("exit status %d", info.ExitCode) + } } } } @@ -1304,8 +1310,7 @@ func (m *Manager) ExecStream(ctx context.Context, t Target, spec ExecSpec) (*Str } pgidFile := "/tmp/.artex-stream-" + randomToken(8) - wrapped := fmt.Sprintf(`echo $$ > %q; trap 'rm -f %q' EXIT; exec "$@"`, pgidFile, pgidFile) - cmd := append([]string{"setsid", "sh", "-c", wrapped, "--"}, spec.Cmd...) + cmd := wrapPGIDCommand(pgidFile, spec.Cmd) execID, err := m.docker.ExecCreate(ctx, containerID, dockerExecCreateReq{ AttachStdin: true, @@ -1359,6 +1364,41 @@ func (m *Manager) ExecStream(ctx context.Context, t Target, spec ExecSpec) (*Str }, nil } +// wrapPGIDCommand records the exec process PID before replacing the shell with +// the target command. Docker's runc already places every exec process into its +// own session and process group (PID == PGID == SID), so we must NOT invoke +// util-linux `setsid` (which without `--wait` forks when PID == PGID and exits +// 0 immediately, causing containerd to cut off stdout/stderr at ~2s and masking +// non-zero exit codes). +func wrapPGIDCommand(pgidFile string, cmd []string) []string { + wrapped := fmt.Sprintf(`echo $$ > %q; exec "$@"`, pgidFile) + return append([]string{"sh", "-c", wrapped, "--"}, cmd...) +} + +// waitExecInspect polls Docker ExecInspect briefly after the stdio stream closes +// so containerd's final Running->false transition settles before reading ExitCode. +func (m *Manager) waitExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) { + var ( + info dockerExecInspect + err error + ) + backoffs := []time.Duration{0, 15 * time.Millisecond, 40 * time.Millisecond, 100 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond} + for _, d := range backoffs { + if d > 0 { + select { + case <-ctx.Done(): + return info, ctx.Err() + case <-time.After(d): + } + } + info, err = m.docker.ExecInspect(ctx, execID) + if err != nil || !info.Running { + return info, err + } + } + return info, err +} + type hijackedWriteCloser struct { h *hijackedExec } diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index e4d26e0..157125a 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -3,8 +3,12 @@ package sandbox import ( "bytes" "encoding/binary" + "errors" "os" + "os/exec" "path/filepath" + "runtime" + "strings" "testing" ) @@ -224,3 +228,27 @@ func TestEnsureWritableDirMigratesNestedFilesWithoutFollowingSymlinks(t *testing t.Fatalf("symlink target outside workspace must stay 0400, got %o", outInfo.Mode().Perm()) } } + +func TestWrapPGIDCommandDoesNotDetachAndPropagatesExitCode(t *testing.T) { + pgidFile := filepath.Join(t.TempDir(), "test.pgid") + cmd := wrapPGIDCommand(pgidFile, []string{"sh", "-c", "echo hi; exit 42"}) + if len(cmd) == 0 || cmd[0] == "setsid" { + t.Fatalf("wrapPGIDCommand must not wrap with detaching setsid, got %v", cmd) + } + if runtime.GOOS == "windows" { + return + } + c := exec.Command(cmd[0], cmd[1:]...) + out, err := c.CombinedOutput() + if strings.TrimSpace(string(out)) != "hi" { + t.Fatalf("expected output 'hi', got %q (err=%v)", string(out), err) + } + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 42 { + t.Fatalf("expected exit code 42, got err=%v", err) + } + pidBytes, rerr := os.ReadFile(pgidFile) + if rerr != nil || strings.TrimSpace(string(pidBytes)) == "" { + t.Fatalf("expected pgid file to contain PID, got %q err=%v", string(pidBytes), rerr) + } +} diff --git a/traffic/netstack.go b/traffic/netstack.go index 9959769..2ae8576 100644 --- a/traffic/netstack.go +++ b/traffic/netstack.go @@ -34,9 +34,9 @@ import ( const ( netstackNICID tcpip.NICID = 1 netstackDefaultMTU uint32 = 1500 - netstackMaxInFlightTCP = 1024 - netstackMaxPendingDials = 512 - netstackDefaultDialTTL = 5 * time.Second + netstackMaxInFlightTCP = 8192 + netstackMaxPendingDials = 4096 + netstackDefaultDialTTL = 2500 * time.Millisecond ) // NetstackConfig configures the gVisor user-space TCP/IP stack attached to a @@ -331,20 +331,29 @@ func (n *NetstackGateway) handleTCPForward(r *tcp.ForwarderRequest) { dstPort := int(id.LocalPort) // Guard against SYN flood / full-port-scan goroutine exhaustion. + // Drop silently (sendReset=false) when saturated so scanners back off and + // retry instead of falsely classifying open/filtered ports as "closed". select { case n.dialCh <- struct{}{}: default: - r.Complete(true) + r.Complete(false) return } go func() { - defer func() { <-n.dialCh }() - n.processTCPForward(r, srcIP, srcPort, dstIP, dstPort) + released := false + releaseSlot := func() { + if !released { + released = true + <-n.dialCh + } + } + defer releaseSlot() + n.processTCPForward(r, srcIP, srcPort, dstIP, dstPort, releaseSlot) }() } -func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP string, srcPort int, dstIP string, dstPort int) { +func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP string, srcPort int, dstIP string, dstPort int, releaseDialSlot func()) { start := time.Now() src := n.backend.ResolveSource(srcIP) if src.SrcIP == "" { @@ -381,13 +390,22 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin dialTarget = targetHostPort } - dialCtx, cancel := context.WithTimeout(n.ctx, n.cfg.DialTimeout) + dialTimeout := n.cfg.DialTimeout + if upstream != nil && dialTimeout < 5*time.Second { + dialTimeout = 5 * time.Second + } + dialCtx, cancel := context.WithTimeout(n.ctx, dialTimeout) dialFn := n.cfg.DialFunc if dialFn == nil { dialFn = dialTCPThroughUpstream } - dstConn, err := dialFn(dialCtx, upstream, dialTarget, n.cfg.DialTimeout) + dstConn, err := dialFn(dialCtx, upstream, dialTarget, dialTimeout) cancel() + // Dial phase finished: free the pending-dial slot immediately so long-lived + // established connections do not starve new outbound dials or port scans. + if releaseDialSlot != nil { + releaseDialSlot() + } if err != nil { // Distinguish closed/refused (send RST -> nmap "closed") from timeout/drop // (drop silently -> nmap "filtered"). @@ -421,6 +439,28 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin r.Complete(false) if tcpErr != nil { _ = dstConn.Close() + // Remote TCP handshake genuinely succeeded (e.g. nmap -sT received SYN-ACK, + // sent ACK, and immediately sent RST before CreateEndpoint returned). Record + // the allowed flow so open-port scan hits are visible in net_flows. + end := time.Now() + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: "tcp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "allow", + UpstreamProxy: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) return } rawClientConn := gonet.NewTCPConn(&wq, ep) @@ -1051,7 +1091,11 @@ func isDialTimeoutErr(err error) bool { if err == nil { return false } - if errors.Is(err, context.DeadlineExceeded) || os.IsTimeout(err) { + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || os.IsTimeout(err) { + return true + } + // Local gateway resource exhaustion must never synthesize a remote RST ("closed"). + if errors.Is(err, syscall.EMFILE) || errors.Is(err, syscall.ENFILE) || errors.Is(err, syscall.EADDRNOTAVAIL) { return true } var ne net.Error diff --git a/traffic/netstack_test.go b/traffic/netstack_test.go index 834081b..76bcb5b 100644 --- a/traffic/netstack_test.go +++ b/traffic/netstack_test.go @@ -646,3 +646,205 @@ func TestProcessDNSQueryToTargetUnderUpstreamProxyNeverSubstitutesHostDNS(t *tes t.Fatalf("expected proxy CONNECT to targetServer 47.116.200.74:53 (not host DNSUpstream), got %v", got) } } + +func buildIPv4TCPPacket(srcIP, dstIP net.IP, srcPort, dstPort uint16, seq, ack uint32, flags header.TCPFlags) []byte { + const ipLen = header.IPv4MinimumSize + const tcpLen = header.TCPMinimumSize + pkt := make([]byte, ipLen+tcpLen) + + ip := header.IPv4(pkt[:ipLen]) + ip.Encode(&header.IPv4Fields{ + TotalLength: uint16(len(pkt)), + ID: 2, + TTL: 64, + Protocol: uint8(header.TCPProtocolNumber), + SrcAddr: header.IPv4(pkt).SourceAddress(), + }) + copy(pkt[12:16], srcIP.To4()) + copy(pkt[16:20], dstIP.To4()) + ip.SetChecksum(0) + ip.SetChecksum(^ip.CalculateChecksum()) + + tcpHdr := header.TCP(pkt[ipLen:]) + binary.BigEndian.PutUint16(tcpHdr[0:2], srcPort) + binary.BigEndian.PutUint16(tcpHdr[2:4], dstPort) + binary.BigEndian.PutUint32(tcpHdr[4:8], seq) + binary.BigEndian.PutUint32(tcpHdr[8:12], ack) + tcpHdr[12] = (tcpLen / 4) << 4 + tcpHdr[13] = uint8(flags) + binary.BigEndian.PutUint16(tcpHdr[14:16], 65535) + + xsum := header.PseudoHeaderChecksum(header.TCPProtocolNumber, ip.SourceAddress(), ip.DestinationAddress(), uint16(tcpLen)) + xsum = checksum.Checksum(tcpHdr, xsum) + tcpHdr.SetChecksum(^xsum) + return pkt +} + +func TestNetstackDialSaturationDropsSilentlyAndReleasesSlotAfterDial(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // An open listener that holds connections open until test ends. + openLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen open: %v", err) + } + defer openLn.Close() + go func() { + for { + c, err := openLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + _, _ = io.Copy(io.Discard, conn) + }(c) + } + }() + openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) + + releaseSlowDial := make(chan struct{}) + defer close(releaseSlowDial) + slowStarted := make(chan struct{}, 2) + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 2 * time.Second, + PeekTimeout: 50 * time.Millisecond, + MaxPendingDials: 1, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + if target == fmt.Sprintf("203.0.113.10:%d", openPort) { + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) + } + if target == "203.0.113.20:80" { + select { + case slowStarted <- struct{}{}: + default: + } + select { + case <-releaseSlowDial: + return nil, context.DeadlineExceeded + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return nil, syscall.ECONNREFUSED + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + // 1. Occupy the single pending-dial slot with a slow filtered target. + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.20"), 46001, 80, 100) + select { + case <-slowStarted: + case <-time.After(time.Second): + t.Fatal("timed out waiting for slow dial to start") + } + + // 2. While saturated, send another SYN -> MUST drop silently (NO synthetic RST). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 46002, openPort, 200) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + t.Fatalf("saturated dialCh must drop silently without synthetic RST, got tcp=%v flags=%v", ok, flags) + case <-time.After(250 * time.Millisecond): + } +} + +func TestNetstackQuickRSTAfterOpenHandshakeStillRecordsNetFlow(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "task", OwnerID: "3", ContainerID: "sbx3", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + + // Silent open server (does not close until peer closes, like SSH waiting for client). + openLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen open: %v", err) + } + defer openLn.Close() + go func() { + for { + c, err := openLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + _, _ = io.Copy(io.Discard, conn) + }(c) + } + }() + openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 500 * time.Millisecond, + PeekTimeout: 50 * time.Millisecond, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + if target == fmt.Sprintf("203.0.113.74:%d", openPort) { + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) + } + return nil, syscall.ECONNREFUSED + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + srcIP := net.ParseIP("172.30.0.3") + dstIP := net.ParseIP("203.0.113.74") + const clientPort uint16 = 47001 + const clientISN uint32 = 5000 + + // Simulate nmap -sT: SYN -> receive SYN-ACK -> immediately send ACK + RST. + pipe.in <- buildIPv4TCPSYN(srcIP, dstIP, clientPort, openPort, clientISN) + var srvSeq uint32 + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + if !ok || !flags.Contains(header.TCPFlagSyn|header.TCPFlagAck) { + t.Fatalf("expected SYN-ACK for open port, got ok=%v flags=%v", ok, flags) + } + ip := header.IPv4(pkt) + tcpHdr := header.TCP(pkt[ip.HeaderLength():]) + srvSeq = tcpHdr.SequenceNumber() + case <-time.After(time.Second): + t.Fatal("timed out waiting for SYN-ACK") + } + + pipe.in <- buildIPv4TCPPacket(srcIP, dstIP, clientPort, openPort, clientISN+1, srvSeq+1, header.TCPFlagAck) + pipe.in <- buildIPv4TCPPacket(srcIP, dstIP, clientPort, openPort, clientISN+1, srvSeq+1, header.TCPFlagRst|header.TCPFlagAck) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + flows, total, err := tr.PageNetFlows(NetFlowQuery{Protocol: "tcp", Action: "allow"}, 0, 10) + if err == nil && total >= 1 { + for _, f := range flows { + if f.DstIP == "203.0.113.74" && f.DstPort == int(openPort) && f.SandboxOwnerID == "3" { + return + } + } + } + time.Sleep(25 * time.Millisecond) + } + flows, total, _ := tr.PageNetFlows(NetFlowQuery{}, 0, 10) + t.Fatalf("expected allow net_flow for quick-RST nmap -sT hit, got total=%d flows=%+v", total, flows) +} diff --git a/traffic/transparent.go b/traffic/transparent.go index 36fdae1..98038e1 100644 --- a/traffic/transparent.go +++ b/traffic/transparent.go @@ -581,17 +581,21 @@ func (g *TransparentGateway) relayConnectedL4TCP( wg.Add(2) go func() { defer wg.Done() - n, _ := io.Copy(io.MultiWriter(dstConn, txCap), clientConn) + n, err := io.Copy(io.MultiWriter(dstConn, txCap), clientConn) bytesTX = n - if cw, ok := dstConn.(interface{ CloseWrite() error }); ok { + if err != nil { + _ = dstConn.Close() + } else if cw, ok := dstConn.(interface{ CloseWrite() error }); ok { _ = cw.CloseWrite() } }() go func() { defer wg.Done() - n, _ := io.Copy(io.MultiWriter(clientConn, rxCap), dstConn) + n, err := io.Copy(io.MultiWriter(clientConn, rxCap), dstConn) bytesRX = n - if cw, ok := clientConn.(interface{ CloseWrite() error }); ok { + if err != nil { + _ = clientConn.Close() + } else if cw, ok := clientConn.(interface{ CloseWrite() error }); ok { _ = cw.CloseWrite() } }()