Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/egress-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,15 @@ jobs:
TestRevisionNftEffectsRealFileAndKernel \
TestTransitionRealNftChangedIPKernelRules

- name: Run privileged drop telemetry regressions
working-directory: components/egress
run: |
# Built-in support also works when modprobe is unavailable.
sudo modprobe nfnetlink_log || true
bash scripts/ci-nft-go-test.sh ./pkg/droptelemetry \
TestDropTelemetryKernel \
TestDropTelemetryBindCloseKernel

- name: Run privileged quarantine packet regressions
working-directory: components/egress
run: |
Expand Down
1 change: 1 addition & 0 deletions components/egress/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ RUN chown mitmproxy:mitmproxy /var/lib/mitmproxy/.mitmproxy/config.yaml \

# All egress runtime artifacts live under one directory to keep paths grouped.
COPY --from=builder /out/egress /opt/opensandbox-egress/egress
COPY components/egress/third_party /opt/opensandbox-egress/licenses
COPY --from=builder /out/opensandbox-supervisor /opt/opensandbox-egress/supervisor
COPY --from=builder /out/egress-trace /opt/opensandbox-egress/egress-trace
# Pre-start hook: reap any mitmdump left over from a previous crashed
Expand Down
4 changes: 4 additions & 0 deletions components/egress/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.26.0

