packet.go 14 KB

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