/
parser.go
67 lines (58 loc) · 1.92 KB
/
parser.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
package httpfuzz
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
// RequestFromFile parses an HTTP request from a file.
func RequestFromFile(filename string) (*Request, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
// Since we're letting the user specify injection points with a delimiter, the content length in the header will not match the body.
// Making them fix it by hand is awful so let's calculate it for them.
// This code only runs once at program startup: we're taking the performance hit now so the rest of the program can be efficient and usable.
diskRequestBytes, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
// Move back to the head of the file so Go's parser can read it
_, err = file.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
req, err := http.ReadRequest(bufio.NewReader(file))
if err != nil {
return nil, err
}
// We don't need to hack up the request body if there isn't one.
if req.ContentLength == 0 {
// Wrap the request in our native Request type for the rest of the program.
return &Request{req}, nil
}
// Replace the body in the seed request with the body on disk and adjust the content length.
// I know this is hacky, but there's tests and this is easier than reimplimenting http.ReadRequest.
bodyOffset := bytes.Index(diskRequestBytes, []byte("\n\n"))
if bodyOffset == -1 {
// Check for unix line endings too
bodyOffset = bytes.Index(diskRequestBytes, []byte("\r\n\r\n"))
if bodyOffset == -1 {
return nil, fmt.Errorf("invalid HTTP request provided")
} else {
bodyOffset += 4
}
} else {
bodyOffset += 2
}
diskBodyBytes := diskRequestBytes[bodyOffset:]
req.Body = ioutil.NopCloser(bytes.NewReader(diskBodyBytes))
req.ContentLength = int64(len(diskBodyBytes))
// Wrap the request in our native Request type for the rest of the program.
return &Request{req}, nil
}