mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-03 04:11:51 +08:00
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.
1379 lines
41 KiB
Go
1379 lines
41 KiB
Go
package traffic
|
||
|
||
import (
|
||
"context"
|
||
"encoding/binary"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"log"
|
||
"net"
|
||
"net/url"
|
||
"os"
|
||
"strconv"
|
||
"strings"
|
||
"sync"
|
||
"sync/atomic"
|
||
"syscall"
|
||
"time"
|
||
"github.com/miekg/dns"
|
||
"gvisor.dev/gvisor/pkg/buffer"
|
||
"gvisor.dev/gvisor/pkg/tcpip"
|
||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
|
||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
||
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
||
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
||
"gvisor.dev/gvisor/pkg/waiter"
|
||
)
|
||
|
||
const (
|
||
netstackNICID tcpip.NICID = 1
|
||
netstackDefaultMTU uint32 = 1500
|
||
netstackMaxInFlightTCP = 8192
|
||
netstackMaxPendingDials = 4096
|
||
netstackDefaultDialTTL = 2500 * time.Millisecond
|
||
)
|
||
|
||
// NetstackConfig configures the gVisor user-space TCP/IP stack attached to a
|
||
// TUN device (or in-memory packet pipe in tests).
|
||
type NetstackConfig struct {
|
||
MTU uint32
|
||
MITMProxyAddr string
|
||
PeekTimeout time.Duration
|
||
DialTimeout time.Duration
|
||
MaxPendingDials int
|
||
// Optional L3 anti-spoofing guard: when set, drop inbound IPv4 packets whose
|
||
// source IP is outside AllowedSrcCIDR or matches any DeniedSrcIPs entry.
|
||
AllowedSrcCIDR string
|
||
DeniedSrcIPs []string
|
||
// Optional hooks for unit tests to override upstream TCP dialing / ICMP echo.
|
||
DialFunc func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error)
|
||
ICMPPingFunc func(ctx context.Context, dstIP net.IP, seq uint16, payload []byte) ([]byte, error)
|
||
}
|
||
|
||
// NetstackGateway implements full-traffic transparent interception over a TUN
|
||
// interface using gVisor netstack with DEFERRED TCP HANDSHAKES:
|
||
//
|
||
// - On incoming TCP SYN, no SYN-ACK is sent until SSRF/blacklist checks pass
|
||
// AND the real remote target (or upstream proxy) accepts the connection.
|
||
// - Remote ECONNREFUSED => sends genuine TCP RST (nmap reports "closed").
|
||
// - Remote dial timeout => silently drops SYN (nmap reports "filtered").
|
||
// - Remote dial success => completes 3-way handshake (nmap reports "open"),
|
||
// sniffs HTTP/TLS for go-mitmproxy MITM decryption, or reuses the already
|
||
// established remote socket directly for raw TCP L4 relay + net_flows capture.
|
||
// - External TCP/53 => uses the same deferred handshake to the real dstIP:53,
|
||
// then inspects/logs DNS-over-TCP frames (never hijacked to host DNS).
|
||
// - External UDP/53 => forwarded to dstIP:53 (or via upstream proxy to dstIP:53).
|
||
// - Non-DNS UDP => subject to SSRF/blacklist and OPSEC UDPPolicy + net_flows.
|
||
type NetstackGateway struct {
|
||
cfg NetstackConfig
|
||
gw *TransparentGateway
|
||
backend TransparentBackend
|
||
|
||
allowedNet *net.IPNet
|
||
deniedSrcIP map[string]struct{}
|
||
|
||
dev io.ReadWriteCloser
|
||
ep *channel.Endpoint
|
||
stk *stack.Stack
|
||
dialCh chan struct{}
|
||
icmpID atomic.Uint32
|
||
|
||
ctx context.Context
|
||
cancel context.CancelFunc
|
||
wg sync.WaitGroup
|
||
}
|
||
|
||
// NewNetstackGateway creates a gVisor netstack gateway reading/writing raw L3
|
||
// IP packets on dev (a Linux TUN fd or test packet pipe).
|
||
func NewNetstackGateway(dev io.ReadWriteCloser, cfg NetstackConfig, backend TransparentBackend) (*NetstackGateway, error) {
|
||
if dev == nil {
|
||
return nil, errors.New("netstack device is nil")
|
||
}
|
||
if cfg.MTU == 0 {
|
||
cfg.MTU = netstackDefaultMTU
|
||
}
|
||
if cfg.PeekTimeout <= 0 {
|
||
cfg.PeekTimeout = 200 * time.Millisecond
|
||
}
|
||
if cfg.DialTimeout <= 0 {
|
||
cfg.DialTimeout = netstackDefaultDialTTL
|
||
}
|
||
if cfg.MaxPendingDials <= 0 {
|
||
cfg.MaxPendingDials = netstackMaxPendingDials
|
||
}
|
||
|
||
ep := channel.New(2048, cfg.MTU, "")
|
||
s := stack.New(stack.Options{
|
||
NetworkProtocols: []stack.NetworkProtocolFactory{
|
||
ipv4.NewProtocol,
|
||
ipv6.NewProtocol,
|
||
},
|
||
TransportProtocols: []stack.TransportProtocolFactory{
|
||
tcp.NewProtocol,
|
||
udp.NewProtocol,
|
||
icmp.NewProtocol4,
|
||
icmp.NewProtocol6,
|
||
},
|
||
})
|
||
|
||
sackOpt := tcpip.TCPSACKEnabled(true)
|
||
_ = s.SetTransportProtocolOption(tcp.ProtocolNumber, &sackOpt)
|
||
|
||
if err := s.CreateNIC(netstackNICID, ep); err != nil {
|
||
return nil, fmt.Errorf("netstack create NIC: %v", err)
|
||
}
|
||
if err := s.SetPromiscuousMode(netstackNICID, true); err != nil {
|
||
s.Destroy()
|
||
return nil, fmt.Errorf("netstack set promiscuous: %v", err)
|
||
}
|
||
if err := s.SetSpoofing(netstackNICID, true); err != nil {
|
||
s.Destroy()
|
||
return nil, fmt.Errorf("netstack set spoofing: %v", err)
|
||
}
|
||
s.SetRouteTable([]tcpip.Route{
|
||
{Destination: header.IPv4EmptySubnet, NIC: netstackNICID},
|
||
{Destination: header.IPv6EmptySubnet, NIC: netstackNICID},
|
||
})
|
||
|
||
var allowedNet *net.IPNet
|
||
if cidr := strings.TrimSpace(cfg.AllowedSrcCIDR); cidr != "" {
|
||
if _, parsed, err := net.ParseCIDR(cidr); err == nil {
|
||
allowedNet = parsed
|
||
}
|
||
}
|
||
deniedSrc := make(map[string]struct{}, len(cfg.DeniedSrcIPs))
|
||
for _, raw := range cfg.DeniedSrcIPs {
|
||
if ip := normalizeIPString(raw); ip != "" {
|
||
deniedSrc[ip] = struct{}{}
|
||
}
|
||
}
|
||
|
||
ctx, cancel := context.WithCancel(context.Background())
|
||
ng := &NetstackGateway{
|
||
cfg: cfg,
|
||
gw: NewTransparentGateway(TransparentConfig{
|
||
MITMProxyAddr: cfg.MITMProxyAddr,
|
||
PeekTimeout: cfg.PeekTimeout,
|
||
DialTimeout: cfg.DialTimeout,
|
||
}, backend),
|
||
backend: backend,
|
||
allowedNet: allowedNet,
|
||
deniedSrcIP: deniedSrc,
|
||
dev: dev,
|
||
ep: ep,
|
||
stk: s,
|
||
dialCh: make(chan struct{}, cfg.MaxPendingDials),
|
||
ctx: ctx,
|
||
cancel: cancel,
|
||
}
|
||
tcpFwd := tcp.NewForwarder(s, 0, netstackMaxInFlightTCP, ng.handleTCPForward)
|
||
s.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpFwd.HandlePacket)
|
||
|
||
udpFwd := udp.NewForwarder(s, ng.handleUDPForward)
|
||
s.SetTransportProtocolHandler(udp.ProtocolNumber, udpFwd.HandlePacket)
|
||
|
||
return ng, nil
|
||
}
|
||
|
||
// Start begins pumping L3 IP packets between the TUN device and gVisor netstack.
|
||
func (n *NetstackGateway) Start() {
|
||
n.wg.Add(2)
|
||
go func() {
|
||
defer n.wg.Done()
|
||
n.pumpInbound()
|
||
}()
|
||
go func() {
|
||
defer n.wg.Done()
|
||
n.pumpOutbound()
|
||
}()
|
||
}
|
||
|
||
// Close tears down the TUN packet pumps and gVisor stack.
|
||
func (n *NetstackGateway) Close() error {
|
||
n.cancel()
|
||
_ = n.dev.Close()
|
||
n.ep.Close()
|
||
n.stk.Destroy()
|
||
_ = n.gw.Close()
|
||
n.wg.Wait()
|
||
return nil
|
||
}
|
||
|
||
func (n *NetstackGateway) pumpInbound() {
|
||
buf := make([]byte, int(n.cfg.MTU)+64)
|
||
var lastErrLog time.Time
|
||
for {
|
||
nr, err := n.dev.Read(buf)
|
||
if err != nil {
|
||
select {
|
||
case <-n.ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
if errors.Is(err, io.EOF) {
|
||
return
|
||
}
|
||
if time.Since(lastErrLog) > 5*time.Second {
|
||
log.Printf("[netstack] tun read error: %v", err)
|
||
lastErrLog = time.Now()
|
||
}
|
||
time.Sleep(25 * time.Millisecond)
|
||
continue
|
||
}
|
||
if nr < 1 {
|
||
continue
|
||
}
|
||
var proto tcpip.NetworkProtocolNumber
|
||
var isIPv4Echo bool
|
||
switch header.IPVersion(buf[:nr]) {
|
||
case header.IPv4Version:
|
||
if nr < header.IPv4MinimumSize {
|
||
continue
|
||
}
|
||
ip4 := header.IPv4(buf[:nr])
|
||
if n.allowedNet != nil || len(n.deniedSrcIP) > 0 {
|
||
srcAddr := ip4.SourceAddress()
|
||
srcIP := net.IP(srcAddr.AsSlice())
|
||
if n.allowedNet != nil && !n.allowedNet.Contains(srcIP) {
|
||
continue
|
||
}
|
||
if _, denied := n.deniedSrcIP[srcIP.String()]; denied {
|
||
continue
|
||
}
|
||
}
|
||
ihl := int(ip4.HeaderLength())
|
||
if ip4.Protocol() == uint8(header.ICMPv4ProtocolNumber) && ihl >= header.IPv4MinimumSize && nr >= ihl+header.ICMPv4MinimumSize {
|
||
if header.ICMPv4(buf[ihl:nr]).Type() == header.ICMPv4Echo {
|
||
isIPv4Echo = true
|
||
}
|
||
}
|
||
proto = header.IPv4ProtocolNumber
|
||
case header.IPv6Version:
|
||
if nr < header.IPv6MinimumSize {
|
||
continue
|
||
}
|
||
if n.allowedNet != nil || len(n.deniedSrcIP) > 0 {
|
||
srcAddr := header.IPv6(buf[:nr]).SourceAddress()
|
||
srcIP := net.IP(srcAddr.AsSlice())
|
||
if n.allowedNet != nil && !n.allowedNet.Contains(srcIP) {
|
||
continue
|
||
}
|
||
if _, denied := n.deniedSrcIP[srcIP.String()]; denied {
|
||
continue
|
||
}
|
||
}
|
||
proto = header.IPv6ProtocolNumber
|
||
default:
|
||
continue
|
||
}
|
||
pktData := make([]byte, nr)
|
||
copy(pktData, buf[:nr])
|
||
if isIPv4Echo {
|
||
// Intercept ICMPv4 Echo BEFORE gVisor's promiscuous stack can synthesize
|
||
// a fake local Echo Reply for dead or blocked targets.
|
||
select {
|
||
case n.dialCh <- struct{}{}:
|
||
go func(raw []byte) {
|
||
defer func() { <-n.dialCh }()
|
||
n.handleICMPv4Echo(raw)
|
||
}(pktData)
|
||
default:
|
||
}
|
||
continue
|
||
}
|
||
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||
Payload: buffer.MakeWithData(pktData),
|
||
})
|
||
n.ep.InjectInbound(proto, pkt)
|
||
pkt.DecRef()
|
||
}
|
||
}
|
||
|
||
func (n *NetstackGateway) pumpOutbound() {
|
||
var lastErrLog time.Time
|
||
for {
|
||
pkt := n.ep.ReadContext(n.ctx)
|
||
if pkt == nil {
|
||
return
|
||
}
|
||
view := pkt.ToView()
|
||
_, err := n.dev.Write(view.AsSlice())
|
||
view.Release()
|
||
pkt.DecRef()
|
||
if err != nil {
|
||
select {
|
||
case <-n.ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
if time.Since(lastErrLog) > 5*time.Second {
|
||
log.Printf("[netstack] tun write error: %v", err)
|
||
lastErrLog = time.Now()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// handleTCPForward implements deferred-handshake TCP interception:
|
||
// the remote target is checked and dialed BEFORE completing the 3-way handshake
|
||
// with the sandbox container so nmap/nc accurately observe open/closed/filtered.
|
||
func (n *NetstackGateway) handleTCPForward(r *tcp.ForwarderRequest) {
|
||
id := r.ID()
|
||
srcIP := normalizeIP(net.IP(id.RemoteAddress.AsSlice())).String()
|
||
srcPort := int(id.RemotePort)
|
||
dstIP := normalizeIP(net.IP(id.LocalAddress.AsSlice())).String()
|
||
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(false)
|
||
return
|
||
}
|
||
|
||
go func() {
|
||
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, releaseDialSlot func()) {
|
||
start := time.Now()
|
||
src := n.backend.ResolveSource(srcIP)
|
||
if src.SrcIP == "" {
|
||
src.SrcIP = srcIP
|
||
}
|
||
|
||
dstHost := n.backend.LookupDNSReverse(dstIP)
|
||
if dstHost == "" {
|
||
dstHost = dstIP
|
||
}
|
||
|
||
// Pre-dial SSRF guard + egress blacklist check (IP & reverse-DNS hostname).
|
||
targetIPPort := net.JoinHostPort(dstIP, strconv.Itoa(dstPort))
|
||
targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(dstPort))
|
||
var blocked *BlockDecision
|
||
if dstHost != dstIP {
|
||
blocked = n.backend.CheckOutbound(targetHostPort, "tcp", src)
|
||
}
|
||
if blocked == nil {
|
||
blocked = n.backend.CheckOutbound(targetIPPort, "tcp", src)
|
||
}
|
||
if blocked != nil {
|
||
r.Complete(true) // immediate TCP RST
|
||
n.recordTCPBlock(start, "tcp", src, srcPort, dstIP, dstHost, dstPort, "", blocked)
|
||
return
|
||
}
|
||
|
||
// Deferred handshake: dial real destination (direct or via upstream proxy) BEFORE
|
||
// sending SYN-ACK to the sandbox container!
|
||
upstream := n.backend.ResolveUpstream(src)
|
||
upstreamLabel := MaskProxyURL(upstream)
|
||
dialTarget := targetIPPort
|
||
if upstream != nil && dstHost != "" && dstHost != dstIP {
|
||
dialTarget = targetHostPort
|
||
}
|
||
|
||
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, 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").
|
||
sendRST := !isDialTimeoutErr(err)
|
||
r.Complete(sendRST)
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: time.Now().Unix(),
|
||
DurationMS: time.Since(start).Milliseconds(),
|
||
Protocol: "tcp",
|
||
DstIP: dstIP,
|
||
DstPort: dstPort,
|
||
DstHost: dstHost,
|
||
Action: "error",
|
||
UpstreamProxy: upstreamLabel,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
SrcPort: srcPort,
|
||
Error: err.Error(),
|
||
})
|
||
return
|
||
}
|
||
|
||
// Remote port is genuinely OPEN -> now complete 3-way handshake with sandbox.
|
||
var wq waiter.Queue
|
||
ep, tcpErr := r.CreateEndpoint(&wq)
|
||
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)
|
||
defer rawClientConn.Close()
|
||
|
||
// Peek client's first bytes to classify HTTP / TLS / raw TCP.
|
||
sniff, clientConn := SniffProtocol(rawClientConn, n.cfg.PeekTimeout)
|
||
|
||
// Re-resolve logical host using SNI / HTTP Host if available, and re-check blacklist.
|
||
logicalHost := dstHost
|
||
if sniff.SNI != "" {
|
||
logicalHost = sniff.SNI
|
||
} else if sniff.Host != "" {
|
||
h, _ := splitHostAndPort(sniff.Host)
|
||
if strings.TrimSpace(h) != "" {
|
||
logicalHost = strings.TrimSpace(h)
|
||
}
|
||
}
|
||
if logicalHost != dstHost && logicalHost != dstIP {
|
||
scheme := string(sniff.Proto)
|
||
if sniff.Proto == ProtoTLS {
|
||
scheme = "https"
|
||
}
|
||
if b2 := n.backend.CheckOutbound(net.JoinHostPort(logicalHost, strconv.Itoa(dstPort)), scheme, src); b2 != nil {
|
||
_ = dstConn.Close()
|
||
n.recordTCPBlock(start, string(sniff.Proto), src, srcPort, dstIP, logicalHost, dstPort, sniff.SNI, b2)
|
||
return
|
||
}
|
||
}
|
||
|
||
// Route sniffed HTTP/TLS into go-mitmproxy when MITM is enabled and host is not downgraded.
|
||
mitmAddr := strings.TrimSpace(n.cfg.MITMProxyAddr)
|
||
if mitmAddr != "" {
|
||
if sniff.Proto == ProtoHTTP {
|
||
_ = dstConn.Close()
|
||
n.gw.forwardHTTPToMITM(clientConn, mitmAddr, logicalHost, dstPort, src)
|
||
return
|
||
}
|
||
if sniff.Proto == ProtoTLS && !n.backend.IsPassthrough(logicalHost) {
|
||
_ = dstConn.Close()
|
||
_ = n.gw.forwardTLSToMITM(clientConn, mitmAddr, logicalHost, dstPort, src)
|
||
return
|
||
}
|
||
}
|
||
|
||
// Direct DNS-over-TCP to an external target:53 (already connected via deferred
|
||
// handshake) -> enforce domain/IP blacklist and log to dns_queries while talking
|
||
// to the real target socket rather than hijacking to the host's DNS resolver.
|
||
if dstPort == 53 && sniff.Proto == ProtoTCP && looksLikeTCPDNS(clientConn) {
|
||
n.serveConnectedTCPDNS(clientConn, dstConn, src, dstIP, upstreamLabel)
|
||
return
|
||
}
|
||
|
||
// Raw TCP (SSH, MySQL, Redis, SMB, nc, nmap -sT) or TLS passthrough:
|
||
// reuse the ALREADY-CONNECTED dstConn (zero double-connect!).
|
||
action := "allow"
|
||
if sniff.Proto == ProtoTLS {
|
||
action = "passthrough"
|
||
}
|
||
n.gw.relayConnectedL4TCP(clientConn, dstConn, start, string(sniff.Proto), action, src, srcPort, dstIP, logicalHost, dstPort, sniff.SNI, upstreamLabel)
|
||
}
|
||
|
||
func (n *NetstackGateway) recordTCPBlock(start time.Time, proto string, src SourceIdentity, srcPort int, dstIP, dstHost string, dstPort int, sni string, b *BlockDecision) {
|
||
n.backend.RecordBlockEvent(EgressBlockEvent{
|
||
At: start.UTC(),
|
||
Host: dstHost,
|
||
Port: strconv.Itoa(dstPort),
|
||
Method: strings.ToUpper(proto),
|
||
URL: fmt.Sprintf("%s://%s:%d", proto, dstHost, dstPort),
|
||
SrcIP: src.SrcIP,
|
||
Scope: src.Scope,
|
||
OwnerID: src.OwnerID,
|
||
Reason: b.Reason,
|
||
RuleKind: b.RuleKind,
|
||
RuleID: b.RuleID,
|
||
Pattern: b.Pattern,
|
||
Source: b.Source,
|
||
})
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: time.Now().Unix(),
|
||
DurationMS: time.Since(start).Milliseconds(),
|
||
Protocol: proto,
|
||
DstIP: dstIP,
|
||
DstPort: dstPort,
|
||
DstHost: dstHost,
|
||
SNI: sni,
|
||
Action: "block",
|
||
BlockReason: b.Reason,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
SrcPort: srcPort,
|
||
})
|
||
}
|
||
|
||
func looksLikeTCPDNS(conn net.Conn) bool {
|
||
pc, ok := conn.(*PeekConn)
|
||
if !ok || pc.br == nil {
|
||
return false
|
||
}
|
||
avail := pc.br.Buffered()
|
||
if avail < 14 { // 2-byte TCP length prefix + 12-byte DNS header minimum
|
||
return false
|
||
}
|
||
hdr, err := pc.br.Peek(2)
|
||
if err != nil {
|
||
return false
|
||
}
|
||
msgLen := int(binary.BigEndian.Uint16(hdr))
|
||
if msgLen < 12 || msgLen > 4096 || avail < 2+msgLen {
|
||
return false
|
||
}
|
||
frame, err := pc.br.Peek(2 + msgLen)
|
||
if err != nil {
|
||
return false
|
||
}
|
||
req := new(dns.Msg)
|
||
if err := req.Unpack(frame[2:]); err != nil || req.Response || len(req.Question) == 0 {
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
func (n *NetstackGateway) recordTCPDNSError(start time.Time, qname, qtype, upstreamTag string, src SourceIdentity, err error) {
|
||
errMsg := "tcp dns exchange failed"
|
||
if err != nil {
|
||
errMsg = err.Error()
|
||
}
|
||
n.backend.RecordDNSQuery(DNSQueryRecord{
|
||
TS: start.Unix(),
|
||
DurationMS: time.Since(start).Milliseconds(),
|
||
QName: qname,
|
||
QType: qtype,
|
||
RCode: dns.RcodeToString[dns.RcodeServerFailure],
|
||
Answers: []string{},
|
||
Action: "error",
|
||
Upstream: upstreamTag,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
Error: errMsg,
|
||
})
|
||
}
|
||
|
||
// writeTCPDNSFrame writes the 2-octet length prefix and DNS message in a single
|
||
// Write call (RFC 7766 Section 8) so strict TCP DNS servers (e.g. AliDNS 223.5.5.5)
|
||
// do not reset connections receiving split length/payload segments.
|
||
func writeTCPDNSFrame(w io.Writer, payload []byte) error {
|
||
frame := make([]byte, 2+len(payload))
|
||
binary.BigEndian.PutUint16(frame[:2], uint16(len(payload)))
|
||
copy(frame[2:], payload)
|
||
_, err := w.Write(frame)
|
||
return err
|
||
}
|
||
|
||
func (n *NetstackGateway) serveConnectedTCPDNS(
|
||
clientConn, dstConn net.Conn,
|
||
src SourceIdentity,
|
||
dstIP string,
|
||
upstreamLabel string,
|
||
) {
|
||
defer dstConn.Close()
|
||
targetAddr := net.JoinHostPort(dstIP, "53")
|
||
upstreamTag := "direct-tcp:" + targetAddr
|
||
if upstreamLabel != "" && upstreamLabel != "direct" {
|
||
upstreamTag = "tcp-via:" + upstreamLabel + "->" + targetAddr
|
||
}
|
||
|
||
for {
|
||
_ = clientConn.SetReadDeadline(time.Now().Add(8 * time.Second))
|
||
var lenBuf [2]byte
|
||
if _, err := io.ReadFull(clientConn, lenBuf[:]); err != nil {
|
||
return
|
||
}
|
||
msgLen := int(binary.BigEndian.Uint16(lenBuf[:]))
|
||
if msgLen <= 0 || msgLen > 65535 {
|
||
return
|
||
}
|
||
raw := make([]byte, msgLen)
|
||
if _, err := io.ReadFull(clientConn, raw); err != nil {
|
||
return
|
||
}
|
||
req := new(dns.Msg)
|
||
if err := req.Unpack(raw); err != nil {
|
||
return
|
||
}
|
||
qStart := time.Now()
|
||
qname := ""
|
||
qtype := "A"
|
||
isZoneTransfer := false
|
||
if len(req.Question) > 0 {
|
||
qname = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Question[0].Name)), ".")
|
||
qtype = dns.TypeToString[req.Question[0].Qtype]
|
||
if qtype == "" {
|
||
qtype = strconv.Itoa(int(req.Question[0].Qtype))
|
||
}
|
||
isZoneTransfer = req.Question[0].Qtype == dns.TypeAXFR || req.Question[0].Qtype == dns.TypeIXFR
|
||
}
|
||
|
||
// Pre-resolution domain check against SSRF guard + global/task egress blacklist.
|
||
if qname != "" {
|
||
if blocked := n.backend.CheckOutbound(qname, "dns", src); blocked != nil {
|
||
refused := new(dns.Msg)
|
||
refused.SetRcode(req, dns.RcodeRefused)
|
||
n.backend.RecordBlockEvent(EgressBlockEvent{
|
||
At: qStart.UTC(),
|
||
Host: qname,
|
||
Port: "53",
|
||
Method: "DNS/" + qtype,
|
||
URL: "dns://" + qname,
|
||
SrcIP: src.SrcIP,
|
||
Scope: src.Scope,
|
||
OwnerID: src.OwnerID,
|
||
Reason: blocked.Reason,
|
||
RuleKind: blocked.RuleKind,
|
||
RuleID: blocked.RuleID,
|
||
Pattern: blocked.Pattern,
|
||
Source: blocked.Source,
|
||
})
|
||
n.backend.RecordDNSQuery(DNSQueryRecord{
|
||
TS: qStart.Unix(),
|
||
DurationMS: time.Since(qStart).Milliseconds(),
|
||
QName: qname,
|
||
QType: qtype,
|
||
RCode: dns.RcodeToString[dns.RcodeRefused],
|
||
Answers: []string{},
|
||
Action: "block",
|
||
BlockReason: blocked.Reason,
|
||
Upstream: upstreamTag,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
})
|
||
if packed, err := refused.Pack(); err == nil {
|
||
_ = writeTCPDNSFrame(clientConn, packed)
|
||
}
|
||
continue
|
||
}
|
||
}
|
||
|
||
// Forward the framed DNS query directly to the already-connected real target dstIP:53.
|
||
_ = dstConn.SetDeadline(time.Now().Add(8 * time.Second))
|
||
if err := writeTCPDNSFrame(dstConn, raw); err != nil {
|
||
n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err)
|
||
return
|
||
}
|
||
if isZoneTransfer {
|
||
// AXFR/IXFR returns a multi-message TCP stream; record the query and pipe verbatim.
|
||
n.backend.RecordDNSQuery(DNSQueryRecord{
|
||
TS: qStart.Unix(),
|
||
DurationMS: time.Since(qStart).Milliseconds(),
|
||
QName: qname,
|
||
QType: qtype,
|
||
RCode: "STREAM",
|
||
Answers: []string{},
|
||
Action: "allow",
|
||
Upstream: upstreamTag,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
})
|
||
_ = dstConn.SetDeadline(time.Time{})
|
||
_ = clientConn.SetDeadline(time.Time{})
|
||
_, _ = io.Copy(clientConn, dstConn)
|
||
return
|
||
}
|
||
|
||
var respLenBuf [2]byte
|
||
if _, err := io.ReadFull(dstConn, respLenBuf[:]); err != nil {
|
||
n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err)
|
||
return
|
||
}
|
||
respLen := int(binary.BigEndian.Uint16(respLenBuf[:]))
|
||
if respLen <= 0 || respLen > 65535 {
|
||
n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, fmt.Errorf("invalid dns tcp response length %d", respLen))
|
||
return
|
||
}
|
||
respRaw := make([]byte, respLen)
|
||
if _, err := io.ReadFull(dstConn, respRaw); err != nil {
|
||
n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err)
|
||
return
|
||
}
|
||
reply := new(dns.Msg)
|
||
if err := reply.Unpack(respRaw); err != nil {
|
||
n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err)
|
||
return
|
||
}
|
||
|
||
answers, resolvedIPs := extractDNSAnswers(reply)
|
||
blockedPost := false
|
||
for _, ipStr := range resolvedIPs {
|
||
if blocked := n.backend.CheckOutbound(ipStr, "dns", src); blocked != nil {
|
||
refused := new(dns.Msg)
|
||
refused.SetRcode(req, dns.RcodeRefused)
|
||
n.backend.RecordBlockEvent(EgressBlockEvent{
|
||
At: qStart.UTC(),
|
||
Host: qname,
|
||
Port: "53",
|
||
Method: "DNS/" + qtype,
|
||
URL: "dns://" + qname + " -> " + ipStr,
|
||
SrcIP: src.SrcIP,
|
||
Scope: src.Scope,
|
||
OwnerID: src.OwnerID,
|
||
Reason: blocked.Reason,
|
||
RuleKind: blocked.RuleKind,
|
||
RuleID: blocked.RuleID,
|
||
Pattern: blocked.Pattern,
|
||
Source: blocked.Source,
|
||
})
|
||
n.backend.RecordDNSQuery(DNSQueryRecord{
|
||
TS: qStart.Unix(),
|
||
DurationMS: time.Since(qStart).Milliseconds(),
|
||
QName: qname,
|
||
QType: qtype,
|
||
RCode: dns.RcodeToString[dns.RcodeRefused],
|
||
Answers: answers,
|
||
Action: "block",
|
||
BlockReason: blocked.Reason,
|
||
Upstream: upstreamTag,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
})
|
||
if packed, err := refused.Pack(); err == nil {
|
||
_ = writeTCPDNSFrame(clientConn, packed)
|
||
}
|
||
blockedPost = true
|
||
break
|
||
}
|
||
}
|
||
if blockedPost {
|
||
continue
|
||
}
|
||
|
||
if qname != "" {
|
||
for _, ipStr := range resolvedIPs {
|
||
n.backend.RememberDNS(ipStr, qname)
|
||
}
|
||
}
|
||
rcode := dns.RcodeToString[reply.Rcode]
|
||
if rcode == "" {
|
||
rcode = strconv.Itoa(reply.Rcode)
|
||
}
|
||
n.backend.RecordDNSQuery(DNSQueryRecord{
|
||
TS: qStart.Unix(),
|
||
DurationMS: time.Since(qStart).Milliseconds(),
|
||
QName: qname,
|
||
QType: qtype,
|
||
RCode: rcode,
|
||
Answers: answers,
|
||
Action: "allow",
|
||
Upstream: upstreamTag,
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
})
|
||
|
||
if err := writeTCPDNSFrame(clientConn, respRaw); err != nil {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
// handleUDPForward intercepts UDP packets routed into netstack:
|
||
// port 53 => ProcessDNSQuery; other ports => TransparentGateway UDP relay/policy.
|
||
func (n *NetstackGateway) handleUDPForward(r *udp.ForwarderRequest) bool {
|
||
id := r.ID()
|
||
srcIP := normalizeIP(net.IP(id.RemoteAddress.AsSlice()))
|
||
srcPort := int(id.RemotePort)
|
||
dstIP := normalizeIP(net.IP(id.LocalAddress.AsSlice()))
|
||
dstPort := int(id.LocalPort)
|
||
|
||
var wq waiter.Queue
|
||
ep, tcpErr := r.CreateEndpoint(&wq)
|
||
if tcpErr != nil {
|
||
return false
|
||
}
|
||
uconn := gonet.NewUDPConn(&wq, ep)
|
||
|
||
go func() {
|
||
defer uconn.Close()
|
||
srcAddr := &net.UDPAddr{IP: srcIP, Port: srcPort}
|
||
origDst := &net.UDPAddr{IP: dstIP, Port: dstPort}
|
||
if dstPort == 53 {
|
||
n.serveNetstackUDPDNS(uconn, srcAddr, origDst)
|
||
return
|
||
}
|
||
n.serveNetstackUDPRelay(uconn, srcAddr, origDst, nil)
|
||
}()
|
||
return true
|
||
}
|
||
|
||
func (n *NetstackGateway) serveNetstackUDPDNS(uconn *gonet.UDPConn, srcAddr, origDst *net.UDPAddr) {
|
||
srcIP := srcAddr.IP.String()
|
||
dstIP := origDst.IP.String()
|
||
src := n.backend.ResolveSource(srcIP)
|
||
if src.SrcIP == "" {
|
||
src.SrcIP = srcIP
|
||
}
|
||
|
||
buf := make([]byte, 4096)
|
||
for {
|
||
_ = uconn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||
nr, _, err := uconn.ReadFrom(buf)
|
||
if err != nil {
|
||
return
|
||
}
|
||
pkt := append([]byte(nil), buf[:nr]...)
|
||
|
||
// Pre-check SSRF / egress blacklist on the destination DNS server IP itself.
|
||
targetIPPort := net.JoinHostPort(dstIP, "53")
|
||
if blocked := n.backend.CheckOutbound(targetIPPort, "udp", src); blocked != nil {
|
||
n.gw.recordBlockedUDP(time.Now(), src, srcAddr.Port, dstIP, dstIP, 53, pkt, blocked)
|
||
return
|
||
}
|
||
|
||
req := new(dns.Msg)
|
||
if nr == 0 || req.Unpack(pkt) != nil || len(req.Question) == 0 {
|
||
// Non-DNS probe (e.g. 0-byte or raw payload UDP scan to port 53):
|
||
// relay as raw UDP so port status is genuinely probed and recorded.
|
||
n.serveNetstackUDPRelay(uconn, srcAddr, origDst, pkt)
|
||
return
|
||
}
|
||
|
||
// Forward directly to origDst:53 when no upstream proxy is active so
|
||
// scanning port 53 on non-DNS hosts never returns a false-positive answer.
|
||
resp, qerr := n.gw.ProcessDNSQueryToTarget(srcIP, req, false, targetIPPort)
|
||
if qerr != nil && errors.Is(qerr, syscall.ECONNREFUSED) {
|
||
n.sendICMPv4PortUnreachable(srcAddr, origDst, pkt)
|
||
return
|
||
}
|
||
if resp == nil {
|
||
continue
|
||
}
|
||
packed, err := resp.Pack()
|
||
if err != nil {
|
||
continue
|
||
}
|
||
_, _ = uconn.Write(packed)
|
||
}
|
||
}
|
||
|
||
func (n *NetstackGateway) serveNetstackUDPRelay(uconn *gonet.UDPConn, srcAddr, origDst *net.UDPAddr, preRead []byte) {
|
||
start := time.Now()
|
||
srcIP := srcAddr.IP.String()
|
||
dstIP := origDst.IP.String()
|
||
dstPort := origDst.Port
|
||
src := n.backend.ResolveSource(srcIP)
|
||
if src.SrcIP == "" {
|
||
src.SrcIP = srcIP
|
||
}
|
||
dstHost := n.backend.LookupDNSReverse(dstIP)
|
||
if dstHost == "" {
|
||
dstHost = dstIP
|
||
}
|
||
|
||
var firstPkt []byte
|
||
if preRead != nil {
|
||
firstPkt = preRead
|
||
} else {
|
||
buf := make([]byte, 65535)
|
||
_ = uconn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||
firstN, _, err := uconn.ReadFrom(buf)
|
||
if err != nil {
|
||
return
|
||
}
|
||
firstPkt = append([]byte(nil), buf[:firstN]...)
|
||
}
|
||
|
||
targetIPPort := net.JoinHostPort(dstIP, strconv.Itoa(dstPort))
|
||
targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(dstPort))
|
||
var blocked *BlockDecision
|
||
if dstHost != dstIP {
|
||
blocked = n.backend.CheckOutbound(targetHostPort, "udp", src)
|
||
}
|
||
if blocked == nil {
|
||
blocked = n.backend.CheckOutbound(targetIPPort, "udp", src)
|
||
}
|
||
if blocked != nil {
|
||
n.gw.recordBlockedUDP(start, src, srcAddr.Port, dstIP, dstHost, dstPort, firstPkt, blocked)
|
||
return
|
||
}
|
||
|
||
policy := NormalizeUDPPolicy(n.backend.UDPPolicy())
|
||
upstream := n.backend.ResolveUpstream(src)
|
||
if policy == UDPPolicyBlock || (policy == UDPPolicyBlockOnProxy && upstream != nil) {
|
||
reason := "UDP 流量已被策略阻断"
|
||
if upstream != nil {
|
||
reason = "已启用出口代理,为防止真实出口 IP 泄露已阻断直连 UDP(OPSEC)"
|
||
}
|
||
n.gw.recordBlockedUDP(start, src, srcAddr.Port, dstIP, dstHost, dstPort, firstPkt, &BlockDecision{
|
||
Reason: reason,
|
||
RuleKind: "udp_policy",
|
||
Source: "udp_policy",
|
||
})
|
||
return
|
||
}
|
||
|
||
remote, err := net.DialUDP("udp", nil, origDst)
|
||
if err != nil {
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: time.Now().Unix(),
|
||
DurationMS: time.Since(start).Milliseconds(),
|
||
Protocol: "udp",
|
||
DstIP: dstIP,
|
||
DstPort: dstPort,
|
||
DstHost: dstHost,
|
||
Action: "error",
|
||
UpstreamProxy: "direct",
|
||
BytesTX: int64(len(firstPkt)),
|
||
TXPreview: clipBytes(firstPkt, maxFlowPreviewBytes),
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
SrcPort: srcAddr.Port,
|
||
Error: err.Error(),
|
||
})
|
||
return
|
||
}
|
||
defer remote.Close()
|
||
|
||
txCap := &limitedCapture{max: maxFlowPreviewBytes}
|
||
rxCap := &limitedCapture{max: maxFlowPreviewBytes}
|
||
var bytesTX, bytesRX int64
|
||
const (
|
||
probeIdleTTL = 5 * time.Second
|
||
activeIdleTTL = 15 * time.Second
|
||
)
|
||
|
||
_, _ = txCap.Write(firstPkt)
|
||
bytesTX = int64(len(firstPkt))
|
||
_, _ = remote.Write(firstPkt)
|
||
|
||
var wg sync.WaitGroup
|
||
wg.Add(2)
|
||
go func() {
|
||
defer wg.Done()
|
||
rb := make([]byte, 65535)
|
||
ttl := probeIdleTTL
|
||
for {
|
||
_ = remote.SetReadDeadline(time.Now().Add(ttl))
|
||
nr, rerr := remote.Read(rb)
|
||
if rerr != nil {
|
||
if errors.Is(rerr, syscall.ECONNREFUSED) {
|
||
n.sendICMPv4PortUnreachable(srcAddr, origDst, firstPkt)
|
||
}
|
||
_ = uconn.Close()
|
||
return
|
||
}
|
||
ttl = activeIdleTTL
|
||
if nr > 0 {
|
||
bytesRX += int64(nr)
|
||
_, _ = rxCap.Write(rb[:nr])
|
||
if _, werr := uconn.Write(rb[:nr]); werr != nil {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
}()
|
||
go func() {
|
||
defer wg.Done()
|
||
cb := make([]byte, 65535)
|
||
for {
|
||
_ = uconn.SetReadDeadline(time.Now().Add(probeIdleTTL))
|
||
nr, _, rerr := uconn.ReadFrom(cb)
|
||
if rerr != nil {
|
||
_ = remote.Close()
|
||
return
|
||
}
|
||
bytesTX += int64(nr)
|
||
if nr > 0 {
|
||
_, _ = txCap.Write(cb[:nr])
|
||
}
|
||
_, _ = remote.Write(cb[:nr])
|
||
}
|
||
}()
|
||
wg.Wait()
|
||
|
||
end := time.Now()
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: end.Unix(),
|
||
DurationMS: end.Sub(start).Milliseconds(),
|
||
Protocol: "udp",
|
||
DstIP: dstIP,
|
||
DstPort: dstPort,
|
||
DstHost: dstHost,
|
||
Action: "allow",
|
||
UpstreamProxy: "direct",
|
||
BytesTX: bytesTX,
|
||
BytesRX: bytesRX,
|
||
TXPreview: txCap.Bytes(),
|
||
RXPreview: rxCap.Bytes(),
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
SrcPort: srcAddr.Port,
|
||
})
|
||
}
|
||
|
||
func isDialTimeoutErr(err error) bool {
|
||
if err == nil {
|
||
return false
|
||
}
|
||
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
|
||
if errors.As(err, &ne) && ne.Timeout() {
|
||
return true
|
||
}
|
||
// ECONNREFUSED / EHOSTUNREACH / ENETUNREACH are active refusals, not timeouts.
|
||
if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EHOSTUNREACH) || errors.Is(err, syscall.ENETUNREACH) {
|
||
return false
|
||
}
|
||
return strings.Contains(strings.ToLower(err.Error()), "i/o timeout")
|
||
}
|
||
|
||
// Suppress unused import warnings if log is needed for diagnostics.
|
||
var _ = log.Printf
|
||
|
||
// sendICMPv4PortUnreachable injects a genuine ICMPv4 Destination Unreachable
|
||
// (Type 3, Code 3) packet back to the sandbox container when the real remote
|
||
// UDP target responds with ECONNREFUSED, so `nmap -sU` accurately reports
|
||
// closed UDP ports as "closed" instead of "open|filtered".
|
||
func (n *NetstackGateway) sendICMPv4PortUnreachable(clientAddr, remoteAddr *net.UDPAddr, udpPayload []byte) {
|
||
src4 := remoteAddr.IP.To4()
|
||
dst4 := clientAddr.IP.To4()
|
||
if src4 == nil || dst4 == nil {
|
||
return
|
||
}
|
||
quotePayloadLen := len(udpPayload)
|
||
if quotePayloadLen > 8 {
|
||
quotePayloadLen = 8
|
||
}
|
||
// Quoted original packet: 20B IPv4 + 8B UDP + up to 8B payload.
|
||
quotedLen := header.IPv4MinimumSize + header.UDPMinimumSize + quotePayloadLen
|
||
icmpLen := header.ICMPv4MinimumSize + quotedLen
|
||
totalLen := header.IPv4MinimumSize + icmpLen
|
||
|
||
pkt := make([]byte, totalLen)
|
||
// Outer IPv4 header: src=remoteAddr, dst=clientAddr, proto=ICMP.
|
||
outerIP := header.IPv4(pkt[:header.IPv4MinimumSize])
|
||
outerIP.Encode(&header.IPv4Fields{
|
||
TotalLength: uint16(totalLen),
|
||
TTL: 64,
|
||
Protocol: uint8(header.ICMPv4ProtocolNumber),
|
||
SrcAddr: tcpip.AddrFrom4Slice(src4),
|
||
DstAddr: tcpip.AddrFrom4Slice(dst4),
|
||
})
|
||
outerIP.SetChecksum(^outerIP.CalculateChecksum())
|
||
|
||
// Quoted inner IPv4 header: src=clientAddr, dst=remoteAddr, proto=UDP.
|
||
quotedOff := header.IPv4MinimumSize + header.ICMPv4MinimumSize
|
||
innerIP := header.IPv4(pkt[quotedOff : quotedOff+header.IPv4MinimumSize])
|
||
innerIP.Encode(&header.IPv4Fields{
|
||
TotalLength: uint16(header.IPv4MinimumSize + header.UDPMinimumSize + len(udpPayload)),
|
||
TTL: 64,
|
||
Protocol: uint8(header.UDPProtocolNumber),
|
||
SrcAddr: tcpip.AddrFrom4Slice(dst4),
|
||
DstAddr: tcpip.AddrFrom4Slice(src4),
|
||
})
|
||
innerIP.SetChecksum(^innerIP.CalculateChecksum())
|
||
|
||
// Quoted inner UDP header + up to 8 bytes of payload.
|
||
udpOff := quotedOff + header.IPv4MinimumSize
|
||
innerUDP := header.UDP(pkt[udpOff : udpOff+header.UDPMinimumSize])
|
||
innerUDP.Encode(&header.UDPFields{
|
||
SrcPort: uint16(clientAddr.Port),
|
||
DstPort: uint16(remoteAddr.Port),
|
||
Length: uint16(header.UDPMinimumSize + len(udpPayload)),
|
||
})
|
||
if quotePayloadLen > 0 {
|
||
copy(pkt[udpOff+header.UDPMinimumSize:], udpPayload[:quotePayloadLen])
|
||
}
|
||
|
||
// ICMPv4 header (Type 3 Dest Unreachable, Code 3 Port Unreachable).
|
||
icmpHdr := header.ICMPv4(pkt[header.IPv4MinimumSize:])
|
||
icmpHdr.SetType(header.ICMPv4DstUnreachable)
|
||
icmpHdr.SetCode(header.ICMPv4PortUnreachable)
|
||
icmpHdr.SetChecksum(0)
|
||
icmpHdr.SetChecksum(header.ICMPv4Checksum(icmpHdr, 0))
|
||
|
||
_, _ = n.dev.Write(pkt)
|
||
}
|
||
|
||
// handleICMPv4Echo enforces SSRF/blacklist/OPSEC policy on sandbox ICMP Echo
|
||
// Requests and forwards allowed pings to the real destination so `ping` and
|
||
// `nmap -PE` observe genuine RTT/loss rather than gVisor's fake local replies.
|
||
func (n *NetstackGateway) handleICMPv4Echo(rawPkt []byte) {
|
||
start := time.Now()
|
||
ip4 := header.IPv4(rawPkt)
|
||
ihl := int(ip4.HeaderLength())
|
||
if ihl < header.IPv4MinimumSize || len(rawPkt) < ihl+header.ICMPv4MinimumSize {
|
||
return
|
||
}
|
||
icmpReq := header.ICMPv4(rawPkt[ihl:])
|
||
if icmpReq.Type() != header.ICMPv4Echo {
|
||
return
|
||
}
|
||
|
||
srcAddr := ip4.SourceAddress()
|
||
dstAddr := ip4.DestinationAddress()
|
||
srcIPBytes := append([]byte(nil), srcAddr.AsSlice()...)
|
||
dstIPBytes := append([]byte(nil), dstAddr.AsSlice()...)
|
||
srcIP := net.IP(srcIPBytes).String()
|
||
dstIP := net.IP(dstIPBytes).String()
|
||
origID := icmpReq.Ident()
|
||
origSeq := icmpReq.Sequence()
|
||
payload := append([]byte(nil), icmpReq.Payload()...)
|
||
|
||
src := n.backend.ResolveSource(srcIP)
|
||
if src.SrcIP == "" {
|
||
src.SrcIP = srcIP
|
||
}
|
||
dstHost := n.backend.LookupDNSReverse(dstIP)
|
||
if dstHost == "" {
|
||
dstHost = dstIP
|
||
}
|
||
|
||
var blocked *BlockDecision
|
||
if dstHost != dstIP {
|
||
blocked = n.backend.CheckOutbound(net.JoinHostPort(dstHost, "0"), "icmp", src)
|
||
}
|
||
if blocked == nil {
|
||
blocked = n.backend.CheckOutbound(net.JoinHostPort(dstIP, "0"), "icmp", src)
|
||
}
|
||
if blocked != nil {
|
||
n.recordTCPBlock(start, "icmp", src, 0, dstIP, dstHost, 0, "", blocked)
|
||
return
|
||
}
|
||
|
||
policy := NormalizeUDPPolicy(n.backend.UDPPolicy())
|
||
upstream := n.backend.ResolveUpstream(src)
|
||
if policy == UDPPolicyBlock || (policy == UDPPolicyBlockOnProxy && upstream != nil) {
|
||
reason := "ICMP traffic blocked by gateway policy"
|
||
if upstream != nil {
|
||
reason = "Direct ICMP blocked while egress proxy is active (OPSEC)"
|
||
}
|
||
n.recordTCPBlock(start, "icmp", src, 0, dstIP, dstHost, 0, "", &BlockDecision{
|
||
Reason: reason,
|
||
RuleKind: "udp_policy",
|
||
Source: "udp_policy",
|
||
})
|
||
return
|
||
}
|
||
|
||
pingTimeout := n.cfg.DialTimeout
|
||
if pingTimeout <= 0 || pingTimeout > 3*time.Second {
|
||
pingTimeout = 2 * time.Second
|
||
}
|
||
pingCtx, cancel := context.WithTimeout(n.ctx, pingTimeout)
|
||
pingFn := n.cfg.ICMPPingFunc
|
||
if pingFn == nil {
|
||
pingFn = n.defaultICMPv4Ping
|
||
}
|
||
replyPayload, err := pingFn(pingCtx, net.IP(dstIPBytes), origSeq, payload)
|
||
cancel()
|
||
|
||
end := time.Now()
|
||
if err != nil {
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: end.Unix(),
|
||
DurationMS: end.Sub(start).Milliseconds(),
|
||
Protocol: "icmp",
|
||
DstIP: dstIP,
|
||
DstHost: dstHost,
|
||
Action: "error",
|
||
UpstreamProxy: "direct",
|
||
BytesTX: int64(len(icmpReq)),
|
||
TXPreview: clipBytes(payload, maxFlowPreviewBytes),
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
Error: err.Error(),
|
||
})
|
||
return
|
||
}
|
||
|
||
n.sendICMPv4EchoReply(net.IP(srcIPBytes), net.IP(dstIPBytes), origID, origSeq, replyPayload)
|
||
n.backend.RecordNetFlow(NetFlowRecord{
|
||
TS: start.Unix(),
|
||
EndedAt: end.Unix(),
|
||
DurationMS: end.Sub(start).Milliseconds(),
|
||
Protocol: "icmp",
|
||
DstIP: dstIP,
|
||
DstHost: dstHost,
|
||
Action: "allow",
|
||
UpstreamProxy: "direct",
|
||
BytesTX: int64(len(icmpReq)),
|
||
BytesRX: int64(header.ICMPv4MinimumSize + len(replyPayload)),
|
||
TXPreview: clipBytes(payload, maxFlowPreviewBytes),
|
||
RXPreview: clipBytes(replyPayload, maxFlowPreviewBytes),
|
||
SandboxScope: src.Scope,
|
||
SandboxOwnerID: src.OwnerID,
|
||
ContainerID: src.ContainerID,
|
||
SessionID: src.SessionID,
|
||
IntentID: src.IntentID,
|
||
SrcIP: src.SrcIP,
|
||
})
|
||
}
|
||
|
||
func (n *NetstackGateway) defaultICMPv4Ping(ctx context.Context, dstIP net.IP, seq uint16, payload []byte) ([]byte, error) {
|
||
conn, err := net.DialIP("ip4:icmp", nil, &net.IPAddr{IP: dstIP})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer conn.Close()
|
||
if dl, ok := ctx.Deadline(); ok {
|
||
_ = conn.SetDeadline(dl)
|
||
}
|
||
|
||
// Use a unique per-probe Echo ID so concurrent sandbox pings never cross-talk.
|
||
probeID := uint16((n.icmpID.Add(1) & 0x7fff) | 0x8000)
|
||
reqBuf := make([]byte, header.ICMPv4MinimumSize+len(payload))
|
||
reqICMP := header.ICMPv4(reqBuf)
|
||
reqICMP.SetType(header.ICMPv4Echo)
|
||
reqICMP.SetCode(0)
|
||
reqICMP.SetIdent(probeID)
|
||
reqICMP.SetSequence(seq)
|
||
copy(reqBuf[header.ICMPv4MinimumSize:], payload)
|
||
reqICMP.SetChecksum(0)
|
||
reqICMP.SetChecksum(header.ICMPv4Checksum(reqICMP, 0))
|
||
|
||
if _, err := conn.Write(reqBuf); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
rb := make([]byte, 2048)
|
||
for {
|
||
nr, err := conn.Read(rb)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if nr < header.IPv4MinimumSize+header.ICMPv4MinimumSize {
|
||
continue
|
||
}
|
||
// Raw ip4:icmp sockets include the outer IPv4 header on read.
|
||
ihl := int(rb[0]&0x0f) * 4
|
||
if ihl < header.IPv4MinimumSize || nr < ihl+header.ICMPv4MinimumSize {
|
||
continue
|
||
}
|
||
resp := header.ICMPv4(rb[ihl:nr])
|
||
if resp.Type() == header.ICMPv4EchoReply && resp.Ident() == probeID && resp.Sequence() == seq {
|
||
return append([]byte(nil), resp.Payload()...), nil
|
||
}
|
||
}
|
||
}
|
||
|
||
func (n *NetstackGateway) sendICMPv4EchoReply(clientIP, remoteIP net.IP, id, seq uint16, payload []byte) {
|
||
src4 := remoteIP.To4()
|
||
dst4 := clientIP.To4()
|
||
if src4 == nil || dst4 == nil {
|
||
return
|
||
}
|
||
totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload)
|
||
if totalLen > int(n.cfg.MTU) {
|
||
payload = payload[:int(n.cfg.MTU)-header.IPv4MinimumSize-header.ICMPv4MinimumSize]
|
||
totalLen = header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload)
|
||
}
|
||
pkt := make([]byte, totalLen)
|
||
outerIP := header.IPv4(pkt[:header.IPv4MinimumSize])
|
||
outerIP.Encode(&header.IPv4Fields{
|
||
TotalLength: uint16(totalLen),
|
||
TTL: 64,
|
||
Protocol: uint8(header.ICMPv4ProtocolNumber),
|
||
SrcAddr: tcpip.AddrFrom4Slice(src4),
|
||
DstAddr: tcpip.AddrFrom4Slice(dst4),
|
||
})
|
||
outerIP.SetChecksum(^outerIP.CalculateChecksum())
|
||
|
||
replyICMP := header.ICMPv4(pkt[header.IPv4MinimumSize:])
|
||
replyICMP.SetType(header.ICMPv4EchoReply)
|
||
replyICMP.SetCode(0)
|
||
replyICMP.SetIdent(id)
|
||
replyICMP.SetSequence(seq)
|
||
copy(pkt[header.IPv4MinimumSize+header.ICMPv4MinimumSize:], payload)
|
||
replyICMP.SetChecksum(0)
|
||
replyICMP.SetChecksum(header.ICMPv4Checksum(replyICMP, 0))
|
||
_, _ = n.dev.Write(pkt)
|
||
}
|