Files
ARTEX-chixuweihu/traffic/netflow_store.go
T
ji ruo d786de90af feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides.
- Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels.
- Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go.
- Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack.
- Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
2026-12-02 02:51:36 +08:00

710 lines
22 KiB
Go

package traffic
import (
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
const netFlowSchema = `
CREATE TABLE IF NOT EXISTS net_flows (
id TEXT PRIMARY KEY,
ts INTEGER NOT NULL,
ended_at INTEGER NOT NULL DEFAULT 0,
duration_ms INTEGER NOT NULL DEFAULT 0,
protocol TEXT NOT NULL,
dst_ip TEXT NOT NULL DEFAULT '',
dst_port INTEGER NOT NULL DEFAULT 0,
dst_host TEXT NOT NULL DEFAULT '',
sni TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL DEFAULT 'allow',
block_reason TEXT NOT NULL DEFAULT '',
upstream_proxy TEXT NOT NULL DEFAULT '',
bytes_tx INTEGER NOT NULL DEFAULT 0,
bytes_rx INTEGER NOT NULL DEFAULT 0,
tx_preview BLOB,
rx_preview BLOB,
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
container_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
intent_id INTEGER NOT NULL DEFAULT 0,
src_ip TEXT NOT NULL DEFAULT '',
src_port INTEGER NOT NULL DEFAULT 0,
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_nf_ts ON net_flows(ts);
CREATE INDEX IF NOT EXISTS idx_nf_proto ON net_flows(protocol, ts);
CREATE INDEX IF NOT EXISTS idx_nf_owner ON net_flows(sandbox_scope, sandbox_owner_id, ts);
CREATE INDEX IF NOT EXISTS idx_nf_dst ON net_flows(dst_host, dst_ip, dst_port);
CREATE INDEX IF NOT EXISTS idx_nf_action ON net_flows(action, ts);
CREATE TABLE IF NOT EXISTS dns_queries (
id TEXT PRIMARY KEY,
ts INTEGER NOT NULL,
duration_ms INTEGER NOT NULL DEFAULT 0,
qname TEXT NOT NULL,
qtype TEXT NOT NULL DEFAULT 'A',
rcode TEXT NOT NULL DEFAULT 'NOERROR',
answers_json TEXT NOT NULL DEFAULT '[]',
action TEXT NOT NULL DEFAULT 'allow',
block_reason TEXT NOT NULL DEFAULT '',
upstream TEXT NOT NULL DEFAULT '',
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
container_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
intent_id INTEGER NOT NULL DEFAULT 0,
src_ip TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_dns_ts ON dns_queries(ts);
CREATE INDEX IF NOT EXISTS idx_dns_qname ON dns_queries(qname, ts);
CREATE INDEX IF NOT EXISTS idx_dns_owner ON dns_queries(sandbox_scope, sandbox_owner_id, ts);
CREATE INDEX IF NOT EXISTS idx_dns_action ON dns_queries(action, ts);
`
const (
// maxFlowPreviewBytes caps per-direction payload previews persisted in SQLite
// so port scans and large binary transfers cannot bloat index.sqlite.
maxFlowPreviewBytes = 4096
// maxNetFlowRows / maxDNSQueryRows bound rolling retention for non-HTTP logs.
maxNetFlowRows = 50000
maxDNSQueryRows = 50000
trimCheckEvery = 500
dnsCacheMax = 4096
dnsCacheTTL = 10 * time.Minute
)
// NetFlowRecord captures one non-HTTP L4 flow (raw TCP, TLS passthrough, UDP)
// or blocked outbound connection observed by the transparent gateway (#218 Phase 3/4).
type NetFlowRecord struct {
ID string `json:"id"`
TS int64 `json:"ts"`
EndedAt int64 `json:"ended_at,omitempty"`
DurationMS int64 `json:"duration_ms"`
Protocol string `json:"protocol"` // tcp, tls, udp
DstIP string `json:"dst_ip"`
DstPort int `json:"dst_port"`
DstHost string `json:"dst_host,omitempty"`
SNI string `json:"sni,omitempty"`
Action string `json:"action"` // allow, block, error, passthrough
BlockReason string `json:"block_reason,omitempty"`
UpstreamProxy string `json:"upstream_proxy,omitempty"`
BytesTX int64 `json:"bytes_tx"`
BytesRX int64 `json:"bytes_rx"`
TXPreview []byte `json:"tx_preview,omitempty"`
RXPreview []byte `json:"rx_preview,omitempty"`
TXPreviewText string `json:"tx_preview_text,omitempty"`
TXPreviewHex string `json:"tx_preview_hex,omitempty"`
TXBinary bool `json:"tx_binary,omitempty"`
RXPreviewText string `json:"rx_preview_text,omitempty"`
RXPreviewHex string `json:"rx_preview_hex,omitempty"`
RXBinary bool `json:"rx_binary,omitempty"`
SandboxScope string `json:"sandbox_scope,omitempty"`
SandboxOwnerID string `json:"sandbox_owner_id,omitempty"`
ContainerID string `json:"container_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IntentID int64 `json:"intent_id,omitempty"`
SrcIP string `json:"src_ip,omitempty"`
SrcPort int `json:"src_port,omitempty"`
Error string `json:"error,omitempty"`
}
// NetFlowQuery filters paged net_flows queries.
type NetFlowQuery struct {
Protocol string
Action string
SandboxScope string
SandboxOwnerID string
ContainerID string
OwnerTaskID string
Query string // matches dst_host, dst_ip, sni, src_ip, block_reason
}
// DNSQueryRecord captures one intercepted DNS query and its answer/block decision.
type DNSQueryRecord struct {
ID string `json:"id"`
TS int64 `json:"ts"`
DurationMS int64 `json:"duration_ms"`
QName string `json:"qname"`
QType string `json:"qtype"`
RCode string `json:"rcode"`
Answers []string `json:"answers"`
Action string `json:"action"` // allow, block, error
BlockReason string `json:"block_reason,omitempty"`
Upstream string `json:"upstream,omitempty"`
SandboxScope string `json:"sandbox_scope,omitempty"`
SandboxOwnerID string `json:"sandbox_owner_id,omitempty"`
ContainerID string `json:"container_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IntentID int64 `json:"intent_id,omitempty"`
SrcIP string `json:"src_ip,omitempty"`
Error string `json:"error,omitempty"`
}
// DNSQueryFilter filters paged dns_queries queries.
type DNSQueryFilter struct {
QType string
RCode string
Action string
SandboxScope string
SandboxOwnerID string
ContainerID string
OwnerTaskID string
Query string // matches qname, answers_json, src_ip, block_reason
}
type dnsCacheEntry struct {
domain string
expiresAt time.Time
}
// dnsReverseCache maps recently resolved IPs back to their queried domain name
// so subsequent raw TCP/UDP connections to that IP carry dst_host attribution
// and domain-based egress blacklist enforcement.
type dnsReverseCache struct {
mu sync.RWMutex
entries map[string]dnsCacheEntry
}
func newDNSReverseCache() *dnsReverseCache {
return &dnsReverseCache{entries: make(map[string]dnsCacheEntry, 128)}
}
func (c *dnsReverseCache) Set(ip, domain string) {
if c == nil {
return
}
ip = normalizeIPString(ip)
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
if ip == "" || domain == "" {
return
}
now := time.Now()
c.mu.Lock()
if len(c.entries) >= dnsCacheMax {
for k, v := range c.entries {
if now.After(v.expiresAt) {
delete(c.entries, k)
}
}
if len(c.entries) >= dnsCacheMax {
// Evict a small slice so writes stay O(1) amortized.
dropped := 0
for k := range c.entries {
delete(c.entries, k)
dropped++
if dropped >= 256 {
break
}
}
}
}
c.entries[ip] = dnsCacheEntry{domain: domain, expiresAt: now.Add(dnsCacheTTL)}
c.mu.Unlock()
}
func (c *dnsReverseCache) Lookup(ip string) string {
if c == nil {
return ""
}
ip = normalizeIPString(ip)
if ip == "" {
return ""
}
c.mu.RLock()
e, ok := c.entries[ip]
c.mu.RUnlock()
if !ok || time.Now().After(e.expiresAt) {
return ""
}
return e.domain
}
// RememberDNS records an ip -> domain mapping in the reverse DNS cache.
func (t *Traffic) RememberDNS(ip, domain string) {
if t == nil || t.dnsCache == nil {
return
}
t.dnsCache.Set(ip, domain)
}
// LookupDNSReverse returns the most recently resolved domain for ip, if cached.
func (t *Traffic) LookupDNSReverse(ip string) string {
if t == nil || t.dnsCache == nil {
return ""
}
return t.dnsCache.Lookup(ip)
}
func ensureNetFlowSchema(ctx context.Context, conn *sql.Conn) error {
_, err := conn.ExecContext(ctx, netFlowSchema)
return err
}
// FormatPayloadPreview converts raw preview bytes into a display-safe UTF-8 text
// preview and hex dump when binary bytes are present.
func FormatPayloadPreview(b []byte) (text string, hexStr string, binary bool) {
if len(b) == 0 {
return "", "", false
}
if len(b) > maxFlowPreviewBytes {
b = b[:maxFlowPreviewBytes]
}
binary = isBinaryPayload(b)
if binary {
capHex := b
if len(capHex) > 1024 {
capHex = capHex[:1024]
}
return sanitizeASCIIPreview(b), hex.EncodeToString(capHex), true
}
return string(b), "", false
}
func isBinaryPayload(b []byte) bool {
if len(b) == 0 {
return false
}
if !utf8.Valid(b) {
return true
}
ctrl := 0
for _, c := range b {
if c == 0 {
return true
}
if c < 0x20 && c != '\n' && c != '\r' && c != '\t' {
ctrl++
}
}
return ctrl*10 > len(b)
}
func sanitizeASCIIPreview(b []byte) string {
var sb strings.Builder
sb.Grow(len(b))
for _, c := range b {
if (c >= 0x20 && c < 0x7f) || c == '\n' || c == '\r' || c == '\t' {
sb.WriteByte(c)
} else {
sb.WriteByte('.')
}
}
return sb.String()
}
// RecordNetFlow persists a non-HTTP flow record into SQLite with bounded
// payload previews and rolling row-count retention.
func (t *Traffic) RecordNetFlow(rec NetFlowRecord) error {
if t == nil || t.db == nil {
return nil
}
now := time.Now()
if rec.TS <= 0 {
rec.TS = now.Unix()
}
if rec.ID == "" {
n := t.seq.Add(1)
rec.ID = fmt.Sprintf("nf-%d-%04d", rec.TS, n%10000)
}
rec.Protocol = strings.ToLower(strings.TrimSpace(rec.Protocol))
if rec.Protocol == "" {
rec.Protocol = "tcp"
}
rec.Action = strings.ToLower(strings.TrimSpace(rec.Action))
if rec.Action == "" {
rec.Action = "allow"
}
if len(rec.TXPreview) > maxFlowPreviewBytes {
rec.TXPreview = rec.TXPreview[:maxFlowPreviewBytes]
}
if len(rec.RXPreview) > maxFlowPreviewBytes {
rec.RXPreview = rec.RXPreview[:maxFlowPreviewBytes]
}
t.wmu.Lock()
defer t.wmu.Unlock()
_, err := t.db.Exec(`INSERT OR REPLACE INTO net_flows(
id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
rec.ID, rec.TS, rec.EndedAt, rec.DurationMS, rec.Protocol, rec.DstIP, rec.DstPort, rec.DstHost, rec.SNI,
rec.Action, rec.BlockReason, rec.UpstreamProxy, rec.BytesTX, rec.BytesRX, rec.TXPreview, rec.RXPreview,
rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.SrcPort, rec.Error,
)
if err != nil {
log.Printf("[traffic] 记录 net_flow %s 失败:%v", rec.ID, err)
return err
}
if t.nfWrites.Add(1)%trimCheckEvery == 0 {
t.trimTableLocked("net_flows", maxNetFlowRows)
}
return nil
}
// RecordDNSQuery persists an intercepted DNS query record into SQLite.
func (t *Traffic) RecordDNSQuery(rec DNSQueryRecord) error {
if t == nil || t.db == nil {
return nil
}
now := time.Now()
if rec.TS <= 0 {
rec.TS = now.Unix()
}
if rec.ID == "" {
n := t.seq.Add(1)
rec.ID = fmt.Sprintf("dns-%d-%04d", rec.TS, n%10000)
}
rec.QName = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(rec.QName)), ".")
if rec.QType == "" {
rec.QType = "A"
}
if rec.Action == "" {
rec.Action = "allow"
}
answers := rec.Answers
if answers == nil {
answers = []string{}
}
answersJSON, _ := json.Marshal(answers)
t.wmu.Lock()
defer t.wmu.Unlock()
_, err := t.db.Exec(`INSERT OR REPLACE INTO dns_queries(
id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
rec.ID, rec.TS, rec.DurationMS, rec.QName, rec.QType, rec.RCode, string(answersJSON), rec.Action, rec.BlockReason, rec.Upstream,
rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.Error,
)
if err != nil {
log.Printf("[traffic] 记录 dns_query %s 失败:%v", rec.ID, err)
return err
}
if t.dnsWrites.Add(1)%trimCheckEvery == 0 {
t.trimTableLocked("dns_queries", maxDNSQueryRows)
}
return nil
}
func (t *Traffic) trimTableLocked(table string, maxRows int) {
var count int
if err := t.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count <= maxRows {
return
}
excess := count - maxRows
if _, err := t.db.Exec(
`DELETE FROM `+table+` WHERE id IN (SELECT id FROM `+table+` ORDER BY ts ASC, rowid ASC LIMIT ?)`,
excess,
); err != nil {
log.Printf("[traffic] 滚动清理 %s 失败:%v", table, err)
return
}
t.reclaim()
}
// PageNetFlows returns a filtered, newest-first page of non-HTTP flow records.
func (t *Traffic) PageNetFlows(q NetFlowQuery, page, size int) ([]NetFlowRecord, int, error) {
if t == nil || t.db == nil {
return []NetFlowRecord{}, 0, nil
}
if page < 0 {
page = 0
}
if size <= 0 || size > 500 {
size = 100
}
var conds []string
var args []any
if p := strings.ToLower(strings.TrimSpace(q.Protocol)); p != "" && p != "all" {
conds = append(conds, `protocol=?`)
args = append(args, p)
}
if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" {
conds = append(conds, `action=?`)
args = append(args, a)
}
if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" {
conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`)
args = append(args, taskID)
}
if sc := strings.TrimSpace(q.SandboxScope); sc != "" {
conds = append(conds, `sandbox_scope=?`)
args = append(args, sc)
}
if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" {
conds = append(conds, `sandbox_owner_id=?`)
args = append(args, ow)
}
if cid := strings.TrimSpace(q.ContainerID); cid != "" {
conds = append(conds, `(container_id=? OR container_id LIKE ?)`)
args = append(args, cid, cid+"%")
}
if kw := strings.TrimSpace(q.Query); kw != "" {
like := "%" + kw + "%"
conds = append(conds, `(dst_host LIKE ? OR dst_ip LIKE ? OR sni LIKE ? OR src_ip LIKE ? OR block_reason LIKE ? OR CAST(dst_port AS TEXT)=?)`)
args = append(args, like, like, like, like, like, kw)
}
where := ""
if len(conds) > 0 {
where = " WHERE " + strings.Join(conds, " AND ")
}
var total int
if err := t.db.QueryRow(`SELECT count(*) FROM net_flows`+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
if total == 0 {
return []NetFlowRecord{}, 0, nil
}
queryArgs := append(append([]any{}, args...), size, page*size)
rows, err := t.db.Query(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
FROM net_flows`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := make([]NetFlowRecord, 0, size)
for rows.Next() {
var r NetFlowRecord
if err := rows.Scan(
&r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI,
&r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error,
); err != nil {
return nil, 0, err
}
out = append(out, r)
}
return out, total, rows.Err()
}
// GetNetFlow fetches one flow record including its TX/RX payload previews.
func (t *Traffic) GetNetFlow(id string) (*NetFlowRecord, error) {
if t == nil || t.db == nil {
return nil, sql.ErrNoRows
}
var r NetFlowRecord
err := t.db.QueryRow(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
FROM net_flows WHERE id=?`, strings.TrimSpace(id)).Scan(
&r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI,
&r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX, &r.TXPreview, &r.RXPreview,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error,
)
if err != nil {
return nil, err
}
r.TXPreviewText, r.TXPreviewHex, r.TXBinary = FormatPayloadPreview(r.TXPreview)
r.RXPreviewText, r.RXPreviewHex, r.RXBinary = FormatPayloadPreview(r.RXPreview)
r.TXPreview = nil
r.RXPreview = nil
return &r, nil
}
// PageDNSQueries returns a filtered, newest-first page of DNS query records.
func (t *Traffic) PageDNSQueries(q DNSQueryFilter, page, size int) ([]DNSQueryRecord, int, error) {
if t == nil || t.db == nil {
return []DNSQueryRecord{}, 0, nil
}
if page < 0 {
page = 0
}
if size <= 0 || size > 500 {
size = 100
}
var conds []string
var args []any
if qt := strings.ToUpper(strings.TrimSpace(q.QType)); qt != "" && qt != "ALL" {
conds = append(conds, `qtype=?`)
args = append(args, qt)
}
if rc := strings.ToUpper(strings.TrimSpace(q.RCode)); rc != "" && rc != "ALL" {
conds = append(conds, `rcode=?`)
args = append(args, rc)
}
if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" {
conds = append(conds, `action=?`)
args = append(args, a)
}
if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" {
conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`)
args = append(args, taskID)
}
if sc := strings.TrimSpace(q.SandboxScope); sc != "" {
conds = append(conds, `sandbox_scope=?`)
args = append(args, sc)
}
if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" {
conds = append(conds, `sandbox_owner_id=?`)
args = append(args, ow)
}
if cid := strings.TrimSpace(q.ContainerID); cid != "" {
conds = append(conds, `(container_id=? OR container_id LIKE ?)`)
args = append(args, cid, cid+"%")
}
if kw := strings.TrimSpace(q.Query); kw != "" {
like := "%" + kw + "%"
conds = append(conds, `(qname LIKE ? OR answers_json LIKE ? OR src_ip LIKE ? OR block_reason LIKE ?)`)
args = append(args, like, like, like, like)
}
where := ""
if len(conds) > 0 {
where = " WHERE " + strings.Join(conds, " AND ")
}
var total int
if err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
if total == 0 {
return []DNSQueryRecord{}, 0, nil
}
queryArgs := append(append([]any{}, args...), size, page*size)
rows, err := t.db.Query(`SELECT id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error
FROM dns_queries`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := make([]DNSQueryRecord, 0, size)
for rows.Next() {
var r DNSQueryRecord
var answersRaw string
if err := rows.Scan(
&r.ID, &r.TS, &r.DurationMS, &r.QName, &r.QType, &r.RCode, &answersRaw, &r.Action, &r.BlockReason, &r.Upstream,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.Error,
); err != nil {
return nil, 0, err
}
if answersRaw != "" {
_ = json.Unmarshal([]byte(answersRaw), &r.Answers)
}
if r.Answers == nil {
r.Answers = []string{}
}
out = append(out, r)
}
return out, total, rows.Err()
}
// CountNetFlows returns total stored rows in net_flows.
func (t *Traffic) CountNetFlows() (int, error) {
if t == nil || t.db == nil {
return 0, nil
}
var n int
err := t.db.QueryRow(`SELECT count(*) FROM net_flows`).Scan(&n)
return n, err
}
// CountDNSQueries returns total stored rows in dns_queries.
func (t *Traffic) CountDNSQueries() (int, error) {
if t == nil || t.db == nil {
return 0, nil
}
var n int
err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`).Scan(&n)
return n, err
}
// DeleteNetFlows deletes net_flows rows, optionally restricted to one sandbox owner.
func (t *Traffic) DeleteNetFlows(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var (
res sql.Result
err error
)
if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" {
res, err = t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID))
} else {
res, err = t.db.Exec(`DELETE FROM net_flows`)
}
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
if n > 0 {
t.reclaim()
}
return n, nil
}
// DeleteDNSQueries deletes dns_queries rows, optionally restricted to one sandbox owner.
func (t *Traffic) DeleteDNSQueries(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var (
res sql.Result
err error
)
if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" {
res, err = t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID))
} else {
res, err = t.db.Exec(`DELETE FROM dns_queries`)
}
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
if n > 0 {
t.reclaim()
}
return n, nil
}
// DeleteNonHTTPByOwner deletes both net_flows and dns_queries attributed to one
// sandbox owner (used when deleting a task with DeleteTraffic enabled).
func (t *Traffic) DeleteNonHTTPByOwner(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil || strings.TrimSpace(scope) == "" || strings.TrimSpace(ownerID) == "" {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var total int64
if res, err := t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil {
n, _ := res.RowsAffected()
total += n
} else {
return 0, err
}
if res, err := t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil {
n, _ := res.RowsAffected()
total += n
} else {
return total, err
}
if total > 0 {
t.reclaim()
}
return total, nil
}
var _ = atomic.Int64{}