segment_linux.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. //go:build linux && !android
  2. // +build linux,!android
  3. // Package virtio implements the pure validation, header-correction, and
  4. // per-segment slicing logic for kernel-supplied TSO/USO superpackets on
  5. // IFF_VNET_HDR TUN devices. It is FD-free and depends only on the byte
  6. // layout of the virtio_net_hdr and the IP/TCP/UDP headers it describes,
  7. // so it can be unit-tested in isolation from the tio Queue runtime.
  8. package virtio
  9. import (
  10. "encoding/binary"
  11. "errors"
  12. "fmt"
  13. "golang.org/x/sys/unix"
  14. "github.com/slackhq/nebula/overlay/checksum"
  15. )
  16. // Protocol header size bounds used to validate / cap kernel-supplied offsets.
  17. const (
  18. ipv4HeaderMinLen = 20 // IHL=5, no options
  19. ipv4HeaderMaxLen = 60 // IHL=15, max options
  20. ipv6FixedLen = 40 // IPv6 base header; extensions would extend this
  21. tcpHeaderMinLen = 20 // data-offset=5, no options
  22. tcpHeaderMaxLen = 60 // data-offset=15, max options
  23. )
  24. // maxSegHdrLen bounds the L3+L4 header we snapshot before stamping each
  25. // segment. The largest header the segmenter supports is IPv4 (max IHL 60)
  26. // plus TCP (max data-offset 60) = 120 bytes; the array is sized to that
  27. // worst case so the snapshot lives on the stack with no per-call heap
  28. // allocation.
  29. const maxSegHdrLen = ipv4HeaderMaxLen + tcpHeaderMaxLen // 120
  30. // Byte offsets inside an IPv4 header.
  31. const (
  32. ipv4TotalLenOff = 2
  33. ipv4IDOff = 4
  34. ipv4ChecksumOff = 10
  35. ipv4SrcOff = 12
  36. ipv4AddrsEnd = 20 // end of dst address (ipv4SrcOff + 2*4)
  37. )
  38. // Byte offsets inside an IPv6 header.
  39. const (
  40. ipv6PayloadLenOff = 4
  41. ipv6SrcOff = 8
  42. ipv6AddrsEnd = 40 // end of dst address (ipv6SrcOff + 2*16)
  43. )
  44. // Byte offsets inside a TCP header (relative to its start, i.e. csumStart).
  45. const (
  46. tcpSeqOff = 4
  47. tcpDataOffOff = 12 // upper nibble is header len in 32-bit words
  48. tcpFlagsOff = 13
  49. tcpChecksumOff = 16
  50. )
  51. // UDP header is fixed at 8 bytes: {sport, dport, length, checksum}.
  52. const (
  53. udpHeaderLen = 8
  54. udpLengthOff = 4
  55. udpChecksumOff = 6
  56. )
  57. // tcpFinPshMask is cleared on every segment except the last of a TSO burst.
  58. const tcpFinPshMask = 0x09 // FIN(0x01) | PSH(0x08)
  59. // tcpCwrFlag is cleared on every segment except the first. Per RFC 3168
  60. // §6.1.2 the CWR bit signals a one-shot transition (the sender just halved
  61. // its window) and must appear on the first segment of a TSO burst only.
  62. const tcpCwrFlag = 0x80
  63. // CheckValid rejects packets whose virtio_net_hdr/IP combination would
  64. // cause a downstream miscompute. The TUN should never emit RSC_INFO and
  65. // the GSO type must agree with the IP version nibble.
  66. func CheckValid(pkt []byte, hdr Hdr) error {
  67. // When RSC_INFO is set the csum_start/csum_offset fields are repurposed to
  68. // carry coalescing info rather than checksum offsets. A TUN writing via
  69. // IFF_VNET_HDR should never emit this, but if it did we would silently
  70. // miscompute the segment checksums — refuse the packet instead.
  71. if hdr.Flags&unix.VIRTIO_NET_HDR_F_RSC_INFO != 0 {
  72. return fmt.Errorf("virtio RSC_INFO flag not supported on TUN reads")
  73. }
  74. if len(pkt) < ipv4HeaderMinLen {
  75. return fmt.Errorf("packet too short")
  76. }
  77. ipVersion := pkt[0] >> 4
  78. switch hdr.GSOType {
  79. case unix.VIRTIO_NET_HDR_GSO_TCPV4:
  80. if ipVersion != 4 {
  81. return fmt.Errorf("invalid IP version %d for GSO type %d", ipVersion, hdr.GSOType)
  82. }
  83. case unix.VIRTIO_NET_HDR_GSO_TCPV6:
  84. if ipVersion != 6 {
  85. return fmt.Errorf("invalid IP version %d for GSO type %d", ipVersion, hdr.GSOType)
  86. }
  87. case unix.VIRTIO_NET_HDR_GSO_UDP_L4:
  88. // USO carries either v4 or v6; the leading nibble disambiguates.
  89. if !(ipVersion == 4 || ipVersion == 6) {
  90. return fmt.Errorf("invalid IP version %d for GSO type %d", ipVersion, hdr.GSOType)
  91. }
  92. default:
  93. if !(ipVersion == 6 || ipVersion == 4) {
  94. return fmt.Errorf("invalid IP version %d for GSO type %d", ipVersion, hdr.GSOType)
  95. }
  96. }
  97. return nil
  98. }
  99. // CorrectHdrLen rewrites hdr.HdrLen based on the actual transport header
  100. // length read out of pkt. The kernel's hdr.HdrLen on the FORWARD path can
  101. // be the length of the entire first packet, so we don't trust it.
  102. func CorrectHdrLen(pkt []byte, hdr *Hdr) error {
  103. // Thank you wireguard-go for documenting these edge-cases
  104. // Don't trust hdr.hdrLen from the kernel as it can be equal to the length
  105. // of the entire first packet when the kernel is handling it as part of a
  106. // FORWARD path. Instead, parse the transport header length and add it onto
  107. // csumStart, which is synonymous for IP header length.
  108. if hdr.GSOType == unix.VIRTIO_NET_HDR_GSO_UDP_L4 {
  109. hdr.HdrLen = hdr.CsumStart + 8
  110. } else {
  111. if len(pkt) <= int(hdr.CsumStart+tcpDataOffOff) {
  112. return errors.New("packet is too short")
  113. }
  114. tcpHLen := uint16(pkt[hdr.CsumStart+tcpDataOffOff] >> 4 * 4)
  115. if tcpHLen < 20 || tcpHLen > 60 {
  116. // A TCP header must be between 20 and 60 bytes in length.
  117. return fmt.Errorf("tcp header len is invalid: %d", tcpHLen)
  118. }
  119. hdr.HdrLen = hdr.CsumStart + tcpHLen
  120. }
  121. if len(pkt) < int(hdr.HdrLen) {
  122. return fmt.Errorf("length of packet (%d) < virtioNetHdr.HdrLen (%d)", len(pkt), hdr.HdrLen)
  123. }
  124. if hdr.HdrLen < hdr.CsumStart {
  125. return fmt.Errorf("virtioNetHdr.HdrLen (%d) < virtioNetHdr.CsumStart (%d)", hdr.HdrLen, hdr.CsumStart)
  126. }
  127. cSumAt := int(hdr.CsumStart + hdr.CsumOffset)
  128. if cSumAt+1 >= len(pkt) {
  129. return fmt.Errorf("end of checksum offset (%d) exceeds packet length (%d)", cSumAt+1, len(pkt))
  130. }
  131. return nil
  132. }
  133. // SegmentTCP walks a TSO superpacket pkt, yielding each segment as a
  134. // slice into pkt itself. Per-segment plaintext is laid out by stamping a
  135. // copy of the original L3+L4 header into pkt at offset i*gsoSize, where it
  136. // sits immediately before that segment's payload chunk in the original
  137. // buffer. The stamp is destructive but harmless: iter i's header write lands
  138. // on pkt[i*G : i*G+hdrLen], which is the tail of seg_{i-1}'s payload (already
  139. // consumed) and ends exactly where seg_i's payload begins, so it never clobbers
  140. // live payload — this holds even when gsoSize < hdrLen. The header bytes are
  141. // sourced from a pristine snapshot taken before the loop (savedHdr), NOT from
  142. // pkt[:hdrLen], because when gsoSize < hdrLen the stamps would otherwise
  143. // overwrite the leading header in place and every stamp after the first would
  144. // copy corrupted bytes. pkt is consumed by this call and must not be inspected
  145. // by the caller after the final yield.
  146. func SegmentTCP(pkt []byte, hdrLenU, csumStartU, gsoSizeU uint16, yield func(seg []byte) error) error {
  147. if gsoSizeU == 0 {
  148. return fmt.Errorf("gso_size is zero")
  149. }
  150. if csumStartU == 0 {
  151. return fmt.Errorf("csum_start is zero")
  152. }
  153. headerLen := int(hdrLenU)
  154. csumStart := int(csumStartU)
  155. if headerLen > maxSegHdrLen {
  156. return fmt.Errorf("header len %d exceeds max %d", headerLen, maxSegHdrLen)
  157. }
  158. isV4 := pkt[0]>>4 == 4
  159. tcpHdrLen := int(pkt[csumStart+tcpDataOffOff]>>4) * 4
  160. payLen := len(pkt) - headerLen
  161. gsoSize := int(gsoSizeU)
  162. numSeg := (payLen + gsoSize - 1) / gsoSize
  163. if numSeg == 0 {
  164. numSeg = 1
  165. }
  166. origSeq := binary.BigEndian.Uint32(pkt[csumStart+tcpSeqOff : csumStart+tcpSeqOff+4])
  167. origFlags := pkt[csumStart+tcpFlagsOff]
  168. var tmp [tcpHeaderMaxLen]byte
  169. copy(tmp[:tcpHdrLen], pkt[csumStart:headerLen])
  170. tmp[tcpSeqOff], tmp[tcpSeqOff+1], tmp[tcpSeqOff+2], tmp[tcpSeqOff+3] = 0, 0, 0, 0
  171. tmp[tcpFlagsOff] = 0
  172. tmp[tcpChecksumOff], tmp[tcpChecksumOff+1] = 0, 0
  173. baseTcpHdrSum := uint32(checksum.Checksum(tmp[:tcpHdrLen], 0))
  174. var baseProtoSum uint32
  175. if isV4 {
  176. baseProtoSum = uint32(checksum.Checksum(pkt[ipv4SrcOff:ipv4AddrsEnd], 0))
  177. } else {
  178. baseProtoSum = uint32(checksum.Checksum(pkt[ipv6SrcOff:ipv6AddrsEnd], 0))
  179. }
  180. baseProtoSum += uint32(unix.IPPROTO_TCP)
  181. var origIPID uint16
  182. var baseIPHdrSum uint32
  183. if isV4 {
  184. origIPID = binary.BigEndian.Uint16(pkt[ipv4IDOff : ipv4IDOff+2])
  185. ihl := int(pkt[0]&0x0f) * 4
  186. if ihl < ipv4HeaderMinLen || ihl > csumStart {
  187. return fmt.Errorf("bad IPv4 IHL: %d", ihl)
  188. }
  189. var ipTmp [ipv4HeaderMaxLen]byte
  190. copy(ipTmp[:ihl], pkt[:ihl])
  191. ipTmp[ipv4TotalLenOff], ipTmp[ipv4TotalLenOff+1] = 0, 0
  192. ipTmp[ipv4IDOff], ipTmp[ipv4IDOff+1] = 0, 0
  193. ipTmp[ipv4ChecksumOff], ipTmp[ipv4ChecksumOff+1] = 0, 0
  194. baseIPHdrSum = uint32(checksum.Checksum(ipTmp[:ihl], 0))
  195. }
  196. // Snapshot the pristine L3+L4 header once. Every segment's header is
  197. // stamped from this copy, so overlapping stamps (gsoSize < headerLen)
  198. // can never corrupt the source. The variable fields (seq/flags/cksum/
  199. // totalLen/id) captured here are stale but are overwritten per segment.
  200. var savedHdr [maxSegHdrLen]byte
  201. copy(savedHdr[:headerLen], pkt[:headerLen])
  202. for i := 0; i < numSeg; i++ {
  203. segStart := i * gsoSize
  204. segEnd := segStart + gsoSize
  205. if segEnd > payLen {
  206. segEnd = payLen
  207. }
  208. segPayLen := segEnd - segStart
  209. segLen := headerLen + segPayLen
  210. headerOff := i * gsoSize
  211. // Stamp the header into place immediately before this segment's
  212. // payload, sourced from the pristine snapshot. Iter 0's header is
  213. // already at pkt[:headerLen] (identical to savedHdr), so only i ≥ 1
  214. // needs the stamp. The per-segment patches below overwrite the
  215. // variable fields.
  216. if i > 0 {
  217. copy(pkt[headerOff:headerOff+headerLen], savedHdr[:headerLen])
  218. }
  219. seg := pkt[headerOff : headerOff+segLen]
  220. segSeq := origSeq + uint32(segStart)
  221. segFlags := origFlags
  222. if i != 0 {
  223. segFlags &^= tcpCwrFlag
  224. }
  225. if i != numSeg-1 {
  226. segFlags &^= tcpFinPshMask
  227. }
  228. totalLen := segLen
  229. if isV4 {
  230. segID := origIPID + uint16(i)
  231. binary.BigEndian.PutUint16(seg[ipv4TotalLenOff:ipv4TotalLenOff+2], uint16(totalLen))
  232. binary.BigEndian.PutUint16(seg[ipv4IDOff:ipv4IDOff+2], segID)
  233. ipSum := baseIPHdrSum + uint32(totalLen) + uint32(segID)
  234. binary.BigEndian.PutUint16(seg[ipv4ChecksumOff:ipv4ChecksumOff+2], foldComplement(ipSum))
  235. } else {
  236. binary.BigEndian.PutUint16(seg[ipv6PayloadLenOff:ipv6PayloadLenOff+2], uint16(headerLen-ipv6FixedLen+segPayLen))
  237. }
  238. binary.BigEndian.PutUint32(seg[csumStart+tcpSeqOff:csumStart+tcpSeqOff+4], segSeq)
  239. seg[csumStart+tcpFlagsOff] = segFlags
  240. tcpLen := tcpHdrLen + segPayLen
  241. // Payload bytes still live at their original offset in pkt. The
  242. // header slide above only writes into pkt[i*G : i*G+H], which is
  243. // the tail of seg_{i-1}'s payload (already consumed) and never
  244. // overlaps seg_i's own payload at pkt[H+i*G : H+(i+1)*G].
  245. paySum := uint32(checksum.Checksum(pkt[headerLen+segStart:headerLen+segEnd], 0))
  246. wide := uint64(baseTcpHdrSum) + uint64(paySum) + uint64(baseProtoSum)
  247. wide += uint64(segSeq) + uint64(segFlags) + uint64(tcpLen)
  248. wide = (wide & 0xffffffff) + (wide >> 32)
  249. wide = (wide & 0xffffffff) + (wide >> 32)
  250. binary.BigEndian.PutUint16(seg[csumStart+tcpChecksumOff:csumStart+tcpChecksumOff+2], foldComplement(uint32(wide)))
  251. if err := yield(seg); err != nil {
  252. return err
  253. }
  254. }
  255. return nil
  256. }
  257. // SegmentUDP walks a USO superpacket, stamping a per-segment-patched copy of
  258. // the original L3+L4 header into pkt at offset i*gsoSize and yielding
  259. // pkt[i*G:i*G+segLen] to the caller. Per-segment patches are total_len +
  260. // IPv4 csum (or IPv6 payload_len) plus the UDP length and checksum. pkt is
  261. // consumed destructively; see SegmentTCP for the layout reasoning, including
  262. // why the header is stamped from a pristine snapshot rather than pkt[:hdrLen]
  263. // (correctness when gsoSize < hdrLen).
  264. //
  265. // UDP-GSO leaves the IPv4 ID identical across segments (the kernel does not
  266. // bump it), which is why the IP-level per-segment work is limited to
  267. // total_len + IPv4 header checksum (v4) or payload_len (v6).
  268. func SegmentUDP(pkt []byte, hdrLenU, csumStartU, gsoSizeU uint16, yield func(seg []byte) error) error {
  269. if gsoSizeU == 0 {
  270. return fmt.Errorf("gso_size is zero")
  271. }
  272. if csumStartU == 0 {
  273. return fmt.Errorf("csum_start is zero")
  274. }
  275. isV4 := pkt[0]>>4 == 4
  276. headerLen := int(hdrLenU)
  277. csumStart := int(csumStartU)
  278. if headerLen > maxSegHdrLen {
  279. return fmt.Errorf("header len %d exceeds max %d", headerLen, maxSegHdrLen)
  280. }
  281. if headerLen-csumStart != udpHeaderLen {
  282. return fmt.Errorf("udp header len mismatch: %d", headerLen-csumStart)
  283. }
  284. payLen := len(pkt) - headerLen
  285. gsoSize := int(gsoSizeU)
  286. numSeg := (payLen + gsoSize - 1) / gsoSize
  287. if numSeg == 0 {
  288. numSeg = 1
  289. }
  290. var udpTmp [udpHeaderLen]byte
  291. copy(udpTmp[:], pkt[csumStart:headerLen])
  292. udpTmp[udpLengthOff], udpTmp[udpLengthOff+1] = 0, 0
  293. udpTmp[udpChecksumOff], udpTmp[udpChecksumOff+1] = 0, 0
  294. baseUDPHdrSum := uint32(checksum.Checksum(udpTmp[:], 0))
  295. var baseProtoSum uint32
  296. if isV4 {
  297. baseProtoSum = uint32(checksum.Checksum(pkt[ipv4SrcOff:ipv4AddrsEnd], 0))
  298. } else {
  299. baseProtoSum = uint32(checksum.Checksum(pkt[ipv6SrcOff:ipv6AddrsEnd], 0))
  300. }
  301. baseProtoSum += uint32(unix.IPPROTO_UDP)
  302. var baseIPHdrSum uint32
  303. if isV4 {
  304. ihl := int(pkt[0]&0x0f) * 4
  305. if ihl < ipv4HeaderMinLen || ihl > csumStart {
  306. return fmt.Errorf("bad IPv4 IHL: %d", ihl)
  307. }
  308. var ipTmp [ipv4HeaderMaxLen]byte
  309. copy(ipTmp[:ihl], pkt[:ihl])
  310. ipTmp[ipv4TotalLenOff], ipTmp[ipv4TotalLenOff+1] = 0, 0
  311. ipTmp[ipv4ChecksumOff], ipTmp[ipv4ChecksumOff+1] = 0, 0
  312. baseIPHdrSum = uint32(checksum.Checksum(ipTmp[:ihl], 0))
  313. }
  314. // Snapshot the pristine L3+L4 header once and stamp every segment from
  315. // it; see SegmentTCP for why sourcing from pkt[:headerLen] corrupts
  316. // segments when gsoSize < headerLen.
  317. var savedHdr [maxSegHdrLen]byte
  318. copy(savedHdr[:headerLen], pkt[:headerLen])
  319. for i := 0; i < numSeg; i++ {
  320. segStart := i * gsoSize
  321. segEnd := segStart + gsoSize
  322. if segEnd > payLen {
  323. segEnd = payLen
  324. }
  325. segPayLen := segEnd - segStart
  326. segLen := headerLen + segPayLen
  327. headerOff := i * gsoSize
  328. if i > 0 {
  329. copy(pkt[headerOff:headerOff+headerLen], savedHdr[:headerLen])
  330. }
  331. seg := pkt[headerOff : headerOff+segLen]
  332. totalLen := segLen
  333. udpLen := udpHeaderLen + segPayLen
  334. if isV4 {
  335. binary.BigEndian.PutUint16(seg[ipv4TotalLenOff:ipv4TotalLenOff+2], uint16(totalLen))
  336. ipSum := baseIPHdrSum + uint32(totalLen)
  337. binary.BigEndian.PutUint16(seg[ipv4ChecksumOff:ipv4ChecksumOff+2], foldComplement(ipSum))
  338. } else {
  339. binary.BigEndian.PutUint16(seg[ipv6PayloadLenOff:ipv6PayloadLenOff+2], uint16(headerLen-ipv6FixedLen+segPayLen))
  340. }
  341. binary.BigEndian.PutUint16(seg[csumStart+udpLengthOff:csumStart+udpLengthOff+2], uint16(udpLen))
  342. paySum := uint32(checksum.Checksum(pkt[headerLen+segStart:headerLen+segEnd], 0))
  343. wide := uint64(baseUDPHdrSum) + uint64(paySum) + uint64(baseProtoSum)
  344. wide += uint64(udpLen) + uint64(udpLen)
  345. wide = (wide & 0xffffffff) + (wide >> 32)
  346. wide = (wide & 0xffffffff) + (wide >> 32)
  347. csum := foldComplement(uint32(wide))
  348. if csum == 0 {
  349. csum = 0xffff
  350. }
  351. binary.BigEndian.PutUint16(seg[csumStart+udpChecksumOff:csumStart+udpChecksumOff+2], csum)
  352. if err := yield(seg); err != nil {
  353. return err
  354. }
  355. }
  356. return nil
  357. }
  358. // FinishChecksum computes the L4 checksum for a non-GSO packet that the kernel
  359. // handed us with NEEDS_CSUM set. csum_start / csum_offset point at the 16-bit
  360. // checksum field; we zero it, fold a full sum (the field was pre-loaded with
  361. // the pseudo-header partial sum by the kernel), and store the result.
  362. func FinishChecksum(seg []byte, hdr Hdr) error {
  363. cs := int(hdr.CsumStart)
  364. co := int(hdr.CsumOffset)
  365. if cs+co+2 > len(seg) {
  366. return fmt.Errorf("csum offsets out of range: start=%d offset=%d len=%d", cs, co, len(seg))
  367. }
  368. // The kernel stores a partial pseudo-header sum at [cs+co:]; sum over the
  369. // L4 region starting at cs, folding the prior partial in as the seed.
  370. partial := binary.BigEndian.Uint16(seg[cs+co : cs+co+2])
  371. seg[cs+co] = 0
  372. seg[cs+co+1] = 0
  373. binary.BigEndian.PutUint16(seg[cs+co:cs+co+2], ^checksum.Checksum(seg[cs:], partial))
  374. return nil
  375. }
  376. // foldComplement folds a 32-bit one's-complement partial sum to 16 bits and
  377. // complements it, yielding the on-wire Internet checksum value.
  378. func foldComplement(sum uint32) uint16 {
  379. sum = (sum & 0xffff) + (sum >> 16)
  380. sum = (sum & 0xffff) + (sum >> 16)
  381. return ^uint16(sum)
  382. }