-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
772 lines (644 loc) · 17.4 KB
/
http.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
package http
import (
"bytes"
"expvar"
"fmt"
"net/url"
"strings"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/procs"
"github.com/elastic/beats/packetbeat/protos"
"github.com/elastic/beats/packetbeat/protos/tcp"
"github.com/elastic/beats/packetbeat/publish"
)
var debugf = logp.MakeDebug("http")
var detailedf = logp.MakeDebug("httpdetailed")
type parserState uint8
const (
stateStart parserState = iota
stateFLine
stateHeaders
stateBody
stateBodyChunkedStart
stateBodyChunked
stateBodyChunkedWaitFinalCRLF
)
var (
unmatchedResponses = expvar.NewInt("http.unmatched_responses")
)
type stream struct {
tcptuple *common.TCPTuple
data []byte
parseOffset int
parseState parserState
bodyReceived int
message *message
}
type httpConnectionData struct {
streams [2]*stream
requests messageList
responses messageList
}
type messageList struct {
head, tail *message
}
// HTTP application level protocol analyser plugin.
type httpPlugin struct {
// config
ports []int
sendRequest bool
sendResponse bool
splitCookie bool
hideKeywords []string
redactAuthorization bool
includeBodyFor []string
maxMessageSize int
parserConfig parserConfig
transactionTimeout time.Duration
results publish.Transactions
}
var (
isDebug = false
isDetailed = false
)
func init() {
protos.Register("http", New)
}
func New(
testMode bool,
results publish.Transactions,
cfg *common.Config,
) (protos.Plugin, error) {
p := &httpPlugin{}
config := defaultConfig
if !testMode {
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
}
if err := p.init(results, &config); err != nil {
return nil, err
}
return p, nil
}
// Init initializes the HTTP protocol analyser.
func (http *httpPlugin) init(results publish.Transactions, config *httpConfig) error {
http.setFromConfig(config)
isDebug = logp.IsDebug("http")
isDetailed = logp.IsDebug("httpdetailed")
http.results = results
return nil
}
func (http *httpPlugin) setFromConfig(config *httpConfig) {
http.ports = config.Ports
http.sendRequest = config.SendRequest
http.sendResponse = config.SendResponse
http.hideKeywords = config.HideKeywords
http.redactAuthorization = config.RedactAuthorization
http.splitCookie = config.SplitCookie
http.parserConfig.realIPHeader = strings.ToLower(config.RealIPHeader)
http.transactionTimeout = config.TransactionTimeout
http.includeBodyFor = config.IncludeBodyFor
http.maxMessageSize = config.MaxMessageSize
if config.SendAllHeaders {
http.parserConfig.sendHeaders = true
http.parserConfig.sendAllHeaders = true
} else {
if len(config.SendHeaders) > 0 {
http.parserConfig.sendHeaders = true
http.parserConfig.headersWhitelist = map[string]bool{}
for _, hdr := range config.SendHeaders {
http.parserConfig.headersWhitelist[strings.ToLower(hdr)] = true
}
}
}
}
// GetPorts lists the port numbers the HTTP protocol analyser will handle.
func (http *httpPlugin) GetPorts() []int {
return http.ports
}
// messageGap is called when a gap of size `nbytes` is found in the
// tcp stream. Decides if we can ignore the gap or it's a parser error
// and we need to drop the stream.
func (http *httpPlugin) messageGap(s *stream, nbytes int) (ok bool, complete bool) {
m := s.message
switch s.parseState {
case stateStart, stateHeaders:
// we know we cannot recover from these
return false, false
case stateBody:
if isDebug {
debugf("gap in body: %d", nbytes)
}
if m.isRequest {
m.notes = append(m.notes, "Packet loss while capturing the request")
} else {
m.notes = append(m.notes, "Packet loss while capturing the response")
}
if !m.hasContentLength && (bytes.Equal(m.connection, constClose) ||
(isVersion(m.version, 1, 0) && !bytes.Equal(m.connection, constKeepAlive))) {
s.bodyReceived += nbytes
m.contentLength += nbytes
return true, false
} else if len(s.data[s.parseOffset:])+nbytes >= m.contentLength-s.bodyReceived {
// we're done, but the last portion of the data is gone
m.end = s.parseOffset
return true, true
} else {
s.bodyReceived += nbytes
return true, false
}
}
// assume we cannot recover
return false, false
}
func (st *stream) PrepareForNewMessage() {
st.data = st.data[st.message.end:]
st.parseState = stateStart
st.parseOffset = 0
st.bodyReceived = 0
st.message = nil
}
// Called when the parser has identified the boundary
// of a message.
func (http *httpPlugin) messageComplete(
conn *httpConnectionData,
tcptuple *common.TCPTuple,
dir uint8,
st *stream,
) {
st.message.raw = st.data[st.message.start:st.message.end]
http.handleHTTP(conn, st.message, tcptuple, dir)
}
// ConnectionTimeout returns the configured HTTP transaction timeout.
func (http *httpPlugin) ConnectionTimeout() time.Duration {
return http.transactionTimeout
}
// Parse function is used to process TCP payloads.
func (http *httpPlugin) Parse(
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
defer logp.Recover("ParseHttp exception")
conn := ensureHTTPConnection(private)
conn = http.doParse(conn, pkt, tcptuple, dir)
if conn == nil {
return nil
}
return conn
}
func ensureHTTPConnection(private protos.ProtocolData) *httpConnectionData {
conn := getHTTPConnection(private)
if conn == nil {
conn = &httpConnectionData{}
}
return conn
}
func getHTTPConnection(private protos.ProtocolData) *httpConnectionData {
if private == nil {
return nil
}
priv, ok := private.(*httpConnectionData)
if !ok {
logp.Warn("http connection data type error")
return nil
}
if priv == nil {
logp.Warn("Unexpected: http connection data not set")
return nil
}
return priv
}
// Parse function is used to process TCP payloads.
func (http *httpPlugin) doParse(
conn *httpConnectionData,
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
) *httpConnectionData {
if isDetailed {
detailedf("Payload received: [%s]", pkt.Payload)
}
extraMsgSize := 0 // size of a "seen" packet for which we don't store the actual bytes
st := conn.streams[dir]
if st == nil {
st = newStream(pkt, tcptuple)
conn.streams[dir] = st
} else {
// concatenate bytes
if len(st.data)+len(pkt.Payload) > http.maxMessageSize {
if isDebug {
debugf("Stream data too large, ignoring message")
}
extraMsgSize = len(pkt.Payload)
} else {
st.data = append(st.data, pkt.Payload...)
}
}
for len(st.data) > 0 {
if st.message == nil {
st.message = &message{ts: pkt.Ts}
}
parser := newParser(&http.parserConfig)
ok, complete := parser.parse(st, extraMsgSize)
if !ok {
// drop this tcp stream. Will retry parsing with the next
// segment in it
conn.streams[dir] = nil
return conn
}
if !complete {
// wait for more data
break
}
// all ok, ship it
http.messageComplete(conn, tcptuple, dir, st)
// and reset stream for next message
st.PrepareForNewMessage()
}
return conn
}
func newStream(pkt *protos.Packet, tcptuple *common.TCPTuple) *stream {
return &stream{
tcptuple: tcptuple,
data: pkt.Payload,
message: &message{ts: pkt.Ts},
}
}
// ReceivedFin will be called when TCP transaction is terminating.
func (http *httpPlugin) ReceivedFin(tcptuple *common.TCPTuple, dir uint8,
private protos.ProtocolData) protos.ProtocolData {
debugf("Received FIN")
conn := getHTTPConnection(private)
if conn == nil {
return private
}
stream := conn.streams[dir]
if stream == nil {
return conn
}
// send whatever data we got so far as complete. This
// is needed for the HTTP/1.0 without Content-Length situation.
if stream.message != nil && len(stream.data[stream.message.start:]) > 0 {
stream.message.raw = stream.data[stream.message.start:]
http.handleHTTP(conn, stream.message, tcptuple, dir)
// and reset message. Probably not needed, just to be sure.
stream.PrepareForNewMessage()
}
return conn
}
// GapInStream is called when a gap of nbytes bytes is found in the stream (due
// to packet loss).
func (http *httpPlugin) GapInStream(tcptuple *common.TCPTuple, dir uint8,
nbytes int, private protos.ProtocolData) (priv protos.ProtocolData, drop bool) {
defer logp.Recover("GapInStream(http) exception")
conn := getHTTPConnection(private)
if conn == nil {
return private, false
}
stream := conn.streams[dir]
if stream == nil || stream.message == nil {
// nothing to do
return private, false
}
ok, complete := http.messageGap(stream, nbytes)
if isDetailed {
detailedf("messageGap returned ok=%v complete=%v", ok, complete)
}
if !ok {
// on errors, drop stream
conn.streams[dir] = nil
return conn, true
}
if complete {
// Current message is complete, we need to publish from here
http.messageComplete(conn, tcptuple, dir, stream)
}
// don't drop the stream, we can ignore the gap
return private, false
}
func (http *httpPlugin) handleHTTP(
conn *httpConnectionData,
m *message,
tcptuple *common.TCPTuple,
dir uint8,
) {
m.tcpTuple = *tcptuple
m.direction = dir
m.cmdlineTuple = procs.ProcWatcher.FindProcessesTuple(tcptuple.IPPort())
http.hideHeaders(m)
if m.isRequest {
if isDebug {
debugf("Received request with tuple: %s", m.tcpTuple)
}
conn.requests.append(m)
} else {
if isDebug {
debugf("Received response with tuple: %s", m.tcpTuple)
}
conn.responses.append(m)
http.correlate(conn)
}
}
func (http *httpPlugin) correlate(conn *httpConnectionData) {
// drop responses with missing requests
if conn.requests.empty() {
for !conn.responses.empty() {
debugf("Response from unknown transaction. Ingoring.")
unmatchedResponses.Add(1)
conn.responses.pop()
}
return
}
// merge requests with responses into transactions
for !conn.responses.empty() && !conn.requests.empty() {
requ := conn.requests.pop()
resp := conn.responses.pop()
trans := http.newTransaction(requ, resp)
if isDebug {
debugf("HTTP transaction completed")
}
http.publishTransaction(trans)
}
}
func (http *httpPlugin) newTransaction(requ, resp *message) common.MapStr {
status := common.OK_STATUS
if resp.statusCode >= 400 {
status = common.ERROR_STATUS
}
// resp_time in milliseconds
responseTime := int32(resp.ts.Sub(requ.ts).Nanoseconds() / 1e6)
path, params, err := http.extractParameters(requ, requ.raw)
if err != nil {
logp.Warn("Fail to parse HTTP parameters: %v", err)
}
src := common.Endpoint{
IP: requ.tcpTuple.SrcIP.String(),
Port: requ.tcpTuple.SrcPort,
Proc: string(requ.cmdlineTuple.Src),
}
dst := common.Endpoint{
IP: requ.tcpTuple.DstIP.String(),
Port: requ.tcpTuple.DstPort,
Proc: string(requ.cmdlineTuple.Dst),
}
if requ.direction == tcp.TCPDirectionReverse {
src, dst = dst, src
}
httpDetails := common.MapStr{
"request": common.MapStr{
"params": params,
"headers": http.collectHeaders(requ),
},
"response": common.MapStr{
"code": resp.statusCode,
"phrase": resp.statusPhrase,
"headers": http.collectHeaders(resp),
},
}
http.setBody(httpDetails["request"].(common.MapStr), requ)
http.setBody(httpDetails["response"].(common.MapStr), resp)
event := common.MapStr{
"@timestamp": common.Time(requ.ts),
"type": "http",
"status": status,
"responsetime": responseTime,
"method": requ.method,
"path": path,
"query": fmt.Sprintf("%s %s", requ.method, path),
"http": httpDetails,
"bytes_out": resp.size,
"bytes_in": requ.size,
"src": &src,
"dst": &dst,
}
if http.sendRequest {
event["request"] = string(http.cutMessageBody(requ))
}
if http.sendResponse {
event["response"] = string(http.cutMessageBody(resp))
}
if len(requ.notes)+len(resp.notes) > 0 {
event["notes"] = append(requ.notes, resp.notes...)
}
if len(requ.realIP) > 0 {
event["real_ip"] = requ.realIP
}
return event
}
func (http *httpPlugin) publishTransaction(event common.MapStr) {
if http.results == nil {
return
}
http.results.PublishTransaction(event)
}
func (http *httpPlugin) collectHeaders(m *message) interface{} {
hdrs := map[string]interface{}{}
hdrs["content-length"] = m.contentLength
if len(m.contentType) > 0 {
hdrs["content-type"] = m.contentType
}
if http.parserConfig.sendHeaders {
cookie := "cookie"
if !m.isRequest {
cookie = "set-cookie"
}
for name, value := range m.headers {
if strings.ToLower(name) == "content-type" {
continue
}
if strings.ToLower(name) == "content-length" {
continue
}
if http.splitCookie && name == cookie {
hdrs[name] = splitCookiesHeader(string(value))
} else {
hdrs[name] = value
}
}
}
return hdrs
}
func (http *httpPlugin) setBody(result common.MapStr, m *message) {
body := string(http.extractBody(m))
if len(body) > 0 {
result["body"] = body
}
}
func splitCookiesHeader(headerVal string) map[string]string {
cookies := map[string]string{}
cstring := strings.Split(headerVal, ";")
for _, cval := range cstring {
cookie := strings.SplitN(cval, "=", 2)
if len(cookie) == 2 {
cookies[strings.ToLower(strings.TrimSpace(cookie[0]))] =
parseCookieValue(strings.TrimSpace(cookie[1]))
}
}
return cookies
}
func parseCookieValue(raw string) string {
// Strip the quotes, if present.
if len(raw) > 1 && raw[0] == '"' && raw[len(raw)-1] == '"' {
raw = raw[1 : len(raw)-1]
}
return raw
}
func (http *httpPlugin) extractBody(m *message) []byte {
body := []byte{}
if len(m.contentType) > 0 && http.shouldIncludeInBody(m.contentType) {
if len(m.chunkedBody) > 0 {
body = append(body, m.chunkedBody...)
} else {
if isDebug {
debugf("Body to include: [%s]", m.raw[m.bodyOffset:])
}
body = append(body, m.raw[m.bodyOffset:]...)
}
}
return body
}
func (http *httpPlugin) cutMessageBody(m *message) []byte {
cutMsg := []byte{}
// add headers always
cutMsg = m.raw[:m.bodyOffset]
// add body
return append(cutMsg, http.extractBody(m)...)
}
func (http *httpPlugin) shouldIncludeInBody(contenttype []byte) bool {
includedBodies := http.includeBodyFor
for _, include := range includedBodies {
if bytes.Contains(contenttype, []byte(include)) {
if isDebug {
debugf("Should Include Body = true Content-Type %s include_body %s",
contenttype, include)
}
return true
}
if isDebug {
debugf("Should Include Body = false Content-Type %s include_body %s",
contenttype, include)
}
}
return false
}
func (http *httpPlugin) hideHeaders(m *message) {
if !m.isRequest || !http.redactAuthorization {
return
}
msg := m.raw
// byte64 != encryption, so obscure it in headers in case of Basic Authentication
redactHeaders := []string{"authorization", "proxy-authorization"}
authText := []byte("uthorization:") // [aA] case insensitive, also catches Proxy-Authorization:
authHeaderStartX := m.headerOffset
authHeaderEndX := m.bodyOffset
for authHeaderStartX < m.bodyOffset {
if isDebug {
debugf("looking for authorization from %d to %d",
authHeaderStartX, authHeaderEndX)
}
startOfHeader := bytes.Index(msg[authHeaderStartX:m.bodyOffset], authText)
if startOfHeader >= 0 {
authHeaderStartX = authHeaderStartX + startOfHeader
endOfHeader := bytes.Index(msg[authHeaderStartX:m.bodyOffset], []byte("\r\n"))
if endOfHeader >= 0 {
authHeaderEndX = authHeaderStartX + endOfHeader
if authHeaderEndX > m.bodyOffset {
authHeaderEndX = m.bodyOffset
}
if isDebug {
debugf("Redact authorization from %d to %d", authHeaderStartX, authHeaderEndX)
}
for i := authHeaderStartX + len(authText); i < authHeaderEndX; i++ {
msg[i] = byte('*')
}
}
}
authHeaderStartX = authHeaderEndX + len("\r\n")
authHeaderEndX = m.bodyOffset
}
for _, header := range redactHeaders {
if len(m.headers[header]) > 0 {
m.headers[header] = []byte("*")
}
}
m.raw = msg
}
func (http *httpPlugin) hideSecrets(values url.Values) url.Values {
params := url.Values{}
for key, array := range values {
for _, value := range array {
if http.isSecretParameter(key) {
params.Add(key, "xxxxx")
} else {
params.Add(key, value)
}
}
}
return params
}
// extractParameters parses the URL and the form parameters and replaces the secrets
// with the string xxxxx. The parameters containing secrets are defined in http.Hide_secrets.
// Returns the Request URI path and the (adjusted) parameters.
func (http *httpPlugin) extractParameters(m *message, msg []byte) (path string, params string, err error) {
var values url.Values
u, err := url.Parse(string(m.requestURI))
if err != nil {
return
}
values = u.Query()
path = u.Path
paramsMap := http.hideSecrets(values)
if m.contentLength > 0 && bytes.Contains(m.contentType, []byte("urlencoded")) {
values, err = url.ParseQuery(string(msg[m.bodyOffset:]))
if err != nil {
return
}
for key, value := range http.hideSecrets(values) {
paramsMap[key] = value
}
}
params = paramsMap.Encode()
if isDetailed {
detailedf("Form parameters: %s", params)
}
return
}
func (http *httpPlugin) isSecretParameter(key string) bool {
for _, keyword := range http.hideKeywords {
if strings.ToLower(key) == keyword {
return true
}
}
return false
}
func (ml *messageList) append(msg *message) {
if ml.tail == nil {
ml.head = msg
} else {
ml.tail.next = msg
}
msg.next = nil
ml.tail = msg
}
func (ml *messageList) empty() bool {
return ml.head == nil
}
func (ml *messageList) pop() *message {
if ml.head == nil {
return nil
}
msg := ml.head
ml.head = ml.head.next
if ml.head == nil {
ml.tail = nil
}
return msg
}
func (ml *messageList) last() *message {
return ml.tail
}