Skip to content
Open
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
1 change: 1 addition & 0 deletions .github/workflows/egress-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ jobs:
sudo modprobe nfnetlink_log || true
bash scripts/ci-nft-go-test.sh ./pkg/droptelemetry \
TestDropTelemetryKernel \
TestDropTelemetryRulesetKernel \
TestDropTelemetryBindCloseKernel

- name: Run privileged quarantine packet regressions
Expand Down
53 changes: 53 additions & 0 deletions components/egress/drop_telemetry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 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 main

import (
"context"
"os"

"github.com/alibaba/opensandbox/egress/pkg/constants"
"github.com/alibaba/opensandbox/egress/pkg/droptelemetry"
"github.com/alibaba/opensandbox/egress/pkg/log"
"github.com/alibaba/opensandbox/egress/pkg/telemetry"
slogger "github.com/alibaba/opensandbox/internal/logger"
)

func startDropTelemetry(ctx context.Context, table string, run droptelemetry.Runner) (*droptelemetry.Runtime, func()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Low] startDropTelemetry has no test

go tool cover -func puts this function at 0%. TestDropAuditSidecar covers auditBlockedPacket only, and TestDropTelemetryRulesetKernel builds its runtime by hand instead of going through here. So three behaviours that exist only in this function are pinned by reading alone: off returning a nil runtime (which is what keeps the default path byte-identical), an invalid value being fatal, and the Start wiring with droptelemetry.Bind and the audit callback.

The off case is the one that guards the default path, so a small test for it would be worth having.

cfg, err := droptelemetry.Parse(os.Getenv)
if err != nil {
log.Fatalf("drop telemetry configuration: %v", err)
}
if cfg.Mode == droptelemetry.Off {
return nil, func() {}
}
rt := droptelemetry.New(cfg, table)
closeNF := rt.Start(ctx, run, droptelemetry.Bind, func(p droptelemetry.Packet) { auditBlockedPacket(p) })
return rt, closeNF
}
func auditBlockedPacket(p droptelemetry.Packet) {
sandboxID := os.Getenv(constants.EnvSandboxID)
fields := []slogger.Field{
{Key: "opensandbox.event", Value: "egress.blocked_ip"},
{Key: "src_ip", Value: p.SrcIP.String()},
{Key: "dst_ip", Value: p.DstIP.String()},
{Key: "dst_port", Value: p.DstPort},
{Key: "proto", Value: p.Proto},
{Key: "reason", Value: string(p.Reason)},
}
fields = append(fields, slogger.Field{Key: "sandbox_id", Value: sandboxID})
telemetry.RecordBlockedSample(string(p.Reason))
log.Logger.With(fields...).Infof("egress blocked IP")
}
109 changes: 109 additions & 0 deletions components/egress/drop_telemetry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// 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 main

import (
"context"
"errors"
"net/netip"
"testing"
"time"

"github.com/stretchr/testify/require"
collectormetrics "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
"google.golang.org/protobuf/proto"

"github.com/alibaba/opensandbox/egress/pkg/constants"
"github.com/alibaba/opensandbox/egress/pkg/droptelemetry"
"github.com/alibaba/opensandbox/egress/pkg/log"
"github.com/alibaba/opensandbox/egress/pkg/telemetry"
slogger "github.com/alibaba/opensandbox/internal/logger"
)

type dropAuditCapture struct {
slogger.Logger
fields map[string]any
events int
}

func (l *dropAuditCapture) With(fields ...slogger.Field) slogger.Logger {
for _, f := range fields {
l.fields[f.Key] = f.Value
}
return l
}
func (l *dropAuditCapture) Infof(string, ...any) { l.events++ }
func TestDropAuditSidecar(t *testing.T) {
prior := log.Logger
capture := &dropAuditCapture{Logger: prior, fields: map[string]any{}}
log.Logger = capture
t.Cleanup(func() { log.Logger = prior })
t.Setenv(constants.EnvSandboxID, "process-id")
p := droptelemetry.Packet{SrcIP: netip.MustParseAddr("10.0.0.5"), DstIP: netip.MustParseAddr("192.0.2.1"), DstPort: 443, Proto: "tcp", Reason: droptelemetry.DenySet}
auditBlockedPacket(p)
require.Equal(t, 1, capture.events)
require.Equal(t, "egress.blocked_ip", capture.fields["opensandbox.event"])
require.Equal(t, "192.0.2.1", capture.fields["dst_ip"])
require.Equal(t, "process-id", capture.fields["sandbox_id"])
require.NotContains(t, capture.fields, "subject_id")
}

