segment_linux.go 16 KB

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