segment_linux_test.go 22 KB

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