Debian Codegraph @

iputil/packet.go

raw
1 package iputil
2
3 import (
4 "encoding/binary"
5
6 "golang.org/x/net/ipv4"
7 "golang.org/x/net/ipv6"
8 )
9
10 const (
11 // MaxIPv4RejectPacketSize is the largest IPv4 reject packet:
12 // - 20 byte ipv4 header
13 // - 8 byte icmpv4 header
14 // - 68 byte body (60 byte max orig ipv4 header + 8 byte orig icmpv4 header)
15 maxIPv4RejectPacketSize = ipv4.HeaderLen + 8 + 60 + 8
16
17 // MaxRejectPacketSize is sized for the largest possible reject packet (IPv6):
18 // - 40 byte ipv6 header
19 // - 8 byte icmpv6 header
20 // - up to 1000 byte body (original packet, possibly truncated. We want to stay
21 // under the MTU with Nebula overhead included)
22 maxIPv6RejectPacketSize = ipv6.HeaderLen + 8 + 1000
23
24 MaxRejectPacketSize = maxIPv6RejectPacketSize
25 )
26
27 func CreateRejectPacket(packet []byte, out []byte) []byte {
28 if len(packet) < 1 {
29 return nil
30 }
31
32 version := int(packet[0] >> 4)
33 switch version {
34 case ipv4.Version:
35 if len(packet) < ipv4.HeaderLen {
36 return nil
37 }
38 // Do not send reject packets for non-first fragments
39 if packet[6]&0x1f != 0 || packet[7] != 0 {
40 return nil
41 }
42 switch packet[9] {
43 case 6: // tcp
44 return ipv4CreateRejectTCPPacket(packet, out)
45 default:
46 return ipv4CreateRejectICMPPacket(packet, out)
47 }
48 case ipv6.Version:
49 if len(packet) < ipv6.HeaderLen {
50 return nil
51 }
52 return ipv6CreateRejectPacket(packet, out)
53 default:
54 return nil
55 }
56 }
57
58 func ipv4CreateRejectICMPPacket(packet []byte, out []byte) []byte {
59 ihl := int(packet[0]&0x0f) << 2
60
61 if len(packet) < ihl {
62 // We need at least this many bytes for this to be a valid packet
63 return nil
64 }
65
66 // Do not generate ICMP errors in response to ICMP error packets
67 if packet[9] == 1 && len(packet) > ihl {
68 icmpType := packet[ihl]
69 if icmpType == 3 || icmpType == 4 || icmpType == 5 || icmpType == 11 || icmpType == 12 {
70 return nil
71 }
72 }
73
74 // ICMP reply includes original header and first 8 bytes of the packet
75 packetLen := min(len(packet), ihl+8)
76
77 outLen := ipv4.HeaderLen + 8 + packetLen
78 if outLen > cap(out) {
79 return nil
80 }
81
82 out = out[:outLen]
83
84 ipHdr := out[0:ipv4.HeaderLen]
85 ipHdr[0] = ipv4.Version<<4 | (ipv4.HeaderLen >> 2) // version, ihl
86 ipHdr[1] = 0 // DSCP, ECN
87 binary.BigEndian.PutUint16(ipHdr[2:], uint16(outLen)) // Total Length
88
89 ipHdr[4] = 0 // id
90 ipHdr[5] = 0 // .
91 ipHdr[6] = 0 // flags, fragment offset
92 ipHdr[7] = 0 // .
93 ipHdr[8] = 64 // TTL
94 ipHdr[9] = 1 // protocol (icmp)
95 ipHdr[10] = 0 // checksum
96 ipHdr[11] = 0 // .
97
98 // Swap dest / src IPs
99 copy(ipHdr[12:16], packet[16:20])
100 copy(ipHdr[16:20], packet[12:16])
101
102 // Calculate checksum
103 binary.BigEndian.PutUint16(ipHdr[10:], tcpipChecksum(ipHdr, 0))
104
105 // ICMP Destination Unreachable
106 icmpOut := out[ipv4.HeaderLen:]
107 icmpOut[0] = 3 // type (Destination unreachable)
108 icmpOut[1] = 13 // code (Communication administratively prohibited)
109 icmpOut[2] = 0 // checksum
110 icmpOut[3] = 0 // .
111 icmpOut[4] = 0 // unused
112 icmpOut[5] = 0 // .
113 icmpOut[6] = 0 // .
114 icmpOut[7] = 0 // .
115
116 // Copy original IP header and first 8 bytes as body
117 copy(icmpOut[8:], packet[:packetLen])
118
119 // Calculate checksum
120 binary.BigEndian.PutUint16(icmpOut[2:], tcpipChecksum(icmpOut, 0))
121
122 return out
123 }
124
125 func ipv4CreateRejectTCPPacket(packet []byte, out []byte) []byte {
126 const tcpLen = 20
127
128 ihl := int(packet[0]&0x0f) << 2
129 outLen := ipv4.HeaderLen + tcpLen
130
131 if len(packet) < ihl+tcpLen {
132 // We need at least this many bytes for this to be a valid packet
133 return nil
134 }
135 if outLen > cap(out) {
136 return nil
137 }
138
139 out = out[:outLen]
140
141 ipHdr := out[0:ipv4.HeaderLen]
142 ipHdr[0] = ipv4.Version<<4 | (ipv4.HeaderLen >> 2) // version, ihl
143 ipHdr[1] = 0 // DSCP, ECN
144 binary.BigEndian.PutUint16(ipHdr[2:], uint16(outLen)) // Total Length
145 ipHdr[4] = 0 // id
146 ipHdr[5] = 0 // .
147 ipHdr[6] = 0 // flags, fragment offset
148 ipHdr[7] = 0 // .
149 ipHdr[8] = 64 // TTL
150 ipHdr[9] = 6 // protocol (tcp)
151 ipHdr[10] = 0 // checksum
152 ipHdr[11] = 0 // .
153
154 // Swap dest / src IPs
155 copy(ipHdr[12:16], packet[16:20])
156 copy(ipHdr[16:20], packet[12:16])
157
158 // Calculate checksum
159 binary.BigEndian.PutUint16(ipHdr[10:], tcpipChecksum(ipHdr, 0))
160
161 // TCP RST
162 tcpIn := packet[ihl:]
163 var ackSeq, seq uint32
164 outFlags := byte(0b00000100) // RST
165
166 // Set seq and ackSeq based on how iptables/netfilter does it in Linux:
167 // - https://github.com/torvalds/linux/blob/v5.19/net/ipv4/netfilter/nf_reject_ipv4.c#L193-L221
168 inAck := tcpIn[13]&0b00010000 != 0
169 if inAck {
170 seq = binary.BigEndian.Uint32(tcpIn[8:])
171 } else {
172 inSyn := uint32((tcpIn[13] & 0b00000010) >> 1)
173 inFin := uint32(tcpIn[13] & 0b00000001)
174 // seq from the packet + syn + fin + tcp segment length
175 ackSeq = binary.BigEndian.Uint32(tcpIn[4:]) + inSyn + inFin + uint32(len(tcpIn)) - uint32(tcpIn[12]>>4)<<2
176 outFlags |= 0b00010000 // ACK
177 }
178
179 tcpOut := out[ipv4.HeaderLen:]
180 // Swap dest / src ports
181 copy(tcpOut[0:2], tcpIn[2:4])
182 copy(tcpOut[2:4], tcpIn[0:2])
183 binary.BigEndian.PutUint32(tcpOut[4:], seq)
184 binary.BigEndian.PutUint32(tcpOut[8:], ackSeq)
185 tcpOut[12] = (tcpLen >> 2) << 4 // data offset, reserved, NS
186 tcpOut[13] = outFlags // CWR, ECE, URG, ACK, PSH, RST, SYN, FIN
187 tcpOut[14] = 0 // window size
188 tcpOut[15] = 0 // .
189 tcpOut[16] = 0 // checksum
190 tcpOut[17] = 0 // .
191 tcpOut[18] = 0 // URG Pointer
192 tcpOut[19] = 0 // .
193
194 // Calculate checksum
195 csum := ipv4PseudoheaderChecksum(ipHdr[12:16], ipHdr[16:20], 6, tcpLen)
196 binary.BigEndian.PutUint16(tcpOut[16:], tcpipChecksum(tcpOut, csum))
197
198 return out
199 }
200
201 func ipv6CreateRejectPacket(packet []byte, out []byte) []byte {
202 proto, offset, isFragment := ipv6FindUpperProtocol(packet)
203 if isFragment {
204 return nil
205 }
206 switch proto {
207 case 6: // tcp
208 return ipv6CreateRejectTCPPacket(packet, out, offset)
209 default:
210 return ipv6CreateRejectICMPPacket(packet, out, proto, offset)
211 }
212 }
213
214 func ipv6CreateRejectICMPPacket(packet []byte, out []byte, proto uint8, offset int) []byte {
215 // Do not generate ICMPv6 errors in response to ICMPv6 error packets
216 if proto == 58 && len(packet) > offset {
217 icmpType := packet[offset]
218 if icmpType >= 1 && icmpType <= 4 {
219 return nil
220 }
221 }
222
223 // Include as much of the original packet as possible, up to 1000 bytes,
224 // so the response fits comfortably within any tunnel MTU.
225 packetLen := min(len(packet), 1000)
226
227 outLen := ipv6.HeaderLen + 8 + packetLen
228 if outLen > cap(out) {
229 return nil
230 }
231
232 out = out[:outLen]
233
234 // IPv6 header
235 ipHdr := out[0:ipv6.HeaderLen]
236 ipHdr[0] = ipv6.Version << 4 // version, traffic class (high bits)
237 ipHdr[1] = 0 // traffic class (low bits), flow label (high bits)
238 ipHdr[2] = 0 // flow label
239 ipHdr[3] = 0 // flow label
240
241 payloadLen := uint16(outLen - ipv6.HeaderLen)
242 binary.BigEndian.PutUint16(ipHdr[4:], payloadLen) // payload length
243 ipHdr[6] = 58 // next header (ICMPv6)
244 ipHdr[7] = 64 // hop limit
245
246 // Swap dest / src IPs (each 16 bytes, src at 8, dst at 24)
247 copy(ipHdr[8:24], packet[24:40])
248 copy(ipHdr[24:40], packet[8:24])
249
250 // ICMPv6 Destination Unreachable
251 icmpOut := out[ipv6.HeaderLen:]
252 icmpOut[0] = 1 // type (Destination Unreachable)
253 icmpOut[1] = 1 // code (Communication with destination administratively prohibited)
254 icmpOut[2] = 0 // checksum
255 icmpOut[3] = 0 // .
256 icmpOut[4] = 0 // unused
257 icmpOut[5] = 0 // .
258 icmpOut[6] = 0 // .
259 icmpOut[7] = 0 // .
260
261 copy(icmpOut[8:], packet[:packetLen])
262
263 // ICMPv6 checksum uses a pseudo-header
264 csum := ipv6PseudoheaderChecksum(ipHdr[8:24], ipHdr[24:40], 58, uint32(payloadLen))
265 binary.BigEndian.PutUint16(icmpOut[2:], tcpipChecksum(icmpOut, csum))
266
267 return out
268 }
269
270 func ipv6CreateRejectTCPPacket(packet []byte, out []byte, offset int) []byte {
271 const tcpLen = 20
272
273 if len(packet) < offset+tcpLen {
274 return nil
275 }
276
277 outLen := ipv6.HeaderLen + tcpLen
278 if outLen > cap(out) {
279 return nil
280 }
281
282 out = out[:outLen]
283
284 // IPv6 header
285 ipHdr := out[0:ipv6.HeaderLen]
286 ipHdr[0] = ipv6.Version << 4 // version, traffic class (high bits)
287 ipHdr[1] = 0 // traffic class (low bits), flow label (high bits)
288 ipHdr[2] = 0 // flow label
289 ipHdr[3] = 0 // flow label
290
291 binary.BigEndian.PutUint16(ipHdr[4:], tcpLen) // payload length
292 ipHdr[6] = 6 // next header (TCP)
293 ipHdr[7] = 64 // hop limit
294
295 // Swap dest / src IPs
296 copy(ipHdr[8:24], packet[24:40])
297 copy(ipHdr[24:40], packet[8:24])
298
299 // TCP RST
300 tcpIn := packet[offset:]
301 var ackSeq, seq uint32
302 outFlags := byte(0b00000100) // RST
303
304 inAck := tcpIn[13]&0b00010000 != 0
305 if inAck {
306 seq = binary.BigEndian.Uint32(tcpIn[8:])
307 } else {
308 inSyn := uint32((tcpIn[13] & 0b00000010) >> 1)
309 inFin := uint32(tcpIn[13] & 0b00000001)
310 ackSeq = binary.BigEndian.Uint32(tcpIn[4:]) + inSyn + inFin + uint32(len(tcpIn)) - uint32(tcpIn[12]>>4)<<2
311 outFlags |= 0b00010000 // ACK
312 }
313
314 tcpOut := out[ipv6.HeaderLen:]
315 // Swap dest / src ports
316 copy(tcpOut[0:2], tcpIn[2:4])
317 copy(tcpOut[2:4], tcpIn[0:2])
318 binary.BigEndian.PutUint32(tcpOut[4:], seq)
319 binary.BigEndian.PutUint32(tcpOut[8:], ackSeq)
320 tcpOut[12] = (tcpLen >> 2) << 4 // data offset, reserved, NS
321 tcpOut[13] = outFlags // CWR, ECE, URG, ACK, PSH, RST, SYN, FIN
322 tcpOut[14] = 0 // window size
323 tcpOut[15] = 0 // .
324 tcpOut[16] = 0 // checksum
325 tcpOut[17] = 0 // .
326 tcpOut[18] = 0 // URG Pointer
327 tcpOut[19] = 0 // .
328
329 // Calculate checksum with IPv6 pseudo-header
330 csum := ipv6PseudoheaderChecksum(ipHdr[8:24], ipHdr[24:40], 6, tcpLen)
331 binary.BigEndian.PutUint16(tcpOut[16:], tcpipChecksum(tcpOut, csum))
332
333 return out
334 }
335
336 func ipv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragment bool) {
337 nextHeader = packet[6]
338 offset = ipv6.HeaderLen
339
340 for {
341 switch nextHeader {
342 case 0, 43, 60: // Hop-by-Hop, Routing, Destination
343 if len(packet) < offset+2 {
344 return nextHeader, offset, isFragment
345 }
346 nextHeader = packet[offset]
347 offset += (int(packet[offset+1]) + 1) << 3
348
349 case 44: // Fragment
350 if len(packet) < offset+8 {
351 return nextHeader, offset, isFragment
352 }
353 if packet[offset+2] != 0 || packet[offset+3]&0xf8 != 0 {
354 isFragment = true
355 }
356 nextHeader = packet[offset]
357 offset += 8
358
359 case 51: // AH
360 if len(packet) < offset+2 {
361 return nextHeader, offset, isFragment
362 }
363 nextHeader = packet[offset]
364 offset += (int(packet[offset+1]) + 2) << 2
365
366 default:
367 return nextHeader, offset, isFragment
368 }
369 }
370 }
371
372 func CreateICMPEchoResponse(packet, out []byte) []byte {
373 if len(packet) < 1 {
374 return nil
375 }
376
377 switch packet[0] >> 4 {
378 case 4:
379 return createICMPv4EchoResponse(packet, out)
380 case 6:
381 return createICMPv6EchoResponse(packet, out)
382 default:
383 return nil
384 }
385 }
386
387 func createICMPv4EchoResponse(packet, out []byte) []byte {
388 // Return early if this is not a simple ICMP Echo Request
389 //TODO: make constants out of these
390 if !(len(packet) >= 28 && len(packet) <= 9001 && packet[0] == 0x45 && packet[9] == 0x01 && packet[20] == 0x08) {
391 return nil
392 }
393
394 // We don't support fragmented packets
395 if packet[7] != 0 || (packet[6]&0x2F != 0) {
396 return nil
397 }
398
399 out = out[:len(packet)]
400
401 copy(out, packet)
402
403 // Swap dest / src IPs and recalculate checksum
404 ipv4 := out[0:20]
405 copy(ipv4[12:16], packet[16:20])
406 copy(ipv4[16:20], packet[12:16])
407 ipv4[10] = 0
408 ipv4[11] = 0
409 binary.BigEndian.PutUint16(ipv4[10:], tcpipChecksum(ipv4, 0))
410
411 // Change type to ICMP Echo Reply and recalculate checksum
412 icmp := out[20:]
413 icmp[0] = 0
414 icmp[2] = 0
415 icmp[3] = 0
416 binary.BigEndian.PutUint16(icmp[2:], tcpipChecksum(icmp, 0))
417
418 return out
419 }
420
421 func createICMPv6EchoResponse(packet, out []byte) []byte {
422 // IPv6 header (40 bytes) + ICMPv6 header (8 bytes minimum)
423 if len(packet) < ipv6.HeaderLen+8 || len(packet) > 9001 {
424 return nil
425 }
426
427 // Next Header must be ICMPv6 (58)
428 if packet[6] != 58 {
429 return nil
430 }
431
432 // ICMPv6 type must be Echo Request (128)
433 if packet[ipv6.HeaderLen] != 128 {
434 return nil
435 }
436
437 out = out[:len(packet)]
438 copy(out, packet)
439
440 // Swap src/dst addresses (bytes 8-23 and 24-39)
441 copy(out[8:24], packet[24:40])
442 copy(out[24:40], packet[8:24])
443
444 // Change ICMPv6 type to Echo Reply (129)
445 icmp := out[ipv6.HeaderLen:]
446 icmp[0] = 129
447 icmp[2] = 0
448 icmp[3] = 0
449
450 // ICMPv6 checksum uses a pseudo-header with src, dst, length, and next header
451 payloadLen := uint32(len(icmp))
452 csum := ipv6PseudoheaderChecksum(out[8:24], out[24:40], 58, payloadLen)
453 binary.BigEndian.PutUint16(icmp[2:], tcpipChecksum(icmp, csum))
454
455 return out
456 }
457
458 // calculates the TCP/IP checksum defined in rfc1071. The passed-in
459 // csum is any initial checksum data that's already been computed.
460 //
461 // based on:
462 // - https://github.com/google/gopacket/blob/v1.1.19/layers/tcpip.go#L50-L70
463 func tcpipChecksum(data []byte, csum uint32) uint16 {
464 // to handle odd lengths, we loop to length - 1, incrementing by 2, then
465 // handle the last byte specifically by checking against the original
466 // length.
467 length := len(data) - 1
468 for i := 0; i < length; i += 2 {
469 // For our test packet, doing this manually is about 25% faster
470 // (740 ns vs. 1000ns) than doing it by calling binary.BigEndian.Uint16.
471 csum += uint32(data[i]) << 8
472 csum += uint32(data[i+1])
473 }
474 if len(data)%2 == 1 {
475 csum += uint32(data[length]) << 8
476 }
477 for csum > 0xffff {
478 csum = (csum >> 16) + (csum & 0xffff)
479 }
480 return ^uint16(csum)
481 }
482
483 // based on:
484 // - https://github.com/google/gopacket/blob/v1.1.19/layers/tcpip.go#L26-L35
485 func ipv4PseudoheaderChecksum(src, dst []byte, proto, length uint32) (csum uint32) {
486 csum += (uint32(src[0]) + uint32(src[2])) << 8
487 csum += uint32(src[1]) + uint32(src[3])
488 csum += (uint32(dst[0]) + uint32(dst[2])) << 8
489 csum += uint32(dst[1]) + uint32(dst[3])
490 csum += proto
491 csum += length & 0xffff
492 csum += length >> 16
493 return csum
494 }
495
496 // based on:
497 // - https://github.com/google/gopacket/blob/v1.1.19/layers/tcpip.go#L37-L48
498 func ipv6PseudoheaderChecksum(src, dst []byte, proto, length uint32) (csum uint32) {
499 for i := 0; i < 16; i += 2 {
500 csum += uint32(src[i]) << 8
501 csum += uint32(src[i+1])
502 csum += uint32(dst[i]) << 8
503 csum += uint32(dst[i+1])
504 }
505 csum += proto
506 csum += length & 0xffff
507 csum += length >> 16
508 return csum
509 }