forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
procs.go
433 lines (358 loc) · 9.46 KB
/
procs.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package procs
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
)
type socketInfo struct {
srcIP, dstIP net.IP
srcPort, dstPort uint16
uid uint32
inode uint64
}
type portProcMapping struct {
port uint16
pid int
proc *process
}
type process struct {
name string
grepper string
pids []int
proc *ProcessesWatcher
refreshPidsTimer <-chan time.Time
}
type ProcessesWatcher struct {
portProcMap map[uint16]portProcMapping
lastMapUpdate time.Time
processes []*process
localAddrs []net.IP
// config
readFromProc bool
maxReadFreq time.Duration
refreshPidsFreq time.Duration
// test helpers
procPrefix string
testSignals *chan bool
}
var ProcWatcher ProcessesWatcher
func (proc *ProcessesWatcher) Init(config ProcsConfig) error {
proc.procPrefix = ""
proc.portProcMap = make(map[uint16]portProcMapping)
proc.lastMapUpdate = time.Now()
proc.readFromProc = config.Enabled
if proc.readFromProc {
if runtime.GOOS != "linux" {
proc.readFromProc = false
logp.Info("Disabled /proc/ reading because not on linux")
} else {
logp.Info("Process matching enabled")
}
} else {
logp.Info("Process matching disabled")
}
if config.MaxProcReadFreq == 0 {
proc.maxReadFreq = 10 * time.Millisecond
} else {
proc.maxReadFreq = config.MaxProcReadFreq
}
if config.RefreshPidsFreq == 0 {
proc.refreshPidsFreq = 1 * time.Second
} else {
proc.refreshPidsFreq = config.RefreshPidsFreq
}
// Read the local IP addresses
var err error
proc.localAddrs, err = common.LocalIPAddrs()
if err != nil {
logp.Err("Error getting local IP addresses: %s", err)
proc.localAddrs = []net.IP{}
}
if proc.readFromProc {
for _, procConfig := range config.Monitored {
grepper := procConfig.CmdlineGrep
if len(grepper) == 0 {
grepper = procConfig.Process
}
p, err := newProcess(proc, procConfig.Process, grepper, time.Tick(proc.refreshPidsFreq))
if err != nil {
logp.Err("NewProcess: %s", err)
} else {
proc.processes = append(proc.processes, p)
}
}
}
return nil
}
func newProcess(proc *ProcessesWatcher, name string, grepper string,
refreshPidsTimer <-chan time.Time) (*process, error) {
p := &process{name: name, proc: proc, grepper: grepper,
refreshPidsTimer: refreshPidsTimer}
// start periodic timer in its own goroutine
go p.refreshPids()
return p, nil
}
func (p *process) refreshPids() {
logp.Debug("procs", "In RefreshPids")
for range p.refreshPidsTimer {
logp.Debug("procs", "In RefreshPids tick")
var err error
p.pids, err = findPidsByCmdlineGrep(p.proc.procPrefix, p.grepper)
if err != nil {
logp.Err("Error finding PID files for %s: %s", p.name, err)
}
logp.Debug("procs", "RefreshPids found pids %s for process %s", p.pids, p.name)
if p.proc.testSignals != nil {
*p.proc.testSignals <- true
}
}
}
func findPidsByCmdlineGrep(prefix string, process string) ([]int, error) {
defer logp.Recover("FindPidsByCmdlineGrep exception")
pids := []int{}
proc, err := os.Open(filepath.Join(prefix, "/proc"))
if err != nil {
return pids, fmt.Errorf("Open /proc: %s", err)
}
defer proc.Close()
names, err := proc.Readdirnames(0)
if err != nil {
return pids, fmt.Errorf("Readdirnames: %s", err)
}
for _, name := range names {
pid, err := strconv.Atoi(name)
if err != nil {
continue
}
cmdline, err := ioutil.ReadFile(filepath.Join(prefix, "/proc/", name, "cmdline"))
if err != nil {
continue
}
if strings.Index(string(cmdline), process) >= 0 {
pids = append(pids, pid)
}
}
return pids, nil
}
func (proc *ProcessesWatcher) FindProcessesTuple(tuple *common.IPPortTuple) (procTuple *common.CmdlineTuple) {
procTuple = &common.CmdlineTuple{}
if !proc.readFromProc {
return
}
if proc.isLocalIP(tuple.SrcIP) {
logp.Debug("procs", "Looking for port %d", tuple.SrcPort)
procTuple.Src = []byte(proc.findProc(tuple.SrcPort))
if len(procTuple.Src) > 0 {
logp.Debug("procs", "Found device %s for port %d", procTuple.Src, tuple.SrcPort)
}
}
if proc.isLocalIP(tuple.DstIP) {
logp.Debug("procs", "Looking for port %d", tuple.DstPort)
procTuple.Dst = []byte(proc.findProc(tuple.DstPort))
if len(procTuple.Dst) > 0 {
logp.Debug("procs", "Found device %s for port %d", procTuple.Dst, tuple.DstPort)
}
}
return
}
func (proc *ProcessesWatcher) findProc(port uint16) (procname string) {
procname = ""
defer logp.Recover("FindProc exception")
p, exists := proc.portProcMap[port]
if exists {
return p.proc.name
}
now := time.Now()
if now.Sub(proc.lastMapUpdate) > proc.maxReadFreq {
proc.lastMapUpdate = now
proc.updateMap()
// try again
p, exists := proc.portProcMap[port]
if exists {
return p.proc.name
}
}
return ""
}
func hexToIpv4(word string) (net.IP, error) {
ip, err := strconv.ParseInt(word, 16, 64)
if err != nil {
return nil, err
}
return net.IPv4(byte(ip), byte(ip>>8), byte(ip>>16), byte(ip>>24)), nil
}
func hexToIpv6(word string) (net.IP, error) {
p := make(net.IP, net.IPv6len)
for i := 0; i < 4; i++ {
part, err := strconv.ParseUint(word[i*8:(i+1)*8], 16, 32)
if err != nil {
return nil, err
}
p[i*4] = byte(part)
p[i*4+1] = byte(part >> 8)
p[i*4+2] = byte(part >> 16)
p[i*4+3] = byte(part >> 24)
}
return p, nil
}
func hexToIP(word string, ipv6 bool) (net.IP, error) {
if ipv6 {
return hexToIpv6(word)
}
return hexToIpv4(word)
}
func hexToIPPort(str []byte, ipv6 bool) (net.IP, uint16, error) {
words := bytes.Split(str, []byte(":"))
if len(words) < 2 {
return nil, 0, errors.New("Didn't find ':' as a separator")
}
ip, err := hexToIP(string(words[0]), ipv6)
if err != nil {
return nil, 0, err
}
port, err := strconv.ParseInt(string(words[1]), 16, 32)
if err != nil {
return nil, 0, err
}
return ip, uint16(port), nil
}
func (proc *ProcessesWatcher) updateMap() {
logp.Debug("procs", "UpdateMap()")
ipv4socks, err := socketsFromProc("/proc/net/tcp", false)
if err != nil {
logp.Err("Parse_Proc_Net_Tcp: %s", err)
return
}
ipv6socks, err := socketsFromProc("/proc/net/tcp6", true)
if err != nil {
logp.Err("Parse_Proc_Net_Tcp ipv6: %s", err)
return
}
socksMap := map[uint64]*socketInfo{}
for _, s := range ipv4socks {
socksMap[s.inode] = s
}
for _, s := range ipv6socks {
socksMap[s.inode] = s
}
for _, p := range proc.processes {
for _, pid := range p.pids {
inodes, err := findSocketsOfPid(proc.procPrefix, pid)
if err != nil {
logp.Err("FindSocketsOfPid: %s", err)
continue
}
for _, inode := range inodes {
sockInfo, exists := socksMap[inode]
if exists {
proc.updateMappingEntry(sockInfo.srcPort, pid, p)
}
}
}
}
}
func socketsFromProc(filename string, ipv6 bool) ([]*socketInfo, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return parseProcNetTCP(file, ipv6)
}
// Parses the /proc/net/tcp file
func parseProcNetTCP(input io.Reader, ipv6 bool) ([]*socketInfo, error) {
buf := bufio.NewReader(input)
sockets := []*socketInfo{}
var err error
var line []byte
for err != io.EOF {
line, err = buf.ReadBytes('\n')
if err != nil && err != io.EOF {
logp.Err("Error reading proc net tcp file: %s", err)
return nil, err
}
words := bytes.Fields(line)
if len(words) < 10 || bytes.Equal(words[0], []byte("sl")) {
logp.Debug("procs", "Less then 10 words (%d) or starting with 'sl': %s", len(words), words)
continue
}
var sock socketInfo
var err error
sock.srcIP, sock.srcPort, err = hexToIPPort(words[1], ipv6)
if err != nil {
logp.Debug("procs", "Error parsing IP and port: %s", err)
continue
}
sock.dstIP, sock.dstPort, err = hexToIPPort(words[2], ipv6)
if err != nil {
logp.Debug("procs", "Error parsing IP and port: %s", err)
continue
}
uid, _ := strconv.Atoi(string(words[7]))
sock.uid = uint32(uid)
inode, _ := strconv.Atoi(string(words[9]))
sock.inode = uint64(inode)
sockets = append(sockets, &sock)
}
return sockets, nil
}
func (proc *ProcessesWatcher) updateMappingEntry(port uint16, pid int, p *process) {
entry := portProcMapping{port: port, pid: pid, proc: p}
// Simply overwrite old entries for now.
// We never expire entries from this map. Since there are 65k possible
// ports, the size of the dict can be max 1.5 MB, which we consider
// reasonable.
proc.portProcMap[port] = entry
logp.Debug("procsdetailed", "UpdateMappingEntry(): port=%d pid=%d", port, p.name)
}
func findSocketsOfPid(prefix string, pid int) (inodes []uint64, err error) {
dirname := filepath.Join(prefix, "/proc", strconv.Itoa(pid), "fd")
procfs, err := os.Open(dirname)
if err != nil {
return []uint64{}, fmt.Errorf("Open: %s", err)
}
defer procfs.Close()
names, err := procfs.Readdirnames(0)
if err != nil {
return []uint64{}, fmt.Errorf("Readdirnames: %s", err)
}
for _, name := range names {
link, err := os.Readlink(filepath.Join(dirname, name))
if err != nil {
logp.Debug("procs", "Readlink %s: %s", name, err)
continue
}
if strings.HasPrefix(link, "socket:[") {
inode, err := strconv.ParseInt(link[8:len(link)-1], 10, 64)
if err != nil {
logp.Debug("procs", "ParseInt: %s:", err)
continue
}
inodes = append(inodes, uint64(inode))
}
}
return inodes, nil
}
func (proc *ProcessesWatcher) isLocalIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
for _, addr := range proc.localAddrs {
if ip.Equal(addr) {
return true
}
}
return false
}