segment_linux_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. //go:build linux && !android
  2. package virtio
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "testing"
  7. "golang.org/x/sys/unix"
  8. "github.com/slackhq/nebula/overlay/checksum"
  9. )
  10. // verifyChecksum confirms that the one's-complement sum across b, seeded with
  11. // a folded pseudo-header sum, equals all-ones (a valid on-wire checksum).
  12. // A corrupted header stamped into a segment makes this fail even when the
  13. // checksum field itself was computed from the (pristine) base sums, because
  14. // the bytes the receiver would sum no longer match what was checksummed.
  15. func verifyChecksum(b []byte, pseudo uint16) bool {
  16. return checksum.Checksum(b, pseudo) == 0xffff
  17. }
  18. // pseudoHeaderIPv4 folds the TCP/UDP pseudo-header sum from a segment's own
  19. // address and length fields, used to independently verify its L4 checksum.
  20. func pseudoHeaderIPv4(src, dst []byte, proto byte, l4Len int) uint16 {
  21. s := uint32(checksum.Checksum(src, 0)) + uint32(checksum.Checksum(dst, 0))
  22. s += uint32(proto) + uint32(l4Len)
  23. s = (s & 0xffff) + (s >> 16)
  24. s = (s & 0xffff) + (s >> 16)
  25. return uint16(s)
  26. }
  27. // buildTCPv4Super constructs a synthetic IPv4/TCP TSO superpacket with a
  28. // payload of payLen bytes and returns it alongside the header fields the
  29. // segmenter needs. The header is a fixed 40 bytes (20 IPv4 + 20 TCP).
  30. func buildTCPv4Super(payLen int) (pkt []byte, hdrLen, csumStart uint16) {
  31. const ipLen = 20
  32. const tcpLen = 20
  33. pkt = make([]byte, ipLen+tcpLen+payLen)
  34. // IPv4 header.
  35. pkt[0] = 0x45 // version 4, IHL 5
  36. binary.BigEndian.PutUint16(pkt[2:4], uint16(ipLen+tcpLen+payLen))
  37. binary.BigEndian.PutUint16(pkt[4:6], 0x4242) // ID
  38. pkt[8] = 64 // TTL
  39. pkt[9] = unix.IPPROTO_TCP
  40. copy(pkt[12:16], []byte{10, 0, 0, 1}) // src
  41. copy(pkt[16:20], []byte{10, 0, 0, 2}) // dst
  42. // TCP header.
  43. binary.BigEndian.PutUint16(pkt[20:22], 12345) // sport
  44. binary.BigEndian.PutUint16(pkt[22:24], 80) // dport
  45. binary.BigEndian.PutUint32(pkt[24:28], 10000) // seq
  46. binary.BigEndian.PutUint32(pkt[28:32], 20000) // ack
  47. pkt[32] = 0x50 // data offset 5 words
  48. pkt[33] = 0x18 // ACK | PSH
  49. binary.BigEndian.PutUint16(pkt[34:36], 65535) // window
  50. for i := range payLen {
  51. pkt[ipLen+tcpLen+i] = byte(i & 0xff)
  52. }
  53. return pkt, ipLen + tcpLen, ipLen
  54. }
  55. // buildUDPv4Super constructs a synthetic IPv4/UDP USO superpacket with a
  56. // payload of payLen bytes. Header is a fixed 28 bytes (20 IPv4 + 8 UDP).
  57. func buildUDPv4Super(payLen int) (pkt []byte, hdrLen, csumStart uint16) {
  58. const ipLen = 20
  59. const udpLen = 8
  60. pkt = make([]byte, ipLen+udpLen+payLen)
  61. pkt[0] = 0x45
  62. binary.BigEndian.PutUint16(pkt[2:4], uint16(ipLen+udpLen+payLen))
  63. binary.BigEndian.PutUint16(pkt[4:6], 0x4242)
  64. pkt[8] = 64
  65. pkt[9] = unix.IPPROTO_UDP
  66. copy(pkt[12:16], []byte{10, 0, 0, 1})
  67. copy(pkt[16:20], []byte{10, 0, 0, 2})
  68. binary.BigEndian.PutUint16(pkt[20:22], 12345) // sport
  69. binary.BigEndian.PutUint16(pkt[22:24], 53) // dport
  70. for i := range payLen {
  71. pkt[ipLen+udpLen+i] = byte(i & 0xff)
  72. }
  73. return pkt, ipLen + udpLen, ipLen
  74. }
  75. // collectTCP segments a fresh copy of pkt and returns each segment as an
  76. // independent slice so assertions can run after segmentation completes.
  77. func collectTCP(t *testing.T, pkt []byte, hdrLen, csumStart, gsoSize uint16) [][]byte {
  78. t.Helper()
  79. work := append([]byte(nil), pkt...)
  80. var out [][]byte
  81. err := SegmentTCP(work, hdrLen, csumStart, gsoSize, func(seg []byte) error {
  82. out = append(out, append([]byte(nil), seg...))
  83. return nil
  84. })
  85. if err != nil {
  86. t.Fatalf("SegmentTCP: %v", err)
  87. }
  88. return out
  89. }
  90. func collectUDP(t *testing.T, pkt []byte, hdrLen, csumStart, gsoSize uint16) [][]byte {
  91. t.Helper()
  92. work := append([]byte(nil), pkt...)
  93. var out [][]byte
  94. err := SegmentUDP(work, hdrLen, csumStart, gsoSize, func(seg []byte) error {
  95. out = append(out, append([]byte(nil), seg...))
  96. return nil
  97. })
  98. if err != nil {
  99. t.Fatalf("SegmentUDP: %v", err)
  100. }
  101. return out
  102. }
  103. // TestSegmentTCPHeaderNotCorrupted is the regression test for the in-place
  104. // header-slide bug: when gsoSize < headerLen the old code stamped each
  105. // segment's header from pkt[:headerLen], which had already been overwritten
  106. // by the previous segment's overlapping stamp, so segments 2..n carried a
  107. // corrupted header (garbage src/dst/ports/seq). Every segment must instead
  108. // carry the ORIGINAL constant header fields with correct per-segment seq.
  109. func TestSegmentTCPHeaderNotCorrupted(t *testing.T) {
  110. const origSeq = 10000
  111. cases := []struct {
  112. name string
  113. payLen int
  114. gsoSize uint16
  115. }{
  116. // gsoSize (8) < headerLen (40): the bug's trigger. Even split.
  117. {"small-gso-even", 40, 8},
  118. // gsoSize (8) < headerLen (40) with a short final segment.
  119. {"small-gso-odd-tail", 44, 8},
  120. // gsoSize (100) >= headerLen (40): the normal path, must still work.
  121. {"normal-gso", 250, 100},
  122. }
  123. for _, tc := range cases {
  124. t.Run(tc.name, func(t *testing.T) {
  125. pkt, hdrLen, csumStart := buildTCPv4Super(tc.payLen)
  126. gso := int(tc.gsoSize)
  127. wantSeg := (tc.payLen + gso - 1) / gso
  128. segs := collectTCP(t, pkt, hdrLen, csumStart, tc.gsoSize)
  129. if len(segs) != wantSeg {
  130. t.Fatalf("got %d segments, want %d", len(segs), wantSeg)
  131. }
  132. off := 0
  133. for i, seg := range segs {
  134. // Constant header fields must be identical to the original in
  135. // EVERY segment. These are exactly the bytes the old code
  136. // corrupted in segments 2..n.
  137. if got := seg[0]; got != 0x45 {
  138. t.Errorf("seg %d: version/IHL byte=%#x want 0x45", i, got)
  139. }
  140. if seg[9] != unix.IPPROTO_TCP {
  141. t.Errorf("seg %d: proto=%d want %d", i, seg[9], unix.IPPROTO_TCP)
  142. }
  143. if !bytes.Equal(seg[12:16], []byte{10, 0, 0, 1}) {
  144. t.Errorf("seg %d: src=%v want [10 0 0 1]", i, seg[12:16])
  145. }
  146. if !bytes.Equal(seg[16:20], []byte{10, 0, 0, 2}) {
  147. t.Errorf("seg %d: dst=%v want [10 0 0 2]", i, seg[16:20])
  148. }
  149. if sport := binary.BigEndian.Uint16(seg[20:22]); sport != 12345 {
  150. t.Errorf("seg %d: sport=%d want 12345", i, sport)
  151. }
  152. if dport := binary.BigEndian.Uint16(seg[22:24]); dport != 80 {
  153. t.Errorf("seg %d: dport=%d want 80", i, dport)
  154. }
  155. if ack := binary.BigEndian.Uint32(seg[28:32]); ack != 20000 {
  156. t.Errorf("seg %d: ack=%d want 20000", i, ack)
  157. }
  158. if seg[32] != 0x50 {
  159. t.Errorf("seg %d: data-offset byte=%#x want 0x50", i, seg[32])
  160. }
  161. // Per-segment seq must advance by the payload offset.
  162. segStart := i * gso
  163. if seq := binary.BigEndian.Uint32(seg[24:28]); seq != uint32(origSeq+segStart) {
  164. t.Errorf("seg %d: seq=%d want %d", i, seq, origSeq+segStart)
  165. }
  166. // Payload bytes must be the original contiguous slice.
  167. segPayLen := len(seg) - int(hdrLen)
  168. wantPay := make([]byte, segPayLen)
  169. for k := range segPayLen {
  170. wantPay[k] = byte((off + k) & 0xff)
  171. }
  172. if !bytes.Equal(seg[hdrLen:], wantPay) {
  173. t.Errorf("seg %d: payload mismatch", i)
  174. }
  175. off += segPayLen
  176. // End-to-end: the stamped header must checksum-verify. A
  177. // corrupted header fails here because the written checksum was
  178. // derived from the pristine header.
  179. if !verifyChecksum(seg[:20], 0) {
  180. t.Errorf("seg %d: bad IPv4 header checksum", i)
  181. }
  182. psum := pseudoHeaderIPv4(seg[12:16], seg[16:20], unix.IPPROTO_TCP, len(seg)-20)
  183. if !verifyChecksum(seg[20:], psum) {
  184. t.Errorf("seg %d: bad TCP checksum", i)
  185. }
  186. }
  187. })
  188. }
  189. }
  190. // TestCorrectHdrLenChecksumBound guards the checksum-field bounds check in
  191. // CorrectHdrLen. The checksum field sits at CsumStart+CsumOffset, so the check
  192. // must be computed from CsumStart+CsumOffset — NOT CsumStart+CsumStart, a
  193. // regression that doubled CsumStart and thus over-tightened the bound (since
  194. // CsumOffset, 6 for UDP / 16 for TCP, is always < CsumStart >= 20). That bogus
  195. // bound spuriously rejected valid small USO superpackets in decodeRead.
  196. func TestCorrectHdrLenChecksumBound(t *testing.T) {
  197. // A valid IPv4 USO superpacket: 20B IPv4 + 8B UDP + two 6-byte segments
  198. // (payload 12) = 40 bytes total. CsumStart=20, CsumOffset=6, so the UDP
  199. // checksum field lives at bytes 26..27, comfortably inside the 40-byte
  200. // packet. The OLD formula computed cSumAt = CsumStart+CsumStart = 40 and
  201. // rejected on cSumAt+1 (41) >= len(pkt) (40); the fix (CsumStart+CsumOffset
  202. // = 26) accepts. This case FAILS against the CsumStart+CsumStart regression.
  203. t.Run("valid-small-uso-accepted", func(t *testing.T) {
  204. pkt, _, csumStart := buildUDPv4Super(12) // total len 40
  205. hdr := NewHeader(
  206. unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, /*flags*/
  207. unix.VIRTIO_NET_HDR_GSO_UDP_L4, /*gsoType*/
  208. 0, /*hdrLen*/
  209. 6, /*gsoSize: two 6-byte segments*/
  210. csumStart, /*csumStart*/
  211. 6, /*csumOffset*/
  212. )
  213. if err := CorrectHdrLen(pkt, &hdr); err != nil {
  214. t.Fatalf("CorrectHdrLen rejected a valid 40-byte USO superpacket: %v", err)
  215. }
  216. if hdr.HdrLen != csumStart+udpHeaderLen {
  217. t.Errorf("HdrLen = %d, want %d", hdr.HdrLen, csumStart+udpHeaderLen)
  218. }
  219. })
  220. // A genuinely-too-short packet: CsumStart=20, CsumOffset=6 means the
  221. // checksum field would end at byte 27, but the packet is only 25 bytes
  222. // (CsumStart+CsumOffset+2 = 28 > 25). CorrectHdrLen must still reject it.
  223. t.Run("too-short-rejected", func(t *testing.T) {
  224. pkt := make([]byte, 25)
  225. pkt[0] = 0x45 // IPv4, IHL 5
  226. hdr := NewHeader(
  227. unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, /*flags*/
  228. unix.VIRTIO_NET_HDR_GSO_UDP_L4, /*gsoType*/
  229. 0, /*hdrLen*/
  230. 6, /*gsoSize*/
  231. 20, /*csumStart*/
  232. 6, /*csumOffset*/
  233. )
  234. if err := CorrectHdrLen(pkt, &hdr); err == nil {
  235. t.Fatalf("CorrectHdrLen accepted a too-short (25-byte) packet")
  236. }
  237. })
  238. }
  239. // TestSegmentUDPHeaderNotCorrupted is the USO counterpart: SegmentUDP performs
  240. // the same header stamp and must be correct when gsoSize < headerLen.
  241. func TestSegmentUDPHeaderNotCorrupted(t *testing.T) {
  242. cases := []struct {
  243. name string
  244. payLen int
  245. gsoSize uint16
  246. }{
  247. {"small-gso-even", 40, 8},
  248. {"small-gso-odd-tail", 44, 8},
  249. {"normal-gso", 250, 100},
  250. }
  251. for _, tc := range cases {
  252. t.Run(tc.name, func(t *testing.T) {
  253. pkt, hdrLen, csumStart := buildUDPv4Super(tc.payLen)
  254. gso := int(tc.gsoSize)
  255. wantSeg := (tc.payLen + gso - 1) / gso
  256. segs := collectUDP(t, pkt, hdrLen, csumStart, tc.gsoSize)
  257. if len(segs) != wantSeg {
  258. t.Fatalf("got %d segments, want %d", len(segs), wantSeg)
  259. }
  260. off := 0
  261. for i, seg := range segs {
  262. if got := seg[0]; got != 0x45 {
  263. t.Errorf("seg %d: version/IHL byte=%#x want 0x45", i, got)
  264. }
  265. if seg[9] != unix.IPPROTO_UDP {
  266. t.Errorf("seg %d: proto=%d want %d", i, seg[9], unix.IPPROTO_UDP)
  267. }
  268. if !bytes.Equal(seg[12:16], []byte{10, 0, 0, 1}) {
  269. t.Errorf("seg %d: src=%v want [10 0 0 1]", i, seg[12:16])
  270. }
  271. if !bytes.Equal(seg[16:20], []byte{10, 0, 0, 2}) {
  272. t.Errorf("seg %d: dst=%v want [10 0 0 2]", i, seg[16:20])
  273. }
  274. if sport := binary.BigEndian.Uint16(seg[20:22]); sport != 12345 {
  275. t.Errorf("seg %d: sport=%d want 12345", i, sport)
  276. }
  277. if dport := binary.BigEndian.Uint16(seg[22:24]); dport != 53 {
  278. t.Errorf("seg %d: dport=%d want 53", i, dport)
  279. }
  280. // Software UDP GSO bumps the IPv4 ID per segment just like TSO
  281. // (inet_gso_segment's fixed-ID case is TCP-only).
  282. if id := binary.BigEndian.Uint16(seg[4:6]); id != 0x4242+uint16(i) {
  283. t.Errorf("seg %d: ip id=%#x want %#x", i, id, 0x4242+uint16(i))
  284. }
  285. segPayLen := len(seg) - int(hdrLen)
  286. if udpLen := binary.BigEndian.Uint16(seg[24:26]); udpLen != uint16(8+segPayLen) {
  287. t.Errorf("seg %d: udp len=%d want %d", i, udpLen, 8+segPayLen)
  288. }
  289. wantPay := make([]byte, segPayLen)
  290. for k := range segPayLen {
  291. wantPay[k] = byte((off + k) & 0xff)
  292. }
  293. if !bytes.Equal(seg[hdrLen:], wantPay) {
  294. t.Errorf("seg %d: payload mismatch", i)
  295. }
  296. off += segPayLen
  297. if !verifyChecksum(seg[:20], 0) {
  298. t.Errorf("seg %d: bad IPv4 header checksum", i)
  299. }
  300. psum := pseudoHeaderIPv4(seg[12:16], seg[16:20], unix.IPPROTO_UDP, len(seg)-20)
  301. if !verifyChecksum(seg[20:], psum) {
  302. t.Errorf("seg %d: bad UDP checksum", i)
  303. }
  304. }
  305. })
  306. }
  307. }
  308. // buildUDPv4Single constructs a single IPv4/UDP datagram with the checksum field pre-loaded with the folded
  309. // pseudo-header sum, which is how a NEEDS_CSUM (CHECKSUM_PARTIAL) packet arrives from the tun.
  310. func buildUDPv4Single(payload []byte) (pkt []byte, hdr Hdr) {
  311. const ipLen, udpLen = 20, 8
  312. pkt = make([]byte, ipLen+udpLen+len(payload))
  313. pkt[0] = 0x45
  314. binary.BigEndian.PutUint16(pkt[2:4], uint16(len(pkt)))
  315. pkt[8] = 64
  316. pkt[9] = unix.IPPROTO_UDP
  317. copy(pkt[12:16], []byte{10, 0, 0, 1})
  318. copy(pkt[16:20], []byte{10, 0, 0, 2})
  319. binary.BigEndian.PutUint16(pkt[ipLen:ipLen+2], 12345)
  320. binary.BigEndian.PutUint16(pkt[ipLen+2:ipLen+4], 53)
  321. binary.BigEndian.PutUint16(pkt[ipLen+4:ipLen+6], uint16(udpLen+len(payload)))
  322. copy(pkt[ipLen+udpLen:], payload)
  323. pseudo := pseudoHeaderIPv4(pkt[12:16], pkt[16:20], unix.IPPROTO_UDP, udpLen+len(payload))
  324. binary.BigEndian.PutUint16(pkt[ipLen+udpChecksumOff:ipLen+udpChecksumOff+2], pseudo)
  325. return pkt, NewHeader(unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, unix.VIRTIO_NET_HDR_GSO_NONE, 0, 0, ipLen, udpChecksumOff)
  326. }
  327. // TestFinishChecksumUDPZeroStoresAllOnes pins RFC 768: a UDP checksum that computes to zero goes on the wire as
  328. // 0xffff, because all-zero is the reserved "no checksum" encoding that IPv6 rejects outright.
  329. func TestFinishChecksumUDPZeroStoresAllOnes(t *testing.T) {
  330. var payload []byte
  331. for i := range 0x10000 {
  332. p := []byte{byte(i >> 8), byte(i)}
  333. pkt, hdr := buildUDPv4Single(p)
  334. cs, co := int(hdr.CsumStart), int(hdr.CsumOffset)
  335. partial := binary.BigEndian.Uint16(pkt[cs+co : cs+co+2])
  336. pkt[cs+co], pkt[cs+co+1] = 0, 0
  337. if ^checksum.Checksum(pkt[cs:], partial) == 0 {
  338. payload = p
  339. break
  340. }
  341. }
  342. if payload == nil {
  343. t.Fatal("no 2-byte payload produced a zero checksum")
  344. }
  345. pkt, hdr := buildUDPv4Single(payload)
  346. if err := FinishChecksum(pkt, hdr); err != nil {
  347. t.Fatalf("FinishChecksum: %v", err)
  348. }
  349. off := int(hdr.CsumStart) + int(hdr.CsumOffset)
  350. if got := binary.BigEndian.Uint16(pkt[off : off+2]); got != 0xffff {
  351. t.Fatalf("stored %#04x, want 0xffff for a UDP checksum that folds to zero", got)
  352. }
  353. }
  354. // TestFinishChecksumTCPZeroPreserved is the other half of the protocol split: zero is a legal TCP checksum and must
  355. // be stored as-is, so the UDP rewrite must not fire on a TCP csum_offset.
  356. func TestFinishChecksumTCPZeroPreserved(t *testing.T) {
  357. const cs, co = 20, tcpChecksumOff
  358. // Seed the partial so the completed checksum lands on zero, the case the UDP path rewrites.
  359. seg := make([]byte, cs+co+2)
  360. for i := range seg[cs:] {
  361. seg[cs+i] = byte(i * 7)
  362. }
  363. var partial uint16
  364. for i := 0; i <= 0xffff; i++ {
  365. binary.BigEndian.PutUint16(seg[cs+co:cs+co+2], uint16(i))
  366. probe := append([]byte(nil), seg...)
  367. probe[cs+co], probe[cs+co+1] = 0, 0
  368. if ^checksum.Checksum(probe[cs:], uint16(i)) == 0 {
  369. partial = uint16(i)
  370. break
  371. }
  372. }
  373. binary.BigEndian.PutUint16(seg[cs+co:cs+co+2], partial)
  374. hdr := NewHeader(unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, unix.VIRTIO_NET_HDR_GSO_NONE, 0, 0, cs, co)
  375. if err := FinishChecksum(seg, hdr); err != nil {
  376. t.Fatalf("FinishChecksum: %v", err)
  377. }
  378. if got := binary.BigEndian.Uint16(seg[cs+co : cs+co+2]); got != 0 {
  379. t.Fatalf("stored %#04x, want 0x0000 (zero is a legal TCP checksum)", got)
  380. }
  381. }
  382. // TestFinishChecksumUDPValidates confirms the ordinary path still produces a checksum a receiver accepts.
  383. func TestFinishChecksumUDPValidates(t *testing.T) {
  384. payload := []byte("the definitive tun offloads branch")
  385. pkt, hdr := buildUDPv4Single(payload)
  386. if err := FinishChecksum(pkt, hdr); err != nil {
  387. t.Fatalf("FinishChecksum: %v", err)
  388. }
  389. pseudo := pseudoHeaderIPv4(pkt[12:16], pkt[16:20], unix.IPPROTO_UDP, 8+len(payload))
  390. if !verifyChecksum(pkt[hdr.CsumStart:], pseudo) {
  391. t.Fatal("completed UDP checksum does not validate")
  392. }
  393. }
  394. // TestCheckValidMasksGSOECN: GSO_ECN is a qualifier bit the kernel ORs
  395. // into gso_type for TSO superpackets with CWR set. CheckValid must
  396. // validate an ECN-qualified type as its base type — previously TCPV4|ECN
  397. // fell into the default case and skipped the IP-version agreement check.
  398. // The qualifier is TCP-only, so it must be rejected on UDP_L4.
  399. func TestCheckValidMasksGSOECN(t *testing.T) {
  400. v4pkt, _, _ := buildTCPv4Super(100)
  401. v6pkt := make([]byte, len(v4pkt))
  402. copy(v6pkt, v4pkt)
  403. v6pkt[0] = 0x60 // claim IPv6
  404. cases := []struct {
  405. name string
  406. pkt []byte
  407. gsoType uint8
  408. wantErr bool
  409. }{
  410. {"tcpv4-ecn-v4", v4pkt, unix.VIRTIO_NET_HDR_GSO_TCPV4 | unix.VIRTIO_NET_HDR_GSO_ECN, false},
  411. {"tcpv4-ecn-v6-mismatch", v6pkt, unix.VIRTIO_NET_HDR_GSO_TCPV4 | unix.VIRTIO_NET_HDR_GSO_ECN, true},
  412. {"tcpv6-ecn-v4-mismatch", v4pkt, unix.VIRTIO_NET_HDR_GSO_TCPV6 | unix.VIRTIO_NET_HDR_GSO_ECN, true},
  413. {"udp-l4-ecn-rejected", v4pkt, unix.VIRTIO_NET_HDR_GSO_UDP_L4 | unix.VIRTIO_NET_HDR_GSO_ECN, true},
  414. {"tcpv4-plain-v4", v4pkt, unix.VIRTIO_NET_HDR_GSO_TCPV4, false},
  415. {"tcpv4-plain-v6-mismatch", v6pkt, unix.VIRTIO_NET_HDR_GSO_TCPV4, true},
  416. }
  417. for _, tc := range cases {
  418. t.Run(tc.name, func(t *testing.T) {
  419. err := CheckValid(tc.pkt, NewHeader(0, tc.gsoType, 0, 100, 0, 0))
  420. if tc.wantErr && err == nil {
  421. t.Errorf("CheckValid(gsoType=%#x) = nil, want error", tc.gsoType)
  422. }
  423. if !tc.wantErr && err != nil {
  424. t.Errorf("CheckValid(gsoType=%#x) = %v, want nil", tc.gsoType, err)
  425. }
  426. })
  427. }
  428. }
  429. // TestCheckValidRejectsZeroGSOSize: a GSO-typed header with gso_size=0 must be
  430. // rejected. It would produce a Packet whose GSOInfo.IsSuperpacket() is false,
  431. // dodging both segmentation and FinishChecksum on its way downstream.
  432. func TestCheckValidRejectsZeroGSOSize(t *testing.T) {
  433. v4pkt, _, _ := buildTCPv4Super(100)
  434. if err := CheckValid(v4pkt, NewHeader(0, unix.VIRTIO_NET_HDR_GSO_TCPV4, 0, 0, 0, 0)); err == nil {
  435. t.Fatal("CheckValid accepted a GSO-typed header with gso_size=0")
  436. }
  437. }
  438. // TestFoldComplementMatchesReference checks the segmenter's fold-and-invert
  439. // against an independent RFC 1071 reference fold, hitting the carry edge
  440. // cases (values whose first fold produces another carry).
  441. func TestFoldComplementMatchesReference(t *testing.T) {
  442. refFold := func(s uint64) uint16 {
  443. for s>>16 != 0 {
  444. s = s&0xffff + s>>16
  445. }
  446. return uint16(s)
  447. }
  448. cases := []uint32{
  449. 0, 1, 0xffff,
  450. 0x10000, // single carry
  451. 0x1fffe, // 0xffff + 0xffff: carry produces another 0xffff
  452. 0xffff0000, // high half only
  453. 0xfffeffff, // first fold yields another carry
  454. 0xffffffff, // worst case
  455. }
  456. for _, c := range cases {
  457. if got, want := foldComplement(c), ^refFold(uint64(c)); got != want {
  458. t.Errorf("foldComplement(%#x) = %#x, want %#x", c, got, want)
  459. }
  460. }
  461. }
  462. // referenceBaseIPv4HdrSum and referenceBaseTCPHdrSum are the straightforward
  463. // implementations that baseIPv4HdrSum/baseTCPHdrSum replaced: copy the header
  464. // into scratch, zero the fields the segment loop rewrites, sum. The production
  465. // versions instead sum in place and subtract those fields via one's-complement
  466. // arithmetic, which is faster but far less obvious — particularly for the TCP
  467. // flags byte, which is only half of a 16-bit word. These references exist so
  468. // that trade is checked rather than asserted.
  469. func referenceBaseIPv4HdrSum(pkt []byte, ihl int) uint32 {
  470. var ipTmp [ipv4HeaderMaxLen]byte
  471. copy(ipTmp[:ihl], pkt[:ihl])
  472. ipTmp[ipv4TotalLenOff], ipTmp[ipv4TotalLenOff+1] = 0, 0
  473. ipTmp[ipv4ChecksumOff], ipTmp[ipv4ChecksumOff+1] = 0, 0
  474. ipTmp[ipv4IDOff], ipTmp[ipv4IDOff+1] = 0, 0
  475. return uint32(checksum.Checksum(ipTmp[:ihl], 0))
  476. }
  477. func referenceBaseTCPHdrSum(pkt []byte, csumStart, headerLen int) uint32 {
  478. tcpLen := headerLen - csumStart
  479. var tmp [tcpHeaderMaxLen]byte
  480. copy(tmp[:tcpLen], pkt[csumStart:headerLen])
  481. tmp[tcpSeqOff], tmp[tcpSeqOff+1], tmp[tcpSeqOff+2], tmp[tcpSeqOff+3] = 0, 0, 0, 0
  482. tmp[tcpFlagsOff] = 0
  483. tmp[tcpChecksumOff], tmp[tcpChecksumOff+1] = 0, 0
  484. return uint32(checksum.Checksum(tmp[:tcpLen], 0))
  485. }
  486. // randSeed is a tiny deterministic PRNG so this test needs no imports beyond
  487. // what the file already has and reproduces identically on every run.
  488. func randByte(state *uint32) byte {
  489. *state = *state*1664525 + 1013904223
  490. return byte(*state >> 24)
  491. }
  492. func TestBaseSumsMatchZeroingReference(t *testing.T) {
  493. state := uint32(12345)
  494. t.Run("ipv4", func(t *testing.T) {
  495. for ihl := ipv4HeaderMinLen; ihl <= ipv4HeaderMaxLen; ihl += 4 {
  496. for range 5000 {
  497. pkt := make([]byte, ihl)
  498. for i := range pkt {
  499. pkt[i] = randByte(&state)
  500. }
  501. pkt[0] = byte(0x40 | (ihl / 4))
  502. want := referenceBaseIPv4HdrSum(pkt, ihl)
  503. got, err := baseIPv4HdrSum(pkt, ihl)
  504. if err != nil {
  505. t.Fatalf("ihl=%d: %v", ihl, err)
  506. }
  507. // Compare the value that reaches the wire: the raw partial
  508. // sums may legally differ by one's-complement -0 vs +0.
  509. for _, tl := range []uint32{20, 1500, 65535} {
  510. for _, id := range []uint32{0, 0x4242, 0xffff} {
  511. if a, b := foldComplement(want+tl+id), foldComplement(got+tl+id); a != b {
  512. t.Fatalf("ihl=%d tl=%d id=%d: %#04x != %#04x", ihl, tl, id, a, b)
  513. }
  514. }
  515. }
  516. }
  517. }
  518. })
  519. t.Run("tcp", func(t *testing.T) {
  520. const csumStart = 20
  521. for dataOff := 5; dataOff <= 15; dataOff++ {
  522. tcpLen := dataOff * 4
  523. headerLen := csumStart + tcpLen
  524. for range 5000 {
  525. pkt := make([]byte, headerLen+64)
  526. for i := range pkt {
  527. pkt[i] = randByte(&state)
  528. }
  529. pkt[0] = 0x45
  530. pkt[csumStart+tcpDataOffOff] = byte(dataOff << 4)
  531. want := referenceBaseTCPHdrSum(pkt, csumStart, headerLen)
  532. got := baseTCPHdrSum(pkt, csumStart, headerLen)
  533. for _, seq := range []uint32{0, 1, 0x4242_4242, 0xffff_ffff} {
  534. for _, fl := range []uint32{0x00, 0x10, 0x18, 0x19, 0xff} {
  535. for _, l4 := range []uint32{20, 1460, 65535} {
  536. a := foldComplement(want + seq + fl + l4)
  537. b := foldComplement(got + seq + fl + l4)
  538. if a != b {
  539. t.Fatalf("dataOff=%d seq=%#x fl=%#x l4=%d: %#04x != %#04x",
  540. dataOff, seq, fl, l4, a, b)
  541. }
  542. }
  543. }
  544. }
  545. }
  546. }
  547. })
  548. }