-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
299 lines (256 loc) · 8.41 KB
/
main.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
package main
import (
//"strconv"
"bufio"
"bytes"
crypto_rand "crypto/rand"
"encoding/binary"
"flag"
"fmt"
"hash/crc64"
"io"
"io/ioutil"
"log"
math_rand "math/rand"
"net"
"net/http"
"os"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/examples/util"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/tcpassembly"
"github.com/google/gopacket/tcpassembly/tcpreader"
)
var fwdDestination = flag.String("destination", "", "Destination of the forwarded requests.")
var fwdPerc = flag.Float64("percentage", 100, "Must be between 0 and 100.")
var fwdBy = flag.String("percentage-by", "", "Can be empty. Otherwise, valid values are: header, remoteaddr.")
var fwdHeader = flag.String("percentage-by-header", "", "If percentage-by is header, then specify the header here.")
var reqPort = flag.Int("filter-request-port", 8080, "Must be between 0 and 65535.")
var xInterface = flag.String("interface", "vxlan0", "Network interface.")
// Build a simple HTTP request parser using tcpassembly.StreamFactory and tcpassembly.Stream interfaces
// httpStreamFactory implements tcpassembly.StreamFactory
type httpStreamFactory struct{}
// httpStream will handle the actual decoding of http requests.
type httpStream struct {
net, transport gopacket.Flow
r tcpreader.ReaderStream
}
func (h *httpStreamFactory) New(net, transport gopacket.Flow) tcpassembly.Stream {
hstream := &httpStream{
net: net,
transport: transport,
r: tcpreader.NewReaderStream(),
}
go hstream.run() // Important... we must guarantee that data from the reader stream is read.
// ReaderStream implements tcpassembly.Stream, so we can return a pointer to it.
return &hstream.r
}
func (h *httpStream) run() {
buf := bufio.NewReader(&h.r)
for {
req, err := http.ReadRequest(buf)
if err == io.EOF {
log.Println("Stream EOF")
return
} else if err != nil {
log.Println("Error reading stream", h.net, h.transport, ":", err)
} else {
reqSourceIP := h.net.Src().String()
reqDestionationPort := h.transport.Dst().String()
// bodyBytes := tcpreader.DiscardBytesToEOF(req.Body)
// fmt.Println(bodyBytes)
/*
originalLen, err := strconv.Atoi(req.Header.Get("Content-Length"))
if err != nil {
log.Println("Invalid content lenght")
log.Println(err)
return
}
all := make([]byte, 0)
if originalLen > 0 {
for {
tmp := make([]byte, 256, 256)
n, err := req.Body.Read(tmp)
log.Printf("Readed %d bytes...\n", n)
all = append(all, tmp[:n]...)
if err == io.EOF {
log.Println("Good body EOF")
break
}
if err != nil && err != io.EOF {
log.Printf("Unexpected body EOF: %s\n", err)
if err.Error() == "unexpected EOF" {
log.Println("Wait for magic...")
} else {
return
}
}
if len(all) >= originalLen {
break
}
}
}
if len(all)!= originalLen {
log.Println("Body len mismatch")
return
}
*/
body, bErr := ioutil.ReadAll(req.Body)
if bErr != nil {
log.Println("Error reading body", ":", bErr)
return
}
req.Body.Close()
go forwardRequest(req, reqSourceIP, reqDestionationPort, body)
}
}
}
func forwardRequest(req *http.Request, reqSourceIP string, reqDestionationPort string, body []byte) {
// if percentage flag is not 100, then a percentage of requests is skipped
if *fwdPerc != 100 {
var uintForSeed uint64
if *fwdBy == "" {
// if percentage-by is empty, then forward only a certain percentage of requests
var b [8]byte
_, err := crypto_rand.Read(b[:])
if err != nil {
log.Println("Error generating crypto random unit for seed", ":", err)
return
}
// uintForSeed is random
uintForSeed = binary.LittleEndian.Uint64(b[:])
} else {
// if percentage-by is not empty, then forward only requests from a certain percentage of headers/remoteaddresses
strForSeed := ""
if *fwdBy == "header" {
strForSeed = req.Header.Get(*fwdHeader)
} else {
strForSeed = reqSourceIP
}
crc64Table := crc64.MakeTable(0xC96C5795D7870F42)
// uintForSeed is derived from strForSeed
uintForSeed = crc64.Checksum([]byte(strForSeed), crc64Table)
}
// generate a consistent random number from the variable uintForSeed
math_rand.Seed(int64(uintForSeed))
randomPercent := math_rand.Float64() * 100
// skip a percentage of requests
if randomPercent > *fwdPerc {
return
}
}
// create a new url from the raw RequestURI sent by the client
url := fmt.Sprintf("%s%s", string(*fwdDestination), req.RequestURI)
log.Printf("New url %s\n", url)
// create a new HTTP request
forwardReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
if err != nil {
return
}
// add headers to the new HTTP request
for header, values := range req.Header {
for _, value := range values {
forwardReq.Header.Add(header, value)
}
}
// Append to X-Forwarded-For the IP of the client or the IP of the latest proxy (if any proxies are in between)
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
forwardReq.Header.Add("X-Forwarded-For", reqSourceIP)
// The three following headers should contain 1 value only, i.e. the outermost port, protocol, and host
// https://tools.ietf.org/html/rfc7239#section-5.4
if forwardReq.Header.Get("X-Forwarded-Port") == "" {
forwardReq.Header.Set("X-Forwarded-Port", reqDestionationPort)
}
if forwardReq.Header.Get("X-Forwarded-Proto") == "" {
forwardReq.Header.Set("X-Forwarded-Proto", "http")
}
if forwardReq.Header.Get("X-Forwarded-Host") == "" {
forwardReq.Header.Set("X-Forwarded-Host", req.Host)
}
// Execute the new HTTP request
httpClient := &http.Client{}
resp, rErr := httpClient.Do(forwardReq)
if rErr != nil {
log.Println("Forward request error", ":", err)
return
}
log.Printf("%s, body size = %d\n", url, len(body))
defer resp.Body.Close()
}
// Listen for incoming connections.
func openTCPClient() {
ln, err := net.Listen("tcp", ":4789")
if err != nil {
// If TCP listener cannot be established, NLB health checks would fail
// For this reason, we OS.exit
log.Println("Error listening on TCP", ":", err)
os.Exit(1)
}
log.Println("Listening on TCP 4789")
for {
// Listen for an incoming connection and close it immediately.
conn, _ := ln.Accept()
conn.Close()
}
}
func main() {
defer util.Run()()
var handle *pcap.Handle
var err error
flag.Parse()
//labels validation
if *fwdPerc > 100 || *fwdPerc < 0 {
err = fmt.Errorf("Flag percentage is not between 0 and 100. Value: %f.", *fwdPerc)
} else if *fwdBy != "" && *fwdBy != "header" && *fwdBy != "remoteaddr" {
err = fmt.Errorf("Flag percentage-by (%s) is not valid.", *fwdBy)
} else if *fwdBy == "header" && *fwdHeader == "" {
err = fmt.Errorf("Flag percentage-by is set to header, but percentage-by-header is empty.")
} else if *reqPort > 65535 || *reqPort < 0 {
err = fmt.Errorf("Flag filter-request-port is not between 0 and 65535. Value: %f.", *fwdPerc)
}
if err != nil {
log.Fatal(err)
}
// Set up pcap packet capture
log.Printf("Starting capture on interface vxlan0")
handle, err = pcap.OpenLive(*xInterface, 8951, true, pcap.BlockForever)
if err != nil {
log.Fatal(err)
}
BPFFilter := fmt.Sprintf("%s%d", "tcp and dst port ", *reqPort)
if err := handle.SetBPFFilter(BPFFilter); err != nil {
log.Fatal(err)
}
// Set up assembly
streamFactory := &httpStreamFactory{}
streamPool := tcpassembly.NewStreamPool(streamFactory)
assembler := tcpassembly.NewAssembler(streamPool)
log.Println("reading in packets")
// Read in packets, pass to assembler.
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
packets := packetSource.Packets()
ticker := time.Tick(time.Minute)
//Open a TCP Client, for NLB Health Checks only
//go openTCPClient()
log.Println("Starting loop")
for {
select {
case packet := <-packets:
// A nil packet indicates the end of a pcap file.
if packet == nil {
return
}
if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
log.Println("Unusable packet")
continue
}
tcp := packet.TransportLayer().(*layers.TCP)
assembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)
case <-ticker:
// Every minute, flush connections that haven't seen activity in the past 1 minute.
assembler.FlushOlderThan(time.Now().Add(time.Minute * -1))
}
}
}