-
Notifications
You must be signed in to change notification settings - Fork 14
/
consumer.go
685 lines (636 loc) · 15.6 KB
/
consumer.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
package gofuzzheaders
import (
"archive/tar"
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"reflect"
"strings"
"unsafe"
securejoin "github.com/cyphar/filepath-securejoin"
)
type ConsumeFuzzer struct {
data []byte
CommandPart []byte
RestOfArray []byte
NumberOfCalls int
position int
fuzzUnexportedFields bool
Funcs map[reflect.Type]reflect.Value
}
func IsDivisibleBy(n int, divisibleby int) bool {
return (n % divisibleby) == 0
}
func NewConsumer(fuzzData []byte) *ConsumeFuzzer {
fuzzMap := make(map[reflect.Type]reflect.Value)
f := &ConsumeFuzzer{data: fuzzData, position: 0, Funcs: fuzzMap}
return f
}
func (f *ConsumeFuzzer) Split(minCalls, maxCalls int) error {
if len(f.data) == 0 {
return errors.New("Could not split")
}
numberOfCalls := int(f.data[0])
if numberOfCalls < minCalls || numberOfCalls > maxCalls {
return errors.New("Bad number of calls")
}
if len(f.data) < numberOfCalls+numberOfCalls+1 {
return errors.New("Length of data does not match required parameters")
}
// Define part 2 and 3 of the data array
commandPart := f.data[1 : numberOfCalls+1]
restOfArray := f.data[numberOfCalls+1:]
// Just a small check. It is necessary
if len(commandPart) != numberOfCalls {
return errors.New("Length of commandPart does not match number of calls")
}
// Check if restOfArray is divisible by numberOfCalls
if !IsDivisibleBy(len(restOfArray), numberOfCalls) {
return errors.New("Length of commandPart does not match number of calls")
}
f.CommandPart = commandPart
f.RestOfArray = restOfArray
f.NumberOfCalls = numberOfCalls
return nil
}
func (f *ConsumeFuzzer) AllowUnexportedFields() {
f.fuzzUnexportedFields = true
}
func (f *ConsumeFuzzer) DisallowUnexportedFields() {
f.fuzzUnexportedFields = false
}
func (f *ConsumeFuzzer) GenerateStruct(targetStruct interface{}) error {
v := reflect.ValueOf(targetStruct)
/*if !v.CanSet() {
return errors.New("This interface cannot be set")
}*/
e := v.Elem()
err := f.fuzzStruct(e, false)
if err != nil {
return err
}
return nil
}
func (f *ConsumeFuzzer) setCustom(v reflect.Value) error {
// First: see if we have a fuzz function for it.
doCustom, ok := f.Funcs[v.Type()]
if !ok {
return fmt.Errorf("Could not find a custom function")
}
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
if !v.CanSet() {
return fmt.Errorf("Could not use a custom function")
}
v.Set(reflect.New(v.Type().Elem()))
}
case reflect.Map:
if v.IsNil() {
if !v.CanSet() {
return fmt.Errorf("Could not use a custom function")
}
v.Set(reflect.MakeMap(v.Type()))
}
default:
return fmt.Errorf("Could not use a custom function")
}
verr := doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
F: f,
})})
// check if we return an error
if verr[0].IsNil() {
return nil
}
return fmt.Errorf("Could not use a custom function")
}
func (f *ConsumeFuzzer) fuzzStruct(e reflect.Value, customFunctions bool) error {
// We check if we should check for custom functions
if customFunctions {
if e.IsValid() {
if e.CanAddr() {
err := f.setCustom(e.Addr())
if err == nil {
return nil
}
}
/* return f.setCustom(e)
_, ok := f.Funcs[e.Type()]
if ok {
if e.CanAddr() {
err := f.setCustom(e.Addr())
if err == nil {
return nil
}
}*/
//return f.setCustom(e)
}
}
switch e.Kind() {
case reflect.Struct:
for i := 0; i < e.NumField(); i++ {
var v reflect.Value
if !e.Field(i).CanSet() {
if f.fuzzUnexportedFields {
v = reflect.NewAt(e.Field(i).Type(), unsafe.Pointer(e.Field(i).UnsafeAddr())).Elem()
}
err := f.fuzzStruct(v, customFunctions)
if err != nil {
return err
}
} else {
/*if e.Field(i).Kind() == reflect.Struct {
//e = reflect.NewAt(e.Type(), unsafe.Pointer(e.UnsafeAddr())).Elem()
//e.Field(i).Set(reflect.New(e.Field(i).Type()))
}*/
v = e.Field(i)
//v = reflect.New(e.Field(i).Type())
err := f.fuzzStruct(v, customFunctions)
if err != nil {
return err
}
/*if e.Field(i).CanSet() {
e.Field(i).Set(v.Elem())
}*/
}
}
case reflect.String:
str, err := f.GetString()
if err != nil {
return err
}
if e.CanSet() {
e.SetString(str)
}
case reflect.Slice:
maxElements := 50
randQty, err := f.GetInt()
if err != nil {
return err
}
numOfElements := randQty % maxElements
uu := reflect.MakeSlice(e.Type(), numOfElements, numOfElements)
for i := 0; i < numOfElements; i++ {
err := f.fuzzStruct(uu.Index(i), customFunctions)
if err != nil {
return err
}
}
if e.CanSet() {
e.Set(uu)
}
case reflect.Uint16:
newInt, err := f.GetUint16()
if err != nil {
return err
}
if e.CanSet() {
e.SetUint(uint64(newInt))
}
case reflect.Uint32:
newInt, err := f.GetUint32()
if err != nil {
return err
}
if e.CanSet() {
e.SetUint(uint64(newInt))
}
case reflect.Uint64:
newInt, err := f.GetInt()
if err != nil {
return err
}
if e.CanSet() {
e.SetUint(uint64(newInt))
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
newInt, err := f.GetInt()
if err != nil {
return err
}
if e.CanSet() {
e.SetInt(int64(newInt))
}
case reflect.Float32:
newFloat, err := f.GetFloat32()
if err != nil {
return err
}
if e.CanSet() {
e.SetFloat(float64(newFloat))
}
case reflect.Float64:
newFloat, err := f.GetFloat64()
if err != nil {
return err
}
if e.CanSet() {
e.SetFloat(float64(newFloat))
}
case reflect.Map:
if e.CanSet() {
e.Set(reflect.MakeMap(e.Type()))
maxElements := 50
randQty, err := f.GetInt()
if err != nil {
return err
}
numOfElements := randQty % maxElements
for i := 0; i < numOfElements; i++ {
key := reflect.New(e.Type().Key()).Elem()
err := f.fuzzStruct(key, customFunctions)
if err != nil {
return err
}
val := reflect.New(e.Type().Elem()).Elem()
err = f.fuzzStruct(val, customFunctions)
if err != nil {
return err
}
e.SetMapIndex(key, val)
}
}
case reflect.Ptr:
if e.CanSet() {
e.Set(reflect.New(e.Type().Elem()))
err := f.fuzzStruct(e.Elem(), customFunctions)
if err != nil {
return err
}
return nil
}
case reflect.Uint8:
b, err := f.GetByte()
if err != nil {
return err
}
if e.CanSet() {
e.SetUint(uint64(b))
}
default:
return nil
}
return nil
}
func (f *ConsumeFuzzer) GetStringArray() (reflect.Value, error) {
// The max size of the array:
max := 20
arraySize := f.position
if arraySize > max {
arraySize = max
}
elemType := reflect.TypeOf("string")
stringArray := reflect.MakeSlice(reflect.SliceOf(elemType), arraySize, arraySize)
if f.position+arraySize >= len(f.data) {
return stringArray, errors.New("Could not make string array")
}
for i := 0; i < arraySize; i++ {
stringSize := int(f.data[f.position])
if f.position+stringSize >= len(f.data) {
return stringArray, nil
}
stringToAppend := string(f.data[f.position : f.position+stringSize])
strVal := reflect.ValueOf(stringToAppend)
stringArray = reflect.Append(stringArray, strVal)
f.position = f.position + stringSize
}
return stringArray, nil
}
func (f *ConsumeFuzzer) GetInt() (int, error) {
if f.position >= len(f.data) {
return 0, errors.New("Not enough bytes to create int")
}
returnInt := int(f.data[f.position])
f.position++
return returnInt, nil
}
func (f *ConsumeFuzzer) GetByte() (byte, error) {
if len(f.data) == 0 {
return 0x00, errors.New("Not enough bytes to get byte")
}
if f.position >= len(f.data) {
return 0x00, errors.New("Not enough bytes to get byte")
}
returnByte := f.data[f.position]
f.position += 1
return returnByte, nil
}
func (f *ConsumeFuzzer) GetNBytes(numberOfBytes int) ([]byte, error) {
returnBytes := make([]byte, 0)
if len(f.data) == 0 {
return returnBytes, errors.New("Not enough bytes to get byte")
}
if f.position >= len(f.data) {
return returnBytes, errors.New("Not enough bytes to get byte")
}
for i := 0; i < numberOfBytes; i++ {
newByte, err := f.GetByte()
if err != nil {
return returnBytes, err
}
returnBytes = append(returnBytes, newByte)
}
return returnBytes, nil
}
func (f *ConsumeFuzzer) GetUint16() (uint16, error) {
u16, err := f.GetNBytes(2)
if err != nil {
return uint16(0), err
}
littleEndian, err := f.GetBool()
if err != nil {
return uint16(0), err
}
if littleEndian {
u16LE := binary.LittleEndian.Uint16(u16)
return u16LE, nil
}
u16BE := binary.BigEndian.Uint16(u16)
return u16BE, nil
}
func (f *ConsumeFuzzer) GetUint32() (uint32, error) {
u32, err := f.GetNBytes(4)
if err != nil {
return uint32(0), err
}
littleEndian, err := f.GetBool()
if err != nil {
return uint32(0), err
}
if littleEndian {
u32LE := binary.LittleEndian.Uint32(u32)
return u32LE, nil
}
u32BE := binary.BigEndian.Uint32(u32)
return u32BE, nil
}
func (f *ConsumeFuzzer) GetUint64() (uint64, error) {
u64, err := f.GetNBytes(8)
if err != nil {
return uint64(0), err
}
littleEndian, err := f.GetBool()
if err != nil {
return uint64(0), err
}
if littleEndian {
u64LE := binary.LittleEndian.Uint64(u64)
return u64LE, nil
}
u64BE := binary.BigEndian.Uint64(u64)
return u64BE, nil
}
func (f *ConsumeFuzzer) GetBytes() ([]byte, error) {
if len(f.data) == 0 || f.position >= len(f.data) {
return nil, errors.New("Not enough bytes to create byte array")
}
length := int(f.data[f.position])
byteBegin := f.position + 1
if byteBegin >= len(f.data) {
return nil, errors.New("Not enough bytes to create byte array")
}
if length == 0 {
return nil, errors.New("Zero-length is not supported")
}
if byteBegin+length >= len(f.data) {
return nil, errors.New("Not enough bytes to create byte array")
}
b := f.data[byteBegin : byteBegin+length]
f.position = byteBegin + length
return b, nil
}
func (f *ConsumeFuzzer) GetString() (string, error) {
if f.position >= len(f.data) {
return "nil", errors.New("Not enough bytes to create string")
}
length := int(f.data[f.position])
byteBegin := f.position + 1
if byteBegin >= len(f.data) {
return "nil", errors.New("Not enough bytes to create string")
}
if byteBegin+length > len(f.data) {
return "nil", errors.New("Not enough bytes to create string")
}
str := string(f.data[byteBegin : byteBegin+length])
f.position = byteBegin + length
return str, nil
}
func (f *ConsumeFuzzer) GetBool() (bool, error) {
if f.position >= len(f.data) {
return false, errors.New("Not enough bytes to create bool")
}
if IsDivisibleBy(int(f.data[f.position]), 2) {
f.position++
return true, nil
} else {
f.position++
return false, nil
}
}
func (f *ConsumeFuzzer) FuzzMap(m interface{}) error {
err := f.GenerateStruct(m)
if err != nil {
return err
}
return nil
}
// TarBytes returns valid bytes for a tar archive
func (f *ConsumeFuzzer) TarBytes() ([]byte, error) {
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
numberOfFiles, err := f.GetInt()
if err != nil {
return nil, err
}
maxNoOfFiles := 100000
for i := 0; i < numberOfFiles%maxNoOfFiles; i++ {
filename, err := f.GetString()
if err != nil {
return nil, err
}
filebody, err := f.GetBytes()
if err != nil {
return nil, err
}
hdr := &tar.Header{}
err = f.GenerateStruct(hdr)
if err != nil {
return nil, err
}
hdr.Name = filename
hdr.Size = int64(len(filebody))
hdr.Mode = 0600
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
if _, err := tw.Write(filebody); err != nil {
return nil, err
}
}
if err := tw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Creates pseudo-random files in rootDir.
// Will create subdirs and place the files there.
// It is the callers responsibility to ensure that
// rootDir exists.
func (f *ConsumeFuzzer) CreateFiles(rootDir string) error {
noOfCreatedFiles := 0
numberOfFiles, err := f.GetInt()
if err != nil {
return err
}
maxNumberOfFiles := numberOfFiles % 4000 // This is completely arbitrary
if maxNumberOfFiles == 0 {
return errors.New("maxNumberOfFiles is nil")
}
for i := 0; i < maxNumberOfFiles; i++ {
subDir, err := f.GetString()
if err != nil {
// We don't stop the fuzzing job if we have created
// some files. In that case we want to feed them
// to the target
if noOfCreatedFiles > 0 {
return nil
}
}
// Avoid going outside the root dir
if strings.Contains(subDir, "../") || (len(subDir) > 0 && subDir[0] == 47) || strings.Contains(subDir, "\\") {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Dir contains invalid chars")
}
}
dirPath, err := securejoin.SecureJoin(rootDir, subDir)
if err != nil {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not join rootDir and subDir securely")
}
}
err = os.MkdirAll(dirPath, 0777)
if err != nil {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not create the subDir")
}
}
fileName, err := f.GetString()
if err != nil {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not get fileName")
}
}
fullFilePath, err := securejoin.SecureJoin(dirPath, fileName)
if err != nil {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not join dir path and file path securely")
}
}
fileContents, err := f.GetBytes()
if err != nil {
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not create the subDir")
}
}
createdFile, err := os.Create(fullFilePath)
if err != nil {
createdFile.Close()
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not create the subDir")
}
}
_, err = createdFile.Write(fileContents)
if err != nil {
createdFile.Close()
if noOfCreatedFiles > 0 {
return nil
} else {
return errors.New("Could not create the subDir")
}
}
createdFile.Close()
noOfCreatedFiles++
}
return nil
}
// Returns a string that can only consists of characters that are
// included in possibleChars. Will return an error if the created
// string does not have the specified length
func (f *ConsumeFuzzer) GetStringFrom(possibleChars string, length int) (string, error) {
returnString := ""
if (len(f.data) - f.position) < length {
return returnString, errors.New("Not enough bytes to create a string")
}
for i := 0; i < length; i++ {
charIndex, err := f.GetInt()
if err != nil {
return returnString, err
}
charToAdd := string(possibleChars[charIndex%len(possibleChars)])
returnString = fmt.Sprintf(returnString + charToAdd)
}
return returnString, nil
}
func (f *ConsumeFuzzer) GetRune() ([]rune, error) {
stringToConvert, err := f.GetString()
if err != nil {
return []rune("nil"), err
}
return []rune(stringToConvert), nil
}
func (f *ConsumeFuzzer) GetFloat32() (float32, error) {
u32, err := f.GetNBytes(4)
if err != nil {
return float32(0.0), err
}
littleEndian, err := f.GetBool()
if err != nil {
return float32(0.0), err
}
if littleEndian {
u32LE := binary.LittleEndian.Uint32(u32)
return math.Float32frombits(u32LE), nil
}
u32BE := binary.BigEndian.Uint32(u32)
return math.Float32frombits(u32BE), nil
}
func (f *ConsumeFuzzer) GetFloat64() (float64, error) {
u64, err := f.GetNBytes(8)
if err != nil {
return float64(0.0), err
}
littleEndian, err := f.GetBool()
if err != nil {
return float64(0.0), err
}
if littleEndian {
u64LE := binary.LittleEndian.Uint64(u64)
return math.Float64frombits(u64LE), nil
}
u64BE := binary.BigEndian.Uint64(u64)
return math.Float64frombits(u64BE), nil
}
func (f *ConsumeFuzzer) CreateSlice(targetSlice interface{}) error {
err := f.GenerateStruct(targetSlice)
if err != nil {
return err
}
return nil
}