-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathldbf.patch
More file actions
4999 lines (4988 loc) · 163 KB
/
Copy pathldbf.patch
File metadata and controls
4999 lines (4988 loc) · 163 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
diff --git a/.gitignore b/.gitignore
index 5e31de7b1..57a2a821c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,3 +25,6 @@ executor/syscalls.h
# vscode
.vscode
+
+# Log files
+*.log
\ No newline at end of file
diff --git a/README.md b/README.md
index a8c48e35f..f20eef93c 100644
--- a/README.md
+++ b/README.md
@@ -42,3 +42,41 @@ For other OS kernels check:
## Disclaimer
This is not an official Google product.
+
+- Specify the path to the LDBF
+
+```
+export LDBF_DIR=/your_LDBF_path
+```
+
+- Specify the path of the generated eBPF program seeds
+
+```
+export LDBF_SEED_DIR=/your_path_of_eBPF_seeds
+```
+
+- Whether to enable debug information about LBPF syscall
+
+```
+export LDBF_DEBUG_BPF_INSN=1
+```
+
+- Whether to reuse the generated BPF instruction program
+
+```
+export LDBF_REUSE_BPF_INSN=1
+```
+
+- Whether to save the kernel dmesg info from QEMU VM
+
+```
+export LDBF_KERNEL_LOG_DIR=/your_path_to_save_kernel_vm_logs
+```
+
+- Set the path of vmlinux to get btf id
+
+```
+export LDBF_VMLINUX_PATH=/your_path_to_vmlinux
+```
+
+- For details on enabling syscalls, please refer to `sample.config`.
\ No newline at end of file
diff --git a/pkg/csource/csource.go b/pkg/csource/csource.go
index d5da107b0..a7d4f5e28 100644
--- a/pkg/csource/csource.go
+++ b/pkg/csource/csource.go
@@ -701,3 +701,34 @@ func toCString(data []byte, readable bool) []byte {
prog.EncodeData(buf, data, readable)
return buf.Bytes()
}
+
+func ExtractBpfLoadInsnArg(p *prog.Prog, callIndex int) (string, error) {
+ csumSeq := 0
+ opts := Options{
+ Trace: false,
+ }
+ ctx := &context{
+ p: p,
+ opts: opts,
+ target: p.Target,
+ sysTarget: targets.Get(p.Target.OS, p.Target.Arch),
+ calls: make(map[string]uint64),
+ }
+
+ exec, err := p.SerializeForExec()
+ if err != nil {
+ return "", fmt.Errorf("failed to serialize program: %w", err)
+ }
+ decoded, err := ctx.target.DeserializeExec(exec, nil)
+ if err != nil {
+ return "", err
+ }
+
+ w := new(bytes.Buffer)
+ bpfSyscall := decoded.Calls[callIndex]
+ for _, copyin := range bpfSyscall.Copyin {
+ ctx.copyin(w, &csumSeq, copyin)
+ }
+
+ return w.String(), nil
+}
diff --git a/pkg/fuzzer/fuzzer.go b/pkg/fuzzer/fuzzer.go
index 17c5af47b..aa97b25fe 100644
--- a/pkg/fuzzer/fuzzer.go
+++ b/pkg/fuzzer/fuzzer.go
@@ -7,6 +7,7 @@ import (
"context"
"fmt"
"math/rand"
+ "os"
"runtime"
"sort"
"sync"
@@ -142,6 +143,19 @@ func (fuzzer *Fuzzer) processResult(req *queue.Request, res *queue.Result, flags
// We do it before unblocking the waiting threads because
// it may result it concurrent modification of req.Prog.
var triage map[int]*triageCall
+
+ var bpfProg *prog.BpfProg
+ if req.Prog.Ldbf != nil {
+ bpfProg = req.Prog.Ldbf.GetLdbfBpfProg()
+ }
+ if bpfProg != nil && os.Getenv("LDBF_REUSE_BPF_INSN") == "" {
+ if bpfProgExecuated, _ := req.Prog.Ldbf.CheckBpfProgExecuated(bpfProg); !bpfProgExecuated {
+ _, err := req.Prog.Ldbf.MarkBpfProgAsExecuated(bpfProg)
+ if err != nil {
+ fmt.Printf("Error marking BPF program as executed: %v\n", err)
+ }
+ }
+ }
if req.ExecOpts.ExecFlags&flatrpc.ExecFlagCollectSignal > 0 && res.Info != nil && !dontTriage {
for call, info := range res.Info.Calls {
fuzzer.triageProgCall(req.Prog, info, call, &triage)
@@ -284,6 +298,7 @@ func (fuzzer *Fuzzer) genFuzz() *queue.Request {
if req == nil {
req = genProgRequest(fuzzer, rnd)
}
+ fuzzer.Config.Collide = false
if fuzzer.Config.Collide && rnd.Intn(3) == 0 {
req = &queue.Request{
Prog: randomCollide(req.Prog, rnd),
diff --git a/pkg/fuzzer/job.go b/pkg/fuzzer/job.go
index 7f1e47bf6..61b1e1ed1 100644
--- a/pkg/fuzzer/job.go
+++ b/pkg/fuzzer/job.go
@@ -7,6 +7,7 @@ import (
"bytes"
"fmt"
"math/rand"
+ "os"
"strings"
"sync"
"sync/atomic"
@@ -14,6 +15,7 @@ import (
"github.com/google/syzkaller/pkg/corpus"
"github.com/google/syzkaller/pkg/cover"
+ "github.com/google/syzkaller/pkg/csource"
"github.com/google/syzkaller/pkg/flatrpc"
"github.com/google/syzkaller/pkg/fuzzer/queue"
"github.com/google/syzkaller/pkg/signal"
@@ -161,12 +163,40 @@ func (job *triageJob) run(fuzzer *Fuzzer) {
wg.Wait()
}
+func handleBpfLoadCallInsn(p *prog.Prog, call int, isBpfRaw bool) {
+ bpfProgArgC, err := csource.ExtractBpfLoadInsnArg(p, call)
+ if err != nil {
+ fmt.Printf("failed to extract bpf load insn arg: %v\n", err)
+ } else {
+ p.Ldbf.ExtBpfProgLoadCallInsn(call, p, bpfProgArgC, isBpfRaw)
+ }
+}
+
+func handleBpfLoadCall(p *prog.Prog, call int) {
+ if os.Getenv("LDBF_DEBUG_BPF_INSN") == "" {
+ return
+ }
+ var bpfProg *prog.BpfProg
+ if p.Ldbf != nil {
+ bpfProg = p.Ldbf.GetLdbfBpfProg()
+ }
+ if bpfProg == nil || bpfProg.BpfRawInsnExtracted {
+ return
+ }
+ if p.CallName(call) == "bpf$LDBF_PROG_LOAD" {
+ handleBpfLoadCallInsn(p, call, false)
+ } else if p.CallName(call) == "bpf$PROG_LOAD" {
+ handleBpfLoadCallInsn(p, call, true)
+ }
+}
+
func (job *triageJob) handleCall(call int, info *triageCall) {
if info.newStableSignal.Empty() {
return
}
p := job.p
+ handleBpfLoadCall(p, call)
if job.flags&ProgMinimized == 0 {
p, call = job.minimize(call, info)
if p == nil {
diff --git a/prog/generation.go b/prog/generation.go
index 09240e858..b9b98e73f 100644
--- a/prog/generation.go
+++ b/prog/generation.go
@@ -15,13 +15,14 @@ func (target *Target) Generate(rs rand.Source, ncalls int, ct *ChoiceTable) *Pro
}
r := newRand(target, rs)
s := newState(target, ct, nil)
- for len(p.Calls) < ncalls {
- calls := r.generateCall(s, p, len(p.Calls))
- for _, c := range calls {
- s.analyze(c)
- p.Calls = append(p.Calls, c)
- }
- }
+ p.initLDBP(r, s)
+ // for len(p.Calls) < ncalls {
+ // calls := r.generateCall(s, p, len(p.Calls))
+ // for _, c := range calls {
+ // s.analyze(c)
+ // p.Calls = append(p.Calls, c)
+ // }
+ // }
// For the last generated call we could get additional calls that create
// resources and overflow ncalls. Remove some of these calls.
// The resources in the last call will be replaced with the default values,
diff --git a/prog/ldbf.go b/prog/ldbf.go
new file mode 100644
index 000000000..f99ae7cd8
--- /dev/null
+++ b/prog/ldbf.go
@@ -0,0 +1,192 @@
+package prog
+
+import (
+ "fmt"
+ "os"
+ "sync"
+)
+
+type LLMDrivenBPFuzzer struct {
+ isEnabled bool
+ LDBFDir string
+ bpfProg *BpfProg
+}
+
+var LdbfRecordSyscalls = []string{
+ "bpf$LDBF_MAP_CREATE",
+ "bpf$LDBF_PROG_LOAD",
+ "bpf$LDBF_BPF_PROG_ATTACH",
+ "bpf$LDBF_BPF_PROG_TEST_RUN",
+ "bpf$LDBF_BPF_BTF_LOAD",
+ "bpf$LDBF_LINK_CREATE",
+}
+
+var LdbfRecordSyscallsSet = make(map[string]struct{})
+
+func initLdbfRecordSyscallsSet() {
+ for _, syscall := range LdbfRecordSyscalls {
+ LdbfRecordSyscallsSet[syscall] = struct{}{}
+ }
+}
+
+// IsMapTypeValid checks if a string is a valid map type using a pre-built hash set.
+func (Ldbf *LLMDrivenBPFuzzer) IsLdbfRecordSyscall(s string) bool {
+ _, ok := LdbfRecordSyscallsSet[s]
+ return ok
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) LogLdbfRecordSyscall() {
+ for _, syscall := range LdbfRecordSyscalls {
+ fmt.Printf("LogLdbfRecordSyscall: Recording syscall: %s\n", syscall)
+ }
+}
+
+// performInitialCleanup contains all initialization cleanup work that should only be performed once
+func performInitialCleanup() {
+ if loraCorpusDir, err := JoinLdbfLoraDir("corpus"); err == nil {
+ if err := os.RemoveAll(loraCorpusDir); err != nil {
+ // fmt.Printf("Warning: failed to remove directory %s: %v\n", loraCorpusDir, err)
+ }
+ } else {
+ // fmt.Printf("Warning: could not get corpus directory for cleanup: %v\n", err)
+ }
+
+ if loraExecuatedDir, err := GetExecuatedDir(); err == nil {
+ if err := os.RemoveAll(loraExecuatedDir); err != nil {
+ // fmt.Printf("Warning: failed to remove directory %s: %v\n", loraExecuatedDir, err)
+ }
+ } else {
+ // fmt.Printf("Warning: could not get execuated directory for cleanup: %v\n", err)
+ }
+}
+
+func initializeLdbf() {
+ performInitialCleanup()
+ initLdbfProgTypeMap()
+ initLdbfRecordSyscallsSet()
+ initBtfMap()
+}
+
+var ldbfInitOnce sync.Once
+
+func NewLLMDrivenBPFFuzzer(enable bool) *LLMDrivenBPFuzzer {
+ if !enable {
+ fmt.Println("LLMDrivenBPFuzzer is not enabled")
+ return nil
+ }
+
+ LDBFDir := os.Getenv("LDBF_DIR") + "/"
+ if LDBFDir == "/" {
+ panic("LDBF_DIR environment variable is not set")
+ }
+
+ Ldbf := &LLMDrivenBPFuzzer{
+ isEnabled: true,
+ LDBFDir: LDBFDir,
+ }
+
+ ldbfInitOnce.Do(initializeLdbf)
+
+ return Ldbf
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) LdbfIsEnabled() bool {
+ return Ldbf.isEnabled
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) GenLdbfPrologue(r *randGen, s *state, p *Prog) {
+ var bpfProg *BpfProg
+
+ if !Ldbf.isEnabled {
+ return
+ }
+
+ bpfProg = Ldbf.genSeedLdbfProg(r)
+ if bpfProg == nil {
+ // fmt.Println("Ldbf: Failed to generate seed BPF program")
+ return
+ }
+
+ btfCalls := Ldbf.genLdbfBtfLoadCall(r, s, bpfProg)
+ for _, c := range btfCalls {
+ s.analyze(c)
+ p.Calls = append(p.Calls, c)
+ }
+
+ mapcalls := Ldbf.genLdbfMapCreateCall(r, s, bpfProg)
+ for _, c := range mapcalls {
+ s.analyze(c)
+ p.Calls = append(p.Calls, c)
+ }
+
+ c0s := Ldbf.genLdbfProgLoadCall(r, s, bpfProg)
+ for _, c := range c0s {
+ s.analyze(c)
+ p.Calls = append(p.Calls, c)
+ }
+ Ldbf.bpfProg = bpfProg
+
+ var c1 *Call
+ for _, c := range c0s {
+ c1 = c
+ bpfProg.BpfProgContext.ProgFD = c1.Ret
+ break
+ }
+
+ // fmt.Println("create link_create call")
+ linkCalls := Ldbf.genLdbfAttachCalls(r, s, bpfProg)
+ for _, c := range linkCalls {
+ s.analyze(c)
+ p.Calls = append(p.Calls, c)
+ }
+ // fmt.Println("finish creating")
+
+ c2s := Ldbf.genLdbfProgTestRunCall(r, s, bpfProg)
+ for _, c := range c2s {
+ s.analyze(c)
+ p.Calls = append(p.Calls, c)
+ }
+
+ // fmt.Printf(("Ldbf: GenLdbfPrologue: req.Prog:%p, BpfProgFilePath: %s\n"), p, bpfProg.BpfProgFilePath)
+ // fmt.Printf(("Ldbf: GenLdbfPrologue: BpfRawInsnFilePath: %s\n"), BpfProg.BpfRawInsnFilePath)
+ // fmt.Printf(("Ldbf: GenLdbfPrologue: BpfRawInsnString: %s\n"), BpfProg.BpfRawInsnString)
+ // p.debugValidate()
+ // fmt.Printf("Ldbf: GenLdbfPrologue: generating program:\n%s\n", p.Serialize())
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) genSeedLdbfProg(r *randGen) *BpfProg {
+ var opt BrfGenProgOpt
+ var bpfProg *BpfProg
+ var ok bool
+
+ opt.useTestSrc = true
+ opt.genProgAttempt = 5
+
+ for i := 0; i < opt.genProgAttempt; i++ {
+ if bpfProg, ok = Ldbf.genLdbfProg(r, opt); !ok {
+ continue
+ }
+
+ bpfProg = TranslateBpfProg(bpfProg)
+ if bpfProg.BpfRawInsnFilePath != "" {
+ bpfProg = FillExtractBpfRawInsn(bpfProg)
+ if bpfProg.BpfRawInsnString != "" {
+ return bpfProg
+ }
+ } else {
+ // fmt.Printf("Failed to compile bpf program\n")
+ }
+ }
+ return nil
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) genLdbfProg(r *randGen, opt BrfGenProgOpt) (*BpfProg, bool) {
+ bpfProg := Ldbf.NewLdbfProg(r, opt)
+
+ if bpfProg == nil {
+ // fmt.Println("Ldbf: Failed to generate BPF program")
+ return nil, false
+ }
+
+ return bpfProg, true
+}
diff --git a/prog/ldbf_attach.go b/prog/ldbf_attach.go
new file mode 100644
index 000000000..0c1975bc0
--- /dev/null
+++ b/prog/ldbf_attach.go
@@ -0,0 +1,574 @@
+package prog
+
+const (
+ CGroupFd int = 0
+ MapFd int = 1
+ IfIndex int = 2
+ FallBack int = 3
+)
+
+const (
+ BPF_CGROUP_INET_INGRESS int = 0x0
+ BPF_CGROUP_INET_EGRESS int = 0x1
+ BPF_CGROUP_INET_SOCK_CREATE int = 0x2
+ BPF_CGROUP_SOCK_OPS int = 0x3
+ BPF_SK_SKB_STREAM_PARSER int = 0x4
+ BPF_SK_SKB_STREAM_VERDICT int = 0x5
+ BPF_CGROUP_DEVICE int = 0x6
+ BPF_SK_MSG_VERDICT int = 0x7
+ BPF_CGROUP_INET4_BIND int = 0x8
+ BPF_CGROUP_INET6_BIND int = 0x9
+ BPF_CGROUP_INET4_CONNECT int = 0xa
+ BPF_CGROUP_INET6_CONNECT int = 0xb
+ BPF_CGROUP_INET4_POST_BIND int = 0xc
+ BPF_CGROUP_INET6_POST_BIND int = 0xd
+ BPF_CGROUP_UDP4_SENDMSG int = 0xe
+ BPF_CGROUP_UDP6_SENDMSG int = 0xf
+ BPF_LIRC_MODE2 int = 0x10
+ BPF_FLOW_DISSECTOR int = 0x11
+ BPF_CGROUP_SYSCTL int = 0x12
+ BPF_CGROUP_UDP4_RECVMSG int = 0x13
+ BPF_CGROUP_UDP6_RECVMSG int = 0x14
+ BPF_CGROUP_GETSOCKOPT int = 0x15
+ BPF_CGROUP_SETSOCKOPT int = 0x16
+ BPF_TRACE_RAW_TP int = 0x17
+ BPF_TRACE_FENTRY int = 0x18
+ BPF_TRACE_FEXIT int = 0x19
+ BPF_MODIFY_RETURN int = 0x1a
+ BPF_LSM_MAC int = 0x1b
+ BPF_TRACE_ITER int = 0x1c
+ BPF_CGROUP_INET4_GETPEERNAME int = 0x1d
+ BPF_CGROUP_INET6_GETPEERNAME int = 0x1e
+ BPF_CGROUP_INET4_GETSOCKNAME int = 0x1f
+ BPF_CGROUP_INET6_GETSOCKNAME int = 0x20
+ BPF_XDP_DEVMAP int = 0x21
+ BPF_CGROUP_INET_SOCK_RELEASE int = 0x22
+ BPF_XDP_CPUMAP int = 0x23
+ BPF_SK_LOOKUP int = 0x24
+ BPF_XDP int = 0x25
+ BPF_SK_SKB_VERDICT int = 0x26
+ BPF_SK_REUSEPORT_SELECT int = 0x27
+ BPF_SK_REUSEPORT_SELECT_OR_MIGRATE int = 0x28
+ BPF_PERF_EVENT int = 0x29
+ BPF_TRACE_KPROBE_MULTI int = 0x2a
+ BPF_LSM_CGROUP int = 0x2b
+ BPF_STRUCT_OPS int = 0x2c
+ BPF_NETFILTER int = 0x2d
+ BPF_TCX_INGRESS int = 0x2e
+ BPF_TCX_EGRESS int = 0x2f
+ BPF_TRACE_UPROBE_MULTI int = 0x30
+ BPF_CGROUP_UNIX_CONNECT int = 0x31
+ BPF_CGROUP_UNIX_SENDMSG int = 0x32
+ BPF_CGROUP_UNIX_RECVMSG int = 0x33
+ BPF_CGROUP_UNIX_GETPEERNAME int = 0x34
+ BPF_CGROUP_UNIX_GETSOCKNAME int = 0x35
+ BPF_NETKIT_PRIMARY int = 0x36
+ BPF_NETKIT_PEER int = 0x37
+ BPF_TRACE_KPROBE_SESSION int = 0x38
+ BPF_TRACE_UPROBE_SESSION int = 0x39
+ __MAX_BPF_ATTACH_TYPE int = 0x3a
+)
+
+const (
+ BTF int = 0
+ Iter int = 1
+ Perf int = 2
+ Kprobe int = 3
+ Trace int = 4
+ Netfilter int = 5
+ Tcx int = 6
+ Uprobe int = 7
+ Netkit int = 8
+)
+
+var Sockets = []string{
+ "socket$inet_udp",
+ "socket$inet_udplite",
+ "socket$inet6_udp",
+ "socket$inet6_udplite",
+ "socket$inet_mptcp",
+ "socket$inet_tcp",
+ "socket$inet6_mptcp",
+ "socket$inet6_tcp",
+ "socket$inet",
+}
+
+type ProgAttachContext struct {
+ Flags int
+ TargetType int
+ TargetFd *ResultArg
+ ExtraType int
+ Extra interface{}
+}
+
+type NetfilterExtra struct {
+ Pf int32 // flags[nfproto, int32]
+ Hooknum int32 // flags[nf_dev_hooks, int32]
+ Priority int32
+ Flags int32 // flags[bpf_link_create_netfilter_flags, int32]
+}
+
+type TracingExtra struct {
+ target_btf_id int32
+ cookie uint64
+}
+
+func makeExtraArg(r *randGen, s *state, targetType int, extraType Type, extraData interface{}) *GroupArg {
+ switch targetType {
+ case Netfilter:
+ return makeNetfilterArg(r, s, extraType, extraData.(NetfilterExtra))
+ case Trace:
+ return makeTracingArg(r, s, extraType, extraData.(TracingExtra))
+
+ }
+ return nil
+}
+
+func makeTracingArg(r *randGen, s *state, tracetype Type, tracedata TracingExtra) *GroupArg {
+ args := []Arg{}
+ for idx, field := range tracetype.(*StructType).Fields {
+ var newArg Arg
+ switch idx {
+ case 0: // target_btf_id - int32
+ newArg = MakeConstArg(field.Type, DirIn, uint64(tracedata.target_btf_id))
+ case 1: // cookie - uint64
+ newArg = MakeConstArg(field.Type, DirIn, uint64(tracedata.cookie))
+ }
+
+ args = append(args, newArg)
+ }
+
+ return MakeGroupArg(tracetype, DirIn, args)
+
+}
+
+func makeNetfilterArg(r *randGen, s *state, nettype Type, netdata NetfilterExtra) *GroupArg {
+ args := []Arg{}
+ for idx, field := range nettype.(*StructType).Fields {
+ var newArg Arg
+ switch idx {
+ case 0: // pf - flags[nfproto, int32]
+ newArg = MakeConstArg(field.Type, DirIn, uint64(netdata.Pf))
+ case 1: // hooknum - flags[nf_dev_hooks, int32]
+ newArg = MakeConstArg(field.Type, DirIn, uint64(netdata.Hooknum))
+ case 2: // priority - int32
+ newArg = MakeConstArg(field.Type, DirIn, uint64(netdata.Priority))
+ case 3: // flags - flags[bpf_link_create_netfilter_flags, int32]
+ newArg = MakeConstArg(field.Type, DirIn, uint64(netdata.Flags))
+
+ }
+
+ args = append(args, newArg)
+ }
+
+ return MakeGroupArg(nettype, DirIn, args)
+
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) genLdbfProgAttachCall(r *randGen, s *state, bpfProg *BpfProg, attachContext *ProgAttachContext) (calls []*Call) {
+ // use bpf$LDBF_BPF_PROG_ATTACH to attach ebpf prog to its target
+ var currentProgAttachCall []*Call
+ meta := r.target.SyscallMap["bpf$LDBF_BPF_PROG_ATTACH"]
+ c := MakeCall(meta, nil)
+ c.Args, calls = r.generateArgs(s, meta.Args, DirIn)
+
+ cArgField, _ := c.Args[1].Type().(*PtrType)
+ linkCreateTypes, _ := cArgField.Elem.(*StructType)
+
+ // bpf_link_create_arg
+ ptrArg, ok := c.Args[1].(*PointerArg)
+ if !ok {
+ return currentProgAttachCall
+ }
+ //bpf_link_create_arg_t
+ linkCreateArgs, ok := ptrArg.Res.(*GroupArg)
+ if !ok || ptrArg.Res == nil {
+ // fmt.Printf("Ldbf: genLdbfMapCreateCall: c.Args[1] is not a PointerArg, got %T\n", c.Args[1])
+ return currentProgAttachCall
+ }
+
+ for argIdx, field := range linkCreateTypes.Fields {
+ var newArg Arg
+ switch argIdx {
+ case 0: // target_fd
+ // calls := Ldbf.createAttachedTarget(r, s, bpfProg)
+ // if len(calls) == 0 {
+ // fmt.Println("Ldbf: genLdbfProgLinkCall: failed to create attach target")
+ // continue
+ // }
+ // currentLinkCreateCall = append(currentLinkCreateCall, calls...)
+ targetTypes := field.Type.(*UnionType)
+ //fmt.Println(targetTypes)
+
+ targetType := targetTypes.Fields[attachContext.TargetType]
+ // fmt.Println("Target type:", targetType)
+ fd := attachContext.TargetFd
+ fdArg := MakeResultArg(targetType.Type, DirIn, fd, 0)
+ newArg = MakeUnionArg(targetTypes, DirIn, fdArg, attachContext.TargetType)
+
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 1: // prog_fd
+ newArg = MakeResultArg(field.Type, DirIn, bpfProg.BpfProgContext.ProgFD, 0)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 2: // attach_type
+ newArg = MakeConstArg(field.Type, DirIn, bpfProg.BpfProgContext.ExpectedAttachType)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 3: // flags
+ newArg = MakeConstArg(field.Type, DirIn, 0)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 4:
+ newArg = MakeResultArg(field.Type, DirIn, nil, 0)
+ // fmt.Println("newArg:", newArg, " type:", field.Type)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ // case 5, 6, 7, 8:
+ // sourceArg := MakeResultArg(field.Type, DirIn, nil, 0)
+ // newArg = MakeUnionArg()
+ // replaceArg(linkCreateArgs.Inner[argIdx], sourceArg)
+ default:
+
+ }
+ }
+ //moreCalls, _ := r.patchConditionalFields(c, s)
+ r.target.assignSizesCall(c)
+ return append(append(calls, currentProgAttachCall...), c)
+
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) genLdbfAttachCalls(r *randGen, s *state, bpfProg *BpfProg) (calls []*Call) {
+ var bpfAttachCalls []*Call
+ progType := bpfProg.BpfProgContext.ProgType
+ //attachType := bpfProg.BpfProgContext.ExpectedAttachType
+ var attachContext ProgAttachContext
+ switch progType {
+ case BPF_PROG_TYPE_CGROUP_SKB, BPF_PROG_TYPE_CGROUP_SOCK, BPF_PROG_TYPE_CGROUP_DEVICE,
+ BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_PROG_TYPE_CGROUP_SOCKOPT,
+ BPF_PROG_TYPE_SOCK_OPS:
+ call := genOpenCall(r, s, "/sys/fs/cgroup", 0, 0)
+ attachContext.TargetFd = call.Ret
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, call)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+ bpfAttachCalls = append(bpfAttachCalls, genRandCalls(r, s, bpfProg, []string{
+ "write", "read", "close", "openat$cgroup",
+ })...)
+
+ case BPF_PROG_TYPE_SK_LOOKUP, BPF_PROG_TYPE_FLOW_DISSECTOR:
+ call := genOpenCall(r, s, "/proc/self/ns/net", 0, 0)
+ attachContext.TargetFd = call.Ret
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, call)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+ bpfAttachCalls = append(bpfAttachCalls, genRandCalls(r, s, bpfProg, []string{
+ "write", "read", "close",
+ })...)
+
+ case BPF_PROG_TYPE_SK_SKB, BPF_PROG_TYPE_SK_MSG:
+ choice := []int{15, 18}
+ mapType := choice[r.Intn(len(choice))]
+ mapCalls := genSingleMapCreateCall(r, s, bpfProg, &bpfMapTypeArray[mapType])
+ if len(mapCalls) == 0 {
+ // fmt.Println("Ldbf: genLdbfProgAttachCall: failed to create map")
+ return bpfAttachCalls
+ }
+ attachContext.TargetFd = mapCalls[len(mapCalls)-1].Ret
+ attachContext.TargetType = MapFd
+ progAttachCalls := Ldbf.genLdbfProgAttachCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, mapCalls...)
+ bpfAttachCalls = append(bpfAttachCalls, progAttachCalls...)
+ bpfAttachCalls = append(bpfAttachCalls, genRandCalls(r, s, bpfProg, []string{
+ "bpf$MAP_LOOKUP_ELEM", "bpf$MAP_UPDATE_ELEM", "bpf$MAP_DELETE_ELEM",
+ })...)
+
+ case BPF_PROG_TYPE_PERF_EVENT, BPF_PROG_TYPE_KPROBE, BPF_PROG_TYPE_TRACEPOINT:
+ call := genHookCall(r, s, bpfProg, "perf_event_open")
+ attachContext.TargetFd = call[len(call)-1].Ret
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, call...)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+
+ case BPF_PROG_TYPE_SOCKET_FILTER, BPF_PROG_TYPE_SK_REUSEPORT:
+ // use setsockopt setsockopt$sock_attach_bpf
+ // fmt.Println("try socket filter")
+ socketCall := genHookCall(r, s, bpfProg, Sockets[r.rand(len(Sockets))]) // AF_INET, SOCK_STREAM
+ setSockOpt := genSetSockOptCall(r, s, socketCall[len(socketCall)-1].Ret, 1, 15, bpfProg.BpfProgContext.ProgFD) // SOL_SOCKET, SO_ATTACH_BPF
+ bpfAttachCalls = append(bpfAttachCalls, socketCall...)
+ bpfAttachCalls = append(bpfAttachCalls, setSockOpt)
+
+ case BPF_PROG_TYPE_NETFILTER:
+ // fmt.Println("try netfilter")
+ netdata := NetfilterExtra{
+ Pf: 2, // AF_INET
+ Hooknum: 4, // NF_INET_POST_ROUTING
+ Priority: 0, // NF_IP_PRI_FIRST
+ Flags: 0, // no flags
+ }
+ attachContext.TargetFd = nil
+ attachContext.Extra = netdata
+ attachContext.ExtraType = Netfilter
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+
+ case BPF_PROG_TYPE_TRACING:
+ // need to enable CONFIG_DYNAMIC_FTRACE CONFIG_FUNCTION_TRACER
+ if bpfProg.BpfProgContext.ExpectedAttachType != uint64(BPF_TRACE_FENTRY) &&
+ bpfProg.BpfProgContext.ExpectedAttachType != uint64(BPF_TRACE_FEXIT) &&
+ bpfProg.BpfProgContext.ExpectedAttachType != uint64(BPF_MODIFY_RETURN) {
+ break
+ }
+
+ // fmt.Println("try tracing")
+ attachContext.TargetFd = nil
+ attachContext.Extra = nil
+ //attachContext.ExtraType = Trace
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+
+ case BPF_PROG_TYPE_LSM:
+ // need to enable CONFIG_DYNAMIC_FTRACE CONFIG_FUNCTION_TRACER
+ if bpfProg.BpfProgContext.ExpectedAttachType != uint64(BPF_LSM_MAC) {
+ break
+ }
+ // fmt.Println("try tracing")
+ attachContext.TargetFd = nil
+ attachContext.Extra = nil
+ //attachContext.ExtraType = Trace
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+
+ case BPF_PROG_TYPE_XDP:
+ // fmt.Println("try xdp")
+ // we need to get ifindex of a net device
+ ifIndexCall, ifIndexRet := genIfIndexCall(r, s, "eth1\x00")
+ attachContext.TargetFd = ifIndexRet
+ linkCreateCalls := Ldbf.genLdbfProgLinkCall(r, s, bpfProg, &attachContext)
+ bpfAttachCalls = append(bpfAttachCalls, ifIndexCall...)
+ bpfAttachCalls = append(bpfAttachCalls, linkCreateCalls...)
+ bpfAttachCalls = append(bpfAttachCalls, genRandCalls(r, s, bpfProg, []string{
+ "write", "read", "close",
+ })...)
+
+ }
+
+ return bpfAttachCalls
+
+}
+
+func (Ldbf *LLMDrivenBPFuzzer) genLdbfProgLinkCall(r *randGen, s *state, bpfProg *BpfProg, attachContext *ProgAttachContext) (calls []*Call) {
+ var currentLinkCreateCall []*Call
+ //progType := bpfProg.BpfProgContext.ProgType
+ linkSyscall := "bpf$LDBF_LINK_CREATE"
+ // if progType == BPF_PROG_TYPE_XDP {
+ // linkSyscall = "bpf$BPF_LINK_CREATE_XDP"
+ // }
+ meta := r.target.SyscallMap[linkSyscall]
+ c := MakeCall(meta, nil)
+ c.Args, calls = r.generateArgs(s, meta.Args, DirIn)
+ // prog_fd PROG_FD
+ // target_fd TARGET_FD
+ // attach_type ATTACH_TYPE
+ // flags FLAGS
+
+ cArgField, _ := c.Args[1].Type().(*PtrType)
+ linkCreateTypes, _ := cArgField.Elem.(*StructType)
+
+ // bpf_link_create_arg
+ ptrArg, ok := c.Args[1].(*PointerArg)
+ if !ok {
+ return currentLinkCreateCall
+ }
+ //bpf_link_create_arg_t
+ linkCreateArgs, ok := ptrArg.Res.(*GroupArg)
+ if !ok || ptrArg.Res == nil {
+ // fmt.Printf("Ldbf: genLdbfMapCreateCall: c.Args[1] is not a PointerArg, got %T\n", c.Args[1])
+ return currentLinkCreateCall
+ }
+
+ for argIdx, field := range linkCreateTypes.Fields {
+ var newArg Arg
+ switch argIdx {
+ case 0: // prog_fd
+ newArg = MakeResultArg(field.Type, DirIn, bpfProg.BpfProgContext.ProgFD, 0)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+ case 1: // target_fd
+ // calls := Ldbf.createAttachedTarget(r, s, bpfProg)
+ // if len(calls) == 0 {
+ // fmt.Println("Ldbf: genLdbfProgLinkCall: failed to create attach target")
+ // continue
+ // }
+ // currentLinkCreateCall = append(currentLinkCreateCall, calls...)
+ fd := attachContext.TargetFd
+ newArg = MakeResultArg(field.Type, DirIn, fd, 0)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 2: // attach_type
+ newArg = MakeConstArg(field.Type, DirIn, bpfProg.BpfProgContext.ExpectedAttachType)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+ case 3: // flags
+ newArg = MakeConstArg(field.Type, DirIn, 0)
+ replaceArg(linkCreateArgs.Inner[argIdx], newArg)
+
+ case 4: // extra
+ if attachContext.Extra == nil {
+ continue
+ }
+ extraTypes := field.Type.(*UnionType)
+ // fmt.Println(extraTypes)
+ // for _, et := range extraTypes.Fields {
+ // // fmt.Println("Extra type option:", et)
+ // }
+
+ extraType := extraTypes.Fields[0].Type.(*UnionType).Fields[attachContext.ExtraType].Type
+ extraArg := makeExtraArg(r, s, attachContext.ExtraType, extraType, attachContext.Extra)
+ if extraArg == nil {
+ // fmt.Println("Ldbf: genLdbfProgLinkCall: failed to create extra arg")
+ continue
+ }
+ replaceArg(linkCreateArgs.Inner[argIdx], MakeUnionArg(extraTypes, DirIn, extraArg, 0))
+
+ default:
+
+ }
+ }
+
+ moreCalls, _ := r.patchConditionalFields(c, s)
+ currentLinkCreateCall = append(currentLinkCreateCall, calls...)
+ currentLinkCreateCall = append(currentLinkCreateCall, moreCalls...)
+ currentLinkCreateCall = append(currentLinkCreateCall, c)
+ r.target.assignSizesCall(c)
+
+ return currentLinkCreateCall
+}
+
+func genOpenCall(r *randGen, s *state, file string, flags int, mode int) (call *Call) {
+ meta := r.target.SyscallMap["open"]
+ c := MakeCall(meta, nil)
+ c.Args, _ = r.generateArgs(s, meta.Args, DirIn)
+
+ pathStr := []byte(file)
+ pathArg := meta.Args[0]
+ pathPtr := pathArg.Type.(*PtrType)
+ pathBuffer := pathPtr.Elem.(*BufferType)
+ pathBufferDir := pathPtr.ElemDir
+ pathBufferArg := MakeDataArg(pathBuffer, pathBufferDir, pathStr)
+ c.Args[0] = r.allocAddr(s, pathArg.Type, pathArg.Dir(DirIn), pathBufferArg.Size(), pathBufferArg)
+
+ flagsArg := MakeConstArg(meta.Args[1].Type, DirIn, uint64(flags))
+ c.Args[1] = flagsArg
+
+ modeArg := MakeConstArg(meta.Args[2].Type, DirIn, uint64(mode))
+ c.Args[2] = modeArg
+
+ r.target.assignSizesCall(c)
+ return c
+
+}
+
+func genSocketCall(r *randGen, s *state, domain int, sock_type int, proto int) (call *Call) {
+ meta := r.target.SyscallMap["socket$inet"]
+ c := MakeCall(meta, nil)
+ c.Args, _ = r.generateArgs(s, meta.Args, DirIn)
+
+ domainArg := MakeConstArg(meta.Args[0].Type, DirIn, uint64(domain))
+ c.Args[0] = domainArg
+
+ typeArg := MakeConstArg(meta.Args[1].Type, DirIn, uint64(sock_type))
+ c.Args[1] = typeArg
+
+ protoArg := MakeConstArg(meta.Args[2].Type, DirIn, uint64(proto))
+ c.Args[2] = protoArg
+
+ r.target.assignSizesCall(c)
+ return c
+}
+
+func genSetSockOptCall(r *randGen, s *state, sockfd *ResultArg, level int, optname int, progfd *ResultArg) (call *Call) {
+ meta := r.target.SyscallMap["setsockopt$sock_attach_bpf"]
+ c := MakeCall(meta, nil)
+ c.Args, _ = r.generateArgs(s, meta.Args, DirIn)
+
+ sockfdArg := MakeResultArg(meta.Args[0].Type, DirIn, sockfd, 0)
+ c.Args[0] = sockfdArg
+
+ levelArg := MakeConstArg(meta.Args[1].Type, DirIn, uint64(level))
+ c.Args[1] = levelArg
+
+ optnameArg := MakeConstArg(meta.Args[2].Type, DirIn, uint64(optname))
+ c.Args[2] = optnameArg
+
+ optvalArg := meta.Args[3]
+ optvalPtr := optvalArg.Type.(*PtrType)
+ progfdArg := MakeResultArg(optvalPtr.Elem, DirIn, progfd, 0)
+ c.Args[3] = r.allocAddr(s, optvalArg.Type, optvalArg.Dir(DirIn), progfdArg.Size(), progfdArg)
+
+ r.patchConditionalFields(c, s)
+ r.target.assignSizesCall(c)
+ return c
+}
+
+func genRandCalls(r *randGen, s *state, bpfProg *BpfProg, callName []string) (calls []*Call) {
+ var randCalls []*Call
+ times := r.Intn(3) + 1
+ for i := 0; i < times; i++ {
+ call := callName[r.Intn(len(callName))]
+ calls := genHookCall(r, s, bpfProg, call)
+ randCalls = append(randCalls, calls...)
+ }
+ return randCalls
+}
+
+func genHookCall(r *randGen, s *state, bpfProg *BpfProg, callName string) (calls []*Call) {
+ var hookCalls []*Call
+ meta := r.target.SyscallMap[callName]
+ c := MakeCall(meta, nil)
+ c.Args, calls = r.generateArgs(s, meta.Args, DirIn)
+ moreCalls, _ := r.patchConditionalFields(c, s)
+ hookCalls = append(hookCalls, calls...)
+ hookCalls = append(hookCalls, moreCalls...)
+ r.target.assignSizesCall(c)
+ hookCalls = append(hookCalls, c)
+ return hookCalls
+}
+
+func genIfIndexCall(r *randGen, s *state, ifName string) (calls []*Call, ret *ResultArg) {
+ var hookCalls []*Call
+ meta := r.target.SyscallMap["ioctl$sock_SIOCGIFINDEX"]
+ c := MakeCall(meta, nil)
+ c.Args, calls = r.generateArgs(s, meta.Args, DirIn)
+
+ socketCall := genSocketCall(r, s, 2, 1, 0) // AF_INET, SOCK_STREAM
+ hookCalls = append(hookCalls, socketCall)
+
+ sockfdArg := MakeResultArg(meta.Args[0].Type, DirIn, socketCall.Ret, 0)
+ c.Args[0] = sockfdArg
+
+ const IFNAMSIZ = 16
+ nameBuffer := make([]byte, IFNAMSIZ)
+ copy(nameBuffer, []byte(ifName))
+
+ ifreqptrArg, ok := c.Args[2].(*PointerArg)
+ if !ok {
+ return hookCalls, nil
+ }
+
+ ifreqArg, ok := ifreqptrArg.Res.(*GroupArg)
+ if !ok {
+ return hookCalls, nil
+ }
+ //fmt.Printf("ifreq Arg inner %v %v %v\n", ifreqArg.Inner, ifreqArg.Inner[0], ifreqArg.Inner[1])
+ ifindexArg := ifreqArg.Inner[1]
+ // replaceArg(ifreqArg.Inner[0], MakeDataArg(ifreqArg.Inner[0].Type(), DirIn, nameBuffer))
+ ret = MakeResultArg(ifindexArg.Type(), DirOut, ifindexArg.(*ResultArg), 0)
+
+ moreCalls, _ := r.patchConditionalFields(c, s)
+ hookCalls = append(hookCalls, calls...)
+ hookCalls = append(hookCalls, moreCalls...)
+ r.target.assignSizesCall(c)
+ hookCalls = append(hookCalls, c)