Repository navigation
feat(egress): wire kernel drop telemetry into sidecars #3125
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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()) { | ||
| 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") | ||
| } | ||
| 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) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 { | ||
|
|
@@ -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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. If the peer-netns setup from the |
||
| _, 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() | ||
|
|
||
| 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": | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ( 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) | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Low]
startDropTelemetryhas no testgo tool cover -funcputs this function at 0%.TestDropAuditSidecarcoversauditBlockedPacketonly, andTestDropTelemetryRulesetKernelbuilds its runtime by hand instead of going through here. So three behaviours that exist only in this function are pinned by reading alone:offreturning a nil runtime (which is what keeps the default path byte-identical), an invalid value being fatal, and theStartwiring withdroptelemetry.Bindand the audit callback.The
offcase is the one that guards the default path, so a small test for it would be worth having.