/
files.go
79 lines (68 loc) · 1.73 KB
/
files.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
package httpfuzz
import (
"crypto/rand"
"fmt"
"io/ioutil"
"path/filepath"
)
// File is a generated file of a given type with associated metadata.
type File struct {
Name string
FileType string
Header []byte
Size int64
Payload []byte
}
// NativeSupportedFileTypes returns a list of file types httpfuzz can generate by default.
func NativeSupportedFileTypes() []string {
keys := []string{}
for key := range headerRegistry {
keys = append(keys, key)
}
return keys
}
// GenerateFile creates valid files of a given type with zeroes in the body.
// It is meant to fuzz files to test file upload.
func GenerateFile(fileType string, size int64, extraExtension string) (*File, error) {
header, found := headerRegistry[fileType]
if !found {
return nil, fmt.Errorf("unsupported file type")
}
payload := make([]byte, size)
// fill the body with random bytes
_, err := rand.Read(payload)
if err != nil {
return nil, err
}
for index, char := range header {
payload[index] = char
}
filename := fmt.Sprintf("name.%s", fileType)
if extraExtension != "" {
filename = fmt.Sprintf("%s.%s", filename, extraExtension)
}
return &File{
Name: filename,
FileType: fileType,
Header: header,
Size: size,
Payload: payload,
}, nil
}
// FileFrom loads a file from the filesystem and wraps it in our native File type.
func FileFrom(path string, extraExtension string) (*File, error) {
fileBytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
filename := filepath.Base(path)
if extraExtension != "" {
filename = fmt.Sprintf("%s.%s", filename, extraExtension)
}
return &File{
Name: filename,
FileType: filepath.Ext(path),
Size: int64(len(fileBytes)),
Payload: fileBytes,
}, nil
}