-
Notifications
You must be signed in to change notification settings - Fork 51
/
autoport.go
292 lines (235 loc) · 6.56 KB
/
autoport.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package nfqdatapath
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"strconv"
"strings"
"sync"
"time"
"go.aporeto.io/trireme-lib/controller/internal/supervisor/iptablesctrl"
"go.aporeto.io/trireme-lib/controller/pkg/pucontext"
"go.aporeto.io/trireme-lib/utils/cgnetcls"
"go.aporeto.io/trireme-lib/utils/portspec"
"go.uber.org/zap"
)
type readSystemFiles interface {
readOpenSockFD(pid string) []string
readProcNetTCP() (inodeMap map[string]string, userMap map[string]map[string]bool, err error)
getCgroupList() []string
listCgroupProcesses(cgroupname string) ([]string, error)
}
type defaultRead struct{}
var readFiles readSystemFiles
var d *defaultRead
var lock sync.RWMutex
const (
procNetTCPFile = "/proc/net/tcp"
uidFieldOffset = 7
inodeFieldOffset = 9
procHeaderLineNum = 0
portOffset = 1
ipPortOffset = 1
sockStateOffset = 3
sockListeningState = "0A"
hexFormat = 16
integerSize = 64
minimumFields = 2
)
func init() {
lock.Lock()
readFiles = d
lock.Unlock()
}
func getUserName(uid string) (string, error) {
u, err := user.LookupId(uid)
if err != nil {
return "", err
}
return u.Username, nil
}
func (d *Datapath) autoPortDiscovery() {
for {
d.findPorts()
time.Sleep(2 * time.Second)
}
}
// resync adds new port for the PU and removes the stale ports
func (d *Datapath) resync(newPortMap map[string]map[string]bool) {
iptablesInstance := iptablesctrl.GetInstance()
if iptablesInstance == nil {
zap.L().Error("iptables instance can not be nil")
return
}
for k, vs := range d.puToPortsMap {
m := newPortMap[k]
for v := range vs {
if m == nil || !m[v] {
err := iptablesInstance.DeletePortFromPortSet(k, v)
if err != nil {
zap.L().Debug("Delete port set returned error", zap.Error(err))
}
// delete the port from contextIDFromTCPPort cache
err = d.contextIDFromTCPPort.RemoveStringPorts(v)
if err != nil {
zap.L().Debug("can not remove port from cache", zap.Error(err))
}
}
}
}
for k, vs := range newPortMap {
m := d.puToPortsMap[k]
for v := range vs {
if m == nil || !m[v] {
portSpec, err := portspec.NewPortSpecFromString(v, k)
if err != nil {
continue
}
d.contextIDFromTCPPort.AddPortSpec(portSpec)
err = iptablesInstance.AddPortToPortSet(k, v)
if err != nil {
zap.L().Error("Failed to add port to portset", zap.String("context", k), zap.String("port", v))
}
}
}
}
d.puToPortsMap = newPortMap
}
var lastRun time.Time
func (d *Datapath) findPorts() {
lock.Lock()
defer lock.Unlock()
// Rate limit this function to run every 5 milliseconds
if time.Since(lastRun) <= 5*time.Millisecond {
return
}
lastRun = time.Now()
cgroupList := readFiles.getCgroupList()
newPUToPortsMap := map[string]map[string]bool{}
inodeMap, userMap, err := readFiles.readProcNetTCP()
if err != nil {
zap.L().Error("/proc/net/tcp read failed with error", zap.Error(err))
return
}
for _, cgroup := range cgroupList {
/* cgroup is also the contextID */
newMap := map[string]bool{}
// check if a PU exists with that contextID and is marked with auto port
pu, err := d.puFromContextID.Get(cgroup)
if err != nil || !pu.(*pucontext.PUContext).Autoport() {
continue
}
procs, err := readFiles.listCgroupProcesses(cgroup)
if err != nil {
zap.L().Warn("Cgroup processes could not be retrieved", zap.Error(err))
continue
}
for _, proc := range procs {
openSockFDs := readFiles.readOpenSockFD(proc)
for _, sock := range openSockFDs {
if inodeMap[sock] != "" {
newMap[inodeMap[sock]] = true
}
}
}
newPUToPortsMap[cgroup] = newMap
}
for user, portMap := range userMap {
if pu, err := d.puFromUser.Get(user); err == nil {
contextID := pu.(*pucontext.PUContext).ID()
newMap := map[string]bool{}
for port := range portMap {
newMap[port] = true
}
newPUToPortsMap[contextID] = newMap
}
}
d.resync(newPUToPortsMap)
}
func (d *defaultRead) readProcNetTCP() (inodeMap map[string]string, userMap map[string]map[string]bool, err error) {
buffer, err := ioutil.ReadFile(procNetTCPFile)
if err != nil {
return nil, nil, fmt.Errorf("Failed to read /proc/net/tcp file %s", err)
}
inodeMap = map[string]string{}
userMap = map[string]map[string]bool{}
s := string(buffer)
for cnt, line := range strings.Split(s, "\n") {
line := strings.Fields(line)
// continue if not a valid line
if len(line) < uidFieldOffset {
continue
}
/* Look at socket which are in listening state only */
if (cnt == procHeaderLineNum) || (line[sockStateOffset] != sockListeningState) {
continue
}
/* Get the UID */
uid := line[uidFieldOffset]
inode := line[inodeFieldOffset]
portString := ""
{
ipPort := strings.Split(line[ipPortOffset], ":")
if len(ipPort) < minimumFields {
zap.L().Warn("Failed to extract port")
continue
}
portNum, err := strconv.ParseInt(ipPort[portOffset], hexFormat, integerSize)
if err != nil {
zap.L().Warn("failed to parse port ", zap.String("port", ipPort[portOffset]))
continue
}
portString = strconv.Itoa(int(portNum))
}
inodeMap[inode] = portString
// /proc/net/tcp file contains uid. Conversion to
// userName is required as they are keys to lookup tables.
userName, err := getUserName(uid)
if err != nil {
zap.L().Debug("Error converting to username", zap.Error(err))
continue
}
portMap := userMap[userName]
if portMap == nil {
portMap = map[string]bool{}
}
portMap[portString] = true
userMap[userName] = portMap
}
return inodeMap, userMap, nil
}
func (d *defaultRead) readOpenSockFD(pid string) []string {
var inodes []string
fdPath := "/proc/" + pid + "/fd/"
buffer, err := ioutil.ReadDir(fdPath)
if err != nil {
zap.L().Warn("Failed to read", zap.String("file", fdPath), zap.Error(err))
return nil
}
for _, f := range buffer {
link, err := os.Readlink(fdPath + f.Name())
if err != nil {
zap.L().Warn("Failed to read", zap.String("file", fdPath+f.Name()))
continue
}
if strings.Contains(link, "socket:") {
socketInode := strings.Split(link, ":")
if len(socketInode) < minimumFields {
zap.L().Warn("Failed to parse socket inodes")
continue
}
inodeString := socketInode[1]
inodeString = strings.TrimSuffix(inodeString, "]")
inodeString = strings.TrimPrefix(inodeString, "[")
inodes = append(inodes, inodeString)
}
}
return inodes
}
func (d *defaultRead) getCgroupList() []string {
return cgnetcls.GetCgroupList()
}
func (d *defaultRead) listCgroupProcesses(cgroupname string) ([]string, error) {
return cgnetcls.ListCgroupProcesses(cgroupname)
}