-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy paththreadstate.rs
More file actions
4860 lines (4206 loc) · 183 KB
/
threadstate.rs
File metadata and controls
4860 lines (4206 loc) · 183 KB
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
use anyhow::{Result, anyhow};
use libc::{
AF_INET, AF_INET6, IPPROTO_ICMP, IPPROTO_IP, IPPROTO_RAW, IPPROTO_TCP, IPPROTO_UDP, SOCK_DGRAM,
SOCK_RAW, SOCK_STREAM,
};
use crate::proto::generated::protect::control::v1::{
ZoneKernelEventParam, ZoneKernelFdInfo, ZoneKernelFdInfoData, ZoneKernelIpv4SocketInfo,
ZoneKernelIpv6SocketInfo, ZoneKernelPidFd, ZoneKernelRegularFileInfo, ZoneKernelSyscallEvent,
ZoneKernelThreadInfo, ZoneKernelThreadSnapshotEvent, ZoneKernelUnixSocketInfo,
zone_kernel_fd_info_data::InfoType,
};
use libscap_bindings::{
consts as ppm_consts,
types::{
ppm_event_code as event_codes, ppm_param_type as param_type, scap_fd_type as fd_types,
scap_l4_proto as l4_types,
},
};
use log::{debug, error, trace, warn};
use std::collections::HashMap;
use std::ffi::CStr;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;
use std::time::Duration;
use strum_macros::Display;
use crate::parsers;
// a handful of libsinsp/libscap consts
// duplicated here
const SE_EINPROGRESS: i64 = 115;
const FLAGS_ROLE_CLIENT: u32 = 1 << 2;
const FLAGS_ROLE_SERVER: u32 = 1 << 3;
const FLAGS_SOCKET_CONNECTED: u32 = 1 << 13;
const FLAGS_IS_CLONED: u32 = 1 << 14;
const FLAGS_CONNECTION_PENDING: u32 = 1 << 15;
const FLAGS_CONNECTION_FAILED: u32 = 1 << 16;
const FLAGS_OVERLAY_UPPER: u32 = 1 << 17;
const FLAGS_OVERLAY_LOWER: u32 = 1 << 18;
const FILE_DESCRIPTOR_PARAM_ID: usize = 2;
const SOCKET_TUPLE_PARAM_ID: usize = 4;
const PPM_CL_CLONE_NEWUSER: u32 = 1 << 20;
#[derive(Debug, Display)]
pub enum ProcessingError {
ZoneCPUHotplug(String),
}
impl std::error::Error for ProcessingError {}
#[derive(Default)]
pub struct ThreadState {
zone_info: HashMap<String, ZoneInfo>,
}
#[derive(Default, Clone)]
pub struct ExecTime {
pub last_switch_ts: u64,
pub previous_switch_ts: u64,
pub cumulative_switch_time: u64,
}
#[derive(Default)]
pub struct ZoneInfo {
seen_threadsnaps: HashMap<u64, ZoneKernelThreadInfo>,
last_enter_event_for_tid: HashMap<u64, ZoneKernelSyscallEvent>,
// TODO(bml) consider dropping this
dropped_fds_by_thread: HashMap<u64, u64>,
last_proc_switch_times_by_cpuid: HashMap<u32, ExecTime>,
boot_epoch: u64,
}
impl ZoneInfo {
pub fn get_threadinfo(&self, thread_id: &u64) -> Option<&ZoneKernelThreadInfo> {
self.seen_threadsnaps.get(thread_id)
}
pub fn get_enter_event(
&self,
exit_event: &ZoneKernelSyscallEvent,
) -> Option<&ZoneKernelSyscallEvent> {
if let Some(enter_event) = self.get_lastevent(&exit_event.thread_id) {
let exit_type = event_codes::from_repr(exit_event.event_type)
.ok_or(anyhow!("could not parse exit event type"))
.expect("should parse");
let enter_type = event_codes::from_repr(enter_event.event_type)
.ok_or(anyhow!("could not parse enter event type"))
.expect("should parse");
let computed_correlate = event_codes::from_repr(exit_event.event_type - 1);
if exit_type == event_codes::PPME_SYSCALL_EXECVE_19_X
&& enter_type == event_codes::PPME_SYSCALL_EXECVEAT_E
{
Some(enter_event)
} else if computed_correlate.is_some()
&& (enter_type != computed_correlate.expect("already checked"))
{
None
} else {
Some(enter_event)
}
} else {
None
}
}
/// This checks
/// - If this is an enter event, whether it's one that specifies a FD, and if so,
/// returns the FD info for that, if we have it.
/// - If this is an exit event,and if so, whether it's one whose enter event we saw specifies an FD, and
/// if so returns the FD info for that, if we have it, otherwise checks if this is one of the rare exit events that also defines an
/// FD num, and returns that fdinfo if present.
///
/// Otherwise, returns None
pub fn get_enterexit_event_fdinfo(
&self,
event: &ZoneKernelSyscallEvent,
) -> Option<ZoneKernelFdInfo> {
if parsers::has_fd(event) {
if parsers::is_enter(event) {
self.get_enter_fdi(event).and_then(|fdi| {
self.with_leader_fdlist_ctx(event, |fdlist| fdlist.get(&fdi).cloned())
})
} else {
parsers::get_fdi(event).and_then(|fdi| {
self.with_leader_fdlist_ctx(event, |fdlist| fdlist.get(&fdi).cloned())
})
}
} else {
None
}
}
pub fn get_thread_groupsize(&self, thread_id: &u64, exclude_leader: bool) -> u64 {
self.seen_threadsnaps
.get(thread_id)
.and_then(|tinfo| tinfo.pid)
.map(|tgroup_pid| {
self.seen_threadsnaps
.values()
.filter(|t| {
t.pid.is_some_and(|tpid| tpid == tgroup_pid)
&& !(parsers::thread_main(t) && exclude_leader)
})
.count() as u64
})
.unwrap_or(0)
}
pub fn get_exectime(&self, cpuid: &u32) -> Option<ExecTime> {
self.last_proc_switch_times_by_cpuid.get(cpuid).cloned()
}
pub fn get_leader_tid(tinfo: &ZoneKernelThreadInfo) -> Option<u64> {
tinfo.pid.or(tinfo.tid)
}
fn get_fd(&self, tinfo: &ZoneKernelThreadInfo, fd: &u64) -> Option<&ZoneKernelFdInfo> {
let owner_id = Self::get_leader_tid(tinfo)?;
self.seen_threadsnaps
.get(&owner_id)
.and_then(|owner| owner.fdlist.get(fd))
}
/// libsinsp always stores all FDs with the parent/main thread,
/// so child threads do not have their own FD list. In fact they
/// go so far as to spuriously mark all threads as CLONE_FILES
/// even if it wasn't set by Linux, to guarantee this view.
///
/// That's a little wonky but 99% of the time it's correct,
/// and for tracking purposes in the rules engine it never makes a difference.
/// And it makes for cheaper fd lookups.
///
/// So that is why *ALL* event parser funcs in this class should add/remove to the leader
/// thread's FD list, and that's what these helpers are for.
fn with_mut_leader_fdinfo_ctx<F, R>(
&mut self,
tinfo: &ZoneKernelThreadInfo,
fd: &u64,
f: F,
) -> Option<R>
where
F: FnOnce(&mut ZoneKernelFdInfo) -> Option<R>,
{
let owner_id = Self::get_leader_tid(tinfo)?;
self.seen_threadsnaps
.get_mut(&owner_id)
.and_then(|owner| owner.fdlist.get_mut(fd))
.and_then(f)
}
fn with_leader_fdlist_ctx<F, R>(&self, event: &ZoneKernelSyscallEvent, f: F) -> Option<R>
where
F: FnOnce(&HashMap<u64, ZoneKernelFdInfo>) -> Option<R>,
{
if let Some(owner_id) = self
.seen_threadsnaps
.get(&event.thread_id)
.and_then(Self::get_leader_tid)
{
self.seen_threadsnaps
.get(&owner_id)
.and_then(|owner| f(&owner.fdlist))
} else {
None
}
}
fn with_mut_leader_fdlist_ctx<F, R>(
&mut self,
event: &ZoneKernelSyscallEvent,
f: F,
) -> Option<R>
where
F: FnOnce(&mut HashMap<u64, ZoneKernelFdInfo>) -> Option<R>,
{
if let Some(owner_id) = self
.seen_threadsnaps
.get_mut(&event.thread_id)
.and_then(|tinfo| Self::get_leader_tid(tinfo))
{
self.seen_threadsnaps
.get_mut(&owner_id)
.and_then(|owner| f(&mut owner.fdlist))
} else {
None
}
}
fn with_mut_leader_ctx<F, R>(&mut self, event: &ZoneKernelSyscallEvent, f: F) -> Option<R>
where
F: FnOnce(&mut ZoneKernelThreadInfo) -> Option<R>,
{
if let Some(owner_id) = self
.seen_threadsnaps
.get_mut(&event.thread_id)
.and_then(|tinfo| Self::get_leader_tid(tinfo))
{
self.seen_threadsnaps.get_mut(&owner_id).and_then(f)
} else {
None
}
}
/// Returns `None` if no threadinfo exists in the zone thread table for the threadid combo
/// specified by the event. Otherwise, runs a FnOnce over a mutable reference to the threadinfo
fn with_mut_threadinfo_ctx<F, R>(&mut self, event: &ZoneKernelSyscallEvent, f: F) -> Option<R>
where
F: FnOnce(&mut ZoneKernelThreadInfo) -> Option<R>,
{
self.seen_threadsnaps.get_mut(&event.thread_id).and_then(f)
}
/// Returns `None` if no threadinfo exists in the zone thread table for the threadid
/// specified by the event. Otherwise, runs a FnOnce over an immutable reference to the threadinfo
fn with_threadinfo_ctx<F, R>(&self, event: &ZoneKernelSyscallEvent, f: F) -> Option<R>
where
F: FnOnce(&ZoneKernelThreadInfo) -> Option<R>,
{
self.seen_threadsnaps.get(&event.thread_id).and_then(f)
}
/// Runs a FnOnce over a mutable reference to the zone thread table,
/// if a thread table exists for that zone.
fn with_mut_threadsnaps_ctx<F, R>(&mut self, f: F) -> Option<R>
where
F: FnOnce(&mut HashMap<u64, ZoneKernelThreadInfo>) -> Option<R>,
{
f(&mut self.seen_threadsnaps)
}
/// See `sinsp_parser::reset` in libsinsp/parsers.cpp.
/// Since we store the whole "sibling enter event", for context on handling a given exit event,
/// we don't need to do most of the stuff the CPP version does, except for storing/invalidating
/// the sibling event.
fn preprocess_event(&mut self, event: &ZoneKernelSyscallEvent, etype: event_codes) {
use event_codes::*;
// if this is an enter event, update the "last_event for this zone/tid"
// table to be *this event*. TODO BML both sinsp code and what I've seen indicate
// that in a lot of cases this pairing stuff isn't totally required, and could be refactored out.
if parsers::is_enter(event) {
// TODO BML scap code sets up enter timestamp here, but I don't think we need that?
// We already know the enter timestamp.
self.last_enter_event_for_tid
.insert(event.thread_id, event.clone());
} else {
// TODO BML scap code sets up enter timestamp here, but I don't think we need that?
// We already know the enter timestamp from lastevent ts.
if let Some(last_evt) = self.last_enter_event_for_tid.get(&event.thread_id) {
// in either of these cases, the last event is the corresponding enter event for this type,
// and we're good.
// mimicking libsinsp - if this is an exit event, and the last enter event does not match,
// we can't use lastevent - clear it.
if !(etype == PPME_SYSCALL_EXECVE_19_X
&& last_evt.event_type == PPME_SYSCALL_EXECVEAT_E as u32)
&& (etype as u32 != last_evt.event_type + 1)
{
self.clear_lastevent(&event.thread_id);
}
}
}
}
fn parse_rw_exit(&mut self, event: &ZoneKernelSyscallEvent, etype: event_codes) -> Result<()> {
use event_codes::*;
if (etype == PPME_SOCKET_SENDMMSG_X || etype == PPME_SOCKET_RECVMMSG_X)
&& event.event_params.is_empty()
{
return Ok(());
}
let tinfo = self.seen_threadsnaps.get(&event.thread_id).cloned();
if (etype == PPME_SOCKET_SEND_X
|| etype == PPME_SOCKET_SENDTO_X
|| etype == PPME_SOCKET_SENDMSG_X)
&& (tinfo.is_some() && self.maybe_get_event_fdinfo(event).is_none())
{
trace!("inferring socket for event: {:?}", event);
self.infer_sendto_sendmsg_fd(event)
}
// we should have inferred the FD in the previous step. If not, give up.
if self.maybe_get_event_fdinfo(event).is_none() {
return Ok(());
}
let retval = parsers::get_retval(event);
let Some(fdi) = parsers::get_fdi(event) else {
warn!("this event reads fds but could not get fdi");
return Ok(());
};
let Some(tinfo) = tinfo else {
warn!("cannot find tinfo rw_exit");
return Ok(());
};
if retval.is_some_and(|v| v >= 0) {
if parsers::reads_fd(event) {
// update the state flags of the FD
let update_fd_tuple = self.with_mut_leader_fdinfo_ctx(&tinfo, &fdi, |mut_fdinfo| {
if mut_fdinfo.fd_type == fd_types::SCAP_FD_IPV4_SOCK as i32
|| mut_fdinfo.fd_type == fd_types::SCAP_FD_IPV6_SOCK as i32
{
mut_fdinfo.state_flags &=
!(FLAGS_CONNECTION_PENDING | FLAGS_CONNECTION_FAILED);
mut_fdinfo.state_flags |= FLAGS_SOCKET_CONNECTED;
}
let tupleparam = if etype == PPME_SOCKET_RECVFROM_X {
2
} else if etype == PPME_SOCKET_RECVMSG_X {
3
} else if etype == PPME_SOCKET_RECVMMSG_X || etype == PPME_SOCKET_RECV_X {
4
} else {
0
};
if tupleparam > 0
&& (mut_fdinfo.info.is_none() || !parsers::is_tcp_socket(mut_fdinfo))
{
// recvfrom contains tuple info.
// If the fd still doesn't contain tuple info (because the socket is a
// datagram one or because some event was lost),
// add it here.
return Some(Self::update_sockfd_from_tuple(
mut_fdinfo,
&event.event_params[tupleparam as usize],
));
}
None
});
let updated_fdinfo = self
.maybe_get_event_fdinfo(event)
.expect("fdinfo must exist");
let updated_fdinfo_type = updated_fdinfo.fd_type;
if update_fd_tuple.is_some_and(|val| val)
&& (updated_fdinfo_type == fd_types::SCAP_FD_IPV4_SOCK as i32
|| updated_fdinfo_type == fd_types::SCAP_FD_IPV6_SOCK as i32)
{
// if we rewrote the fdinfo, then determine the role and update
// easier to do this outside the mut ref closure
if parsers::is_role_none(updated_fdinfo) {
// default to server port
let mut is_server = true;
if let Some((sport, dport)) =
updated_fdinfo
.info
.as_ref()
.and_then(|info| match &info.info_type {
Some(InfoType::Ipv4Socket(s)) => {
Some((s.source_port, s.dest_port))
}
_ => None,
})
{
// try to infer
is_server = self
.with_threadinfo_ctx(event, |tinfo| {
Some(parsers::is_server_port(tinfo, sport, dport, true))
})
.expect("threadinfo must be there");
}
self.with_mut_leader_fdinfo_ctx(&tinfo, &fdi, |mut_fdinfo| {
if is_server {
Self::set_role_server(mut_fdinfo);
} else {
Self::set_role_client(mut_fdinfo);
Self::swap_addresses(mut_fdinfo);
}
Some(())
});
}
}
// Since you can use Unix sockets to pass FDs between processes,
// libsinsp here tries to parse out the SCM_RIGHTS info from
// RECVMSG to extract any FDs there.
//
// I'm TODOing this because the current libsinsp approach
// always does a hard `/proc` host query for these and doesn't rely
// on the thread/fd table, for Reasons (it's tricky).
//
// Passing FDs around with unix sockets is something of a corner case tho,
// so for now skipping.
if updated_fdinfo_type == fd_types::SCAP_FD_UNIX_SOCK as i32 {
debug!("TODO unix socket SCM_RIGHTS FD parsing");
}
} else {
//does not read from FD
if etype == PPME_SOCKET_SEND_X
|| etype == PPME_SOCKET_SENDTO_X
|| etype == PPME_SOCKET_SENDMSG_X
|| etype == PPME_SOCKET_SENDMMSG_X
{
// update the state flags of the FD
let update_fd_tuple =
self.with_mut_leader_fdinfo_ctx(&tinfo, &fdi, |mut_fdinfo| {
if mut_fdinfo.info.is_none() || !parsers::is_tcp_socket(mut_fdinfo) {
// send, sendto, sendmsg and sendmmsg contain tuple info in the exit event.
// If the fd still doesn't contain tuple info (because the socket is a datagram one
// or because some event was lost), add it here.
let tupleparam = 4;
return Some(Self::update_sockfd_from_tuple(
mut_fdinfo,
&event.event_params[tupleparam as usize],
));
}
None
});
let updated_fdinfo = self
.maybe_get_event_fdinfo(event)
.expect("fdinfo must exist");
let updated_fdinfo_type = updated_fdinfo.fd_type;
if update_fd_tuple.is_some_and(|val| val)
&& (updated_fdinfo_type == fd_types::SCAP_FD_IPV4_SOCK as i32
|| updated_fdinfo_type == fd_types::SCAP_FD_IPV6_SOCK as i32)
{
// if we rewrote the fdinfo, then determine the role and update
// easier to do this outside the mut ref closure
if parsers::is_role_none(updated_fdinfo) {
// default to client port
let mut is_server = false;
if let Some((sport, dport)) =
updated_fdinfo.info.as_ref().and_then(|info| {
match &info.info_type {
Some(InfoType::Ipv4Socket(s)) => {
Some((s.source_port, s.dest_port))
}
_ => None,
}
})
{
// try to infer
is_server = self
.with_threadinfo_ctx(event, |tinfo| {
Some(parsers::is_server_port(tinfo, sport, dport, false))
})
.expect("threadinfo must be there");
}
self.with_mut_leader_fdinfo_ctx(&tinfo, &fdi, |mut_fdinfo| {
if is_server {
Self::set_role_server(mut_fdinfo);
Self::swap_addresses(mut_fdinfo);
} else {
Self::set_role_client(mut_fdinfo);
}
Some(())
});
}
}
}
}
}
Ok(())
}
/// returns a reference to the ZoneKernelFdInfo in the table, for this event's specified thread,
/// and it's specified FD number.
///
/// Not all events carry an FD number (see parsers::has_fd) and we may not have an entry for this one in the table.
/// In both of those cases, this will return None
fn maybe_get_event_fdinfo(&self, event: &ZoneKernelSyscallEvent) -> Option<&ZoneKernelFdInfo> {
let tinfo = self.seen_threadsnaps.get(&event.thread_id);
if let Some(fdi) = parsers::get_fdi(event)
&& let Some(thread_info) = tinfo
{
return self.get_fd(thread_info, &fdi);
};
None
}
/// If we receive a call to 'send()/sendto()/sendmsg()' and the event's m_fdinfo is nullptr,
/// then we likely missed the call to 'socket()' that created the file
/// descriptor. In that case, we'll guess that it's a SOCK_DGRAM/UDP socket
/// and create the fdinfo based on that.
///
/// Precondition: we have a thread entry for the event's thread,
/// but no fd entry for the fd in that thread entry.
fn infer_sendto_sendmsg_fd(&mut self, event: &ZoneKernelSyscallEvent) {
if let Some(retval) = parsers::get_retval(event)
&& retval < 0
{
//syscall failed, can't trust.
return;
}
if event.event_params[FILE_DESCRIPTOR_PARAM_ID].param_type != param_type::PT_FD as u32 {
warn!("unexpected param type for sendto/sendmsg exit, cannot infer FD");
}
let fd: Option<u64> = event.event_params[FILE_DESCRIPTOR_PARAM_ID]
.param_data
.as_slice()
.try_into()
.ok()
.map(i64::from_ne_bytes)
.and_then(|i| i.try_into().ok());
let family = i32::from_ne_bytes(
event.event_params[SOCKET_TUPLE_PARAM_ID]
.param_data
.as_slice()
.try_into()
.unwrap_or_default(),
);
let domain = if family == AF_INET {
ppm_consts::PPM_AF_INET
} else if family == AF_INET6 {
ppm_consts::PPM_AF_INET6
} else {
debug!("not an inet family for sendto/sendmsg socket type, ignoring");
ppm_consts::PPM_AF_UNSPEC
};
// libsinsp: "Here we're assuming send*() means SOCK_DGRAM/UDP, but it
// can be used with TCP. We have no way to know for sure at
// this point."
self.add_socket_fd(event, fd, domain, SOCK_DGRAM, IPPROTO_UDP)
}
fn add_socket_fd(
&mut self,
event: &ZoneKernelSyscallEvent,
fdi: Option<u64>,
domain: u32,
s_type: i32,
protocol: i32,
) {
use ppm_consts::*;
if fdi.is_none() {
error!("cannot add socket, invalid fd");
return;
}
let is_v4 = domain == PPM_AF_INET;
let mut fdinfo = ZoneKernelFdInfo {
fd: fdi,
..Default::default()
};
match domain {
PPM_AF_UNIX => {
fdinfo.fd_type = fd_types::SCAP_FD_UNIX_SOCK as i32;
}
PPM_AF_INET | PPM_AF_INET6 => {
fdinfo.fd_type = if is_v4 {
fd_types::SCAP_FD_IPV4_SOCK as i32
} else {
fd_types::SCAP_FD_IPV6_SOCK as i32
};
let ip_proto = match protocol {
IPPROTO_TCP => {
if s_type == SOCK_RAW {
l4_types::SCAP_L4_RAW
} else {
l4_types::SCAP_L4_TCP
}
}
IPPROTO_UDP => {
if s_type == SOCK_RAW {
l4_types::SCAP_L4_RAW
} else {
l4_types::SCAP_L4_UDP
}
}
IPPROTO_IP => {
if (s_type & 0xff) == SOCK_STREAM {
l4_types::SCAP_L4_TCP
} else if (s_type & 0xff) == SOCK_DGRAM {
l4_types::SCAP_L4_UDP
} else {
warn!("unexpected socket protocol type");
l4_types::SCAP_L4_UNKNOWN
}
}
IPPROTO_ICMP => {
if s_type == SOCK_RAW {
l4_types::SCAP_L4_RAW
} else {
l4_types::SCAP_L4_ICMP
}
}
IPPROTO_RAW => l4_types::SCAP_L4_RAW,
_ => l4_types::SCAP_L4_UNKNOWN,
};
if is_v4 {
let sock_info = ZoneKernelIpv4SocketInfo {
protocol: ip_proto as i32,
..Default::default()
};
fdinfo.info = Some(ZoneKernelFdInfoData {
info_type: Some(InfoType::Ipv4Socket(sock_info)),
})
} else {
let sock_info = ZoneKernelIpv6SocketInfo {
protocol: ip_proto as i32,
..Default::default()
};
fdinfo.info = Some(ZoneKernelFdInfoData {
info_type: Some(InfoType::Ipv6Socket(sock_info)),
})
}
}
PPM_AF_NETLINK => {
fdinfo.fd_type = fd_types::SCAP_FD_NETLINK as i32;
}
_ => {
fdinfo.fd_type = fd_types::SCAP_FD_UNKNOWN as i32;
debug!(
"unknown FD type domain: {:?} protocol: {:?}",
domain, protocol
)
}
}
self.with_mut_leader_fdlist_ctx(event, |fdlist| {
fdlist.insert(fdi.expect("previously checked"), fdinfo)
});
}
/// Parses the exit events of OPEN-type syscalls, collecting new FD info, and updating the FD table for a given
/// thread in the thread table when a new file descriptor is obtained by that thread.
fn parse_create_open_exit(
&mut self,
event: &ZoneKernelSyscallEvent,
etype: event_codes,
) -> Result<()> {
use event_codes::*;
let Some(tinfo) = self.seen_threadsnaps.get(&event.thread_id) else {
return Ok(());
};
let enter_evt = if etype != PPME_SYSCALL_OPEN_BY_HANDLE_AT_X {
self.get_lastevent(&event.thread_id)
} else {
None
};
let fd = parsers::get_retval(event);
let mut exit_name: String;
let mut exit_flags: u32;
let mut exit_dirfd: i64;
let mut exit_sdir: Option<PathBuf>;
let mut exit_dev: Option<u32> = None;
let mut exit_ino: Option<u64> = None;
match etype {
PPME_SYSCALL_OPEN_X => {
exit_name = event.event_params[1].param_pretty.clone();
exit_flags =
u32::from_ne_bytes(event.event_params[2].param_data.as_slice().try_into()?);
if event.event_params.len() > 4 {
exit_dev = Some(u32::from_ne_bytes(
event.event_params[4].param_data.as_slice().try_into()?,
));
if event.event_params.len() > 4 {
exit_ino = Some(u64::from_ne_bytes(
event.event_params[4].param_data.as_slice().try_into()?,
));
}
}
if let Some(enter) = enter_evt
&& enter.event_params.len() >= 2
{
let enter_name = enter.event_params[0].param_pretty.clone();
let enter_flags =
u32::from_ne_bytes(enter.event_params[1].param_data.as_slice().try_into()?);
// override with enter event name if set
if !enter.event_name.is_empty() && enter.event_name != "<NA>" {
exit_name = enter_name;
// keep flags added by the syscall exit probe if present
let mask = !(ppm_consts::PPM_O_F_CREATED - 1);
let added_flags = exit_flags & mask;
exit_flags = enter_flags | added_flags;
}
}
exit_sdir = Some(PathBuf::from(&tinfo.cwd));
}
PPME_SYSCALL_CREAT_X => {
exit_name = event.event_params[1].param_pretty.clone();
exit_flags = 0;
if event.event_params.len() > 3 {
exit_dev = Some(u32::from_ne_bytes(
event.event_params[3].param_data.as_slice().try_into()?,
));
if event.event_params.len() > 4 {
exit_ino = Some(u64::from_ne_bytes(
event.event_params[4].param_data.as_slice().try_into()?,
));
if event.event_params.len() > 5 {
let creat_flags = u32::from_ne_bytes(
event.event_params[5].param_data.as_slice().try_into()?,
);
if (creat_flags & ppm_consts::PPM_FD_UPPER_LAYER_CREAT) != 0 {
exit_flags |= ppm_consts::PPM_FD_UPPER_LAYER;
} else if (creat_flags & ppm_consts::PPM_FD_LOWER_LAYER_CREAT) != 0 {
exit_flags |= ppm_consts::PPM_FD_LOWER_LAYER;
}
}
}
}
if let Some(enter) = enter_evt
&& !enter.event_params.is_empty()
{
let enter_name = enter.event_params[0].param_pretty.clone();
let enter_flags = 0;
// override with enter event name if set
if !enter.event_name.is_empty() && enter.event_name != "<NA>" {
exit_name = enter_name;
exit_flags |= enter_flags
}
}
exit_sdir = Some(PathBuf::from(&tinfo.cwd));
}
PPME_SYSCALL_OPENAT_X => {
exit_flags = 0;
exit_sdir = None;
exit_name = "<NA>".into();
if let Some(enter) = enter_evt {
exit_name = enter.event_params[1].param_pretty.clone();
exit_flags =
u32::from_ne_bytes(enter.event_params[2].param_data.as_slice().try_into()?);
exit_dirfd =
i64::from_ne_bytes(enter.event_params[0].param_data.as_slice().try_into()?);
exit_sdir = self.parse_dirfd(event, &exit_name, exit_dirfd);
}
}
PPME_SYSCALL_OPENAT_2_X | PPME_SYSCALL_OPENAT2_X => {
exit_name = event.event_params[2].param_pretty.clone();
exit_flags =
u32::from_ne_bytes(event.event_params[3].param_data.as_slice().try_into()?);
exit_dirfd =
i64::from_ne_bytes(event.event_params[1].param_data.as_slice().try_into()?);
if etype == PPME_SYSCALL_OPENAT_2_X && event.event_params.len() > 5 {
exit_dev = Some(u32::from_ne_bytes(
event.event_params[5].param_data.as_slice().try_into()?,
));
exit_ino = if event.event_params.len() > 6 {
Some(u64::from_ne_bytes(
event.event_params[6].param_data.as_slice().try_into()?,
))
} else {
None
};
} else if etype == PPME_SYSCALL_OPENAT2_X && event.event_params.len() > 6 {
exit_dev = Some(u32::from_ne_bytes(
event.event_params[6].param_data.as_slice().try_into()?,
));
exit_ino = if event.event_params.len() > 7 {
Some(u64::from_ne_bytes(
event.event_params[7].param_data.as_slice().try_into()?,
))
} else {
None
};
}
if let Some(enter) = enter_evt
&& event.event_params.len() >= 3
{
let enter_name = enter.event_params[1].param_pretty.clone();
let enter_flags =
u32::from_ne_bytes(enter.event_params[2].param_data.as_slice().try_into()?);
let enter_dirfd =
i64::from_ne_bytes(enter.event_params[0].param_data.as_slice().try_into()?);
// override with enter event name if set
if !enter.event_name.is_empty() && enter.event_name != "<NA>" {
exit_name = enter_name;
// keep flags added by the syscall exit probe if present
let mask = !(ppm_consts::PPM_O_F_CREATED - 1);
let added_flags = exit_flags & mask;
exit_flags = enter_flags | added_flags;
exit_dirfd = enter_dirfd;
}
}
exit_sdir = self.parse_dirfd(event, &exit_name, exit_dirfd);
}
PPME_SYSCALL_OPEN_BY_HANDLE_AT_X => {
exit_flags =
u32::from_ne_bytes(event.event_params[2].param_data.as_slice().try_into()?);
exit_name = event.event_params[3].param_pretty.clone();
// The driver implementation always serves an absolute path for open_by_handle_at using
// dpath traversal; hence there is no need to interpret the path relative to mountfd.
exit_sdir = None;
if event.event_params.len() > 4 {
exit_dev = Some(u32::from_ne_bytes(
event.event_params[4].param_data.as_slice().try_into()?,
));
exit_ino = if event.event_params.len() > 5 {
Some(u64::from_ne_bytes(
event.event_params[5].param_data.as_slice().try_into()?,
))
} else {
None
};
}
// The driver implementation always serves an absolute path for open_by_handle_at using
// dpath traversal; hence there is no need to interpret the path relative to mountfd.
}
_ => {
debug!("skipped open exit event: {:?}", event);
return Ok(());
}
}
let fullpath = if let Some(path) = exit_sdir {
// join will handle cases where `exit_name` is already an abs path.
path.join(exit_name)
} else {
PathBuf::from(exit_name)
};
if let Some(fd_) = fd
&& fd_ >= 0
{
let valid_fd = fd_ as u64; // we just checked
let fdinfo = ZoneKernelFdInfo {
fd: Some(valid_fd),
inode: exit_ino.unwrap_or(0),
fd_type: if exit_flags & ppm_consts::PPM_O_DIRECTORY != 0 {
fd_types::SCAP_FD_DIRECTORY as i32
} else {
fd_types::SCAP_FD_FILE_V2 as i32
},
info: Some(ZoneKernelFdInfoData {
info_type: Some(InfoType::RegularFile(ZoneKernelRegularFileInfo {
open_flags: exit_flags,
mount_id: 0,
device: exit_dev.unwrap_or(0),
name: fullpath.to_string_lossy().to_string(),
})),
}),
open_flags: exit_flags,
state_flags: {
let mut flags = 0;
if exit_flags & ppm_consts::PPM_FD_UPPER_LAYER != 0 {
flags |= FLAGS_OVERLAY_UPPER;
}
if exit_flags & ppm_consts::PPM_FD_LOWER_LAYER != 0 {
flags |= FLAGS_OVERLAY_LOWER;
}
flags
},
};
self.with_mut_leader_fdlist_ctx(event, |fdlist| fdlist.insert(valid_fd, fdinfo));
}
Ok(())
}
/// These syscalls act on FDs we should have already seen,
/// so this is largely a no-op for us.
/// TODO(bml) test, but I think we can skip this.
fn parse_fchmod_fchown_exit(
&mut self,
event: &ZoneKernelSyscallEvent,
_etype: event_codes,
) -> Result<()> {
let tinfo = self.seen_threadsnaps.get(&event.thread_id);
// if no thread info, bail
if tinfo.is_none() {
debug!("no thread found for fchmod/fchown");
return Ok(());
}
let param_idx = 1;
if event.event_params[param_idx].param_type != param_type::PT_FD as u32 {
warn!("unexpected param type for fchmod/fchown exit, cannot infer FD");
}
Ok(())
}
/// TODO(bml) mostly unused I think
fn parse_fspath_related_exit(
&mut self,
event: &ZoneKernelSyscallEvent,
_etype: event_codes,
) -> Result<()> {
if let Some(_enter_event) = self.get_lastevent(&event.thread_id) {
// TODO(bml) all this does is fetch the enter event's name for a corresponding exit event and
// save it off. We don't need that.
}
Ok(())
}
fn parse_unshare_setns_exit(
&mut self,
event: &ZoneKernelSyscallEvent,
etype: event_codes,
) -> Result<()> {
use event_codes::*;
let tinfo = self.seen_threadsnaps.get(&event.thread_id);
// if no thread info, bail
if tinfo.is_none() {
debug!("no thread found for unshare/setns: {:?}", event);
return Ok(());
}
if parsers::get_retval(event).is_some_and(|val| val < 0) {
warn!("no retval found for unshare/setns: {:?}", event);
return Ok(());
}
let flags = match etype {
PPME_SYSCALL_UNSHARE_X => {
u32::from_ne_bytes(event.event_params[1].param_data.as_slice().try_into()?)
}
PPME_SYSCALL_SETNS_X => {
u32::from_ne_bytes(event.event_params[2].param_data.as_slice().try_into()?)
}
_ => 0,
};
if flags & PPM_CL_CLONE_NEWUSER == 0 {
return Ok(());
}
// on unshare, threads start with "all caps"
self.with_mut_threadinfo_ctx(event, |mut_tinfo| {
let max_caps = parsers::get_all_caps_bitmask();
mut_tinfo.cap_permitted = max_caps;
mut_tinfo.cap_effective = max_caps;