func TestDropReceiveErrorGauge(t *testing.T) {
export := captureTransitions(t)
t.Cleanup(func() { telemetry.SetDropSampler(false, "disabled") })
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := droptelemetry.DefaultConfig()
cfg.Mode = droptelemetry.Sample
cfg.Poll = time.Hour
rt := droptelemetry.New(cfg, "unused")
var receiveError func(error)
stop := rt.Start(ctx, func(context.Context, string) ([]byte, error) { return nil, nil }, func(_ context.Context, _ droptelemetry.Config, _ func(droptelemetry.Packet), failure func(error)) (func(), error) {
receiveError = failure
return func() {}, nil
}, func(droptelemetry.Packet) {})
defer stop()
require.NotNil(t, receiveError)
receiveError(errors.New("injected receive failure"))
flushCtx, flushCancel := context.WithTimeout(ctx, 5*time.Second)
defer flushCancel()
require.NoError(t, telemetry.ForceFlush(flushCtx))
var body []byte
select {
case body = <-export.received:
case <-flushCtx.Done():
t.Fatal("sampler gauge was not exported")
}
var request collectormetrics.ExportMetricsServiceRequest
require.NoError(t, proto.Unmarshal(body, &request))
found := false
for _, resource := range request.ResourceMetrics {
for _, scope := range resource.ScopeMetrics {
for _, m := range scope.Metrics {
if m.Name != "egress.drop_telemetry.sampler_up" {
continue
}
points := m.GetGauge().DataPoints
require.Len(t, points, 1)
require.EqualValues(t, 0, points[0].GetAsInt())
require.Len(t, points[0].Attributes, 1)
require.Equal(t, "cause", points[0].Attributes[0].Key)
require.Equal(t, "receive", points[0].Attributes[0].Value.GetStringValue())
found = true
}
}
}
require.True(t, found)
}
3 changes: 3 additions & 0 deletions components/egress/forward_mode.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,10 @@ func runForwardSidecar(ctx context.Context, fm *forwardMode) {
}

