1
0

packet.go 16 KB

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