/
fragment_packet.go
411 lines (333 loc) · 11.7 KB
/
fragment_packet.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
package actions
import (
"encoding/binary"
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/getlantern/geneva/common"
"github.com/getlantern/geneva/internal"
"github.com/getlantern/geneva/internal/scanner"
)
// FragmentAction is a Geneva action that splits a packet into two fragments and applies separate
// action trees to each.
//
// As an example, if Proto is "IP" and FragSize is 8, this will fragment a 60-byte IP packet into
// two fragments: the first will contain the first eight bytes of the original packet's payload, and
// the second will contain the remaining 52 bytes. Each fragment will retain the original header
// (modulo the fields that must be updated to mark it as a fragmented packet). If the Proto's header
// includes a checksum, it will be recomputed.
type FragmentAction struct {
// Proto is the protocol layer where the packet will be fragmented.
proto gopacket.LayerType
// FragSize is the offset into the protocol's payload where fragmentation will happen.
FragSize int
// InOrder specifies whether to return the fragments in order.
InOrder bool
overlap int
// FirstFragmentAction is the action to apply to the first fragment.
FirstFragmentAction Action
// SecondFragmentAction is the action to apply to the second fragment.
SecondFragmentAction Action
}
func (a *FragmentAction) Proto() string {
switch a.proto {
case layers.LayerTypeIPv4:
return "IP"
case layers.LayerTypeTCP:
return "TCP"
case layers.LayerTypeUDP:
return "UDP"
default:
return ""
}
}
// Apply applies this action to the given packet.
func (a *FragmentAction) Apply(packet gopacket.Packet) ([]gopacket.Packet, error) {
var (
err error
packets []gopacket.Packet
lpackets, rpackets []gopacket.Packet
)
switch a.proto {
case layers.LayerTypeIPv4:
// Note: the original Geneva code only fragments IPv4, not IPv6.
packets, err = FragmentIPPacket(packet, a.FragSize)
case layers.LayerTypeTCP:
packets, err = fragmentTCPSegment(packet, a.FragSize)
default:
// TODO: should we log this?
packets, err = duplicate(packet)
}
if err != nil {
return nil, fmt.Errorf("failed to fragment: %w", err)
}
if len(packets) == 2 && !a.InOrder {
packets = []gopacket.Packet{packets[1], packets[0]}
}
if lpackets, err = a.FirstFragmentAction.Apply(packets[0]); err != nil {
return nil, fmt.Errorf("failed to apply action to first fragment: %w", err)
}
if rpackets, err = a.SecondFragmentAction.Apply(packets[1]); err != nil {
return nil, fmt.Errorf("failed to apply action to second fragment: %w", err)
}
return append(lpackets, rpackets...), nil
}
func fragmentTCPSegment(packet gopacket.Packet, fragSize int) ([]gopacket.Packet, error) {
// XXX: the original Geneva code does not seem to handle TCP segmentation for IPv6 packets,
// so we don't either for now.
if packet.NetworkLayer().LayerType() != layers.LayerTypeIPv4 {
return duplicate(packet)
}
if packet.TransportLayer() == nil ||
packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
return duplicate(packet)
}
tcpPayload := packet.TransportLayer().LayerPayload()
tcpPayloadLen := len(tcpPayload)
if tcpPayloadLen == 0 {
return duplicate(packet)
}
if fragSize == -1 || fragSize > tcpPayloadLen-1 {
fragSize = tcpPayloadLen / 2
}
// XXX: upstream Geneva supports "overlap bytes"; i.e., taking the first few bytes of the
// second fragment and tacking them onto the end of the first fragment. It's not mentioned
// in the original paper. We don't do this right now, but could later.
headersLen := len(packet.Data()) - tcpPayloadLen
// Strangely, all the manual bit-banging below was easier than dealing with creating packets
// using gopacket.
ofs := len(
packet.Data(),
) - len(
packet.NetworkLayer().LayerContents(),
) - len(
packet.NetworkLayer().LayerPayload(),
)
if ofs < 0 {
// something bad has happened, so let's bail.
return nil, errors.New("error calculating offset to network layer")
}
// create the first fragment.
f1Len := headersLen + fragSize
buf := make([]byte, f1Len)
copy(buf, packet.Data()[:f1Len])
ipv4Buf := buf[ofs:]
// fix up the IP header's Total Length field
binary.BigEndian.PutUint16(ipv4Buf[2:], uint16(f1Len-ofs))
ipHdrLen := uint16(ipv4Buf[0]&0x0f) * 4
first := gopacket.NewPacket(buf, packet.Layers()[0].LayerType(), gopacket.NoCopy)
updateChecksums(first)
// create the second fragment.
f2Len := headersLen + tcpPayloadLen - fragSize
buf = make([]byte, f2Len)
copy(buf, packet.Data()[:headersLen])
copy(buf[headersLen:], packet.Data()[headersLen+fragSize:])
ipv4Buf = buf[ofs:]
// fix up the IP header's Total Length field
binary.BigEndian.PutUint16(ipv4Buf[2:], uint16(f2Len-ofs))
// Fix up the TCP sequence number.
// Excitingly, Go does integer wrapping, so we don't have to.
tcp := ipv4Buf[ipHdrLen:]
seqNum := binary.BigEndian.Uint32(tcp[4:])
seqNum += uint32(fragSize)
binary.BigEndian.PutUint32(tcp[4:], seqNum)
second := gopacket.NewPacket(buf, packet.Layers()[0].LayerType(), gopacket.NoCopy)
updateChecksums(second)
return []gopacket.Packet{first, second}, nil
}
// FragmentIPPacket will fragment an IPv4 or IPv6 packet into two packets at the given 8-byte chunk
// offset.
//
// The first fragment will include up to (fragSize * 8) bytes of the IP packet's payload, and the
// second fragment will include the rest.
func FragmentIPPacket(packet gopacket.Packet, fragSize int) ([]gopacket.Packet, error) {
if packet.NetworkLayer() == nil ||
packet.NetworkLayer().LayerType() != layers.LayerTypeIPv4 {
return duplicate(packet)
}
plen := len(packet.NetworkLayer().LayerPayload())
if plen == 0 {
return duplicate(packet)
}
if fragSize == -1 || (fragSize*8)%8 > plen || plen <= 8 {
fragSize = plen / 2 / 8
}
// corner case: if fragSize is 0, just return the original packet.
if fragSize == 0 {
return []gopacket.Packet{packet}, nil
}
// from this point on we can assume that the IP payload is _at least_ (fragSize*8) bytes
// long
ofs := len(
packet.Data(),
) - len(
packet.NetworkLayer().LayerContents(),
) - len(
packet.NetworkLayer().LayerPayload(),
)
if ofs < 0 {
// something bad has happened, so let's bail.
return nil, errors.New("error calculating offset to network layer")
}
buf := make([]byte, len(packet.Data()))
copy(buf, packet.Data())
ipv4Buf := buf[ofs:]
hdrLen := uint16((ipv4Buf[0] & 0x0f) * 4)
payloadLen := binary.BigEndian.Uint16(ipv4Buf[2:]) - hdrLen
// fix up the fragment size to a multiple of 8 to satisfy fragment offset value
offset := uint16((fragSize * 8))
// update the total length of the first fragmented packet
binary.BigEndian.PutUint16(ipv4Buf[2:], hdrLen+offset)
// set the More Fragments bit, and make the fragment offset 0
flagsAndFrags := (binary.BigEndian.Uint16(ipv4Buf[6:]) | 0x20) & 0xe0
binary.LittleEndian.PutUint16(ipv4Buf[6:], flagsAndFrags)
// slice off everything past the first fragment's end
buf = buf[:uint16(ofs)+hdrLen+offset]
first := gopacket.NewPacket(buf, packet.Layers()[0].LayerType(), gopacket.NoCopy)
if ipv4, ok := first.Layer(layers.LayerTypeIPv4).(*layers.IPv4); ok && ipv4 != nil {
common.UpdateIPv4Checksum(ipv4)
}
// Now start on the second fragment.
// First copy the old IP header as-is, then copy just the second fragment's payload right
// after.
buf = make([]byte, len(packet.Data())-int(offset))
copy(buf, packet.Data()[:uint16(ofs)+hdrLen])
ipv4Buf = buf[ofs:]
copy(ipv4Buf[hdrLen:], packet.Data()[uint16(ofs)+hdrLen+offset:])
// fix up the length
binary.BigEndian.PutUint16(ipv4Buf[2:], hdrLen+payloadLen-offset)
// clear the MF bit and set the fragment offset appropriately
flagsAndFrags = (binary.BigEndian.Uint16(ipv4Buf[6:]) & 0x40) + uint16(fragSize)
binary.BigEndian.PutUint16(ipv4Buf[6:], flagsAndFrags)
second := gopacket.NewPacket(buf, packet.Layers()[0].LayerType(), gopacket.NoCopy)
if ipv4, _ := second.Layer(layers.LayerTypeIPv4).(*layers.IPv4); ipv4 != nil {
common.UpdateIPv4Checksum(ipv4)
}
return []gopacket.Packet{first, second}, nil
}
func updateChecksums(packet gopacket.Packet) {
if ipv4, _ := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4); ipv4 != nil {
common.UpdateIPv4Checksum(ipv4)
}
if tcp, _ := packet.Layer(layers.LayerTypeTCP).(*layers.TCP); tcp != nil {
common.UpdateTCPChecksum(tcp)
}
}
// VerifyIPv4Checksum verifies whether an IPv4 header's checksum field is correct.
func VerifyIPv4Checksum(header []byte) bool {
c := internal.OnesComplementChecksum{}
for i := 0; i < len(header); i += 2 {
c.Add(binary.BigEndian.Uint16(header[i:]))
}
return c.Finalize() == 0
}
// String returns a string representation of this Action.
func (a *FragmentAction) String() string {
actions := [2]string{"", ""}
if _, ok := a.FirstFragmentAction.(*SendAction); !ok {
actions[0] = a.FirstFragmentAction.String()
}
if _, ok := a.SecondFragmentAction.(*SendAction); !ok {
actions[1] = a.SecondFragmentAction.String()
}
var actStr string
if len(actions[0])+len(actions[1]) > 0 {
actStr = fmt.Sprintf("(%s,%s)", actions[0], actions[1])
}
return fmt.Sprintf("fragment{%s:%d:%t}%s",
a.Proto(), a.FragSize, a.InOrder, actStr)
}
// ParseFragmentAction parses a string representation of a "fragment" action.
//
// If the string is malformed, an error will be returned instead.
func ParseFragmentAction(s *scanner.Scanner) (Action, error) {
if _, err := s.Expect("fragment{"); err != nil {
return nil, fmt.Errorf("invalid fragment rule at %d: %w", s.Pos(), err)
}
str, err := s.Until('}')
if err != nil {
return nil, fmt.Errorf("invalid fragment rule at %d: %w", s.Pos(), err)
}
_, _ = s.Pop()
fields := strings.Split(str, ":")
if len(fields) < 3 {
return nil, fmt.Errorf(
"not enough fields for fragment rule at %d (got %d)",
s.Pos(),
len(fields),
)
}
action := &FragmentAction{}
switch strings.ToLower(fields[0]) {
case "ip":
action.proto = layers.LayerTypeIPv4
case "tcp":
action.proto = layers.LayerTypeTCP
case "udp":
action.proto = layers.LayerTypeUDP
default:
return nil, fmt.Errorf(
"invalid fragment rule: %q is not a recognized protocol",
fields[0],
)
}
ofs, err := strconv.ParseInt(fields[1], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid fragment rule: %q is not a valid offset", fields[1])
}
action.FragSize = int(ofs)
if action.InOrder, err = strconv.ParseBool(fields[2]); err != nil {
return nil, fmt.Errorf(
"invalid fragment rule: %q is not a valid boolean",
fields[2],
)
}
if len(fields) == 4 {
overlap, err := strconv.ParseInt(fields[3], 10, 16)
if err != nil {
return nil, fmt.Errorf(
"invalid fragment rule: %q is not a valid overlap",
fields[3],
)
}
action.overlap = int(overlap)
}
if _, err = s.Expect("("); err != nil {
action.FirstFragmentAction = &SendAction{}
action.SecondFragmentAction = &SendAction{}
return action, nil //nolint:nilerr
}
if action.FirstFragmentAction, err = ParseAction(s); err != nil {
if !errors.Is(err, ErrInvalidAction) {
return nil, err
}
if c, err2 := s.Peek(); err2 == nil && c == ',' {
action.FirstFragmentAction = &SendAction{}
} else {
return nil, fmt.Errorf("error parsing first action of fragment rule: %w", err)
}
}
if _, err = s.Expect(","); err != nil {
return nil, fmt.Errorf(
"unexpected token in fragment rule: %w",
internal.EOFUnexpected(err),
)
}
if action.SecondFragmentAction, err = ParseAction(s); err != nil {
if c, err2 := s.Peek(); err2 == nil && c == ')' {
action.SecondFragmentAction = &SendAction{}
} else {
return nil, fmt.Errorf("error parsing second action of fragment rule: %w", err)
}
}
if _, err := s.Expect(")"); err != nil {
return nil, fmt.Errorf(
"unexpected token in fragment rule: %w",
internal.EOFUnexpected(err),
)
}
return action, nil
}