/
pkgtopb.go
1391 lines (1302 loc) · 39.6 KB
/
pkgtopb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pkgtofuzzinput
import (
"bufio"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"unicode"
"go/ast"
"go/token"
"golang.org/x/tools/go/packages"
)
type PkgFuncArgClass uint8
const (
PkgFuncArgClassProto PkgFuncArgClass = 0
PkgFuncArgClassUnhandled PkgFuncArgClass = 1
PkgFuncArgClassPkgGen PkgFuncArgClass = 2
PkgFuncArgClassProtoGen PkgFuncArgClass = 3
PkgFuncArgClassPkgConst PkgFuncArgClass = 4
PkgFuncArgClassUnknown PkgFuncArgClass = 5
PkgFuncArgClassPkgGenA PkgFuncArgClass = 6
PkgFuncArgClassPkgStruct PkgFuncArgClass = 7
)
type PkgFuncArg struct {
Name string
FieldType string
Proto PkgFuncArgClass
Prefix string
Suffix string
}
type PkgFuncResult struct {
FieldType string
Used bool
Prefix string
Suffix string
//form : star, array...
}
type PkgFunction struct {
Name string
Recv string
Suffix string
Args []PkgFuncArg
Returns []PkgFuncResult
SrcDst uint8
}
type PkgType struct {
Name string
Values []string
Args []PkgFuncArg
}
type PkgDescription struct {
Functions []PkgFunction
Types []PkgType
}
var ProtoGenerators = map[string]string{
"io.RuneReader": "strings.NewReader",
"io.ReaderAt": "bytes.NewReader",
"io.Reader": "bytes.NewReader",
"io.Writer": "bytes.NewBuffer",
"bufio.Reader": "CreateBufioReader",
"big.Int": "CreateBigInt",
"net.Conn": "CreateFuzzingConn",
"int": "int",
"rune": "GetRune",
"byte": "byte",
"uint": "uint",
"uint8": "uint8",
"uint16": "uint16",
"[]int": "ConvertIntArray",
"[]uint16": "ConvertUint16Array",
}
var ProtoGenerated = map[string]string{
"io.RuneReader": "string",
"io.ReaderAt": "bytes",
"io.Reader": "bytes",
"io.Writer": "bytes",
"bufio.Reader": "bytes",
"big.Int": "bytes",
"net.Conn": "bytes",
"int": "int64",
"rune": "string",
"byte": "uint32",
"uint": "uint32",
"uint8": "uint32",
"uint16": "uint32",
"[]int": "repeated int64",
"[]uint16": "repeated int64",
}
func GolangArgumentClassName(e ast.Expr) (PkgFuncArgClass, string) {
// this is likely incomplete
switch i := e.(type) {
case *ast.Ident:
switch i.Name {
case "uint32", "int32", "string", "bool", "int64", "uint64":
return PkgFuncArgClassProto, i.Name
case "float32":
return PkgFuncArgClassProto, "float"
case "float64":
return PkgFuncArgClassProto, "double"
case "int", "rune", "byte", "uint8", "uint16", "uint":
return PkgFuncArgClassProtoGen, i.Name
case "any":
return PkgFuncArgClassProto, "NgoloFuzzAny"
}
case *ast.FuncType:
return PkgFuncArgClassUnhandled, ""
case *ast.Ellipsis:
return PkgFuncArgClassUnhandled, ""
case *ast.InterfaceType:
if len(i.Methods.List) == 0 { // any
return PkgFuncArgClassProto, "NgoloFuzzAny"
}
return PkgFuncArgClassUnhandled, ""
case *ast.ChanType:
return PkgFuncArgClassUnhandled, ""
case *ast.MapType:
kc, kn := GolangArgumentClassName(i.Key)
if kc == PkgFuncArgClassProto {
vc, vn := GolangArgumentClassName(i.Value)
if vc == PkgFuncArgClassProto {
return PkgFuncArgClassProto, fmt.Sprintf("map<%s, %s>", kn, vn)
}
}
return PkgFuncArgClassUnhandled, ""
case *ast.ArrayType:
switch i2 := i.Elt.(type) {
case *ast.ArrayType:
switch i3 := i2.Elt.(type) {
case *ast.Ident:
switch i3.Name {
case "byte":
if i.Len == nil && i2.Len == nil {
return PkgFuncArgClassProto, "repeated bytes"
}
}
}
case *ast.Ident:
switch i2.Name {
case "byte", "uint8":
if i.Len == nil {
// no fixed size arrays in protobuf...
return PkgFuncArgClassProto, "bytes"
}
case "uint16":
return PkgFuncArgClassProtoGen, "[]uint16"
case "int":
return PkgFuncArgClassProtoGen, "[]int"
case "float64":
return PkgFuncArgClassProto, "repeated float64"
case "string":
return PkgFuncArgClassProto, "repeated string"
default:
return PkgFuncArgClassPkgGenA, i2.Name
}
}
case *ast.StarExpr:
switch i2 := i.X.(type) {
case *ast.SelectorExpr:
switch i3 := i2.X.(type) {
case *ast.Ident:
se := fmt.Sprintf("%s.%s", i3.Name, i2.Sel.Name)
switch se {
case "big.Int", "bufio.Reader":
return PkgFuncArgClassProtoGen, se
}
}
}
case *ast.SelectorExpr:
switch i2 := i.X.(type) {
case *ast.Ident:
se := fmt.Sprintf("%s.%s", i2.Name, i.Sel.Name)
switch se {
case "io.RuneReader", "io.ReaderAt", "io.Reader", "io.Writer", "bufio.Reader", "net.Conn":
return PkgFuncArgClassProtoGen, se
}
}
}
name, ok := astGetName(e)
if ok {
return PkgFuncArgClassPkgGen, name
}
return PkgFuncArgClassUnknown, ""
}
func PackageToProtobuf(pkg *packages.Package, descr PkgDescription, w io.StringWriter, outdir string) error {
//There may exist a package to do this, but it looks simple enough to do it from scratch
w.WriteString(`syntax = "proto3";` + "\n")
w.WriteString(`package ngolofuzz;` + "\n")
w.WriteString(`option go_package = "./;` + outdir + `";` + "\n\n")
for _, r := range descr.Types {
if len(r.Values) > 0 {
w.WriteString(`enum ` + r.Name + `Enum {` + "\n")
for v := range r.Values {
w.WriteString(fmt.Sprintf(" %s = %d;\n", r.Values[v], v))
}
w.WriteString("}\n\n")
} else if len(r.Args) > 0 {
idx := 1
w.WriteString(`message ` + r.Name + `Struct {` + "\n")
for a := range r.Args {
switch r.Args[a].Proto {
case PkgFuncArgClassPkgConst:
w.WriteString(fmt.Sprintf(" %sEnum %s = %d;\n", r.Args[a].FieldType, r.Args[a].Name, idx))
idx = idx + 1
case PkgFuncArgClassProto:
w.WriteString(fmt.Sprintf(" %s %s = %d;\n", r.Args[a].FieldType, r.Args[a].Name, idx))
idx = idx + 1
case PkgFuncArgClassProtoGen:
w.WriteString(fmt.Sprintf(" %s %s = %d;\n", ProtoGenerated[r.Args[a].FieldType], r.Args[a].Name, idx))
idx = idx + 1
}
}
w.WriteString("}\n\n")
}
}
for _, m := range descr.Functions {
w.WriteString(`message ` + m.Recv + m.Name + `Args {` + "\n")
idx := 1
for a := range m.Args {
switch m.Args[a].Proto {
case PkgFuncArgClassPkgConst:
w.WriteString(fmt.Sprintf(" %sEnum %s = %d;\n", m.Args[a].FieldType, m.Args[a].Name, idx))
idx = idx + 1
case PkgFuncArgClassProto:
w.WriteString(fmt.Sprintf(" %s %s = %d;\n", m.Args[a].FieldType, m.Args[a].Name, idx))
idx = idx + 1
case PkgFuncArgClassProtoGen:
w.WriteString(fmt.Sprintf(" %s %s = %d;\n", ProtoGenerated[m.Args[a].FieldType], m.Args[a].Name, idx))
idx = idx + 1
case PkgFuncArgClassPkgStruct:
w.WriteString(fmt.Sprintf(" %sStruct %s = %d;\n", m.Args[a].FieldType, m.Args[a].Name, idx))
idx = idx + 1
}
}
w.WriteString("}\n")
}
w.WriteString("\n")
w.WriteString(`message NgoloFuzzOne {` + "\n")
w.WriteString(` oneof item {` + "\n")
for m := range descr.Functions {
w.WriteString(fmt.Sprintf(" %s%sArgs %s%s = %d;\n", descr.Functions[m].Recv, descr.Functions[m].Name, descr.Functions[m].Recv, descr.Functions[m].Name, m+1))
}
w.WriteString(" }\n}\n")
//TODO only add it if necessary
w.WriteString(`message NgoloFuzzAny {` + "\n")
w.WriteString(` oneof item {` + "\n")
w.WriteString(" double DoubleArgs = 1;\n")
w.WriteString(" int64 Int64Args = 2;\n")
w.WriteString(" bool BoolArgs = 3;\n")
w.WriteString(" string StringArgs = 4;\n")
w.WriteString(" bytes BytesArgs = 5;\n")
w.WriteString(" }\n}\n")
w.WriteString(`message NgoloFuzzList { repeated NgoloFuzzOne list = 1; }`)
return nil
}
const fuzzTarget1 = `//go:build gofuzz
package %s
import (
"google.golang.org/protobuf/proto"
`
const fuzzTarget2 = `)
type FuzzingConn struct {
buf []byte
offset int
}
func (c *FuzzingConn) Read(b []byte) (n int, err error) {
if c.offset >= len(c.buf) {
return 0, io.EOF
}
if len(b) < len(c.buf)+c.offset {
copy(b, c.buf[c.offset:])
c.offset += len(b)
return len(b), nil
}
copy(b, c.buf[c.offset:])
r := len(c.buf) - c.offset
c.offset = len(c.buf)
return r, nil
}
func (c *FuzzingConn) Write(b []byte) (n int, err error) {
return len(b), nil
}
func (c *FuzzingConn) Close() error {
c.offset = len(c.buf)
return nil
}
type FuzzingAddr struct{}
func (c *FuzzingAddr) Network() string {
return "fuzz_addr_net"
}
func (c *FuzzingAddr) String() string {
return "fuzz_addr_string"
}
func (c *FuzzingConn) LocalAddr() net.Addr {
return &FuzzingAddr{}
}
func (c *FuzzingConn) RemoteAddr() net.Addr {
return &FuzzingAddr{}
}
func (c *FuzzingConn) SetDeadline(t time.Time) error {
return nil
}
func (c *FuzzingConn) SetReadDeadline(t time.Time) error {
return nil
}
func (c *FuzzingConn) SetWriteDeadline(t time.Time) error {
return nil
}
func CreateFuzzingConn(a []byte) *FuzzingConn {
r := &FuzzingConn{}
r.buf = a
return r
}
//TODO only add these functions if needed
func CreateBigInt(a []byte) *big.Int {
r := new(big.Int)
r.SetBytes(a)
return r
}
func CreateBufioReader(a []byte) *bufio.Reader {
return bufio.NewReader(bytes.NewBuffer(a))
}
func ConvertIntArray(a []int64) []int {
r := make([]int, len(a))
for i := range a {
r[i] = int(a[i])
}
return r
}
func ConvertUint16Array(a []int64) []uint16 {
r := make([]uint16, len(a))
for i := range a {
r[i] = uint16(a[i])
}
return r
}
func GetRune(s string) rune {
for _, c := range s {
return c
}
return '\x00'
}
`
const fuzzTarget3 = `func FuzzNG_valid(data []byte) int {
gen := &NgoloFuzzList{}
err := proto.Unmarshal(data, gen)
if err != nil {
panic("Failed to unmarshal LPM generated variables")
}
defer func() {
if r := recover(); r != nil {
switch r.(type) {
case string:
//do nothing
default:
panic(r)
}
}
}()
runtime.GC()
return FuzzNG_List(gen)
}
// we are unsure the input is a valid protobuf
func FuzzNG_unsure(data []byte) int {
gen := &NgoloFuzzList{}
err := proto.Unmarshal(data, gen)
if err != nil {
return 0
}
defer func() {
if r := recover(); r != nil {
switch r.(type) {
case string:
//do nothing
default:
panic(r)
}
}
}()
runtime.GC()
return FuzzNG_List(gen)
}
var initialized bool
func FuzzNG_List(gen *NgoloFuzzList) int {
if !initialized {
repro := os.Getenv("FUZZ_NG_REPRODUCER")
if len(repro) > 0 {
f, err := os.Create(repro)
if err != nil {
log.Fatalf("Failed to open %s : %s", repro, err)
} else {
PrintNG_List(gen, f)
}
}
initialized = true
}
`
// fix camel case for rare functions not having it like rsa.DecryptPKCS1v15
func CamelUpper(s string) string {
return s[0:1] + strings.ToUpper(s[1:2]) + s[2:3]
}
var badCamel = regexp.MustCompile(`([0-9])([a-z])([0-9])`)
func CamelCase(s string) string {
return badCamel.ReplaceAllStringFunc(s, CamelUpper)
}
func TitleCase(s string) string {
if len(s) > 0 && s[0] == '_' {
return "X" + strings.Title(s[1:])
}
return strings.Title(s)
}
func PackageToFuzzTarget(pkg *packages.Package, descr PkgDescription, w io.StringWriter, outdir string, limits string) error {
// maybe args parsing should be done earlier...
limitsList := strings.Split(limits, ",")
if len(limits) == 0 {
limitsList = limitsList[:0]
}
limitsMap := make(map[string]bool, len(limitsList))
for k := range limitsList {
limitsMap[limitsList[k]] = true
}
//maybe we should create AST and generate go from there
w.WriteString(fmt.Sprintf(fuzzTarget1, outdir))
// import other package needed from args such as strings
toimport := make(map[string]bool)
toimport[pkg.ID] = true
toimport["fmt"] = true
toimport["bufio"] = true
toimport["bytes"] = true
toimport["io"] = true
toimport["log"] = true
toimport["net"] = true
toimport["os"] = true
toimport["time"] = true
toimport["runtime"] = true
toimport["math/big"] = true
for _, m := range descr.Functions {
for a := range m.Args {
switch m.Args[a].Proto {
case PkgFuncArgClassProtoGen:
pkgGenNames := strings.Split(ProtoGenerators[m.Args[a].FieldType], ".")
if len(pkgGenNames) == 2 {
toimport[pkgGenNames[0]] = true
}
}
}
}
keys := make([]string, 0, len(toimport))
for k := range toimport {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
w.WriteString("\t\"" + k + "\"\n")
}
w.WriteString(fuzzTarget2)
pkgSplit := strings.Split(pkg.ID, "/")
pkgImportName := pkgSplit[len(pkgSplit)-1]
// write functions returning type with constants
for _, r := range descr.Types {
if len(r.Values) > 0 {
w.WriteString("\nfunc " + r.Name + "NewFromFuzz(p " + r.Name + "Enum) " + pkgImportName + "." + r.Name + "{\n")
if len(r.Values) > 1 {
w.WriteString("\tswitch p {\n")
for i := 0; i < len(r.Values)-1; i++ {
w.WriteString(fmt.Sprintf("\t\tcase %d:\n", i+1))
w.WriteString("\t\t\treturn " + pkgImportName + "." + r.Values[i+1] + "\n")
}
w.WriteString("\t}\n")
}
w.WriteString("\treturn " + pkgImportName + "." + r.Values[0] + "\n")
w.WriteString("}\n\n")
w.WriteString("\nfunc Convert" + r.Name + "NewFromFuzz(a []" + r.Name + "Enum) []" + pkgImportName + "." + r.Name + "{\n")
w.WriteString("\tr := make([]" + pkgImportName + "." + r.Name + ", len(a))\n")
w.WriteString("\tfor i := range a {\n")
w.WriteString("\t\tr[i] = " + r.Name + "NewFromFuzz(a[i])\n")
w.WriteString("\t}\n")
w.WriteString("\treturn r\n")
w.WriteString("}\n\n")
} else if len(r.Args) > 0 {
w.WriteString("\nfunc " + r.Name + "NewFromFuzz(p *" + r.Name + "Struct) *" + pkgImportName + "." + r.Name + "{\n")
w.WriteString("\tif p == nil {\n")
w.WriteString("\t\treturn nil\n")
w.WriteString("\t}\n")
w.WriteString("\treturn &" + pkgImportName + "." + r.Name + "{\n")
for i := range r.Args {
w.WriteString("\t\t" + r.Args[i].Name + ": ")
switch r.Args[i].Proto {
case PkgFuncArgClassPkgConst:
if strings.HasPrefix(r.Args[i].FieldType, "repeated ") {
w.WriteString(fmt.Sprintf("Convert%s(p.%s)", r.Args[i].FieldType[len("repeated "):]+"NewFromFuzz", r.Args[i].Name))
} else {
w.WriteString(fmt.Sprintf("%s(p.%s)", r.Args[i].FieldType+"NewFromFuzz", r.Args[i].Name))
}
case PkgFuncArgClassProto:
w.WriteString(fmt.Sprintf("p.%s%s", r.Args[i].Name, r.Args[i].Suffix))
case PkgFuncArgClassProtoGen:
w.WriteString(fmt.Sprintf("%s(p.%s)", ProtoGenerators[r.Args[i].FieldType], r.Args[i].Name))
}
w.WriteString(",\n")
}
w.WriteString("\t}\n")
w.WriteString("}\n\n")
}
}
w.WriteString(fuzzTarget3)
for _, r := range descr.Types {
if len(r.Values) == 0 && len(r.Args) == 0 {
w.WriteString(fmt.Sprintf("\tvar %sResults []*%s.%s\n", r.Name, pkgImportName, r.Name))
w.WriteString(fmt.Sprintf("\t%sResultsIndex := 0\n", r.Name))
}
}
w.WriteString("\tfor l := range gen.List {\n")
w.WriteString("\tif l > 4096 {\n")
w.WriteString("\t\treturn 0\n")
w.WriteString("\t}\n")
w.WriteString("\t\tswitch a := gen.List[l].Item.(type) {\n")
for _, m := range descr.Functions {
w.WriteString(fmt.Sprintf("\t\tcase *NgoloFuzzOne_%s%s%s:\n", m.Recv, CamelCase(m.Name), m.Suffix))
//prepare args
for a := range m.Args {
switch m.Args[a].Proto {
case PkgFuncArgClassPkgGen:
w.WriteString(fmt.Sprintf("\t\t\tif len(%sResults) == 0 {\n", m.Args[a].FieldType))
w.WriteString("\t\t\t\tcontinue\n\t\t\t}\n")
w.WriteString(fmt.Sprintf("\t\t\targ%d := %s%sResults[%sResultsIndex]\n", a, m.Args[a].Prefix, m.Args[a].FieldType, m.Args[a].FieldType))
w.WriteString(fmt.Sprintf("\t\t\t%sResultsIndex = (%sResultsIndex + 1) %% len(%sResults)\n", m.Args[a].FieldType, m.Args[a].FieldType, m.Args[a].FieldType))
case PkgFuncArgClassProtoGen:
w.WriteString(fmt.Sprintf("\t\t\targ%d := ", a))
w.WriteString(fmt.Sprintf("%s(a.%s%s%s.%s)\n", ProtoGenerators[m.Args[a].FieldType], m.Recv, CamelCase(m.Name), m.Suffix, TitleCase(m.Args[a].Name)))
case PkgFuncArgClassPkgConst:
w.WriteString(fmt.Sprintf("\t\t\targ%d := ", a))
w.WriteString(fmt.Sprintf("%s(a.%s%s.%s)\n", m.Args[a].FieldType+"NewFromFuzz", m.Recv, m.Name, strings.Title(m.Args[a].Name)))
case PkgFuncArgClassPkgStruct:
w.WriteString(fmt.Sprintf("\t\t\targ%d := ", a))
w.WriteString(fmt.Sprintf("%s(a.%s%s.%s)\n", m.Args[a].FieldType+"NewFromFuzz", m.Recv, m.Name, strings.Title(m.Args[a].Name)))
w.WriteString(fmt.Sprintf("\t\t\tif arg%d == nil {\n", a))
w.WriteString("\t\t\t\t continue\n")
w.WriteString("\t\t\t}\n")
case PkgFuncArgClassProto:
// The parameter 2 could be improved
if m.Args[a].Name == "dst" && m.Args[a].FieldType == "bytes" && m.SrcDst == FNG_DSTSRC_DST|FNG_DSTSRC_SRC {
w.WriteString(fmt.Sprintf("\t\t\ta.%s%s%s.Dst = make([]byte, 2*len(a.%s%s%s.Src))\n", m.Recv, m.Name, m.Suffix, m.Recv, m.Name, m.Suffix))
}
}
}
//call
w.WriteString("\t\t\t")
useReturn := false
for a := range m.Returns {
if m.Returns[a].Used {
useReturn = true
break
}
}
if useReturn {
comma := false
for a := range m.Returns {
if comma {
w.WriteString(", ")
} else {
comma = true
}
if m.Returns[a].Used {
w.WriteString(fmt.Sprintf("r%d", a))
} else {
w.WriteString("_")
}
}
w.WriteString(" := ")
}
if len(m.Recv) > 0 {
w.WriteString("arg0.")
} else {
w.WriteString(fmt.Sprintf("%s.", pkgImportName))
}
w.WriteString(fmt.Sprintf("%s(", m.Name))
comma := false
for a := range m.Args {
if len(m.Recv) > 0 && a == 0 {
continue
}
if comma {
w.WriteString(", ")
} else {
comma = true
}
switch m.Args[a].Proto {
case PkgFuncArgClassProto:
w.WriteString(fmt.Sprintf("a.%s%s%s.%s", m.Recv, CamelCase(m.Name), m.Suffix, strings.Title(m.Args[a].Name)))
case PkgFuncArgClassPkgGen, PkgFuncArgClassProtoGen, PkgFuncArgClassPkgConst, PkgFuncArgClassPkgStruct:
w.WriteString(fmt.Sprintf("arg%d", a))
}
// check if this parameter must be limited like rand.Prime.bits
_, ok := limitsMap[fmt.Sprintf("%s%s.%s", m.Recv, m.Name, m.Args[a].Name)]
if ok {
// constant is good enough for now
w.WriteString(" % 0x10001")
}
}
w.WriteString(")\n")
if useReturn {
for a := range m.Returns {
if m.Returns[a].Used {
if m.Returns[a].Prefix == "" && m.Returns[a].Suffix == "" {
w.WriteString(fmt.Sprintf("\t\t\tif r%d != nil{\n\t", a))
}
if m.Returns[a].FieldType == "error" {
w.WriteString(fmt.Sprintf("\t\t\tr%d.Error()\n", a))
w.WriteString("\t\t\treturn 0\n")
} else {
w.WriteString(fmt.Sprintf("\t\t\t%sResults = append(%sResults, %sr%d%s)\n", m.Returns[a].FieldType, m.Returns[a].FieldType, m.Returns[a].Prefix, a, m.Returns[a].Suffix))
}
if m.Returns[a].Prefix == "" && m.Returns[a].Suffix == "" {
w.WriteString(fmt.Sprintf("\t\t\t}\n"))
}
}
}
}
}
w.WriteString("\t\t}\n\t}\n\treturn 1\n}\n\n")
w.WriteString("func PrintNG_List(gen *NgoloFuzzList, w io.StringWriter) {\n")
for _, r := range descr.Types {
if len(r.Values) == 0 && len(r.Args) == 0 {
w.WriteString(fmt.Sprintf("\t%sNb := 0\n", r.Name))
w.WriteString(fmt.Sprintf("\t%sResultsIndex := 0\n", r.Name))
}
}
w.WriteString("\tfor l := range gen.List {\n")
w.WriteString("\t\tswitch a := gen.List[l].Item.(type) {\n")
for _, m := range descr.Functions {
w.WriteString(fmt.Sprintf("\t\tcase *NgoloFuzzOne_%s%s%s:\n", m.Recv, CamelCase(m.Name), m.Suffix))
//prepare args
for a := range m.Args {
switch m.Args[a].Proto {
case PkgFuncArgClassPkgGen:
w.WriteString(fmt.Sprintf("\t\t\tif %sNb == 0 {\n", m.Args[a].FieldType))
w.WriteString("\t\t\t\tcontinue\n\t\t\t}\n")
}
}
//call
useReturn := false
for a := range m.Returns {
if m.Returns[a].Used && m.Returns[a].FieldType != "error" {
useReturn = true
break
}
}
formatArgs := make([]string, 0, 16)
w.WriteString("\t\t\tw.WriteString(fmt.Sprintf(\"")
nbprints := make(map[string]int)
if useReturn {
comma := false
for a := range m.Returns {
if comma {
w.WriteString(", ")
} else {
comma = true
}
if m.Returns[a].Used && m.Returns[a].FieldType != "error" {
w.WriteString(fmt.Sprintf("%s%%d", m.Returns[a].FieldType))
formatArgs = append(formatArgs, fmt.Sprintf("%sNb", m.Returns[a].FieldType))
} else {
w.WriteString("_")
}
}
w.WriteString(" := ")
}
if len(m.Recv) > 0 {
if m.Args[0].Proto == PkgFuncArgClassPkgConst || m.Args[0].Proto == PkgFuncArgClassPkgStruct {
w.WriteString(fmt.Sprintf("%s(%%#+v).", m.Args[0].FieldType+"NewFromFuzz"))
formatArgs = append(formatArgs, fmt.Sprintf("a.%s%s.%s", m.Recv, m.Name, strings.Title(m.Args[0].Name)))
} else {
w.WriteString(fmt.Sprintf("%s%%d.", m.Args[0].FieldType))
formatArgs = append(formatArgs, fmt.Sprintf("%sResultsIndex", m.Args[0].FieldType))
nbprints[m.Args[0].FieldType] = 1
}
} else {
w.WriteString(fmt.Sprintf("%s.", pkgImportName))
}
w.WriteString(fmt.Sprintf("%s(", m.Name))
comma := false
for a := range m.Args {
if len(m.Recv) > 0 && a == 0 {
continue
}
if comma {
w.WriteString(", ")
} else {
comma = true
}
switch m.Args[a].Proto {
case PkgFuncArgClassProto:
w.WriteString(fmt.Sprintf("%%#+v"))
formatArgs = append(formatArgs, fmt.Sprintf("a.%s%s%s.%s", m.Recv, CamelCase(m.Name), m.Suffix, strings.Title(m.Args[a].Name)))
case PkgFuncArgClassProtoGen:
w.WriteString(fmt.Sprintf("%s(%%#+v)", ProtoGenerators[m.Args[a].FieldType]))
formatArgs = append(formatArgs, fmt.Sprintf("a.%s%s%s.%s", m.Recv, CamelCase(m.Name), m.Suffix, TitleCase(m.Args[a].Name)))
case PkgFuncArgClassPkgConst, PkgFuncArgClassPkgStruct:
w.WriteString(fmt.Sprintf("%s(%%#+v)", m.Args[a].FieldType+"NewFromFuzz"))
formatArgs = append(formatArgs, fmt.Sprintf("a.%s%s.%s", m.Recv, m.Name, strings.Title(m.Args[a].Name)))
case PkgFuncArgClassPkgGen:
w.WriteString(fmt.Sprintf("%s%%d", m.Args[a].FieldType))
nbprint := nbprints[m.Args[a].FieldType]
formatArgs = append(formatArgs, fmt.Sprintf("(%sResultsIndex + %d) %% %sNb", m.Args[a].FieldType, nbprint, m.Args[a].FieldType))
nbprints[m.Args[a].FieldType] = nbprint + 1
}
_, ok := limitsMap[fmt.Sprintf("%s%s.%s", m.Recv, m.Name, m.Args[a].Name)]
if ok {
w.WriteString(" %% 0x10001")
}
}
w.WriteString(`)\n"`)
for _, f := range formatArgs {
w.WriteString(", ")
w.WriteString(f)
}
w.WriteString("))\n")
//save
if useReturn {
for a := range m.Returns {
if m.Returns[a].Used && m.Returns[a].FieldType != "error" {
w.WriteString(fmt.Sprintf("\t\t\t%sNb = %sNb + 1\n", m.Returns[a].FieldType, m.Returns[a].FieldType))
}
}
}
for a := range m.Args {
if m.Args[a].Proto == PkgFuncArgClassPkgGen {
w.WriteString(fmt.Sprintf("\t\t\t%sResultsIndex = (%sResultsIndex + 1) %% %sNb\n", m.Args[a].FieldType, m.Args[a].FieldType, m.Args[a].FieldType))
}
}
}
w.WriteString("\t\t}\n\t}\n}\n")
return nil
}
func pkgFunCorpusable(funcname string, decls []ast.Decl, descr PkgDescription) (bool, *PkgFunction) {
for d := range decls {
switch f := decls[d].(type) {
case *ast.FuncDecl:
if f.Recv == nil && f.Name.String() == funcname {
interesting := false
possible := true
for f2 := range descr.Functions {
if len(descr.Functions[f2].Recv) == 0 && descr.Functions[f2].Name == f.Name.String() {
for a := range descr.Functions[f2].Args {
switch descr.Functions[f2].Args[a].FieldType {
case "string", "io.ReaderAt", "io.Reader", "bufio.Reader":
interesting = true
case "int32", "int64", "uint32", "uint64":
// still possible
default:
possible = false
}
}
return (interesting && possible), &descr.Functions[f2]
}
}
}
}
}
return false, nil
}
func PackageToCorpus(pkg *packages.Package, descr PkgDescription, outdir string) error {
for s := range pkg.Syntax {
file, err := os.Open(pkg.CompiledGoFiles[s])
if err != nil {
log.Printf("Failed reading file : %s", err)
return err
}
// create a copy of the file, just adding some lines in it
fcopy, err := os.Create(filepath.Join(outdir, filepath.Base(pkg.CompiledGoFiles[s])))
if err != nil {
log.Printf("Failed creating file : %s", err)
return err
}
scanner := bufio.NewScanner(file)
// optionally, resize scanner's capacity for lines over 64K, see next example
for scanner.Scan() {
l := scanner.Text()
fcopy.WriteString(l + "\n")
if strings.HasPrefix(l, "func ") {
funcname := strings.Split(l[5:], "(")[0]
ok, nfun := pkgFunCorpusable(funcname, pkg.Syntax[s].Decls, descr)
// if function can generate an item for corpus let's do it
if ok {
mline := fmt.Sprintf("NgoloCorpusMarshal(&NgoloFuzzOne_%s{%s: &%sArgs{", funcname, funcname, funcname)
for a := range nfun.Args {
argname := nfun.Args[a].Name
switch nfun.Args[a].FieldType {
case "io.ReaderAt":
fcopy.WriteString(fmt.Sprintf("ngolo_%s, _ := io.ReadAll(io.NewSectionReader(%s, 0, 0x100000))\n", nfun.Args[a].Name, nfun.Args[a].Name))
argname = "ngolo_" + argname
case "io.Reader", "bufio.Reader":
fcopy.WriteString(fmt.Sprintf("ngolo_%s, _ := io.ReadAll(%s)\n", nfun.Args[a].Name, nfun.Args[a].Name))
argname = "ngolo_" + argname
}
if a > 0 {
mline = mline + ", "
}
mline = mline + fmt.Sprintf("%s: %s", TitleCase(nfun.Args[a].Name), argname)
}
mline = mline + "}})\n"
fcopy.WriteString(mline)
for a := range nfun.Args {
switch nfun.Args[a].FieldType {
case "io.ReaderAt", "io.Reader", "bufio.Reader":
fcopy.WriteString(fmt.Sprintf("%s = bytes.NewReader(ngolo_%s)\n", nfun.Args[a].Name, nfun.Args[a].Name))
}
}
}
}
}
file.Close()
fcopy.Close()
}
return nil
}
func PackageToFuzzer(pkgname string, outdir string, exclude string, limits string) error {
pkg, err := PackageFromName(pkgname)
if err != nil {
log.Printf("Failed loading package : %s", err)
return err
}
if len(pkg.GoFiles) == 0 {
log.Printf("No files in package")
return fmt.Errorf("No files in package")
}
log.Printf("Found package in %s", filepath.Dir(pkg.GoFiles[0]))
ngdir := outdir
err = os.MkdirAll(ngdir, 0777)
if err != nil {
log.Printf("Failed creating dir %s : %s", ngdir, err)
return err
}
descr, err := PackageToProtobufMessagesDescription(pkg, exclude)
if err != nil {
return err
}
ngProtoFilename := filepath.Join(ngdir, "ngolofuzz.proto")
f, err := os.Create(ngProtoFilename)
if err != nil {
log.Printf("Failed creating file : %s", err)
return err
}
err = PackageToProtobuf(pkg, descr, f, outdir)
if err != nil {
return err
}
f.Close()
ngProtoFilename = filepath.Join(ngdir, "fuzz_ng.go")
f, err = os.Create(ngProtoFilename)
if err != nil {
log.Printf("Failed creating file : %s", err)
return err
}
err = PackageToFuzzTarget(pkg, descr, f, outdir, limits)
if err != nil {
return err
}
f.Close()
cdir := filepath.Join(ngdir, "corpus")
err = os.MkdirAll(cdir, 0777)
if err != nil {
log.Printf("Failed creating dir %s : %s", cdir, err)
return err
}
copydir := filepath.Join(ngdir, "copy")
err = os.MkdirAll(copydir, 0777)
if err != nil {
log.Printf("Failed creating dir %s : %s", copydir, err)
return err
}
err = PackageToCorpus(pkg, descr, copydir)
if err != nil {
log.Printf("Failed creating corpus : %s", err)
}
return nil
}
func PackageFromName(pkgname string) (*packages.Package, error) {
cfg := &packages.Config{Mode: packages.NeedFiles | packages.NeedSyntax | packages.NeedCompiledGoFiles}
pkgs, err := packages.Load(cfg, pkgname)
if err != nil {
return nil, err
}
if len(pkgs) != 1 {
return nil, fmt.Errorf("Unexpectedly got %d packages", len(pkgs))
}
return pkgs[0], nil
}
// Flags
const FNG_TYPE_RESULT uint8 = 1
const FNG_TYPE_ARG uint8 = 2
// has some defined constants
const FNG_TYPE_CONST uint8 = 4
// struct with exported fields (which can be built without a function)
const FNG_TYPE_STRUCTEXP uint8 = 8
const FNG_DSTSRC_DST = 1
const FNG_DSTSRC_SRC = 2
func astGetName(a ast.Expr) (string, bool) {
switch e := a.(type) {
case *ast.StarExpr:
return astGetName(e.X)
case *ast.Ident:
return e.Name, true
case *ast.ArrayType:
return astGetName(e.Elt)
//default:
//panic(fmt.Sprintf("lol %#+v", e))
case *ast.SelectorExpr:
switch i2 := e.X.(type) {
case *ast.Ident:
se := fmt.Sprintf("%s.%s", i2.Name, e.Sel.Name)
return se, true
}
case *ast.MapType:
return "mapkv", true