/
resolver.go
187 lines (161 loc) · 5.91 KB
/
resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build linux
// Package tc holds tc related files
package tc
import (
"fmt"
"os"
"sync"
"github.com/DataDog/datadog-go/v5/statsd"
manager "github.com/DataDog/ebpf-manager"
"github.com/hashicorp/go-multierror"
"github.com/vishvananda/netlink"
"github.com/DataDog/datadog-agent/pkg/collector/corechecks/ebpf/probe/ebpfcheck"
"github.com/DataDog/datadog-agent/pkg/security/ebpf/probes"
"github.com/DataDog/datadog-agent/pkg/security/metrics"
"github.com/DataDog/datadog-agent/pkg/security/probe/config"
"github.com/DataDog/datadog-agent/pkg/security/secl/model"
)
// NetDeviceKey is used to uniquely identify a network device
type NetDeviceKey struct {
IfIndex uint32
NetNS uint32
NetworkDirection manager.TrafficType
}
// Resolver defines a TC resolver
type Resolver struct {
sync.RWMutex
config *config.Config
programs map[NetDeviceKey]*manager.Probe
}
// NewResolver returns a TC resolver
func NewResolver(config *config.Config) *Resolver {
return &Resolver{
config: config,
programs: make(map[NetDeviceKey]*manager.Probe),
}
}
// SendTCProgramsStats sends TC programs stats
func (tcr *Resolver) SendTCProgramsStats(statsdClient statsd.ClientInterface) {
tcr.RLock()
defer tcr.RUnlock()
if val := float64(len(tcr.programs)); val > 0 {
_ = statsdClient.Gauge(metrics.MetricTCProgram, val, []string{}, 1.0)
}
}
// SelectTCProbes selects TC probes
func (tcr *Resolver) SelectTCProbes() manager.ProbesSelector {
tcr.RLock()
defer tcr.RUnlock()
// Although unlikely, a race is still possible with the umount event of a network namespace:
// - a reload event is triggered
// - selectTCProbes is invoked and the list of currently running probes is generated
// - a container exits and the umount event of its network namespace is handled now (= its TC programs are stopped)
// - the manager executes UpdateActivatedProbes
// In this setup, if we didn't use the best effort selector, the manager would try to init & attach a program that
// was deleted when the container exited.
var activatedProbes manager.BestEffort
for _, tcProbe := range tcr.programs {
if tcProbe.IsRunning() {
activatedProbes.Selectors = append(activatedProbes.Selectors, &manager.ProbeSelector{
ProbeIdentificationPair: tcProbe.ProbeIdentificationPair,
})
}
}
return &activatedProbes
}
// SetupNewTCClassifierWithNetNSHandle creates and attaches TC probes on the provided device. WARNING: this function
// will not close the provided netns handle, so the caller of this function needs to take care of it.
func (tcr *Resolver) SetupNewTCClassifierWithNetNSHandle(device model.NetDevice, netnsHandle *os.File, m *manager.Manager) error {
tcr.Lock()
defer tcr.Unlock()
var combinedErr multierror.Error
for _, tcProbe := range probes.GetTCProbes() {
// make sure we're not overriding an existing network probe
deviceKey := NetDeviceKey{IfIndex: device.IfIndex, NetNS: device.NetNS, NetworkDirection: tcProbe.NetworkDirection}
_, ok := tcr.programs[deviceKey]
if ok {
continue
}
newProbe := tcProbe.Copy()
newProbe.CopyProgram = true
newProbe.UID = probes.SecurityAgentUID + device.GetKey()
newProbe.IfIndex = int(device.IfIndex)
newProbe.IfIndexNetns = uint64(netnsHandle.Fd())
newProbe.IfIndexNetnsID = device.NetNS
newProbe.KeepProgramSpec = false
newProbe.TCFilterPrio = tcr.config.NetworkClassifierPriority
newProbe.TCFilterHandle = netlink.MakeHandle(0, tcr.config.NetworkClassifierHandle)
netnsEditor := []manager.ConstantEditor{
{
Name: "netns",
Value: uint64(device.NetNS),
},
}
if err := m.CloneProgram(probes.SecurityAgentUID, newProbe, netnsEditor, nil); err != nil {
_ = multierror.Append(&combinedErr, fmt.Errorf("couldn't clone %s: %v", tcProbe.ProbeIdentificationPair, err))
} else {
tcr.programs[deviceKey] = newProbe
// do not use dynamic program name here, it explodes cardinality
ebpfcheck.AddProgramNameMapping(newProbe.ID(), newProbe.EBPFFuncName, "cws")
}
}
return combinedErr.ErrorOrNil()
}
// FlushNetworkNamespaceID flushes network ID
func (tcr *Resolver) FlushNetworkNamespaceID(namespaceID uint32, m *manager.Manager) {
tcr.Lock()
defer tcr.Unlock()
for tcKey, tcProbe := range tcr.programs {
if tcKey.NetNS == namespaceID {
_ = m.DetachHook(tcProbe.ProbeIdentificationPair)
delete(tcr.programs, tcKey)
}
}
}
// FlushInactiveProbes detaches and deletes inactive probes. This function returns a map containing the count of interfaces
// per network namespace (ignoring the interfaces that are lazily deleted).
func (tcr *Resolver) FlushInactiveProbes(m *manager.Manager, isLazy func(string) bool) map[uint32]int {
tcr.Lock()
defer tcr.Unlock()
probesCountNoLazyDeletion := make(map[uint32]int)
var linkName string
for tcKey, tcProbe := range tcr.programs {
if !tcProbe.IsTCFilterActive() {
_ = m.DetachHook(tcProbe.ProbeIdentificationPair)
delete(tcr.programs, tcKey)
} else {
link, err := tcProbe.ResolveLink()
if err == nil {
linkName = link.Attrs().Name
} else {
linkName = ""
}
// ignore interfaces that are lazily deleted
if link.Attrs().HardwareAddr.String() != "" && !isLazy(linkName) {
probesCountNoLazyDeletion[tcKey.NetNS]++
}
}
}
return probesCountNoLazyDeletion
}
// ResolveNetworkDeviceIfName resolves network device name
func (tcr *Resolver) ResolveNetworkDeviceIfName(ifIndex, netNS uint32) (string, bool) {
tcr.RLock()
defer tcr.RUnlock()
for _, direction := range []manager.TrafficType{manager.Egress, manager.Ingress} {
key := NetDeviceKey{
IfIndex: ifIndex,
NetNS: netNS,
NetworkDirection: direction,
}
tcProbe, ok := tcr.programs[key]
if ok {
return tcProbe.IfName, true
}
}
return "", false
}