fix(sandbox,traffic): keep sandbox command output and free scan dial slots

Docker exec no longer wraps commands in setsid, which exited immediately and cut stdout after about two seconds. Netstack releases the pending-dial slot once the handshake finishes, raises the in-flight limits, and treats local file-descriptor exhaustion as a silent drop. The gateway container gets a higher open-file limit.
This commit is contained in:
ji ruo committed 2026-12-02 17:45:28 +08:00
1 parent ee5ac6e6dd
commit 8bac4960e7
6 files changed
+346 -24

No files matched your search

+202
View File
@@ -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)
}