-
Notifications
You must be signed in to change notification settings - Fork 51
/
helpers.go
407 lines (313 loc) · 11.4 KB
/
helpers.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
package packet
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"strconv"
"go.uber.org/zap"
"golang.org/x/net/ipv4"
)
// Helpher functions for the package, mainly for debugging and validation
// They are not used by the main package
// VerifyIPv4Checksum returns true if the IP header checksum is correct
// for this packet, false otherwise. Note that the checksum is not
// modified.
func (p *Packet) VerifyIPv4Checksum() bool {
sum := p.computeIPv4Checksum()
return sum == p.ipHdr.ipChecksum
}
// UpdateIPv4Checksum computes the IP header checksum and updates the
// packet with the value.
func (p *Packet) UpdateIPv4Checksum() {
p.ipHdr.ipChecksum = p.computeIPv4Checksum()
binary.BigEndian.PutUint16(p.ipHdr.Buffer[ipv4ChecksumPos:ipv4ChecksumPos+2], p.ipHdr.ipChecksum)
}
// VerifyTCPChecksum returns true if the TCP header checksum is correct
// for this packet, false otherwise. Note that the checksum is not
// modified.
func (p *Packet) VerifyTCPChecksum() bool {
sum := p.computeTCPChecksum()
return sum == p.tcpHdr.tcpChecksum
}
// UpdateTCPChecksum computes the TCP header checksum and updates the
// packet with the value.
func (p *Packet) UpdateTCPChecksum() {
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
p.tcpHdr.tcpChecksum = p.computeTCPChecksum()
binary.BigEndian.PutUint16(buffer[tcpChecksumPos:tcpChecksumPos+2], p.tcpHdr.tcpChecksum)
}
// UpdateTCPFlags
func (p *Packet) updateTCPFlags(tcpFlags uint8) {
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
buffer[tcpFlagsOffsetPos] = tcpFlags
}
// ConvertAcktoFinAck function removes the data from the packet
// It is called only if the packet is Ack or Psh/Ack
// converts psh/ack to fin/ack packet.
func (p *Packet) ConvertAcktoFinAck() error {
var tcpFlags uint8
tcpFlags = tcpFlags | TCPFinMask
tcpFlags = tcpFlags | TCPAckMask
p.updateTCPFlags(tcpFlags)
p.tcpHdr.tcpFlags = tcpFlags
if err := p.TCPDataDetach(0); err != nil {
return fmt.Errorf("ack packet in wrong format")
}
p.DropTCPDetachedBytes()
return nil
}
//PacketToStringTCP returns a string representation of fields contained in this packet.
func (p *Packet) PacketToStringTCP() string {
var buf bytes.Buffer
buf.WriteString("(error)")
header, err := ipv4.ParseHeader(p.ipHdr.Buffer)
if err == nil {
buf.Reset()
buf.WriteString(header.String())
buf.WriteString(" srcport=")
buf.WriteString(strconv.Itoa(int(p.SourcePort())))
buf.WriteString(" dstport=")
buf.WriteString(strconv.Itoa(int(p.DestPort())))
buf.WriteString(" tcpcksum=")
buf.WriteString(fmt.Sprintf("0x%0x", p.tcpHdr.tcpChecksum))
buf.WriteString(" data")
buf.WriteString(hex.EncodeToString(p.GetTCPBytes()))
}
return buf.String()
}
// Computes the IP header checksum. The packet is not modified.
func (p *Packet) computeIPv4Checksum() uint16 {
// IP packet checksum is computed with the checksum value set to zero
p.ipHdr.Buffer[ipv4ChecksumPos] = 0
p.ipHdr.Buffer[ipv4ChecksumPos+1] = 0
// Compute checksum, over IP header only
sum := checksum(p.ipHdr.Buffer[:p.ipHdr.ipHeaderLen])
// Restore the previous checksum (whether correct or not, as this function doesn't change it)
binary.BigEndian.PutUint16(p.ipHdr.Buffer[ipv4ChecksumPos:ipv4ChecksumPos+2], p.ipHdr.ipChecksum)
return sum
}
// Computes the TCP header checksum. The packet is not modified.
func (p *Packet) computeTCPChecksum() uint16 {
var csum uint32
var buf [2]byte
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
tcpBufSize := uint16(len(buffer) + len(p.tcpHdr.tcpData) + len(p.tcpHdr.tcpOptions))
oldCsumLow := buffer[tcpChecksumPos]
oldCsumHigh := buffer[tcpChecksumPos+1]
// Put 0 to calculate the checksum. We will reset it back after the checksum
buffer[tcpChecksumPos] = 0
buffer[tcpChecksumPos+1] = 0
if p.ipHdr.version == V4 {
csum = partialChecksum(0, p.ipHdr.Buffer[ipv4SourceAddrPos:ipv4SourceAddrPos+4])
csum = partialChecksum(csum, p.ipHdr.Buffer[ipv4DestAddrPos:ipv4DestAddrPos+4])
} else {
csum = partialChecksum(0, p.ipHdr.Buffer[ipv6SourceAddrPos:ipv6SourceAddrPos+16])
csum = partialChecksum(csum, p.ipHdr.Buffer[ipv6DestAddrPos:ipv6DestAddrPos+16])
}
// reserved 0 byte
buf[0] = 0
// tcp option 6
buf[1] = 6
csum = partialChecksum(csum, buf[:])
binary.BigEndian.PutUint16(buf[:], tcpBufSize)
csum = partialChecksum(csum, buf[:])
csum = partialChecksum(csum, buffer)
csum = partialChecksum(csum, p.tcpHdr.tcpOptions)
csum = partialChecksum(csum, p.tcpHdr.tcpData)
csum16 := finalizeChecksum(csum)
// restore the checksum
buffer[tcpChecksumPos] = oldCsumLow
buffer[tcpChecksumPos+1] = oldCsumHigh
return csum16
}
// incCsum16 implements rfc1624, equation 3.
func incCsum16(start, old, new uint16) uint16 {
start = start ^ 0xffff
old = old ^ 0xffff
csum := uint32(start) + uint32(old) + uint32(new)
for (csum >> 16) > 0 {
csum = (csum & 0xffff) + ((csum >> 16) & 0xffff)
}
csum = csum ^ 0xffff
return uint16(csum)
}
func csumConvert32To16bit(sum uint32) uint16 {
for sum > 0xffff {
sum = (sum >> 16) + (sum & 0xffff)
}
return uint16(sum)
}
// Computes a sum of 16 bit numbers
func checksumDelta(init uint32, buf []byte) uint32 {
sum := init
for ; len(buf) >= 2; buf = buf[2:] {
sum += uint32(buf[0])<<8 | uint32(buf[1])
}
if len(buf) > 0 {
sum += uint32(buf[0]) << 8
}
return sum
}
// Computes a checksum over the given slice.
func checksum(buf []byte) uint16 {
sum32 := checksumDelta(0, buf)
sum16 := csumConvert32To16bit(sum32)
csum := ^sum16
return csum
}
func partialChecksum(csum uint32, buf []byte) uint32 {
return checksumDelta(csum, buf)
}
func finalizeChecksum(csum32 uint32) uint16 {
csum16 := csumConvert32To16bit(csum32)
csum := ^csum16
return csum
}
func (p *Packet) updateUDPv6Checksum() {
var csum uint32
var tmp [4]byte
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
csum = partialChecksum(0, p.ipHdr.sourceAddress)
csum = partialChecksum(csum, p.ipHdr.destinationAddress)
binary.BigEndian.PutUint32(tmp[:], uint32(len(buffer)))
csum = partialChecksum(csum, tmp[:])
tmp = [4]byte{0, 0, 0, 17}
csum = partialChecksum(csum, tmp[:])
buffer[udpChecksumPos] = 0
buffer[udpChecksumPos+1] = 0
csum = partialChecksum(csum, buffer[:])
p.udpHdr.udpChecksum = finalizeChecksum(csum)
// update checksum
binary.BigEndian.PutUint16(buffer[udpChecksumPos:udpChecksumPos+2], p.udpHdr.udpChecksum)
}
func (p *Packet) fixupUDPHdr() {
// checksum set to 0, ignored by the stack
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
binary.BigEndian.PutUint16(buffer[udpLengthPos:udpLengthPos+2], uint16(len(buffer)))
}
func (p *Packet) fixupUDPChecksum() {
if p.ipHdr.version == V4 {
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
buffer[udpChecksumPos] = 0
buffer[udpChecksumPos+1] = 0
} else {
p.updateUDPv6Checksum()
}
}
// ReadUDPToken returnthe UDP token. Gets called only during the handshake process.
func (p *Packet) ReadUDPToken() []byte {
buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
// 8 byte udp header, 20 byte udp marker
if len(buffer) <= udpJwtTokenOffset {
return []byte{}
}
return buffer[udpJwtTokenOffset:]
}
// UDPTokenAttach attached udp packet signature and tokens.
func (p *Packet) UDPTokenAttach(udpdata []byte, udptoken []byte) {
udpData := []byte{}
udpData = append(udpData, udpdata...)
udpData = append(udpData, udptoken...)
p.udpHdr.udpData = udpData
packetLenIncrease := uint16(len(udpdata) + len(udptoken))
// IP Header Processing
p.FixupIPHdrOnDataModify(p.ipHdr.ipTotalLength, p.ipHdr.ipTotalLength+packetLenIncrease)
// Attach Data @ the end of current buffer
p.ipHdr.Buffer = append(p.ipHdr.Buffer, udpData...)
p.fixupUDPHdr()
p.fixupUDPChecksum()
}
// UDPDataAttach Attaches UDP data post encryption.
func (p *Packet) UDPDataAttach(header, udpdata []byte) {
// Attach Data @ the end of current buffer
p.ipHdr.Buffer = append(p.ipHdr.Buffer, header...)
p.ipHdr.Buffer = append(p.ipHdr.Buffer, udpdata...)
// IP Header Processing
p.FixupIPHdrOnDataModify(p.ipHdr.ipTotalLength, uint16(len(p.ipHdr.Buffer)))
p.fixupUDPHdr()
p.fixupUDPChecksum()
}
// UDPDataDetach detaches UDP payload from the Buffer. Called only during Encrypt/Decrypt.
func (p *Packet) UDPDataDetach() {
// Create constants for IP header + UDP header. copy ?
p.ipHdr.Buffer = p.ipHdr.Buffer[:p.ipHdr.ipHeaderLen+UDPDataPos]
}
// CreateReverseFlowPacket modifies the packet for reverse flow.
func (p *Packet) CreateReverseFlowPacket() {
buffer := p.ipHdr.Buffer
// reverse ip addresses
if p.ipHdr.version == V4 {
copy(buffer[ipv4SourceAddrPos:ipv4SourceAddrPos+4], p.ipHdr.destinationAddress)
copy(buffer[ipv4DestAddrPos:ipv4DestAddrPos+4], p.ipHdr.sourceAddress)
} else {
copy(buffer[ipv6SourceAddrPos:ipv6SourceAddrPos+16], p.ipHdr.destinationAddress)
copy(buffer[ipv6DestAddrPos:ipv6DestAddrPos+16], p.ipHdr.sourceAddress)
}
buffer = buffer[p.ipHdr.ipHeaderLen:]
// reverse ports
binary.BigEndian.PutUint16(buffer[udpSourcePortPos:udpSourcePortPos+2], p.udpHdr.destinationPort)
binary.BigEndian.PutUint16(buffer[udpDestPortPos:udpDestPortPos+2], p.udpHdr.sourcePort)
// swap in our packet structures
p.ipHdr.sourceAddress, p.ipHdr.destinationAddress = p.ipHdr.destinationAddress, p.ipHdr.sourceAddress
p.udpHdr.sourcePort, p.udpHdr.destinationPort = p.udpHdr.destinationPort, p.udpHdr.sourcePort
// Just get the IP/UDP header. Ignore the rest. No need for packet
p.ipHdr.Buffer = p.ipHdr.Buffer[:p.ipHdr.ipHeaderLen+UDPDataPos]
p.FixupIPHdrOnDataModify(p.ipHdr.ipTotalLength, uint16(p.ipHdr.ipHeaderLen+UDPDataPos))
if p.ipHdr.version == V4 {
p.UpdateIPv4Checksum()
}
p.fixupUDPHdr()
p.fixupUDPChecksum()
}
// GetUDPType returns udp type of packet.
func (p *Packet) GetUDPType() byte {
// Every UDP control packet has a 20 byte packet signature. The
// first 2 bytes represent the following control information.
// Byte 0 : Bits 0,1 are reserved fields.
// Bits 2,3,4 represent version information.
// Bits 5,6 represent udp packet type,
// Bit 7 represents encryption. (currently unused).
// Byte 1: reserved for future use.
// Bytes [2:20]: Packet signature.
return GetUDPTypeFromBuffer(p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:])
}
// GetUDPTypeFromBuffer gets the UDP packet from a raw buffer.,
func GetUDPTypeFromBuffer(buffer []byte) byte {
if len(buffer) < (UDPDataPos + UDPSignatureLen) {
return 0
}
marker := buffer[UDPDataPos:udpSignatureEnd]
// check for packet signature.
if !bytes.Equal(buffer[udpAuthMarkerOffset:udpSignatureEnd], []byte(UDPAuthMarker)) {
zap.L().Debug("Not an Aporeto control Packet")
return 0
}
// control packet. byte 0 has packet type information.
return marker[0] & UDPPacketMask
}
//GetTCPFlags returns the tcp flags from the packet
func (p *Packet) GetTCPFlags() uint8 {
return p.tcpHdr.tcpFlags
}
//SetTCPFlags allows to set the tcp flags on the packet
func (p *Packet) SetTCPFlags(flags uint8) {
p.tcpHdr.tcpFlags = flags
}
// CreateUDPAuthMarker creates a UDP auth marker.
func CreateUDPAuthMarker(packetType uint8) []byte {
// Every UDP control packet has a 20 byte packet signature. The
// first 2 bytes represent the following control information.
// Byte 0 : Bits 0,1 are reserved fields.
// Bits 2,3,4 represent version information.
// Bits 5, 6, 7 represent udp packet type,
// Byte 1: reserved for future use.
// Bytes [2:20]: Packet signature.
marker := make([]byte, UDPSignatureLen)
// ignore version info as of now.
marker[0] |= packetType // byte 0
marker[1] = 0 // byte 1
// byte 2 - 19
copy(marker[2:], []byte(UDPAuthMarker))
return marker
}