/
reader.go
219 lines (197 loc) · 5.53 KB
/
reader.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
package reader
import (
"bufio"
"compress/gzip"
"io"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
"github.com/colinnewell/pcap-cli/tcp"
"github.com/google/gopacket"
"github.com/google/gopacket/tcpassembly/tcpreader"
)
type HTTPConversationReaders struct {
mu sync.Mutex
conversations map[ConversationAddress][]Conversation
}
type ConversationAddress struct {
IP, Port gopacket.Flow
}
type Conversation struct {
Address ConversationAddress
Request *http.Request
RequestBody []byte
Response *http.Response
ResponseBody []byte
RequestSeen []time.Time
ResponseSeen []time.Time
// FastCGI info if present
Errors []string
}
func New() *HTTPConversationReaders {
conversations := make(map[ConversationAddress][]Conversation)
return &HTTPConversationReaders{
conversations: conversations,
}
}
type streamDecoder func(*tcp.SavePointReader, *tcp.TimeCaptureReader, gopacket.Flow, gopacket.Flow) error
func drain(spr *tcp.SavePointReader, _ *tcp.TimeCaptureReader, _, _ gopacket.Flow) error {
tcpreader.DiscardBytesToEOF(spr)
return nil
}
// ReadStream tries to read tcp connections and extract HTTP conversations.
func (h *HTTPConversationReaders) ReadStream(r tcp.Stream, a, b gopacket.Flow, completed chan interface{}) {
t := tcp.NewTimeCaptureReader(r)
spr := tcp.NewSavePointReader(t)
decoders := []streamDecoder{
h.ReadHTTPRequest,
h.ReadHTTPResponse,
h.ReadFCGIRequest,
drain,
}
for {
for i, decode := range decoders {
err := decode(spr, t, a, b)
if err == nil {
break
}
if err == io.EOF {
return
} else if err != nil {
// don't need to restore before the last one
if i+1 < len(decoders) {
// can discard the save point on the final restore
spr.Restore(i < len(decoders))
}
}
}
t.Reset()
}
}
func (h *HTTPConversationReaders) GetConversations() []Conversation {
var conversations []Conversation
for _, c := range h.conversations {
conversations = append(conversations, c...)
}
return conversations
}
// ReadHTTPResponse try to read the stream as an HTTP response.
func (h *HTTPConversationReaders) ReadHTTPResponse(spr *tcp.SavePointReader, t *tcp.TimeCaptureReader, a, b gopacket.Flow) error {
buf := bufio.NewReader(spr)
res, err := http.ReadResponse(buf, nil)
if err != nil {
return err
}
spr.SavePoint()
defer res.Body.Close()
var reader io.ReadCloser
if res.Header.Get("Content-Encoding") == "gzip" {
reader, err = gzip.NewReader(res.Body)
if err != nil {
// just get it raw
reader = res.Body
} else {
defer reader.Close()
}
} else {
reader = res.Body
}
body, err := ioutil.ReadAll(reader)
// unexpected EOF reading trailer seems to indicate truncated stream when
// dealing with chunked encdoing. If we fall back to not reading it, we
// still have the same basic output, just with all the chunking arterfacts.
if err != nil && err.Error() != "http: unexpected EOF reading trailer" {
spr.Restore(true)
buf = bufio.NewReader(spr)
body, err = ioutil.ReadAll(buf)
if err != nil {
log.Println("Got an error trying to read it raw, let's just discard")
tcpreader.DiscardBytesToEOF(buf)
}
}
h.addResponse(a, b, res, body, t.Seen())
return err
}
// ReadHTTPRequest try to read the stream as an HTTP request.
func (h *HTTPConversationReaders) ReadHTTPRequest(spr *tcp.SavePointReader, t *tcp.TimeCaptureReader, a, b gopacket.Flow) error {
spr.SavePoint()
buf := bufio.NewReader(spr)
req, err := http.ReadRequest(buf)
if err != nil {
return err
}
spr.SavePoint()
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
spr.Restore(true)
buf = bufio.NewReader(spr)
body, err = ioutil.ReadAll(buf)
if err != nil {
log.Println("Got an error trying to read it raw, let's just discard")
tcpreader.DiscardBytesToEOF(buf)
}
}
h.addRequest(a, b, req, body, t.Seen())
return err
}
func (h *HTTPConversationReaders) addRequest(a, b gopacket.Flow, req *http.Request, body []byte, seen []time.Time) {
address := ConversationAddress{IP: a, Port: b}
h.mu.Lock()
defer h.mu.Unlock()
conversations := h.conversations[address]
for n := 0; n < len(conversations); n++ {
c := conversations[n]
if conversations[n].Request == nil {
c.Request = req
c.RequestBody = body
c.RequestSeen = seen
h.conversations[address][n] = c
return
}
}
h.conversations[address] = append(h.conversations[address], Conversation{
Address: address,
Request: req,
RequestBody: body,
RequestSeen: seen,
})
}
func (h *HTTPConversationReaders) addErrorToResponse(a, b gopacket.Flow, errString string) {
h.updateResponse(a, b, func(c *Conversation) {
c.Errors = append(c.Errors, errString)
})
}
func (h *HTTPConversationReaders) addResponse(a, b gopacket.Flow, res *http.Response, body []byte, seen []time.Time) {
h.updateResponse(a, b, func(c *Conversation) {
c.Response = res
c.ResponseBody = body
c.ResponseSeen = seen
})
}
func (h *HTTPConversationReaders) updateResponse(a, b gopacket.Flow, update func(*Conversation)) {
address := ConversationAddress{IP: a.Reverse(), Port: b.Reverse()}
h.mu.Lock()
defer h.mu.Unlock()
conversations := h.conversations[address]
if conversations == nil {
c := Conversation{
Address: address,
}
update(&c)
h.conversations[address] = append(h.conversations[address], c)
return
}
for n := 0; n < len(conversations); n++ {
c := conversations[n]
if conversations[n].Response == nil {
update(&c)
h.conversations[address][n] = c
break
}
// FIXME: should think about what we do when we don't find
// the other side of the conversation.
}
}