require (
github.com/alibaba/opensandbox/internal v0.0.0
github.com/florianl/go-nflog/v2 v2.3.0
github.com/miekg/dns v1.1.61
github.com/shirou/gopsutil v3.21.11+incompatible
github.com/stretchr/testify v1.12.1
Expand All @@ -25,8 +26,11 @@ require (
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/mdlayher/netlink v1.9.1-0.20260312172110-2a932c0fc1ae // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
Expand Down
6 changes: 6 additions & 0 deletions components/egress/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/florianl/go-nflog/v2 v2.3.0 h1:mghOcw09/XPs9dEoR1ffKPNC/tsNRCuhq/2BTz2GRjQ=
github.com/florianl/go-nflog/v2 v2.3.0/go.mod h1:ob11SI7TLgZJVZj356/kiD5DtTzKLw/caENAKeVSgSM=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
Expand All @@ -21,6 +23,10 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mdlayher/netlink v1.9.1-0.20260312172110-2a932c0fc1ae h1:sOtbiuSoORJRY86KHJ3dqJ6cgppzEEZF8SLU7MpCWhE=
github.com/mdlayher/netlink v1.9.1-0.20260312172110-2a932c0fc1ae/go.mod h1:YBnl5BXsCoRuwBjKKlZ+aYmEoq0r12FDA/3JC+94KDg=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/miekg/dns v1.1.61 h1:nLxbwF3XxhwVSm8g9Dghm9MHPaUZuqhPiGL+675ZmEs=
github.com/miekg/dns v1.1.61/go.mod h1:mnAarhS3nWaW+NVP2wTkYVIZyHNJ098SJZUki3eykwQ=
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
Expand Down
87 changes: 87 additions & 0 deletions components/egress/pkg/droptelemetry/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2026 The OpenSandbox Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package droptelemetry

import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)

const (
EnvMode = "OPENSANDBOX_EGRESS_DROP_TELEMETRY"
EnvRate = "OPENSANDBOX_EGRESS_DROP_LOG_RATE"
EnvPoll = "OPENSANDBOX_EGRESS_DROP_COUNTER_POLL"
)

// The group is fixed because it is netns-local and the receiver filters by prefix and reason.
const nflogGroup uint16 = 3085

type Mode string

const (
Off Mode = "off"
Counter Mode = "counter"
Sample Mode = "sample"
)

type Config struct {
Mode Mode
Group uint16
Rate string
Burst uint32
Poll time.Duration
}

func DefaultConfig() Config {
return Config{Mode: Off, Group: nflogGroup, Rate: "20/second", Burst: 40, Poll: 15 * time.Second}
}

var ratePattern = regexp.MustCompile(`^[1-9][0-9]*/(second|minute|hour|day)$`)

func Parse(getenv func(string) string) (Config, error) {
c := DefaultConfig()
if v := strings.TrimSpace(getenv(EnvMode)); v != "" {
c.Mode = Mode(v)
}
if c.Mode != Off && c.Mode != Counter && c.Mode != Sample {
return c, fmt.Errorf("%s must be off, counter or sample", EnvMode)
}
if c.Mode == Off {
return c, nil
}
if v := getenv(EnvRate); v != "" {
if !ratePattern.MatchString(v) {
return c, fmt.Errorf("invalid %s", EnvRate)
}
n, e := strconv.ParseUint(strings.Split(v, "/")[0], 10, 32)
if e != nil || n == 0 {
return c, fmt.Errorf("invalid %s", EnvRate)
}
c.Rate = v
// Twice the rate count, capped at 1000, bounds each rule's token bucket.
c.Burst = uint32(max(1, min(2*n, 1000)))
}
if v := getenv(EnvPoll); v != "" {
d, e := time.ParseDuration(v)
if e != nil || d <= 0 {
return c, fmt.Errorf("invalid %s", EnvPoll)
}
c.Poll = d
}
return c, nil
}
210 changes: 210 additions & 0 deletions components/egress/pkg/droptelemetry/kernel_linux_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// Copyright 2026 The OpenSandbox Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build linux

package droptelemetry_test

import (
"context"
"errors"
"net"
"os"
"os/exec"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/alibaba/opensandbox/egress/pkg/droptelemetry"
)

func privateDropNetNS(t *testing.T, ctx context.Context) bool {
t.Helper()
if os.Getenv("OPENSANDBOX_NFT_TEST") != "1" {
t.Skip("kernel validation not executed: set OPENSANDBOX_NFT_TEST=1")
}
parent := os.Getenv("OPENSANDBOX_DROP_PARENT_NETNS")
current, err := os.Readlink("/proc/self/ns/net")
require.NoError(t, err)
if parent != "" {
require.NotEqual(t, parent, current)
t.Logf("private netns %s, parent %s", current, parent)
return true
}
cmd := exec.CommandContext(ctx, "unshare", "--net", os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v", "-test.timeout=45s")
cmd.Env = append(os.Environ(), "OPENSANDBOX_DROP_PARENT_NETNS="+current)
out, err := cmd.CombinedOutput()
require.NoError(t, err, "%s", out)
t.Logf("%s", out)
if strings.Contains(string(out), "NFLOG_UNAVAILABLE:") {
t.Skip("NFLOG_UNAVAILABLE: see private-netns output")
}
return false
}
func runKernelNft(ctx context.Context, script string) ([]byte, error) {
cmd := exec.CommandContext(ctx, "nft", "-f", "-")
cmd.Stdin = strings.NewReader(script)
return cmd.CombinedOutput()
}
func requireNFLOG(t *testing.T, ctx context.Context, cfg droptelemetry.Config, rt *droptelemetry.Runtime, onPacket func(droptelemetry.Packet)) func() {
t.Helper()
var bindErr, probeErr error
closeNF := rt.Start(ctx, func(ctx context.Context, s string) ([]byte, error) {
out, e := runKernelNft(ctx, s)
probeErr = e
return out, e
}, func(ctx context.Context, c droptelemetry.Config, packet func(droptelemetry.Packet), failure func(error)) (func(), error) {
closeNF, e := droptelemetry.Bind(ctx, c, packet, failure)
bindErr = e
return closeNF, e
}, onPacket)
t.Cleanup(closeNF)
if bindErr != nil {
msg := strings.ToLower(bindErr.Error())
if strings.Contains(msg, "protocol not supported") || strings.Contains(msg, "operation not supported") || strings.Contains(msg, "no such file or directory") {
t.Skipf("NFLOG_UNAVAILABLE: %v", bindErr)
}
require.NoError(t, bindErr)
}
require.NoError(t, probeErr)
return closeNF
}
func TestDropTelemetryKernel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
if !privateDropNetNS(t, ctx) {
return
}
out, err := exec.CommandContext(ctx, "ip", "link", "set", "lo", "up").CombinedOutput()
require.NoError(t, err, "%s", out)
cfg := droptelemetry.DefaultConfig()
cfg.Mode = droptelemetry.Sample
cfg.Rate = "1/minute"
cfg.Burst = 1
cfg.Poll = time.Hour
rt := droptelemetry.New(cfg, "drop_test")
samples := make(chan droptelemetry.Packet, 64)
requireNFLOG(t, ctx, cfg, rt, func(p droptelemetry.Packet) {
select {
case samples <- p:
default:
}
})
run := rt.Wrap(runKernelNft, func(line string) droptelemetry.Reason {
if strings.Contains(line, "udp dport") {
return droptelemetry.DoT
}
if strings.Contains(line, "tcp dport") {
return droptelemetry.PortDeny
}
return droptelemetry.DenySet
})
_, err = run(ctx, "add table inet drop_test\nadd chain inet drop_test output { type filter hook output priority 0; policy accept; }\nadd rule inet drop_test output udp dport 15354 drop\nadd rule inet drop_test output tcp dport 15355 drop\nadd rule inet drop_test output ip daddr 127.0.0.2 drop\n")
require.NoError(t, err)
udp, err := net.ListenPacket("udp4", "127.0.0.1:15354")
require.NoError(t, err)
defer udp.Close()
tcp, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 15355})
require.NoError(t, err)
defer tcp.Close()
for i := 0; i < 8; i++ {
conn, e := net.Dial("udp4", "127.0.0.1:15354")
require.NoError(t, e)
_, e = conn.Write([]byte("drop test"))
require.True(t, e == nil || errors.Is(e, syscall.EPERM), "%v", e)
conn.Close()
}
for i := 0; i < 3; i++ {
conn, e := net.DialTimeout("tcp4", "127.0.0.1:15355", 80*time.Millisecond)
if conn != nil {
conn.Close()
}
require.Error(t, e, "SYN must still be dropped after sample limit is exhausted")
}
conn, err := net.Dial("udp4", "127.0.0.2:15356")
require.NoError(t, err)
_, err = conn.Write([]byte("address-only drop"))
require.True(t, err == nil || errors.Is(err, syscall.EPERM), "%v", err)
conn.Close()
seen := map[string]int{}
deadline := time.NewTimer(2 * time.Second)
defer deadline.Stop()
collect:
for {
select {
case p := <-samples:
seen[string(p.Reason)+":"+p.Proto]++
require.True(t, p.SrcIP.IsLoopback())
case <-deadline.C:
break collect
}
}
require.Equal(t, 1, seen["dot:udp"])
require.Equal(t, 1, seen["port_deny:tcp"])
require.Equal(t, 1, seen["deny_set:udp"])
require.NoError(t, udp.SetReadDeadline(time.Now().Add(50*time.Millisecond)))
_, _, err = udp.ReadFrom(make([]byte, 32))
require.Error(t, err, "even UDP packets above the sample limit remain dropped")
require.NoError(t, tcp.SetDeadline(time.Now().Add(50*time.Millisecond)))
accepted, err := tcp.Accept()
if accepted != nil {
accepted.Close()
}
require.Error(t, err)
data, err := exec.CommandContext(ctx, "nft", "-j", "list", "counters", "table", "inet", "drop_test").CombinedOutput()
require.NoError(t, err, "%s", data)
counts, err := droptelemetry.ParseCounters(data)
require.NoError(t, err)
require.EqualValues(t, 8, counts["dot"])
require.GreaterOrEqual(t, counts["port_deny"], uint64(3))
require.EqualValues(t, 1, counts["deny_set"])
t.Logf("samples=%v counters=%v; over-limit TCP/UDP delivery blocked", seen, counts)
}
func TestDropTelemetryBindCloseKernel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if !privateDropNetNS(t, ctx) {
return
}
cfg := droptelemetry.DefaultConfig()
var callbacks atomic.Int64
closeNF, err := droptelemetry.Bind(ctx, cfg, func(droptelemetry.Packet) {}, func(error) { callbacks.Add(1) })
if err != nil {
msg := strings.ToLower(err.Error())
if strings.Contains(msg, "protocol not supported") || strings.Contains(msg, "operation not supported") || strings.Contains(msg, "no such file or directory") {
t.Skipf("NFLOG_UNAVAILABLE: %v", err)
}
require.NoError(t, err)
}
t.Cleanup(closeNF)
closed := make(chan struct{})
go func() { closeNF(); close(closed) }()
select {
case <-closed:
case <-time.After(2 * time.Second):
cancel()
<-closed
t.Fatal("NFLOG close blocked while the parent context was live")
}
require.NoError(t, ctx.Err(), "closing the receiver must not cancel its parent")
require.Zero(t, callbacks.Load(), "socket closure must not invoke the receive error callback")
time.Sleep(50 * time.Millisecond)
require.Zero(t, callbacks.Load(), "closed receiver must not spin on receive errors")
closeNF()
t.Log("receiver closed with a live parent context; no error callback loop")
}
Loading
Loading