-
Notifications
You must be signed in to change notification settings - Fork 201
/
process.go
2843 lines (2534 loc) · 84.8 KB
/
process.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package probe
import (
"fmt"
"net"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/agent/probe/ringbuffer"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/fsmon"
"github.com/neuvector/neuvector/share/global"
"github.com/neuvector/neuvector/share/osutil"
"github.com/neuvector/neuvector/share/utils"
)
const retryReadProcMax int = 1
const (
escalatReported uint = 1 << iota
reversShReported
reversShConfirmed
suspicReported
dnsTunnelReported
profileReported
historyReported
)
type procEventHdr struct {
what uint32
cpu uint32
timeStampNano uint64
}
type userNs struct {
users map[int]string
root int
uidMin int
}
type procContainer struct {
id string
rootPid int
children utils.Set // pid pool from rootPid (major)
outsider utils.Set // pid pool from outside
newBorn int
userns *userNs
//map of port listened by multiple processes
portsMap map[osutil.SocketInfo]*procApp
checkRemovedPort uint
fInfo map[string]*fileInfo
}
type procInternal struct {
pname string
ppath string
name string
path string
cmds []string
user string
pid int
ppid int
sid int
pgid int
ruid int
euid int
retry int
inspectTimes uint
startTime time.Time
lastScanTime time.Time
scanTimes uint
reported uint
action string
riskyChild bool
riskType string
execScanDone bool // scan mode only
}
type suspicProcInfo struct {
ingress bool
msg string
}
var suspicProcMap map[string]*suspicProcInfo = map[string]*suspicProcInfo{
"nmap": {false, "Port Scanner"},
"nc": {false, "netcat process"},
"ncat": {false, "netcat process"},
"netcat": {false, "netcat process"},
"sshd": {true, "ssh from remote"},
"ssh": {false, "ssh to remote"},
"scp": {false, "Secure copy"},
"telnet": {false, "telnet to remote"},
"in.telnetd": {true, "telnet from remote"},
"iodine": {false, "dns tunneling"},
"iodined": {true, "dns tunneling"},
"dnscat": {false, "dns tunneling"},
"dns2tcpc": {false, "dns tunneling"},
"dns2tcpd": {true, "dns tunneling"},
"socat": {false, "socat relay process"},
}
var kubeProcs map[string]int = map[string]int{
"kubelet": 1,
"kube-apiserver": 1,
"hyperkube": 1,
}
//var linuxShells utils.Set = utils.NewSet("sh", "dash", "bash", "rbash")
// Can be called with process that has exited
func (p *Probe) proc2CLUS(proc *procInternal) *share.CLUSProcess {
var euser string
ppid, gid, sid, status, _ := osutil.GetProcessPIDs(proc.pid)
if ppid != -1 {
euser = p.getUserName(proc.pid, proc.euid)
} else {
euser = proc.user
status = "Exited"
}
output := &share.CLUSProcess{
Name: proc.name,
Pid: uint32(proc.pid),
PPid: uint32(proc.ppid),
PGid: uint32(gid),
PSid: uint32(sid),
RUid: uint32(proc.ruid),
EUid: uint32(proc.euid),
Root: proc.euid == 0,
Cmds: proc.cmds,
User: euser,
Status: status,
StartAt: proc.startTime.UTC().Unix(),
Action: proc.action,
}
return output
}
func clearContainerProcesses(c *procContainer) {
c.children.Clear()
c.outsider.Clear()
}
func isContainerProcess(c *procContainer, pid int) bool {
return c.children.Contains(pid) || c.outsider.Contains(pid)
}
/////
func (p *Probe) isDockerDaemonProcess(proc *procInternal, id string) bool {
if id == "" { // host porcesses
if global.RT.IsRuntimeProcess(proc.pname, nil) {
// skip: runtime processes
return true
}
if p.bKubePlatform {
if _, ok := kubeProcs[proc.pname]; ok {
// skip: kube processes
return true
}
}
}
return proc.name == global.RT.String() || proc.pname == global.RT.String()
}
////
// scan at timestamp: 0, 2, 4, 8, 16, 24, 32
// after 1 minute, it scans once every minute
const udpSessionQualification uint = 20 //seconds
const procReexamCycle uint = 60 //repeat re-exam every 60 seconds
var scanAt = [...]uint{0, 2, 4, 8, 16, 24, 32} //during the initial time of a new process
var procReexamMaxTimes uint = uint(len(scanAt)) //Max scan times before scanning every procReexamCycle
func shouldScanProc(proc *procInternal) bool {
var scan bool
if proc.scanTimes == 0 {
scan = true
proc.scanTimes++
proc.lastScanTime = time.Now() // reset, trigger a faster scanning port action
} else {
gap := uint(time.Since(proc.lastScanTime).Seconds())
if proc.scanTimes < procReexamMaxTimes {
if gap > scanAt[proc.scanTimes] {
scan = true
proc.scanTimes++
}
} else {
//rescan process every procReexamCycle
if gap > procReexamCycle {
scan = true
proc.lastScanTime = time.Now() // keep the 1 min cycle
}
}
// if scan {
// log.WithFields(log.Fields{"pid": proc.pid, "next": proc.scanTimes, "gap": gap}).Debug()
// }
}
return scan
}
//to check whether the processes in a container ports have changed
// UDP session: report only long-lasting UDP sessions (qualification: 20 second).
// It's impossible to distinguish a server or a client from /proc/net/udp[udp6]
// server case:
// (s1) create a udp socket => no entry in the /proc/net/udp
// (s2) bind()sk_state=TCP_ESTABLISH => shown with inode in the /proc/net/udp
// (s3) socket closed => the entry is deleted in the /proc/net/udp
//
// client case (for example, nslookup, its default timeout is 5+ sec):
// (c1) create a udp socket => no entry in the /proc/net/udp
// (c2) send dns query (short and fast), sk_state=TCP_ESTABLISH => shown with inode in the /proc/net/udp
// (c3) wait for response, sk_state=TCP_CLOSE => still shown with inode in the /proc/net/udp
// (c4) receive the reposnse (can not find the sk_state changes)
// (c5) socket closed => the entry is deleted in the /proc/net/udp
//
// When (c3) or (c4) takes too long, we have this false-positive cases.
// Also, it is impossible to catch the (c2) event by a polling method.
func (p *Probe) checkProcAppPorts(c *procContainer, rateLimit bool) bool {
var addPort, notify bool
var socketTbl map[uint32]osutil.SocketInfo
// remove closed socket ports
c.checkRemovedPort++
if c.checkRemovedPort > 4 { // every 10 = 5 x 2 seconds
c.checkRemovedPort = 0
//active socket table for a container: /proc/1/net/<tcp, tcp6, udp, udp6>
socketTbl = osutil.GetContainerSocketTable(c.rootPid)
// the obsoleted sockets and treat them as the closed ports
for pport, papp := range c.portsMap {
if _, ok := socketTbl[pport.INode]; !ok {
if papp.DelConfirmed { // gone
log.WithFields(log.Fields{"pport": pport}).Debug("delete: done")
delete(c.portsMap, pport)
notify = true
} else {
papp.DelConfirmed = true
if !papp.AddConfirmed {
// log.WithFields(log.Fields{"pport": pport}).Debug("delete: not confirmed yet")
delete(c.portsMap, pport)
} else {
// some servers might recover their services very soon.
// wait for another cycle to avoid too many workload updates.
log.WithFields(log.Fields{"pport": pport, "papp": papp}).Debug("delete: wait")
}
}
}
}
// no session: skip below add probes
if len(socketTbl) == 0 {
return notify
}
}
// add active socket ports
// probing all children in this container
pids := c.children.Union(c.outsider)
for pid := range pids.Iter() {
if proc := p.pidProcMap[pid.(int)]; proc != nil {
if rateLimit && !shouldScanProc(proc) {
// log.WithFields(log.Fields{"pid": proc.pid, "root": c.rootPid}).Debug("skip")
continue
}
//active (socket) inodes for a process: /proc/<pid>/fd/<number> -> socket[<inode>]
inodes, err := osutil.GetProcessSocketInodes(proc.pid)
if err != nil || inodes.Cardinality() == 0 {
continue
}
// retrive while the probe is set
if socketTbl == nil {
socketTbl = osutil.GetContainerSocketTable(c.rootPid)
// no session: skip below all probes
if len(socketTbl) == 0 {
return notify
}
}
// search the protocol-type/port from the container's socketTable
for fd := range inodes.Iter() {
if pport, ok := socketTbl[fd.(uint32)]; ok {
// is a tcp listener or a meaningful udp session
if papp, ok := c.portsMap[pport]; ok {
papp.Pids.Add(pid)
papp.DelConfirmed = false // reset
// log.WithFields(log.Fields{"pport": pport, "since": time.Since(papp.SessionInitTime)}).Debug("continuous session")
if !papp.AddConfirmed {
// For a valid udp session, it must last for a qualication period
if uint(time.Since(papp.SessionInitTime).Seconds()) > udpSessionQualification {
papp.AddConfirmed = true
addPort = true
notify = true
log.WithFields(log.Fields{"pid": pid, "pport": pport, "since": time.Since(papp.SessionInitTime)}).Debug("confirm: udp session")
}
}
} else {
papp := &procApp{Pids: utils.NewSet(pid), SessionInitTime: time.Now()}
c.portsMap[pport] = papp
proc.scanTimes = 0 // scan more aggressively
if pport.IPProto == syscall.IPPROTO_UDP {
log.WithFields(log.Fields{"pid": pid, "pport": pport}).Debug("wait: udp session")
} else {
log.WithFields(log.Fields{"pid": pid, "pport": pport}).Debug("add: tcp listener")
papp.AddConfirmed = true
addPort = true
notify = true
}
}
}
}
}
}
//get port's application
if addPort {
getAppMap(c.portsMap)
}
return notify
}
//get a container's listen ports and application map
func (p *Probe) GetContainerAppPorts(id string) (utils.Set, map[share.CLUSProtoPort]*share.CLUSApp) {
appMap := make(map[share.CLUSProtoPort]*share.CLUSApp)
listensAll := utils.NewSet()
p.lockProcMux()
defer p.unlockProcMux()
if c, ok := p.containerMap[id]; ok {
//return all listened ports in a container
for k, papp := range c.portsMap {
port := share.CLUSProtoPort{IPProto: k.IPProto, Port: k.Port}
if !papp.AddConfirmed {
continue
}
listensAll.Add(port)
if papp.App.Port != 0 {
appMap[port] = &papp.App
}
}
}
return listensAll, appMap
}
func (p *Probe) GetContainerProcs(id string) []*share.CLUSProcess {
p.lockProcMux()
defer p.unlockProcMux()
if c, ok := p.containerMap[id]; ok {
pids := c.children.Union(c.outsider)
procs := make([]*share.CLUSProcess, 0, pids.Cardinality())
for pid := range pids.Iter() {
if proc := p.pidProcMap[pid.(int)]; proc != nil {
procs = append(procs, p.proc2CLUS(proc))
}
}
return procs
} else {
return make([]*share.CLUSProcess, 0)
}
}
func (p *Probe) GetContainerProcHistory(id string) []*share.CLUSProcess {
p.lockProcMux()
defer p.unlockProcMux()
if r, ok := p.procHistoryMap[id]; ok {
history := r.DumpExt()
procs := make([]*share.CLUSProcess, len(history))
for i, proc := range history {
procs[i] = p.proc2CLUS(proc.(*procInternal))
}
return procs
} else {
return make([]*share.CLUSProcess, 0)
}
}
//put all host processes in a virtual container, id=="". so we can handle host process same as other container
func (p *Probe) addHost(pid int) {
c := &procContainer{
id: "",
children: utils.NewSet(pid),
outsider: utils.NewSet(), // empty
rootPid: 1,
newBorn: 0,
userns: &userNs{users: make(map[int]string), uidMin: osutil.UserUidMin},
portsMap: make(map[osutil.SocketInfo]*procApp),
fInfo: make(map[string]*fileInfo),
}
p.containerMap[""] = c
p.pidContainerMap[pid] = c
//load the users from host
if root, min, err := osutil.GetAllUsers(c.rootPid, c.userns.users); err == nil {
c.userns.root = root
c.userns.uidMin = min
}
}
func (p *Probe) inspectFirstContainerProc(proc *procInternal) {
if proc.user == "" {
proc.user = p.getUserName(proc.pid, proc.euid)
}
if proc.path == "" {
proc.path, _ = global.SYS.GetFilePath(proc.pid)
}
if proc.name == "" {
proc.name, _, _, _ = osutil.GetProcessUIDs(proc.pid)
}
ppid, _, _, _, _ := osutil.GetProcessPIDs(proc.pid)
if ppid > 1 {
proc.ppid = ppid
proc.pname, _, _, _ = osutil.GetProcessUIDs(proc.ppid)
proc.ppath, _ = global.SYS.GetFilePath(proc.ppid)
}
}
func (p *Probe) addContainer(id string, proc *procInternal, scanMode bool) {
var pid int = proc.pid
c := &procContainer{
id: id,
// rootPid: pid, // must rely on external api, like docker
children: utils.NewSet(pid),
outsider: utils.NewSet(), // empty
newBorn: 1,
userns: &userNs{users: make(map[int]string), uidMin: osutil.UserUidMin},
portsMap: make(map[osutil.SocketInfo]*procApp),
fInfo: make(map[string]*fileInfo),
}
if p.containerStops.Contains(c.id) {
p.containerStops.Remove(c.id)
}
p.containerMap[id] = c
if _, ok := p.pidContainerMap[pid]; ok {
delete(p.pidContainerMap, pid) // update
}
p.pidContainerMap[pid] = c
p.resetIoNodes = true // JW
//load the users from container
if root, min, err := osutil.GetAllUsers(pid, c.userns.users); err == nil {
c.userns.root = root
c.userns.uidMin = min
}
if scanMode {
p.inspectFirstContainerProc(proc)
} else {
// check if the process is assigned to host before. if so, remove from host
if c1, ok := p.containerMap[""]; ok && c1.children.Contains(proc.pid) {
c1.children.Remove(proc.pid)
}
}
log.WithFields(log.Fields{"pid": pid, "id": id, "cnt": len(p.containerMap) - 2}).Debug("PROC: New container")
}
func (p *Probe) addContainerProcess(c *procContainer, pid int) {
p.pidContainerMap[pid] = c
// check if the process is assigned to host before. if so, remove from host
if c.id != "" {
// log.WithFields(log.Fields{"pid": pid, "id": c.id}).Debug("")
if c1, ok := p.containerMap[""]; ok {
if c1.children.Contains(pid) {
c1.children.Remove(pid) // nodes has one pool
}
}
if c.id == p.selfID {
c.children.Add(pid) // the children of the nstools are ambiguous and can be in other namespaces
} else {
c.outsider.Add(pid) // temporary: c.children
}
} else {
c.children.Add(pid) // nodes only has a pool
}
}
func (p *Probe) removeProcessInContainer(pid int) {
containerRemoved := false
if c, ok := p.pidContainerMap[pid]; ok {
// retrive the rootPid
if c.rootPid == 0 {
c.rootPid = p.getContainerPid(c.id)
}
if c.rootPid != 0 && c.rootPid == pid { // rootPid exited, remove this container
containerRemoved = true
} else {
c.children.Remove(pid) // it should belong to either one of pools
c.outsider.Remove(pid)
if c.children.Cardinality() == 0 && c.outsider.Cardinality() == 0 { // check the pools
// No process is in this container so we can remove the container
containerRemoved = true
if c.rootPid != 0 {
if _, exist := p.pidProcMap[c.rootPid]; exist {
// The root process is still alive but has not been learned from the process monitor, we could remove
// the container accidentally. The following logic is to prevent this.
log.WithFields(log.Fields{"root": c.rootPid}).Info("PROC: add root process to container")
p.addContainerProcess(c, c.rootPid)
containerRemoved = false
}
} else {
// no valid rootPid: it could be a "flash" container, delete it
// for example: "docker run ubuntu echo 123"
log.WithFields(log.Fields{"pid": pid}).Info("PROC: orphan container")
}
}
}
// the container has exited, clean up
if containerRemoved {
clearContainerProcesses(c)
p.containerStops.Add(c.id)
delete(p.containerMap, c.id)
log.WithFields(log.Fields{"pid": pid, "id": c.id, "cnt": len(p.containerMap) - 2}).Debug("PROC: Container remove")
}
// TODO: what if the container was removed, does it need to remove all netwroking references?
for _, papp := range c.portsMap {
if papp.Pids.Contains(pid) {
papp.Pids.Remove(pid)
}
}
}
}
func (p *Probe) isAgentNsOperation(proc *procInternal) bool {
// children of nstools
return proc.ppath == "/usr/local/bin/nstools" || p.agentMntNsId != global.SYS.GetMntNamespaceId(proc.pid)
}
func (p *Probe) isAgentProcess(sid int, id string) bool {
return id == p.selfID || p.agentSessionID == sid // it will exclude all processes from the same container
}
func (p *Probe) evaluateRuncTrigger(id string, proc *procInternal) {
if id == "" {
if strings.HasSuffix(proc.path, "/runc") {
trigger := false
// runc [global options] command [command options] [arguments...]
for i, param := range proc.cmds {
if i == 0 {
if !strings.Contains(param, "runc") {
break
}
continue
}
if strings.HasPrefix(param, "--") { // skip name and global option
continue
}
if param == "start" || param == "kill" {
trigger = true
}
break
}
////
if trigger {
log.WithFields(log.Fields{
"parent": proc.pname,
"ppath": proc.ppath,
"name": proc.name,
"path": proc.path,
"cmd": proc.cmds,
}).Debug("PROC: runc trigger")
}
}
}
}
// Debug purpose:
func (p *Probe) printProcReport(id string, proc *procInternal) {
var s string
if id == "" {
s = "[host]"
// return
} else if p.isAgentProcess(proc.sid, id) {
// if p.isAgentNsOperation(proc) {
// return
// }
// s = "[self]"
return // hide all information
} else {
s = fmt.Sprintf("[%s]", id[:4])
}
mLog.WithFields(log.Fields{"id": s,
"pid": proc.pid,
"ppid": proc.ppid,
"sid": proc.sid,
"pgid": proc.pgid,
"user": proc.user,
"parent": proc.pname,
"ppath": proc.ppath,
"name": proc.name,
"path": proc.path,
"cmd": proc.cmds,
"action": proc.action,
"riskType": proc.riskType,
}).Debug("PROC:")
// Test sample for performance evaluations
// p.sleepTestCounter(proc, c.id)
}
func (p *Probe) sleepTestCounter(proc *procInternal, id string) {
if id != "" {
if proc.cmds[0] == "sleep" { // sleep batch script
p.profileSleepTestCnt++
} else if proc.cmds[0] == "top" { // reset and read the result
s := fmt.Sprintf("PROC: sleep cnt= %d\n", p.profileSleepTestCnt)
log.Debug(s)
p.profileSleepTestCnt = 0
}
}
}
func (p *Probe) isSuspiciousProcess(proc *procInternal, id string) (*suspicProcInfo, bool) {
if id == "" && proc.name == "sshd" { // exclude sshd from group nodes
proc.riskType = "" // reset
return nil, false
}
// normal process
info, ok := suspicProcMap[proc.name]
if !ok {
// keep tracing on target suspicous tree
if proc.action == share.PolicyActionCheckApp { // parent is suspicious
return suspicProcMap[proc.riskType], true
}
return nil, false
}
/// new finding
proc.riskType = proc.name // updated
proc.action = share.PolicyActionCheckApp // tag it
return info, ok
}
// TODO, improved it with snapshot, passing by reference for all structures
func (p *Probe) evalNewRunningApp(pid int) {
p.lockProcMux() // minimum section lock
c, _ := p.pidContainerMap[pid]
proc, ok := p.pidProcMap[pid] // bottom-line
if ok {
// the same pid might go throuth here twice, do not change its tag
if proc.action != share.PolicyActionCheckApp {
if pproc, okp := p.pidProcMap[proc.ppid]; okp {
proc.riskyChild = pproc.action == share.PolicyActionCheckApp
proc.action = pproc.action // put the initial action as same as parent
proc.riskType = pproc.riskType // then, it will go through the policy screening later
}
}
//// NV5430: possible memory panic condition resulted by "delete(p.pidProcMap, pid)"
//// clone the proc by a deep-copy
prc := *proc
if len(proc.cmds) > 0 {
prc.cmds = make([]string, len(proc.cmds))
copy(prc.cmds, proc.cmds)
}
proc = &prc
}
p.unlockProcMux() // minimum section lock
if !ok || c == nil {
// disappeared, short-live application
return
}
// last chance to update fields
if c.id != "" { // container processes only, skip host processes
if proc.cmds != nil && proc.cmds[0] != "sshd:" {
cmds, _ := global.SYS.ReadCmdLine(proc.pid)
if cmds != nil && cmds[0] != "" {
proc.cmds = cmds // caught the last movement
}
}
if path, err := global.SYS.GetFilePath(proc.pid); err == nil { // the latest exe path
if path != "" && path != "/" {
proc.path = path // avoid the false condition with not-existed exec path
}
}
if proc.name != "" {
if _, ok := p.isSuspiciousProcess(proc, c.id); !ok {
proc.name, _, _, _ = osutil.GetProcessUIDs(proc.pid)
}
} else {
proc.name, _, _, _ = osutil.GetProcessUIDs(proc.pid)
}
}
///////////// Normal decision path /////////////////
p.evaluateApplication(proc, c.id, false, false)
// update its results
p.lockProcMux() // minimum section lock
if _, ok := p.pidProcMap[pid]; ok {
p.pidProcMap[pid] = proc
}
p.unlockProcMux() // minimum section lock
}
func (p *Probe) addContainerCandidateFromProc(proc *procInternal) (*procContainer, bool) {
c, res := p.addContainerCandidate(proc, false)
if res == 1 {
// log.WithFields(log.Fields{"pid": proc.pid}).Info("PROC: Found new container from process")
return c, true
} else if res == 0 { // new container process
return c, true
}
return nil, false
}
// root escalation check
func (p *Probe) rootEscalationCheck(proc *procInternal, c *procContainer) {
if parent, ok := p.pidProcMap[proc.ppid]; ok {
// p.updateProcess(proc)
grandParent, ok := p.pidProcMap[parent.ppid]
if !ok {
// some process might change the parent pid, reload it
p.updateProcess(parent)
grandParent, ok = p.pidProcMap[parent.ppid]
}
if ok {
//if c is empty, it's host process. check whether the process is inside container,
//because the user map is different. the root process of a container's parent is host process.
//make sure the parent and grand parent are in same container(or host)
if isContainerProcess(c, parent.ppid) {
//grand parent uid exclude system user < 1000
if (grandParent.euid-c.userns.root) >= c.userns.uidMin &&
parent.euid == c.userns.root &&
proc.euid == c.userns.root {
if rUser, eUser, notAuth := p.checkUserGroup(grandParent, c); notAuth {
go p.evalRootEscal(proc, grandParent, c.id, rUser, eUser, c.userns.root)
}
}
}
}
}
}
// pidNetlink: authorization from real user
func (p *Probe) checkUserGroup_uidChange(escalProc *procInternal, c *procContainer) (string, string, bool) {
// verify the user authority
rUser := p.getUserName(escalProc.pid, escalProc.ruid) // real user
eUser := p.getUserName(escalProc.pid, escalProc.euid) // effective user
// should check the "real user" whether it is in the adm, root, sudo groups
if rUser == "" {
log.WithFields(log.Fields{"ruid": escalProc.ruid, "euid": escalProc.euid}).Error("Get User name fail")
return "", "", true
}
if auth, err := osutil.CheckUidAuthority(rUser, escalProc.pid); err != nil {
log.WithFields(log.Fields{"err": err}).Error("Check user authority fail")
return "", "", true
} else if auth == true {
return "", "", false
}
return rUser, eUser, true
}
/////
func isSudoCommand(cmds []string) bool {
length := len(cmds)
switch {
case length == 1:
if cmds[0] == "sudo" || cmds[0] == "su" {
return true
}
case length > 1: // it could be "su -c /bin/ps neuvector"
for i, cmd := range cmds {
if i == 0 {
if cmd != "su" {
break
}
} else if cmd[:1] == "-" { // option
continue
} else {
if cmd == "root" {
return true
}
return false
}
}
}
return false
}
// pidNetlink: root escalation check
func (p *Probe) rootEscalationCheck_uidChange(proc *procInternal, c *procContainer) {
parent, ok := p.pidProcMap[proc.ppid]
if !ok { // parent has not been caught
if !osutil.IsPidValid(proc.ppid) {
log.WithFields(log.Fields{"ppid": proc.ppid, "pid": proc.pid}).Info("PROC: parent exited")
return
}
now := time.Now()
parent = &procInternal{
pid: proc.ppid,
ppid: proc.ppid,
sid: proc.sid,
pgid: proc.pgid,
startTime: now,
lastScanTime: now,
action: share.PolicyActionAllow,
}
// construct parent process
p.updateProcess(parent) // get name, ppid, ruid, euid
parent.user = p.getUserName(parent.pid, parent.euid) // get parent's username
parent.path, _ = global.SYS.GetFilePath(parent.pid) // get parent's executable name
p.pidProcMap[parent.pid] = parent
p.addContainerProcess(c, parent.pid) // add parent
log.WithFields(log.Fields{"pid": parent.pid, "ruid": parent.ruid}).Debug("PROC: patch parent")
}
if (parent.reported & escalatReported) > 0 {
return
}
if proc.ruid == parent.ruid { // no change by real user id
return
}
// Wait 100ms and see if euid drops to normal user
time.Sleep(time.Millisecond * 100)
if !osutil.IsPidValid(proc.pid) {
log.WithFields(log.Fields{"proc": proc}).Debug("skip short-lived")
return
}
p.updateProcess(proc)
if proc.ruid == parent.ruid { // no change by real user id
return
}
// log.WithFields(log.Fields{"parent": parent, "c.userns": c.userns}).Debug("PROC:")
log.WithFields(log.Fields{"parent": parent.ruid, "current": proc.ruid}).Debug("PROC:")
// ruid_rebased >= uidMin && euid == root
if (parent.ruid-c.userns.root) >= c.userns.uidMin && // valid user range
proc.ruid == c.userns.root { // user at root privilege level
p.updateProcess(parent) // obtain latest parent data
if _, _, notAuth := p.checkUserGroup_uidChange(parent, c); notAuth {
if len(parent.cmds) == 0 {
parent.cmds, _ = global.SYS.ReadCmdLine(proc.ppid)
}
// skip if: userapp (user) -> (sudo)shell cmd -> children(established root)
if isSudoCommand(parent.cmds) {
return
}
// skip if: pgid is one of below processes (above and below "parent" checks might not be necessary)
if pgrp, ok := p.pidProcMap[proc.pgid]; ok && isSudoCommand(pgrp.cmds) {
return
}
// skip if: sid is one of below processes
if psid, ok := p.pidProcMap[proc.sid]; ok && isSudoCommand(psid.cmds) {
return
}
// skip: "-bash" is a command when: (1) "a sshd session" (2) "sudo -i" in the ssh session (filtered above)
if parent.pname == "sshd" {
if len(parent.cmds) > 0 && parent.cmds[0] == "-bash" {
// log.Debug("PROC: skip sshd")
return
}
}
// report its grand parent (useful for user to find the root cause)
if parent.pid != parent.ppid { // not from the lost parent link
if gp, ok := p.pidProcMap[parent.ppid]; ok {
if len(gp.cmds) == 0 {
gp.cmds, _ = global.SYS.ReadCmdLine(gp.pid)
}
// skip if: (sudo)userapp(user) -> shell cmd(*) -> children(established root)
if isSudoCommand(gp.cmds) {
return
}
// filter false-positive cases: grandparent is root
if gp.ruid == 0 {
mLog.WithFields(log.Fields{"grandparent": gp}).Debug()
return
}
// found it
log.WithFields(log.Fields{"grandparent": gp}).Debug("PROC: ")
log.WithFields(log.Fields{"parent": parent}).Debug("PROC: ")
log.WithFields(log.Fields{"proc": proc}).Debug("PROC: ")
// uid tuple: (euid, ruid)
// userapp(user, user) -> shell cmd(user, user) [report] -> children(root, root)
p.reportEscalation(c.id, parent, gp)
}
}
}
}
}
func (p *Probe) handleProcFork(pid, ppid int, name string) (inContainer bool, pc *procInternal, pp *procInternal) {
var insideContainer bool
now := time.Now()
// log.Debug("PROC: fork: ", ppid, "->", pid)
// dynamic allocation
proc := &procInternal{
name: name,
pid: pid,
ppid: ppid,
sid: osutil.GetSessionId(pid),
pgid: osutil.GetProcessGroupId(pid),
startTime: now,
lastScanTime: now,
action: share.PolicyActionAllow,
}
if parent, ok := p.pidProcMap[proc.ppid]; ok {
// Inherit parent's information
proc.pname = parent.name
proc.ppath = parent.path
proc.user = parent.user
proc.ruid = parent.ruid // assumed, if modified, it should be updated by UID change event
proc.euid = parent.euid
// tag the child
if parent.action == share.PolicyActionCheckApp {
proc.action = parent.action
proc.riskType = parent.riskType
}
// pick up the late information
if proc.user == "" {
proc.user = p.getUserName(proc.ppid, proc.euid) // get parent's username
}
if proc.pname == "" {
proc.pname, _, _, _ = osutil.GetProcessUIDs(proc.ppid) // get parent's name
}
if proc.ppath == "" {
proc.ppath, _ = global.SYS.GetFilePath(proc.ppid) // get parent's executable name
}
if exist, ok := p.pidProcMap[proc.pid]; ok {
// state machine acts like a LIFO or realigned mode?, EXEC before FORK event
if c, ok := p.pidContainerMap[proc.pid]; ok {
insideContainer = c.id != ""
proc.ppid = ppid
} else {
if c1, ok := p.addContainerCandidateFromProc(proc); ok {
insideContainer = c1.id != ""
} else { // a hole by reBuiltProcessTables
// log.WithFields(log.Fields{"pid": pid, "ppid": ppid}).Debug("PROC: Process not in conatiner map")
insideContainer = false // assume
}
}
proc.action = exist.action
proc.reported = exist.reported
p.pidProcMap[proc.pid] = proc
return insideContainer, proc, nil
} else {
p.pidProcMap[proc.pid] = proc // new into process map
p.inspectProcess.Add(proc)
}
if c, ok := p.pidContainerMap[proc.ppid]; ok {
insideContainer = c.id != ""
// If parent is in the container, the child is too
p.addContainerProcess(c, proc.pid)
}
} else {
// log.WithFields(log.Fields{"pid": pid, "ppid": ppid, "name": name}).Debug("Process parent not in map")
// dynamic allocations
proc_p := &procInternal{
pid: ppid,
ppid: ppid,
sid: proc.sid,