-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathscap_bpf.c
2042 lines (1730 loc) · 55.7 KB
/
scap_bpf.c
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
/*
Copyright (C) 2021 The Falco Authors.
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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
#include <gelf.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <dirent.h>
#include "strl.h"
#define SCAP_HANDLE_T struct bpf_engine
#include "bpf.h"
#include "engine_handle.h"
#include "scap.h"
#include "scap-int.h"
#include "scap_bpf.h"
#include "scap_engine_util.h"
#include "driver_config.h"
#include "../../driver/bpf/types.h"
#include "../../driver/bpf/maps.h"
#include "compat/misc.h"
#include "compat/bpf.h"
#include "strl.h"
#include "noop.h"
#include "strerror.h"
static const char * const bpf_kernel_counters_stats_names[] = {
[BPF_N_EVTS] = "n_evts",
[BPF_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total",
[BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter",
[BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit",
[BPF_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter",
[BPF_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit",
[BPF_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter",
[BPF_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit",
[BPF_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter",
[BPF_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit",
[BPF_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter",
[BPF_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit",
[BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter",
[BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit",
[BPF_N_DROPS_SCRATCH_MAP] = "n_drops_scratch_map",
[BPF_N_DROPS_PAGE_FAULTS] = "n_drops_page_faults",
[BPF_N_DROPS_BUG] = "n_drops_bug",
[BPF_N_DROPS] = "n_drops",
};
static const char * const bpf_libbpf_stats_names[] = {
[RUN_CNT] = ".run_cnt", ///< `bpf_prog_info` run_cnt.
[RUN_TIME_NS] = ".run_time_ns", ///<`bpf_prog_info` run_time_ns.
[AVG_TIME_NS] = ".avg_time_ns", ///< Average time spent in bpg program, calculation: run_time_ns / run_cnt.
};
static inline scap_evt* scap_bpf_next_event(scap_device* dev)
{
return scap_bpf_evt_from_perf_sample(dev->m_sn_next_event);
}
static inline void scap_bpf_advance_to_next_evt(scap_device* dev, scap_evt *event)
{
scap_bpf_advance_to_evt(dev, true,
dev->m_sn_next_event,
&dev->m_sn_next_event,
&dev->m_sn_len);
}
#define GET_BUF_POINTERS scap_bpf_get_buf_pointers
#define ADVANCE_TAIL scap_bpf_advance_tail
#define ADVANCE_TO_EVT scap_bpf_advance_to_next_evt
#define READBUF scap_bpf_readbuf
#define NEXT_EVENT scap_bpf_next_event
#include "ringbuffer/ringbuffer.h"
//
// Some of this code is taken from the kernel samples under samples/bpf,
// namely the parsing of the ELF objects, which is very tedious and not
// worth reinventing from scratch. The code has been readapted and simplified
// to tailor our use case. In the future, a full switch to libbpf
// is possible, but at the moment is not very worth the effort considering the
// subset of features needed.
//
struct bpf_map_data {
int fd;
size_t elf_offset;
struct bpf_map_def def;
};
static struct bpf_engine* alloc_handle(scap_t* main_handle, char* lasterr_ptr)
{
struct bpf_engine *engine = calloc(1, sizeof(struct bpf_engine));
if(engine)
{
engine->m_lasterr = lasterr_ptr;
for(int j=0; j < BPF_PROGS_TAIL_CALLED_MAX; j++)
{
engine->m_tail_called_fds[j] = -1;
}
for(int j=0; j < BPF_PROG_ATTACHED_MAX; j++)
{
engine->m_attached_progs[j].fd = -1;
}
}
return engine;
}
static void free_handle(struct scap_engine_handle engine)
{
free(engine.m_handle);
}
#ifndef UINT32_MAX
# define UINT32_MAX (4294967295U)
#endif
/* Recommended log buffer size.
* Taken from libbpf source code: https://github.com/libbpf/libbpf/blob/67a4b1464349345e483df26ed93f8d388a60cee1/src/bpf.h#L201
*/
static const int BPF_LOG_SIZE = UINT32_MAX >> 8; /* verifier maximum in kernels <= 5.1 */
static char* license;
#define FILLER_NAME_FN(x) #x,
static const char *g_filler_names[PPM_FILLER_MAX] = {
FILLER_LIST_MAPPER(FILLER_NAME_FN)
};
#undef FILLER_NAME_FN
static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr, unsigned int size)
{
return syscall(__NR_bpf, cmd, attr, size);
}
static int sys_perf_event_open(struct perf_event_attr *attr,
pid_t pid, int cpu, int group_fd,
unsigned long flags)
{
return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags);
}
static inline __u64 ptr_to_u64(const void *ptr)
{
return (__u64) (unsigned long) ptr;
}
/* Here the filler_name is something like 'sys_open_x'.
* Starting from the entire section name 'raw_tracepoint/filler/sys_open_x'
* here we obtain just the final part 'sys_open_x'.
*/
static int32_t lookup_filler_id(const char *filler_name)
{
int j;
/* In our table we must have a filler_name corresponding to the final
* part of the elf section.
*/
for(j = 0; j < sizeof(g_filler_names) / sizeof(g_filler_names[0]); ++j)
{
if(strcmp(filler_name, g_filler_names[j]) == 0)
{
return j;
}
}
return -1;
}
static int bpf_map_update_elem(int fd, const void *key, const void *value, uint64_t flags)
{
union bpf_attr attr;
bzero(&attr, sizeof(attr));
attr.map_fd = fd;
attr.key = (unsigned long) key;
attr.value = (unsigned long) value;
attr.flags = flags;
return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
}
static int bpf_map_lookup_elem(int fd, const void *key, void *value)
{
union bpf_attr attr;
bzero(&attr, sizeof(attr));
attr.map_fd = fd;
attr.key = (unsigned long) key;
attr.value = (unsigned long) value;
return sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}
static int bpf_map_create(enum bpf_map_type map_type,
int key_size, int value_size, int max_entries,
uint32_t map_flags)
{
union bpf_attr attr;
bzero(&attr, sizeof(attr));
attr.map_type = map_type;
attr.key_size = key_size;
attr.value_size = value_size;
attr.max_entries = max_entries;
attr.map_flags = map_flags;
return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
}
static int bpf_map_freeze(int fd)
{
union bpf_attr attr;
bzero(&attr, sizeof(attr));
attr.map_fd = fd;
/* Do not check for errors as BPF_MAP_FREEZE was introduced in kernel 5.2 */
sys_bpf(BPF_MAP_FREEZE, &attr, sizeof(attr));
return SCAP_SUCCESS;
}
static int bpf_obj_get_info_by_fd(int fd, void *info, __u32 *info_len)
{
union bpf_attr attr;
int err;
bzero(&attr, sizeof(attr));
attr.info.bpf_fd = fd;
attr.info.info_len = *info_len;
attr.info.info = ptr_to_u64(info);
err = sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));
if (!err)
*info_len = attr.info.info_len;
return SCAP_SUCCESS;
}
static int bpf_load_program(const struct bpf_insn *insns,
enum bpf_prog_type type,
size_t insns_cnt,
char *log_buf,
size_t log_buf_sz,
const char *prog_name)
{
union bpf_attr attr;
int fd;
bzero(&attr, sizeof(attr));
attr.prog_type = type;
attr.insn_cnt = (uint32_t) insns_cnt;
attr.insns = (unsigned long) insns;
attr.license = (unsigned long) license;
attr.log_buf = (unsigned long) NULL;
attr.log_size = 0;
attr.log_level = 0;
if (prog_name != NULL) {
snprintf(attr.prog_name, BPF_OBJ_NAME_LEN, "%s", prog_name);
}
/* Try a first time without catching verifier logs.
* If `log_buf` paramater is NULL it means that we have no intention
* to collect verifier logs in any case, so only 1 attempt is enough,
* the second one would be useless without catching logs.
*/
fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
if(fd >= 0 || !log_buf || !log_buf_sz)
{
return fd;
}
/* Try a second time catching verifier logs. This step is performed
* only if we have a buffer for collecting them (so only if we
* pass to `bpf_load_program()` function a `log_buf`!= NULL).
*/
attr.log_buf = (unsigned long) log_buf;
attr.log_size = log_buf_sz;
attr.log_level = 1;
log_buf[0] = 0;
return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
}
static int32_t get_elf_section(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname, GElf_Shdr *shdr, Elf_Data **data)
{
Elf_Scn *scn = elf_getscn(elf, i);
if(!scn)
{
return SCAP_FAILURE;
}
if(gelf_getshdr(scn, shdr) != shdr)
{
return SCAP_FAILURE;
}
*shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
if(!*shname || !shdr->sh_size)
{
return SCAP_FAILURE;
}
*data = elf_getdata(scn, 0);
if(!*data || elf_getdata(scn, *data) != NULL)
{
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
static int cmp_symbols(const void *l, const void *r)
{
const GElf_Sym *lsym = (const GElf_Sym *)l;
const GElf_Sym *rsym = (const GElf_Sym *)r;
if(lsym->st_value < rsym->st_value)
{
return -1;
}
else if(lsym->st_value > rsym->st_value)
{
return 1;
}
else
{
return 0;
}
}
static int32_t load_elf_maps_section(struct bpf_engine *handle, struct bpf_map_data *maps,
int maps_shndx, Elf *elf, Elf_Data *symbols,
int strtabidx, int *nr_maps)
{
Elf_Data *data_maps = NULL;
GElf_Sym *sym;
Elf_Scn *scn;
int i;
scn = elf_getscn(elf, maps_shndx);
if(scn)
{
data_maps = elf_getdata(scn, NULL);
}
if(!scn || !data_maps)
{
return scap_errprintf(handle->m_lasterr, 0, "Failed to get Elf_Data from maps section %d", maps_shndx);
}
*nr_maps = 0;
sym = calloc(BPF_MAPS_MAX + 1, sizeof(GElf_Sym));
if(sym == NULL)
{
return scap_errprintf(handle->m_lasterr, 0, "calloc(BPF_MAPS_MAX + 1) failed");
}
for(i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++)
{
ASSERT(*nr_maps < BPF_MAPS_MAX + 1);
if(!gelf_getsym(symbols, i, &sym[*nr_maps]))
{
continue;
}
if(sym[*nr_maps].st_shndx != maps_shndx)
{
continue;
}
(*nr_maps)++;
}
qsort(sym, *nr_maps, sizeof(GElf_Sym), cmp_symbols);
ASSERT(data_maps->d_size / *nr_maps == sizeof(struct bpf_map_def));
for(i = 0; i < *nr_maps; i++)
{
struct bpf_map_def *def;
size_t offset;
offset = sym[i].st_value;
def = (struct bpf_map_def *)(data_maps->d_buf + offset);
maps[i].elf_offset = offset;
memcpy(&maps[i].def, def, sizeof(struct bpf_map_def));
}
free(sym);
return SCAP_SUCCESS;
}
static int32_t load_maps(struct bpf_engine *handle, struct bpf_map_data *maps, int nr_maps)
{
int j;
for(j = 0; j < nr_maps; ++j)
{
if(j == SCAP_PERF_MAP ||
j == SCAP_LOCAL_STATE_MAP ||
j == SCAP_FRAME_SCRATCH_MAP ||
j == SCAP_TMP_SCRATCH_MAP)
{
maps[j].def.max_entries = handle->m_ncpus;
}
handle->m_bpf_map_fds[j] = bpf_map_create(maps[j].def.type,
maps[j].def.key_size,
maps[j].def.value_size,
maps[j].def.max_entries,
maps[j].def.map_flags);
maps[j].fd = handle->m_bpf_map_fds[j];
if(handle->m_bpf_map_fds[j] < 0)
{
return scap_errprintf(handle->m_lasterr, -handle->m_bpf_map_fds[j], "can't create map %d", j);
}
if(maps[j].def.type == BPF_MAP_TYPE_PROG_ARRAY)
{
handle->m_bpf_prog_array_map_idx = j;
}
}
return SCAP_SUCCESS;
}
static int32_t parse_relocations(struct bpf_engine *handle, Elf_Data *data, Elf_Data *symbols,
GElf_Shdr *shdr, struct bpf_insn *insn,
struct bpf_map_data *maps, int nr_maps)
{
int nrels;
int i;
nrels = shdr->sh_size / shdr->sh_entsize;
for(i = 0; i < nrels; i++)
{
GElf_Sym sym;
GElf_Rel rel;
unsigned int insn_idx;
bool match = false;
int map_idx;
gelf_getrel(data, i, &rel);
insn_idx = rel.r_offset / sizeof(struct bpf_insn);
gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
if(insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW))
{
return scap_errprintf(handle->m_lasterr, 0, "invalid relocation for insn[%d].code 0x%x", insn_idx, insn[insn_idx].code);
}
insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
for(map_idx = 0; map_idx < nr_maps; map_idx++)
{
if(maps[map_idx].elf_offset == sym.st_value)
{
match = true;
break;
}
}
if(match)
{
insn[insn_idx].imm = maps[map_idx].fd;
}
else
{
return scap_errprintf(handle->m_lasterr, 0, "invalid relocation for insn[%d] no map_data match\n", insn_idx);
}
}
return SCAP_SUCCESS;
}
/* load all bpf programs */
static int32_t load_single_prog(struct bpf_engine* handle, const char *event, struct bpf_insn *prog, int size)
{
enum bpf_prog_type program_type;
size_t insns_cnt;
bool raw_tp;
int err;
int fd;
const char *final_section_name = NULL;
insns_cnt = size / sizeof(struct bpf_insn);
char *error = malloc(BPF_LOG_SIZE);
if(!error)
{
return scap_errprintf(handle->m_lasterr, 0, "malloc(BPF_LOG_BUF_SIZE) failed");
}
const char *full_event = event;
if(memcmp(event, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0)
{
raw_tp = true;
program_type = BPF_PROG_TYPE_RAW_TRACEPOINT;
event += sizeof("raw_tracepoint/") - 1;
}
else
{
raw_tp = false;
program_type = BPF_PROG_TYPE_TRACEPOINT;
event += sizeof("tracepoint/") - 1;
}
if(*event == 0)
{
free(error);
return scap_errprintf(handle->m_lasterr, 0, "event name cannot be empty");
}
/* 'event' looks like "raw_tracepoint/raw_syscalls/sys_enter". Skip
* to the last word after '/', if possible.
*/
final_section_name = strrchr(event, '/');
if (final_section_name != NULL) {
final_section_name++;
} else {
final_section_name = event;
}
fd = bpf_load_program(prog, program_type, insns_cnt, error, BPF_LOG_SIZE, final_section_name);
if(fd < 0)
{
/* It is possible than some old kernels don't support the prog_name so in case
* of loading failure, we try again the loading without the name. See it in libbpf:
* https://github.com/torvalds/linux/blob/16a8829130ca22666ac6236178a6233208d425c3/tools/lib/bpf/libbpf.c#L4833
*/
fd = bpf_load_program(prog, program_type, insns_cnt, error, BPF_LOG_SIZE, NULL);
if(fd < 0)
{
fprintf(stderr, "-- BEGIN PROG LOAD LOG --\n%s\n-- END PROG LOAD LOG --\n", error);
free(error);
return scap_errprintf(handle->m_lasterr, -fd, "libscap: bpf_load_program() event=%s", full_event);
}
}
free(error);
/* If the program is tail called, so not directly attached to the kernel ("filler")
* we save the fd and populate the filler table. Note that we store the `fd` to free
* the prog at the end of the capture, we will never use it again during the capture!
*/
if(memcmp(event, "filler/", sizeof("filler/") - 1) == 0)
{
if(handle->m_tail_called_cnt + 1 >= BPF_PROGS_TAIL_CALLED_MAX)
{
return scap_errprintf(handle->m_lasterr, 0, "libscap: too many tail_called programs recorded: %d (limit is %d)", handle->m_tail_called_cnt + 1 ,BPF_PROGS_TAIL_CALLED_MAX);
}
handle->m_tail_called_fds[handle->m_tail_called_cnt++] = fd;
event += sizeof("filler/") - 1;
if(*event == 0)
{
return scap_errprintf(handle->m_lasterr, 0, "filler name cannot be empty");
}
int prog_id = lookup_filler_id(event);
if(prog_id == -1)
{
return scap_errprintf(handle->m_lasterr, 0, "invalid filler name: %s", event);
}
else if (prog_id >= BPF_PROGS_TAIL_CALLED_MAX)
{
return scap_errprintf(handle->m_lasterr, 0, "program ID exceeds BPF_PROGS_TAIL_CALLED_MAX limit (%d/%d)", prog_id, BPF_PROGS_TAIL_CALLED_MAX);
}
/* Fill the tail table. The key is our filler internal code extracted
* from `g_filler_names` in `lookup_filler_id` function. The value
* is the program fd.
*/
err = bpf_map_update_elem(handle->m_bpf_map_fds[handle->m_bpf_prog_array_map_idx], &prog_id, &fd, BPF_ANY);
if(err < 0)
{
return scap_errprintf(handle->m_lasterr, -err, "failure populating program array");
}
return SCAP_SUCCESS;
}
/* If we reach this point we are evaluating a program that should be directly attached to the kernel */
if(is_sys_enter(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SYS_ENTER], raw_tp, event, fd);
}
if(is_sys_exit(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SYS_EXIT], raw_tp, event, fd);
}
if(is_sched_proc_exit(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT], raw_tp, event, fd);
}
if(is_sched_switch(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_SWITCH], raw_tp, event, fd);
}
if(is_page_fault_user(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER], raw_tp, event, fd);
}
if(is_page_fault_kernel(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL], raw_tp, event, fd);
}
if(is_signal_deliver(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER], raw_tp, event, fd);
}
if(is_sched_prog_fork_move_args(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS], raw_tp, event, fd);
}
if(is_sched_prog_fork_missing_child(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD], raw_tp, event, fd);
}
if(is_sched_prog_exec_missing_exit(event))
{
fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT], raw_tp, event, fd);
}
return SCAP_SUCCESS;
}
static int32_t load_bpf_file(struct bpf_engine *handle)
{
int j;
int maps_shndx = 0;
int strtabidx = 0;
GElf_Shdr shdr;
GElf_Shdr shdr_prog;
Elf_Data *data;
Elf_Data *data_prog;
Elf_Data *symbols = NULL;
char *shname;
char *shname_prog;
int nr_maps = 0;
struct bpf_map_data maps[BPF_MAPS_MAX];
struct utsname osname;
int32_t res = SCAP_FAILURE;
bool got_api_version = false;
bool got_schema_version = false;
if(uname(&osname))
{
return scap_errprintf(handle->m_lasterr, errno, "can't call uname()");
}
if(elf_version(EV_CURRENT) == EV_NONE)
{
return scap_errprintf(handle->m_lasterr, 0, "invalid ELF version");
}
if (!handle->elf)
{
handle->program_fd = open(handle->m_filepath, O_RDONLY, 0);
if(handle->program_fd < 0)
{
return scap_errprintf(handle->m_lasterr, 0, "can't open BPF probe '%s'", handle->m_filepath);
}
handle->elf = elf_begin(handle->program_fd, ELF_C_READ_MMAP_PRIVATE, NULL);
if(!handle->elf)
{
scap_errprintf(handle->m_lasterr, 0, "can't read ELF format");
goto end;
}
if(gelf_getehdr(handle->elf, &handle->ehdr) != &handle->ehdr)
{
scap_errprintf(handle->m_lasterr, 0, "can't read ELF header");
goto end;
}
for(j = 0; j < handle->ehdr.e_shnum; ++j)
{
if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS)
{
continue;
}
if(strcmp(shname, "maps") == 0)
{
maps_shndx = j;
}
else if(shdr.sh_type == SHT_SYMTAB)
{
strtabidx = shdr.sh_link;
symbols = data;
}
else if(strcmp(shname, "kernel_version") == 0)
{
if(strcmp(osname.release, data->d_buf))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "BPF probe is compiled for %s, but running version is %s",
(char *)data->d_buf, osname.release);
goto end;
}
}
else if(strcmp(shname, "api_version") == 0)
{
got_api_version = true;
memcpy(&handle->m_api_version, data->d_buf, sizeof(handle->m_api_version));
}
else if(strcmp(shname, "schema_version") == 0)
{
got_schema_version = true;
memcpy(&handle->m_schema_version, data->d_buf, sizeof(handle->m_schema_version));
}
else if(strcmp(shname, "license") == 0)
{
license = data->d_buf;
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "BPF probe license is %s", license);
}
}
if(!got_api_version)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing api_version section");
goto end;
}
if(!got_schema_version)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing schema_version section");
goto end;
}
if(!symbols)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing SHT_SYMTAB section");
goto end;
}
if(maps_shndx)
{
if(load_elf_maps_section(handle, maps, maps_shndx, handle->elf, symbols, strtabidx, &nr_maps) != SCAP_SUCCESS)
{
goto end;
}
if(load_maps(handle, maps, nr_maps) != SCAP_SUCCESS)
{
goto end;
}
}
for(j = 0; j < handle->ehdr.e_shnum; ++j)
{
if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS)
{
continue;
}
if(shdr.sh_type == SHT_REL)
{
struct bpf_insn *insns;
if(get_elf_section(handle->elf, shdr.sh_info, &handle->ehdr, &shname_prog, &shdr_prog, &data_prog) != SCAP_SUCCESS)
{
continue;
}
insns = (struct bpf_insn *)data_prog->d_buf;
if(parse_relocations(handle, data, symbols, &shdr, insns, maps, nr_maps))
{
continue;
}
}
}
}
res = SCAP_SUCCESS;
end:
return res;
}
static int load_all_progs(struct bpf_engine *handle)
{
GElf_Shdr shdr;
Elf_Data *data;
char *shname;
for(int j = 0; j < handle->ehdr.e_shnum; ++j)
{
if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS)
{
continue;
}
if(memcmp(shname, "tracepoint/", sizeof("tracepoint/") - 1) == 0 ||
memcmp(shname, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0)
{
if(load_single_prog(handle, shname, data->d_buf, data->d_size) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
}
}
return SCAP_SUCCESS;
}
static int allocate_scap_stats_v2(struct bpf_engine *handle)
{
int nprogs_attached = 0;
for(int j=0; j < BPF_PROG_ATTACHED_MAX; j++)
{
if (handle->m_attached_progs[j].fd != -1)
{
nprogs_attached++;
}
}
handle->m_nstats = (BPF_MAX_KERNEL_COUNTERS_STATS + (nprogs_attached * BPF_MAX_LIBBPF_STATS));
handle->m_stats = (scap_stats_v2 *)malloc(handle->m_nstats * sizeof(scap_stats_v2));
if(!handle->m_stats)
{
handle->m_nstats = 0;
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
static void *perf_event_mmap(struct bpf_engine *handle, int fd, unsigned long *size, unsigned long buf_bytes_dim)
{
int page_size = getpagesize();
unsigned long ring_size = buf_bytes_dim;
int header_size = page_size;
unsigned long total_size = ring_size * 2 + header_size;
*size = 0;
//
// All this playing with MAP_FIXED might be very very wrong, revisit
//
void *tmp = mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if(tmp == MAP_FAILED)
{
scap_errprintf(handle->m_lasterr, errno, "mmap (1) failed (If you get memory allocation errors try to reduce the buffer dimension)");
return MAP_FAILED;
}
// Map the second copy to allow us to handle the wrap case normally
void *p1 = mmap(tmp + ring_size, ring_size + header_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
if(p1 == MAP_FAILED)
{
scap_errprintf(handle->m_lasterr, errno, "mmap (2) failed (If you get memory allocation errors try to reduce the buffer dimension)");
munmap(tmp, total_size);
return MAP_FAILED;
}
ASSERT(p1 == tmp + ring_size);
// Map the main copy
void *p2 = mmap(tmp, ring_size + header_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
if(p2 == MAP_FAILED)
{
scap_errprintf(handle->m_lasterr, errno, "mmap (3) failed (If you get memory allocation errors try to reduce the buffer dimension)");
munmap(tmp, total_size);
return MAP_FAILED;
}
ASSERT(p2 == tmp);
*size = total_size;
return tmp;
}
static int32_t populate_syscall_table_map(struct bpf_engine *handle)
{
int j;
int ret;
for(j = 0; j < SYSCALL_TABLE_SIZE; ++j)
{
const struct syscall_evt_pair *p = &g_syscall_table[j];
if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SYSCALL_TABLE], &j, p, BPF_ANY)) != 0)
{
return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SYSCALL_TABLE bpf_map_update_elem");
}
}
return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_SYSCALL_TABLE]);
}
static int32_t set_single_syscall_of_interest(struct bpf_engine *handle, int syscall_id, bool interesting)
{
int ret = 0;
if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_INTERESTING_SYSCALLS_TABLE], &syscall_id, &interesting, BPF_ANY)) != 0)
{
return scap_errprintf(handle->m_lasterr, -ret, "SCAP_INTERESTING_SYSCALLS_TABLE unable to update syscall: %d", syscall_id);
}
return SCAP_SUCCESS;
}
static int32_t populate_event_table_map(struct bpf_engine *handle)
{
int j;
int ret;
for(j = 0; j < PPM_EVENT_MAX; ++j)
{
const struct ppm_event_info *e = &g_event_info[j];
if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_EVENT_INFO_TABLE], &j, e, BPF_ANY)) != 0)
{
return scap_errprintf(handle->m_lasterr, -ret, "SCAP_EVENT_INFO_TABLE bpf_map_update_elem");
}
}
return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_EVENT_INFO_TABLE]);
}
static int32_t populate_fillers_table_map(struct bpf_engine *handle)
{
int j;
int ret;
for(j = 0; j < PPM_EVENT_MAX; ++j)
{
const struct ppm_event_entry *e = &g_ppm_events[j];
if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_FILLERS_TABLE], &j, e, BPF_ANY)) != 0)
{
return scap_errprintf(handle->m_lasterr, -ret, "SCAP_FILLERS_TABLE bpf_map_update_elem ");
}
}
/* Even if the filler ppm code is defined it could happen that there
* is no filler implementation, some fillers are architecture-specifc.
* For example `sched_prog_exec` filler exists only on `ARM64` while
* `sys_pagefault_e` exists only on `x86`.
*/
return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_FILLERS_TABLE]);
}
static int enforce_sc_set(struct bpf_engine* handle)
{
/* handle->capturing == false means that we want to disable the capture */
bool* sc_set = handle->curr_sc_set.ppm_sc;
bool empty_sc_set[PPM_SC_MAX] = {0};
if(!handle->capturing)
{
/* empty set to erase all */
sc_set = empty_sc_set;
}
int ret = 0;
int syscall_id = 0;
/* Special tracepoints, their attachment depends on interesting syscalls */
bool sys_enter = false;