1
0

packet.go 17 KB

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