mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
fix(traffic,server,sandbox): fix TCP/53 false positives, add error-traffic storage toggle, and fix spawn_task/sandbox polling
- Route external TCP/53 through netstack deferred handshake and real-target DNS inspection (RFC 7766 single-write framing) instead of hijacking to host DNS. - Preserve explicit targetServer in ProcessDNSQueryToTarget under upstream proxy so external UDP/53 probes never fall back to host DNSUpstream. - Default error traffic storage (net_flows/dns_queries action=error) to off with hot-toggle controls synced across gateway, Proxy & Egress, and Traffic pages. - Restore json.Unmarshal in spawn_task orchestration tool and poll live sandbox container state in chat/task controls.
This commit is contained in:
1 parent
07309e4530
commit
d5926d6420
22 files changed
+1189
-101
No files matched your search
@@ -42,6 +42,7 @@ type GatewayPolicySnapshot struct {
|
||||
PassthroughHosts []string `json:"passthrough_hosts,omitempty"`
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream,omitempty"`
|
||||
StoreErrorTraffic bool `json:"store_error_traffic"`
|
||||
}
|
||||
|
||||
// GatewayEventBatch is posted by artex-gateway to POST /api/internal/gateway/events.
|
||||
@@ -65,6 +66,7 @@ type RemotePolicyState struct {
|
||||
passthroughHosts map[string]struct{}
|
||||
udpPolicy string
|
||||
dnsUpstream string
|
||||
storeErrorTraffic bool
|
||||
dnsCache *dnsReverseCache
|
||||
gatewayToken string
|
||||
onNetFlow func(NetFlowRecord)
|
||||
@@ -171,6 +173,7 @@ func (s *RemotePolicyState) Apply(snap GatewayPolicySnapshot) {
|
||||
s.passthroughHosts = pass
|
||||
s.udpPolicy = NormalizeUDPPolicy(snap.UDPPolicy)
|
||||
s.dnsUpstream = strings.TrimSpace(snap.DNSUpstream)
|
||||
s.storeErrorTraffic = snap.StoreErrorTraffic
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -253,12 +256,18 @@ func (s *RemotePolicyState) RememberDNS(ip, domain string) {
|
||||
}
|
||||
|
||||
func (s *RemotePolicyState) RecordNetFlow(rec NetFlowRecord) {
|
||||
if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() {
|
||||
return
|
||||
}
|
||||
if s.onNetFlow != nil {
|
||||
s.onNetFlow(rec)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemotePolicyState) RecordDNSQuery(rec DNSQueryRecord) {
|
||||
if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() {
|
||||
return
|
||||
}
|
||||
if s.onDNSQuery != nil {
|
||||
s.onDNSQuery(rec)
|
||||
}
|
||||
@@ -282,6 +291,12 @@ func (s *RemotePolicyState) DNSUpstream() string {
|
||||
return s.dnsUpstream
|
||||
}
|
||||
|
||||
func (s *RemotePolicyState) StoreErrorTraffic() bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.storeErrorTraffic
|
||||
}
|
||||
|
||||
func (s *RemotePolicyState) GatewayToken() string {
|
||||
return s.gatewayToken
|
||||
}
|
||||
@@ -325,6 +325,9 @@ func (t *Traffic) RecordNetFlow(rec NetFlowRecord) error {
|
||||
if rec.Action == "" {
|
||||
rec.Action = "allow"
|
||||
}
|
||||
if rec.Action == "error" && !t.StoreErrorTraffic() {
|
||||
return nil
|
||||
}
|
||||
if len(rec.TXPreview) > maxFlowPreviewBytes {
|
||||
rec.TXPreview = rec.TXPreview[:maxFlowPreviewBytes]
|
||||
}
|
||||
@@ -370,9 +373,13 @@ func (t *Traffic) RecordDNSQuery(rec DNSQueryRecord) error {
|
||||
if rec.QType == "" {
|
||||
rec.QType = "A"
|
||||
}
|
||||
rec.Action = strings.ToLower(strings.TrimSpace(rec.Action))
|
||||
if rec.Action == "" {
|
||||
rec.Action = "allow"
|
||||
}
|
||||
if rec.Action == "error" && !t.StoreErrorTraffic() {
|
||||
return nil
|
||||
}
|
||||
answers := rec.Answers
|
||||
if answers == nil {
|
||||
answers = []string{}
|
||||
|
||||
+285
-38
@@ -66,7 +66,9 @@ type NetstackConfig struct {
|
||||
// - 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.
|
||||
// - UDP/53 and TCP/53 => intercepted and processed through ProcessDNSQuery.
|
||||
// - 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
|
||||
@@ -349,20 +351,6 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin
|
||||
src.SrcIP = srcIP
|
||||
}
|
||||
|
||||
// DNS-over-TCP (port 53): accept locally and route through ProcessDNSQuery.
|
||||
if dstPort == 53 {
|
||||
var wq waiter.Queue
|
||||
ep, tcpErr := r.CreateEndpoint(&wq)
|
||||
r.Complete(false)
|
||||
if tcpErr != nil {
|
||||
return
|
||||
}
|
||||
conn := gonet.NewTCPConn(&wq, ep)
|
||||
defer conn.Close()
|
||||
n.serveSingleTCPDNS(conn, srcIP)
|
||||
return
|
||||
}
|
||||
|
||||
dstHost := n.backend.LookupDNSReverse(dstIP)
|
||||
if dstHost == "" {
|
||||
dstHost = dstIP
|
||||
@@ -478,6 +466,14 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin
|
||||
}
|
||||
}
|
||||
|
||||
// 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"
|
||||
@@ -524,36 +520,287 @@ func (n *NetstackGateway) recordTCPBlock(start time.Time, proto string, src Sour
|
||||
})
|
||||
}
|
||||
|
||||
func (n *NetstackGateway) serveSingleTCPDNS(conn net.Conn, srcIP string) {
|
||||
_ = conn.SetDeadline(time.Now().Add(8 * time.Second))
|
||||
var lenBuf [2]byte
|
||||
if _, err := io.ReadFull(conn, lenBuf[:]); err != nil {
|
||||
return
|
||||
func looksLikeTCPDNS(conn net.Conn) bool {
|
||||
pc, ok := conn.(*PeekConn)
|
||||
if !ok || pc.br == nil {
|
||||
return false
|
||||
}
|
||||
msgLen := int(binary.BigEndian.Uint16(lenBuf[:]))
|
||||
if msgLen <= 0 || msgLen > 65535 {
|
||||
return
|
||||
avail := pc.br.Buffered()
|
||||
if avail < 14 { // 2-byte TCP length prefix + 12-byte DNS header minimum
|
||||
return false
|
||||
}
|
||||
raw := make([]byte, msgLen)
|
||||
if _, err := io.ReadFull(conn, raw); err != nil {
|
||||
return
|
||||
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(raw); err != nil {
|
||||
return
|
||||
if err := req.Unpack(frame[2:]); err != nil || req.Response || len(req.Question) == 0 {
|
||||
return false
|
||||
}
|
||||
resp := n.gw.ProcessDNSQuery(srcIP, req, true)
|
||||
if resp == nil {
|
||||
return
|
||||
}
|
||||
packed, err := resp.Pack()
|
||||
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 {
|
||||
return
|
||||
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
|
||||
}
|
||||
}
|
||||
var outLen [2]byte
|
||||
binary.BigEndian.PutUint16(outLen[:], uint16(len(packed)))
|
||||
_, _ = conn.Write(outLen[:])
|
||||
_, _ = conn.Write(packed)
|
||||
}
|
||||
|
||||
// handleUDPForward intercepts UDP packets routed into netstack:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package traffic
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
@@ -8,9 +9,13 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/checksum"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
@@ -312,6 +317,7 @@ func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) {
|
||||
t.Fatalf("open traffic: %v", err)
|
||||
}
|
||||
defer tr.Close()
|
||||
tr.SetStoreErrorTraffic(true)
|
||||
tr.SetEgressBlacklist([]EgressBlacklistRule{{
|
||||
ID: "blk-icmp",
|
||||
Kind: "ip",
|
||||
@@ -392,3 +398,251 @@ func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) {
|
||||
t.Fatalf("expected >=3 recorded icmp flows (allow/error/block), got total=%d err=%v flows=%+v", total, err, flows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetstackTCP53DeferredHandshakeNoFalsePositiveAndRealDNS(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: "53", ContainerID: "sbx53", SrcIP: srcIP}, true
|
||||
}
|
||||
return SourceIdentity{}, false
|
||||
})
|
||||
tr.SetEgressBlacklist([]EgressBlacklistRule{
|
||||
{ID: "blk-dom", Enabled: true, Kind: "domain", Pattern: "blocked.example"},
|
||||
})
|
||||
|
||||
// Start a mock authoritative TCP DNS server returning 198.51.100.77.
|
||||
dnsLn, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen mock tcp dns: %v", err)
|
||||
}
|
||||
defer dnsLn.Close()
|
||||
go func() {
|
||||
for {
|
||||
c, err := dnsLn.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
for {
|
||||
var lb [2]byte
|
||||
if _, err := io.ReadFull(conn, lb[:]); err != nil {
|
||||
return
|
||||
}
|
||||
n := int(binary.BigEndian.Uint16(lb[:]))
|
||||
buf := make([]byte, n)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
return
|
||||
}
|
||||
req := new(dns.Msg)
|
||||
if err := req.Unpack(buf); err != nil {
|
||||
return
|
||||
}
|
||||
resp := new(dns.Msg)
|
||||
resp.SetReply(req)
|
||||
if len(req.Question) > 0 {
|
||||
resp.Answer = append(resp.Answer, &dns.A{
|
||||
Hdr: dns.RR_Header{Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60},
|
||||
A: net.ParseIP("198.51.100.77"),
|
||||
})
|
||||
}
|
||||
packed, err := resp.Pack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var outLb [2]byte
|
||||
binary.BigEndian.PutUint16(outLb[:], uint16(len(packed)))
|
||||
_, _ = conn.Write(outLb[:])
|
||||
_, _ = conn.Write(packed)
|
||||
}
|
||||
}(c)
|
||||
}
|
||||
}()
|
||||
|
||||
pipe := newMemTunPipe()
|
||||
ns, err := NewNetstackGateway(pipe, NetstackConfig{
|
||||
DialTimeout: 150 * time.Millisecond,
|
||||
PeekTimeout: 80 * time.Millisecond,
|
||||
DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) {
|
||||
switch target {
|
||||
case "203.0.113.74:53":
|
||||
return nil, context.DeadlineExceeded
|
||||
case "203.0.113.75:53":
|
||||
return nil, syscall.ECONNREFUSED
|
||||
case "203.0.113.53:53":
|
||||
return dialTCPThroughUpstream(ctx, upstream, dnsLn.Addr().String(), timeout)
|
||||
default:
|
||||
return nil, syscall.ECONNREFUSED
|
||||
}
|
||||
},
|
||||
}, LocalTransparentBackend{T: tr})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNetstackGateway: %v", err)
|
||||
}
|
||||
ns.Start()
|
||||
defer ns.Close()
|
||||
|
||||
// 1. Filtered external target:53/TCP (repro of 47.116.200.74:53) -> MUST NOT receive SYN-ACK.
|
||||
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.74"), 45001, 53, 1001)
|
||||
select {
|
||||
case pkt := <-pipe.out:
|
||||
flags, ok := parseTCPFlags(pkt)
|
||||
t.Fatalf("filtered TCP/53 must drop silently, got tcp=%v flags=%v", ok, flags)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
|
||||
// 2. Closed external target:53/TCP -> MUST receive RST (not SYN-ACK).
|
||||
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.75"), 45002, 53, 1002)
|
||||
select {
|
||||
case pkt := <-pipe.out:
|
||||
flags, ok := parseTCPFlags(pkt)
|
||||
if !ok || !flags.Contains(header.TCPFlagRst) || flags.Contains(header.TCPFlagSyn) {
|
||||
t.Fatalf("closed TCP/53 expected RST without SYN, got ok=%v flags=%v", ok, flags)
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("timed out waiting for RST on closed TCP/53")
|
||||
}
|
||||
|
||||
// 3. Direct unit check of serveConnectedTCPDNS against real target socket:
|
||||
// allowed query gets target's real answer (198.51.100.77) and logs direct-tcp:203.0.113.53:53;
|
||||
// blacklisted domain gets REFUSED and logs block without hitting upstream.
|
||||
clientSide, gwClient := net.Pipe()
|
||||
dstConn, err := net.DialTimeout("tcp4", dnsLn.Addr().String(), time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("dial mock dns: %v", err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer gwClient.Close()
|
||||
sniff, peeked := SniffProtocol(gwClient, 200*time.Millisecond)
|
||||
if sniff.Proto != ProtoTCP || !looksLikeTCPDNS(peeked) {
|
||||
t.Errorf("expected looksLikeTCPDNS=true, proto=%s", sniff.Proto)
|
||||
return
|
||||
}
|
||||
ns.serveConnectedTCPDNS(peeked, dstConn, SourceIdentity{Scope: "task", OwnerID: "53", SrcIP: "172.30.0.3"}, "203.0.113.53", "direct")
|
||||
}()
|
||||
|
||||
sendTCPQuery := func(qname string) *dns.Msg {
|
||||
q := new(dns.Msg)
|
||||
q.SetQuestion(dns.Fqdn(qname), dns.TypeA)
|
||||
packed, err := q.Pack()
|
||||
if err != nil {
|
||||
t.Fatalf("pack query: %v", err)
|
||||
}
|
||||
var lb [2]byte
|
||||
binary.BigEndian.PutUint16(lb[:], uint16(len(packed)))
|
||||
if _, err := clientSide.Write(append(lb[:], packed...)); err != nil {
|
||||
t.Fatalf("write query: %v", err)
|
||||
}
|
||||
var rlb [2]byte
|
||||
if _, err := io.ReadFull(clientSide, rlb[:]); err != nil {
|
||||
t.Fatalf("read resp len: %v", err)
|
||||
}
|
||||
rbuf := make([]byte, binary.BigEndian.Uint16(rlb[:]))
|
||||
if _, err := io.ReadFull(clientSide, rbuf); err != nil {
|
||||
t.Fatalf("read resp: %v", err)
|
||||
}
|
||||
resp := new(dns.Msg)
|
||||
if err := resp.Unpack(rbuf); err != nil {
|
||||
t.Fatalf("unpack resp: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
okResp := sendTCPQuery("ok.example")
|
||||
if okResp.Rcode != dns.RcodeSuccess || len(okResp.Answer) != 1 || okResp.Answer[0].(*dns.A).A.String() != "198.51.100.77" {
|
||||
t.Fatalf("unexpected real TCP DNS answer: %+v", okResp)
|
||||
}
|
||||
blkResp := sendTCPQuery("blocked.example")
|
||||
if blkResp.Rcode != dns.RcodeRefused {
|
||||
t.Fatalf("expected REFUSED for blacklisted domain, got rcode=%d", blkResp.Rcode)
|
||||
}
|
||||
_ = clientSide.Close()
|
||||
<-done
|
||||
|
||||
rows, total, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 10)
|
||||
if err != nil || total != 2 {
|
||||
t.Fatalf("expected 2 recorded TCP DNS queries, got total=%d err=%v rows=%+v", total, err, rows)
|
||||
}
|
||||
var sawOK, sawBlk bool
|
||||
for _, r := range rows {
|
||||
if r.QName == "ok.example" && r.Action == "allow" && r.Upstream == "direct-tcp:203.0.113.53:53" {
|
||||
sawOK = true
|
||||
}
|
||||
if r.QName == "blocked.example" && r.Action == "block" && r.Upstream == "direct-tcp:203.0.113.53:53" {
|
||||
sawBlk = true
|
||||
}
|
||||
}
|
||||
if !sawOK || !sawBlk {
|
||||
t.Fatalf("expected both ok (direct-tcp:203.0.113.53:53) and blocked rows, got %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDNSQueryToTargetUnderUpstreamProxyNeverSubstitutesHostDNS(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()
|
||||
|
||||
// Set a host DNS upstream that MUST NOT be contacted when targetServer is explicit.
|
||||
tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "198.51.100.254:53")
|
||||
|
||||
// Mock HTTP CONNECT proxy that records the requested CONNECT target and rejects 47.116.200.74:53.
|
||||
proxyLn, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen proxy: %v", err)
|
||||
}
|
||||
defer proxyLn.Close()
|
||||
var mu sync.Mutex
|
||||
var connectTargets []string
|
||||
go func() {
|
||||
for {
|
||||
c, err := proxyLn.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
br := bufio.NewReader(conn)
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 && parts[0] == "CONNECT" {
|
||||
mu.Lock()
|
||||
connectTargets = append(connectTargets, parts[1])
|
||||
mu.Unlock()
|
||||
}
|
||||
_, _ = conn.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n"))
|
||||
}(c)
|
||||
}
|
||||
}()
|
||||
|
||||
proxyURL, _ := url.Parse("http://" + proxyLn.Addr().String())
|
||||
tr.SetUpstreamResolver(func(SourceIdentity) (*url.URL, bool) {
|
||||
return proxyURL, true
|
||||
})
|
||||
|
||||
gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr})
|
||||
q := new(dns.Msg)
|
||||
q.SetQuestion("example.com.", dns.TypeA)
|
||||
resp, qerr := gw.ProcessDNSQueryToTarget("172.30.0.3", q, false, "47.116.200.74:53")
|
||||
if resp != nil || qerr == nil {
|
||||
t.Fatalf("expected (nil, err) when targetServer fails through proxy, got resp=%v err=%v", resp, qerr)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
got := append([]string(nil), connectTargets...)
|
||||
mu.Unlock()
|
||||
if len(got) != 1 || got[0] != "47.116.200.74:53" {
|
||||
t.Fatalf("expected proxy CONNECT to targetServer 47.116.200.74:53 (not host DNSUpstream), got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,7 @@ type Traffic struct {
|
||||
gatewayToken string
|
||||
udpPolicy string
|
||||
dnsUpstream string
|
||||
storeErrorTraffic atomic.Bool
|
||||
ssrfCfg *SSRFGuardConfig
|
||||
dnsCache *dnsReverseCache
|
||||
nfWrites atomic.Int64
|
||||
|
||||
+26
-4
@@ -646,9 +646,10 @@ func (g *TransparentGateway) ProcessDNSQuery(srcIP string, r *dns.Msg, viaTCP bo
|
||||
|
||||
// ProcessDNSQueryToTarget evaluates a direct DNS request sent to a specific
|
||||
// destination IP:port (e.g. `dig @223.5.5.5` or `nmap -sU -p 53 <target>`).
|
||||
// When no upstream proxy is active, it queries targetServer directly and returns
|
||||
// (nil, err) on upstream failure instead of synthesizing SERVFAIL, preventing
|
||||
// false-positive `53/udp open` reports on non-DNS hosts.
|
||||
// It always queries targetServer (directly or via upstream proxy when active)
|
||||
// and never substitutes the host's DNSUpstream(), returning (nil, err) on
|
||||
// failure instead of synthesizing SERVFAIL to prevent false-positive open
|
||||
// resolver / `53/udp open` reports on non-DNS hosts.
|
||||
func (g *TransparentGateway) ProcessDNSQueryToTarget(srcIP string, r *dns.Msg, viaTCP bool, targetServer string) (*dns.Msg, error) {
|
||||
return g.processDNSQuery(srcIP, r, viaTCP, strings.TrimSpace(targetServer), false)
|
||||
}
|
||||
@@ -712,13 +713,20 @@ func (g *TransparentGateway) processDNSQuery(srcIP string, r *dns.Msg, viaTCP bo
|
||||
|
||||
upstreamProxy := g.backend.ResolveUpstream(src)
|
||||
dnsServer := ""
|
||||
if upstreamProxy == nil && targetServer != "" {
|
||||
if targetServer != "" {
|
||||
dnsServer = targetServer
|
||||
} else {
|
||||
dnsServer = strings.TrimSpace(g.backend.DNSUpstream())
|
||||
if dnsServer == "" {
|
||||
dnsServer = defaultSystemDNSUpstream()
|
||||
}
|
||||
if upstreamProxy != nil {
|
||||
// A remote upstream proxy cannot reach the host's loopback stub (e.g. 127.0.0.53).
|
||||
h, _ := splitHostAndPort(dnsServer)
|
||||
if ip := net.ParseIP(strings.TrimSpace(h)); ip != nil && ip.IsLoopback() {
|
||||
dnsServer = "8.8.8.8:53"
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(dnsServer); err != nil {
|
||||
dnsServer = net.JoinHostPort(dnsServer, "53")
|
||||
@@ -1417,6 +1425,20 @@ func (t *Traffic) DNSUpstream() string {
|
||||
return t.dnsUpstream
|
||||
}
|
||||
|
||||
func (t *Traffic) SetStoreErrorTraffic(enabled bool) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.storeErrorTraffic.Store(enabled)
|
||||
}
|
||||
|
||||
func (t *Traffic) StoreErrorTraffic() bool {
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
return t.storeErrorTraffic.Load()
|
||||
}
|
||||
|
||||
// PassthroughHosts returns the list of hostnames currently downgraded to L4 passthrough.
|
||||
func (t *Traffic) PassthroughHosts() []string {
|
||||
if t == nil {
|
||||
|
||||
@@ -521,3 +521,73 @@ func TestPerSourceUpstreamOverrideAndTransparentHTTPBridge(t *testing.T) {
|
||||
// Silence unused tls import check if not needed.
|
||||
_ = tls.VersionTLS12
|
||||
}
|
||||
|
||||
func TestStoreErrorTrafficDefaultOffAndToggle(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()
|
||||
|
||||
if tr.StoreErrorTraffic() {
|
||||
t.Fatalf("expected StoreErrorTraffic to default to false")
|
||||
}
|
||||
|
||||
// Default OFF: error flows and DNS error queries are dropped; allow/block/passthrough are stored.
|
||||
_ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-allow", Protocol: "tcp", DstIP: "1.1.1.1", DstPort: 80, Action: "allow"})
|
||||
_ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-block", Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 80, Action: "block"})
|
||||
_ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-pass", Protocol: "tls", DstIP: "1.1.1.3", DstPort: 443, Action: "passthrough"})
|
||||
_ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-dropped", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"})
|
||||
|
||||
_ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-allow", QName: "ok.example", QType: "A", Action: "allow"})
|
||||
_ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-block", QName: "bad.example", QType: "A", Action: "block"})
|
||||
_ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-dropped", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"})
|
||||
|
||||
flows, totalFlows, err := tr.PageNetFlows(NetFlowQuery{}, 0, 20)
|
||||
if err != nil || totalFlows != 3 || len(flows) != 3 {
|
||||
t.Fatalf("expected 3 non-error flows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalFlows, flows, err)
|
||||
}
|
||||
dnsRows, totalDNS, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 20)
|
||||
if err != nil || totalDNS != 2 || len(dnsRows) != 2 {
|
||||
t.Fatalf("expected 2 non-error DNS rows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalDNS, dnsRows, err)
|
||||
}
|
||||
|
||||
// Enable error storage -> error flows & DNS errors are persisted.
|
||||
tr.SetStoreErrorTraffic(true)
|
||||
if !tr.StoreErrorTraffic() {
|
||||
t.Fatalf("expected StoreErrorTraffic=true after toggle")
|
||||
}
|
||||
_ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-kept", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"})
|
||||
_ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-kept", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"})
|
||||
|
||||
errFlows, errFlowTotal, _ := tr.PageNetFlows(NetFlowQuery{Action: "error"}, 0, 10)
|
||||
if errFlowTotal != 1 || len(errFlows) != 1 || errFlows[0].ID != "nf-err-kept" {
|
||||
t.Fatalf("expected 1 stored error flow after enabling, got total=%d rows=%+v", errFlowTotal, errFlows)
|
||||
}
|
||||
errDNS, errDNSTotal, _ := tr.PageDNSQueries(DNSQueryFilter{Action: "error"}, 0, 10)
|
||||
if errDNSTotal != 1 || len(errDNS) != 1 || errDNS[0].ID != "dns-err-kept" {
|
||||
t.Fatalf("expected 1 stored error DNS query after enabling, got total=%d rows=%+v", errDNSTotal, errDNS)
|
||||
}
|
||||
|
||||
// RemotePolicyState mirrors default-off and snapshot toggle before queueing events.
|
||||
var gotFlows []NetFlowRecord
|
||||
var gotDNS []DNSQueryRecord
|
||||
rs := NewRemotePolicyState("tok",
|
||||
func(r NetFlowRecord) { gotFlows = append(gotFlows, r) },
|
||||
func(r DNSQueryRecord) { gotDNS = append(gotDNS, r) },
|
||||
nil,
|
||||
)
|
||||
rs.RecordNetFlow(NetFlowRecord{ID: "r-err-1", Action: "error"})
|
||||
rs.RecordNetFlow(NetFlowRecord{ID: "r-ok-1", Action: "allow"})
|
||||
rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-1", Action: "error"})
|
||||
rs.RecordDNSQuery(DNSQueryRecord{ID: "d-ok-1", Action: "allow"})
|
||||
if len(gotFlows) != 1 || gotFlows[0].ID != "r-ok-1" || len(gotDNS) != 1 || gotDNS[0].ID != "d-ok-1" {
|
||||
t.Fatalf("RemotePolicyState should drop error events by default: flows=%+v dns=%+v", gotFlows, gotDNS)
|
||||
}
|
||||
rs.Apply(GatewayPolicySnapshot{UDPPolicy: UDPPolicyBlockOnProxy, StoreErrorTraffic: true})
|
||||
rs.RecordNetFlow(NetFlowRecord{ID: "r-err-2", Action: "error"})
|
||||
rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-2", Action: "error"})
|
||||
if len(gotFlows) != 2 || gotFlows[1].ID != "r-err-2" || len(gotDNS) != 2 || gotDNS[1].ID != "d-err-2" {
|
||||
t.Fatalf("RemotePolicyState should forward error events when enabled: flows=%+v dns=%+v", gotFlows, gotDNS)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user