packet.go 16 KB

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