ep, gatewayIsLiteral := buildForwardEndpoint(fm.gateway.Host, fm.gateway.Port, constants.ForwarderMarkValue, hostsPath)
dropRuntime, closeDrop := startDropTelemetry(ctx, "opensandbox", nftables.RunDropProbe)
defer closeDrop()
nftMgr := nftables.NewManagerWithOptions(nftables.Options{
DropTelemetry: dropRuntime,
UpstreamProxy: ep,
Telemetry: telemetryEP,
ForwardRedirectPort: constants.DefaultForwarderPort,
Expand Down
14 changes: 13 additions & 1 deletion components/egress/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (

"github.com/alibaba/opensandbox/egress/pkg/constants"
"github.com/alibaba/opensandbox/egress/pkg/dnsproxy"
"github.com/alibaba/opensandbox/egress/pkg/droptelemetry"
"github.com/alibaba/opensandbox/egress/pkg/events"
"github.com/alibaba/opensandbox/egress/pkg/iptables"
"github.com/alibaba/opensandbox/egress/pkg/log"
Expand All @@ -50,6 +51,11 @@ func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()

if strings.TrimSpace(os.Getenv(constants.EnvEgressProfile)) != constants.ProfileFastSandbox {
if _, err := droptelemetry.Parse(os.Getenv); err != nil {
log.Fatalf("drop telemetry configuration: %v", err)
}
}
ctx = withLogger(ctx)
defer log.Logger.Sync()

Expand Down Expand Up @@ -153,7 +159,13 @@ func main() {
// upstreamSpec was already validated at startup; it scopes the infra nft
// exception and lets DNS exempt the proxy hostname from sandbox policy
// without feeding the allow sets.
nftMgr, err := createNftManager(mode, upstreamSpec)
var dropRuntime *droptelemetry.Runtime
if constants.ModeUsesNft(mode) {
var closeDrop func()
dropRuntime, closeDrop = startDropTelemetry(ctx, "opensandbox", nftables.RunDropProbe)
defer closeDrop()
}
nftMgr, err := createNftManager(mode, upstreamSpec, dropRuntime)
if err != nil {
log.Fatalf("nftables options: %v", err)
}
Expand Down
4 changes: 3 additions & 1 deletion components/egress/nft.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (

"github.com/alibaba/opensandbox/egress/pkg/constants"
"github.com/alibaba/opensandbox/egress/pkg/dnsproxy"
"github.com/alibaba/opensandbox/egress/pkg/droptelemetry"
"github.com/alibaba/opensandbox/egress/pkg/log"
"github.com/alibaba/opensandbox/egress/pkg/mitmproxy"
"github.com/alibaba/opensandbox/egress/pkg/nftables"
Expand All @@ -33,14 +34,15 @@ import (
)

// createNftManager is non-nil only when mode includes the nft token (e.g. dns+nft).
func createNftManager(mode string, upstream *mitmproxy.UpstreamProxySpec) (nftApplier, error) {
func createNftManager(mode string, upstream *mitmproxy.UpstreamProxySpec, drop *droptelemetry.Runtime) (nftApplier, error) {
if !constants.ModeUsesNft(mode) {
return nil, nil
}
opts, err := parseNftOptions(upstream)
if err != nil {
return nil, err
}
opts.DropTelemetry = drop
return nftables.NewManagerWithOptions(opts), nil
}

Expand Down
24 changes: 24 additions & 0 deletions components/egress/pkg/droptelemetry/kernel_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import (
"github.com/stretchr/testify/require"

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

func privateDropNetNS(t *testing.T, ctx context.Context) bool {
Expand Down Expand Up @@ -175,6 +177,28 @@ collect:
require.EqualValues(t, 1, counts["deny_set"])
t.Logf("samples=%v counters=%v; over-limit TCP/UDP delivery blocked", seen, counts)
}
func TestDropTelemetryRulesetKernel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
if !privateDropNetNS(t, ctx) {
return
}
cfg := droptelemetry.DefaultConfig()
cfg.Mode = droptelemetry.Sample
cfg.Poll = time.Hour
probe := droptelemetry.New(cfg, "unused")
requireNFLOG(t, ctx, cfg, probe, func(droptelemetry.Packet) {})
pol, err := policy.ParsePolicy(`{"defaultAction":"deny","egress":[{"action":"deny","target":"192.0.2.8","ports":[22]},{"action":"deny","target":"2001:db8::/64"}]}`)
require.NoError(t, err)
side := nftables.NewManagerWithOptions(nftables.Options{BlockDoT: true, BlockDoH443: true, DropTelemetry: droptelemetry.New(cfg, "opensandbox")})
require.NoError(t, side.ApplyStatic(ctx, pol))
require.NoError(t, side.ApplyStatic(ctx, pol))
require.NoError(t, side.RemoveEnforcement(ctx))
Comment on lines +194 to +196

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Low] The instrumented sidecar ruleset is never exercised on the data plane

This applies the instrumented sidecar table twice and removes it, which shows nft accepts the syntax, but no packet goes through it. TestDropTelemetryKernel checks drop-after-limit and the counters on the synthetic drop_test ruleset, so "existing drop matches and verdicts are retained" for the real sidecar ruleset is currently pinned at script-text level only (TestDropTelemetryEveryDrop).

If the peer-netns setup from the pkg/nftables kernel tests can be reused here, would it be practical to send one SYN to a denied port and one UDP packet to a denied address, and assert the drop plus the matching counter?

_, err = exec.CommandContext(ctx, "nft", "list", "table", "inet", "opensandbox").CombinedOutput()
require.Error(t, err, "delete-only removal must remove the instrumented table")
t.Log("sidecar delete-only removal passed")
}

func TestDropTelemetryBindCloseKernel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
Expand Down
44 changes: 44 additions & 0 deletions components/egress/pkg/nftables/drop_telemetry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 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 nftables

import (
"context"
"strings"

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

func dropReason(line string) droptelemetry.Reason {
switch {
case strings.Contains(line, "ct state established,related"):
return droptelemetry.EstablishedRevoke
case strings.Contains(line, "dport 853"):
return droptelemetry.DoT
case strings.Contains(line, "dport 443"):
return droptelemetry.DoH
case strings.Contains(line, "daddr @deny_"):
return droptelemetry.DenySet
case strings.Contains(line, "tcp dport {"):
return droptelemetry.PortDeny
case line == "add rule inet opensandbox egress drop":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Low] Table and chain names are hardcoded in three places

This exact match spells out the table and chain that the package owns as unexported constants (tableName / chainName, manager.go:39-40), and the same "opensandbox" literal is passed to startDropTelemetry at main.go:165 and forward_mode.go:296. They agree today. After a rename they would drift silently: the counter reads would target a missing table (skipped as errCounterTableMissing), and this branch would stop matching, which makes the default-deny rule an unmapped drop and rejects every instrumented apply once telemetry is on.

Could this be built from the constants, with the table name exported so the two wiring call sites share it?

return droptelemetry.DefaultDeny
}
return ""
}

func RunDropProbe(ctx context.Context, script string) ([]byte, error) {
return defaultRunner(ctx, script)
}
Loading
Loading