This repository has been archived by the owner on Oct 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
814 lines (742 loc) · 26.8 KB
/
main.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
/*
* Copyright 2020-2021 Banco Bilbao Vizcaya Argentaria, S.A.
*
* 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.
*/
// CAVEAT EMPTOR: The current design assumes that the surveilled process spawned by
// BIFF will wait for each and every descendant to die before dying himself.
// Otherwise, the descendants surviving the parent surveilled process won't be
// monitored after the fact.
// TODO: Log argv of the execve-ees
// TODO: Log the case of each hashed file (input, output, or inputoutput)
// TODO: Don't try to hash special files, log event instead
package main
import "C"
import (
"crypto/md5"
"errors"
"fmt"
"io"
"log"
"os"
"runtime"
"sync"
"syscall"
"go.uber.org/zap" // https://github.com/uber-go/zap
"golang.org/x/sys/unix"
)
const (
// Biff, named after the classic UNIX® Biff email notification program¹
// is a small helper program that is used as a way for proctool's
// goroutines to send messages to proctool's main goroutine/thread,
// which is usually blocked Wait4()ing for Ptrace events, and thus would
// not be able to read from a channel as is standard practice.
// proctool spawns a ptraced biff, which in turn spawns the process
// specified to proctool via Argv. When proctool goroutines want to
// signal the main goroutine, they simply send a UNIX® signal to biff,
// which is ptraced by proctool, and thus proctool main goroutine will
// awaken from the Wait4(), determine that the reason of the awakening
// is biff being signaled, and read a message from a preordained
// channel.
// Note that this implementation is an act of desperation upon facing
// the tricky interface provided by ptrace(). Without biff, we were
// unable to employ goroutines effectively.
// [1]: http://www.catb.org/jargon/html/B/biff.html
biffProcess = "[ProcTool Biff]"
channelReady = syscall.SIGUSR1
isBiff = 1 << iota
isSyscall
isSignal
isExit
stopCauseIgnorable = 0
stopCauseSurveilledSyscall = isSyscall
stopCauseSurveilledSignal = isSignal
stopCauseSurveilledExit = isExit
stopCauseBiffSyscall = isBiff | isSyscall
stopCauseBiffSignal = isBiff | isSignal
stopCauseBiffExit = isBiff | isExit
syscallStopPointUnmonitored = iota
syscallStopPointCloneReturn
syscallStopPointOpenatReturn
syscallStopPointOpenReturn
syscallStopPointExecveCall
O_RDONLY = iota
O_RDWR
O_WRONLY
O_TRUNC_RDWR
)
func main() {
// XXX: Can we initialize the logger here? We have to ensure syncing
// with a defer (can we even do that with os.Exit on main?)
//
// setupLogger()
log.SetFlags(log.LstdFlags | log.Lshortfile)
config := zap.NewProductionConfig()
config.Sampling = nil
logger, _ := config.Build()
defer logger.Sync()
zap.ReplaceGlobals(logger)
os.Exit(trace())
}
func setupLogger() {
// TODO: check the environment for var: TBD that signifies where to send the output (path to file)
// TODO: we need a logger for the special occasions (when surveilled cannot be
// spawned, or traced, or whatever). When abort is the only way forward.
// We'll dump info to stderr, then.
}
func isTracer() bool {
return os.Args[0] != biffProcess
}
func startBiff() (pid, pgid int, err error) {
fd, err := unix.MemfdCreate("biff", unix.MFD_CLOEXEC)
if err != nil {
return
}
_, err = unix.Write(fd, BiffBlob)
if err != nil {
return
}
biff, err := os.StartProcess(
fmt.Sprintf("/proc/self/fd/%d", fd),
append([]string{biffProcess}, os.Args[1:]...),
&os.ProcAttr{
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
Sys: &syscall.SysProcAttr{
Ptrace: true,
},
},
)
if err != nil {
return
}
pid = biff.Pid
_, err = biff.Wait()
if err != nil {
return
}
pgid, err = syscall.Getpgid(biff.Pid)
return
}
func traceBiff(pid int) error {
// https://medium.com/golangspec/making-debugger-in-golang-part-ii-d2b8eb2f19e0
err := syscall.PtraceSetOptions(
pid,
syscall.PTRACE_O_TRACECLONE|syscall.PTRACE_O_TRACEFORK|syscall.PTRACE_O_TRACEVFORK|syscall.PTRACE_O_TRACEEXEC,
)
if err != nil {
return err
}
return syscall.PtraceCont(pid, 0)
}
func decodeStopCause(wstatus syscall.WaitStatus, traceePid, biffPid int) (stopCause int) {
if traceePid == biffPid {
stopCause |= isBiff
}
if wstatus.Exited() {
stopCause |= isExit
} else if wstatus.StopSignal() == syscall.SIGTRAP {
stopCause |= isSyscall
} else {
stopCause |= isSignal
}
return
}
func isAsyncTaskFinishedSignal(biffPgid int, wstatus syscall.WaitStatus) bool {
// TODO: check that the sender.Pgid matches biffPgid
// XXX: Not sure how to achieve this :-(
// See https://stackoverflow.com/questions/30219751/go-get-signal-origin
return wstatus.StopSignal() == channelReady
}
type safeBool struct {
Value bool
m sync.Mutex
}
func (f *safeBool) Lock() {
f.m.Lock()
}
func (f *safeBool) SetAndUnlock(v bool) {
f.Value = v
f.m.Unlock()
}
func decodeSyscallStopPoint(regs syscall.PtraceRegs, isReturning bool) int {
// NOTE: ptrace stop-enter-syscall and stop-exit-syscall cannot be
// distinguised by the contents of the registers.
// RTFM!
if syscall_number := regs.Orig_rax; syscall_number == syscall.SYS_EXECVE && !isReturning {
return syscallStopPointExecveCall
// } else if syscall_number == syscall.SYS_OPENAT && isReturning { XXX: handle this, plz!
} else if syscall_number == syscall.SYS_CLONE || syscall_number == syscall.SYS_FORK || syscall_number == syscall.SYS_VFORK {
return syscallStopPointCloneReturn
} else if syscall_number == syscall.SYS_OPENAT {
return syscallStopPointOpenatReturn
} else if syscall_number == syscall.SYS_OPEN {
return syscallStopPointOpenReturn
} else {
return syscallStopPointUnmonitored
}
}
func getOpenPath(pid int, regs syscall.PtraceRegs) (string, error) {
path, err := readString(pid, uintptr(regs.Rdi))
if err != nil {
return "", err
}
return path, nil
}
func getOpenAtPath(pid int, regs syscall.PtraceRegs) (string, error) {
path, err := readString(pid, uintptr(regs.Rsi))
if err != nil {
return "", err
}
return path, nil
}
func getExecvePath(pid int, regs syscall.PtraceRegs) (string, error) {
path, err := readString(pid, uintptr(regs.Rdi))
if err != nil {
return "", err
}
return path, nil
}
func isOpenAtOk(regs syscall.PtraceRegs) bool {
return int64(regs.Rax) > -1
}
func getClonePid(regs syscall.PtraceRegs) int {
return int(regs.Rax)
}
func getOpenAtMode(regs syscall.PtraceRegs) int {
if regs.Rdx&syscall.O_RDWR != 0 {
if regs.Rdx&syscall.O_TRUNC != 0 {
return O_TRUNC_RDWR
} else {
return O_RDWR
}
} else if regs.Rdx&syscall.O_WRONLY != 0 {
return O_WRONLY
} else { // O_RDONLY
return O_RDONLY
}
}
func getOpenMode(regs syscall.PtraceRegs) int {
if regs.Rsi&syscall.O_RDWR != 0 {
if regs.Rsi&syscall.O_TRUNC != 0 {
return O_TRUNC_RDWR
} else {
return O_RDWR
}
} else if regs.Rsi&syscall.O_WRONLY != 0 {
return O_WRONLY
} else { // O_RDONLY
return O_RDONLY
}
}
func getOpenAtFd(regs syscall.PtraceRegs) int {
return int(regs.Rax)
}
func readString(pid int, addr uintptr) (string, error) {
data := make([]byte, 4096)
bytes_copied, _ := syscall.PtracePeekData(pid, addr, data)
if bytes_copied == 0 {
return "", fmt.Errorf("0-byte string returned")
}
str := C.GoString((*C.char)(C.CBytes(data)))
return str, nil
}
func hashFile(filename string) (string, error) {
fi, err := os.Stat(filename)
if err != nil {
return "", err
}
if !fi.Mode().IsRegular() {
return "", errors.New("Not a regular file")
}
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func sendContinue(biffPid, traceePid int, stoppedSurveilledPid chan int) {
err := syscall.Kill(biffPid, channelReady)
if err != nil {
zap.L().Error("Cannot signal biff about available message", zap.Error(err))
}
stoppedSurveilledPid <- traceePid
}
func hashFileAndContinue(biffPid, traceePid, fd int, path string, stoppedSurveilledPid chan int) {
defer sendContinue(biffPid, traceePid, stoppedSurveilledPid)
if hash, err := hashFile(path); err != nil {
zap.L().Error("Cannot hash file via path", zap.Int("pid", traceePid), zap.Int("fd", fd), zap.String("path", path), zap.Error(err))
} else {
zap.L().Info("Hashed file", zap.String("path", path), zap.String("hash", hash))
}
return
}
func hashExecAndContinue(biffPid, traceePid int, path string, stoppedSurveilledPid chan int) {
defer sendContinue(biffPid, traceePid, stoppedSurveilledPid)
if hash, err := hashFile(path); err != nil {
zap.L().Error("Cannot hash file via path", zap.String("path", path), zap.Error(err))
} else {
zap.L().Info("Hashed file", zap.String("path", path), zap.String("hash", hash))
}
return
}
func trace() (exitStatus int) {
runtime.LockOSThread()
zap.L().Info("Starting biff process")
biffPid, biffPgid, err := startBiff()
if err != nil {
zap.L().Fatal("Cannot start biff process", zap.Error(err))
}
err = traceBiff(biffPid)
if err != nil {
zap.L().Fatal("Cannot trace biff process", zap.Error(err))
}
var alteredFiles sync.Map // addressing by path [string]*safeBool
var pendingHashes sync.WaitGroup
stoppedSurveilledPid := make(chan int)
returningFromSyscall := make(map[int]bool)
traceStep := 0
defer pendingHashes.Wait()
defer alteredFiles.Range(
func(key, value interface{}) bool {
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
path := key.(string)
wasModified := value.(*safeBool)
wasModified.Lock()
defer wasModified.SetAndUnlock(false)
// Already hashed, skipping
if !wasModified.Value {
return
}
if hash, err := hashFile(path); err != nil {
zap.L().Error(
"A pending hash cannot be performed. Maybe the file was deleted?",
zap.String("path", path),
zap.Error(err),
zap.Bool("wasModified", wasModified.Value),
)
} else {
zap.L().Info(
"A pending hash was performed after all processes finished.",
zap.String("path", path),
zap.Bool("wasModified", wasModified.Value),
zap.String("hash", hash))
}
}()
return true
})
for {
traceStep++
wstatus := syscall.WaitStatus(0)
traceePid, err := syscall.Wait4(-1, &wstatus, syscall.WALL, nil)
if err != nil {
zap.L().Info("There are no more children to wait for", zap.Error(err), zap.Int("traceStep", traceStep))
// XXX: This will happend once all children finish
return
}
switch stopCause := decodeStopCause(wstatus, traceePid, biffPid); stopCause {
case stopCauseBiffExit:
exitStatus = wstatus.ExitStatus()
zap.L().Info(
"Biff process exited",
zap.Int("traceePid", traceePid),
zap.String("stopCause", "STOPCAUSE_BIFF_EXIT"),
zap.Int("traceStep", traceStep),
zap.Int("exitStatus", exitStatus),
)
case stopCauseBiffSignal:
if isAsyncTaskFinishedSignal(biffPgid, wstatus) {
surveilledToBeContinued := <-stoppedSurveilledPid
zap.L().Info(
"Biff process received a signal from an async task allowing a surveilled to continue",
zap.Int("traceePid", traceePid),
zap.String("stopCause", "STOPCAUSE_BIFF_SIGNAL"),
zap.Int("traceStep", traceStep),
zap.Int("surveilledToBeContinued", surveilledToBeContinued))
syscall.PtraceSyscall(surveilledToBeContinued, 0)
syscall.PtraceCont(traceePid, 0)
// TODO: Capture errors
} else {
zap.L().Info(
"Biff process received an unknown signal!",
zap.Int("traceePid", traceePid),
zap.String("stopCause", "STOPCAUSE_BIFF_SIGNAL"),
zap.Int("traceStep", traceStep),
zap.Int("stopSignal", int(wstatus.StopSignal())),
)
syscall.PtraceCont(traceePid, int(wstatus.StopSignal()))
}
case stopCauseBiffSyscall:
zap.L().Info(
"Biff process stop calling or returning from syscall",
zap.Int("traceePid", traceePid),
zap.String("stopCause", "STOPCAUSE_BIFF_SYSCALL"),
zap.Int("traceStep", traceStep),
)
syscall.PtraceCont(traceePid, 0)
case stopCauseSurveilledExit:
zap.L().Info("Surveiled process exited", zap.Int("traceePid", traceePid), zap.String("stopCause", "STOPCAUSE_SURVEILLED_EXIT"), zap.Int("traceStep", traceStep))
// TODO: it's reckoning day! hash any files opened by the deceased,
// which might have not percolated via ptrace() because reasons
// (and the kernel closed on its behalf)
// TODO: this hash should only happen if this process was the last
// writer standing (either, O_RDWR, or O_WRONLY)
case stopCauseSurveilledSignal:
zap.L().Info("Surveiled process received a signal", zap.Int("traceePid", traceePid), zap.String("stopCause", "STOPCAUSE_SURVEILLED_SIGNAL"), zap.Int("traceStep", traceStep))
syscall.PtraceSyscall(traceePid, int(wstatus.StopSignal()))
case stopCauseSurveilledSyscall:
// TODO: encapsulate this in a struct w/ decodeSyscallStopPoint as a method?
isReturning := returningFromSyscall[traceePid]
returningFromSyscall[traceePid] = !isReturning
regs := &syscall.PtraceRegs{}
err = syscall.PtraceGetRegs(traceePid, regs)
if err != nil {
zap.L().Error("Error reading registers of a surveiled process when tracing a syscall. Maybe the process was killed?", zap.Int("traceePid", traceePid), zap.Int("traceStep", traceStep), zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"))
continue
}
switch syscallStopPoint := decodeSyscallStopPoint(*regs, isReturning); syscallStopPoint {
case syscallStopPointExecveCall:
path, err := getExecvePath(traceePid, *regs)
if err != nil {
zap.L().Error(
"Error analyzing execve() syscall. path was not pointing to a proper string",
zap.Int("traceePid", traceePid),
zap.Error(err),
zap.Int("traceStep", traceStep),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_EXECVE_CALL"))
syscall.PtraceSyscall(traceePid, 0)
} else {
zap.L().Info(
"A execve() was intercepted and the pointed path found. Hashing file before allowing the process to continue",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("path", path),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_EXECVE_CALL"))
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
hashExecAndContinue(biffPid, traceePid, path, stoppedSurveilledPid) // process continuation will be handled by STOPCAUSE_BIFF_SIGNAL > isAsyncTaskFinishedSignal()
}()
}
case syscallStopPointCloneReturn:
childPid := getClonePid(*regs)
if childPid > 0 {
zap.L().Info(
"A clone call just returned",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("childPid", childPid),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_CLONE_CALL"))
}
syscall.PtraceSyscall(traceePid, 0)
case syscallStopPointOpenatReturn:
if isOpenAtOk(*regs) {
path, err := getOpenAtPath(traceePid, *regs)
if err != nil {
zap.L().Error(
"Kernel reported that the file was open correctly but we can't read the path string",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"))
syscall.PtraceSyscall(traceePid, 0)
} else {
fd := getOpenAtFd(*regs)
mode := getOpenAtMode(*regs)
switch mode {
case O_RDONLY:
zap.L().Info(
"Surveilled is about to open a file in RDONLY mode. Hashing in background and allowing it to continue.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
// Dead or alive, you're coming with me
func() {
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(false)
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
if hash, err := hashFile(path); err != nil {
zap.L().Error(
"Cannot hash file via path",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
} else {
zap.L().Info(
"Successful file hash",
zap.String("path", path),
zap.String("hash", hash),
zap.String("mode", "O_RDONLY"),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
}
return
}()
err := syscall.PtraceSyscall(traceePid, 0)
if err != nil {
zap.L().Error(
"Error allowing surveiled to continue after stopping it in an openat call. Maybe the process was killed?",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
}
}()
case O_RDWR:
zap.L().Info(
"Surveilled is about to open a file in RDWR mode. Stopping it until the hash is done.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_RDWR"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(true)
hashFileAndContinue(biffPid, traceePid, fd, path, stoppedSurveilledPid) // process continuation will be handled by STOPCAUSE_BIFF_SIGNAL > isAsyncTaskFinishedSignal()
}()
case O_WRONLY, O_TRUNC_RDWR: // Nota del Ruso: sólo importan las lecturas; WR al cierre (0x1623498761923487162938764912837649128374691)
zap.L().Info(
"Surveilled is about to open a file in WRONLY mode. We will mark this file as modified; it will be hashed when another process tries to open it for reading or when everyone dies.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_RDWR"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"))
func() {
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(true)
err := syscall.PtraceSyscall(traceePid, 0)
if err != nil {
// TODO: log process is dead
}
}()
}
}
} else {
zap.L().Info(
"The process tried to open a file but the kernel returned an error",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("Rax", int(regs.Rax)),
zap.Int("Orig_rax", int(regs.Orig_rax)),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPENAT_RETURN"),
)
syscall.PtraceSyscall(traceePid, 0)
}
case syscallStopPointOpenReturn:
if isOpenAtOk(*regs) {
path, err := getOpenPath(traceePid, *regs)
if err != nil {
zap.L().Error(
"Kernel reported that the file was open correctly but we can't read the path string",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"))
syscall.PtraceSyscall(traceePid, 0)
} else {
fd := getOpenAtFd(*regs)
mode := getOpenMode(*regs)
switch mode {
case O_RDONLY:
zap.L().Info(
"Surveilled is about to open a file in RDONLY mode. Hashing in background and allowing it to continue.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
// Dead or alive, you're coming with me
func() {
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(false)
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
if hash, err := hashFile(path); err != nil {
zap.L().Error(
"Cannot hash file via path",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
} else {
zap.L().Info(
"Successful file hash",
zap.String("path", path),
zap.String("hash", hash),
zap.String("mode", "O_RDONLY"),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
}
return
}()
err := syscall.PtraceSyscall(traceePid, 0)
if err != nil {
zap.L().Error(
"Error allowing surveiled to continue after stopping it in an openat call. Maybe the process was killed?",
zap.Error(err),
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("path", path),
zap.String("mode", "O_RDONLY"),
zap.Int("fd", fd),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
}
}()
case O_RDWR:
zap.L().Info(
"Surveilled is about to open a file in RDWR mode. Stopping it until the hash is done.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_RDWR"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
pendingHashes.Add(1)
go func() {
defer pendingHashes.Done()
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(true)
hashFileAndContinue(biffPid, traceePid, fd, path, stoppedSurveilledPid) // process continuation will be handled by STOPCAUSE_BIFF_SIGNAL > isAsyncTaskFinishedSignal()
}()
case O_WRONLY, O_TRUNC_RDWR: // Nota del Ruso: sólo importan las lecturas; WR al cierre (0x1623498761923487162938764912837649128374691)
zap.L().Info(
"Surveilled is about to open a file in WRONLY mode. We will mark this file as modified; it will be hashed when another process tries to open it for reading or when everyone dies.",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("fd", fd),
zap.String("path", path),
zap.String("mode", "O_WRONLY"),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"))
func() {
tmp, _ := alteredFiles.LoadOrStore(path, &safeBool{})
flag := tmp.(*safeBool)
flag.Lock()
defer flag.SetAndUnlock(true)
err := syscall.PtraceSyscall(traceePid, 0)
if err != nil {
// TODO: log process is dead
}
}()
}
}
} else {
zap.L().Info(
"The process tried to open a file but the kernel returned an error",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.Int("Rax", int(regs.Rax)),
zap.Int("Orig_rax", int(regs.Orig_rax)),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_OPEN_RETURN"),
)
syscall.PtraceSyscall(traceePid, 0)
}
case syscallStopPointUnmonitored:
zap.L().Info(
"Analyzing SYSCALL_STOP_POINT_UNMONITORED",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.String("syscallStopPoint", "SYSCALL_STOP_POINT_UNMONITORED"),
zap.Int("Orig_rax", int(regs.Orig_rax)),
zap.Int("biffPid", biffPid),
)
syscall.PtraceSyscall(traceePid, 0)
default:
zap.L().Fatal(
"Unmanaged SYSCALL_STOP_POINT",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("stopCause", "STOPCAUSE_SURVEILLED_SYSCALL"),
zap.Int("syscallStopPoint", syscallStopPoint),
)
}
case stopCauseIgnorable:
zap.L().Error(
"Attending STOPCAUSE_IGNORABLE. Cannot get tracee PGID",
zap.Int("traceePid", traceePid),
zap.Int("traceStep", traceStep),
zap.String("stopCause", "STOPCAUSE_IGNORABLE"),
)
syscall.PtraceSyscall(traceePid, 0)
default:
zap.L().Fatal(
"Unmanaged STOPCAUSE",
zap.Int("traceePid", traceePid),
zap.Int("stopCause", stopCause),
zap.Int("traceStep", traceStep),
)
}
}
}