flow_rx_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //go:build linux && !android && !e2e_testing
  2. package nebula
  3. import (
  4. "fmt"
  5. "net/netip"
  6. "sync/atomic"
  7. "testing"
  8. "time"
  9. "github.com/flynn/noise"
  10. "github.com/slackhq/nebula/header"
  11. "github.com/slackhq/nebula/noiseutil"
  12. "github.com/slackhq/nebula/udp"
  13. "github.com/stretchr/testify/require"
  14. "go.uber.org/goleak"
  15. )
  16. // TestFlowStagedRXOrderAndReplay feeds every packet behind a forgery of it, from another address, and a replay of
  17. // it, then a test packet that jumps the window and the whole stream again, with shuffled workers and a slow tun,
  18. // through small and large batches: the tun sees each segment once, in order, the window marks them all, the forgeries
  19. // neither consume a counter nor roam, and the jump does not get the earlier data packets of its batch rejected.
  20. func TestFlowStagedRXOrderAndReplay(t *testing.T) {
  21. defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
  22. for _, cipher := range []noise.CipherFunc{noiseutil.CipherAESGCM, noise.CipherChaChaPoly} {
  23. for _, batchLen := range []int{8, 1000} {
  24. t.Run(fmt.Sprintf("%s/batch=%d", cipher.CipherName(), batchLen), func(t *testing.T) {
  25. sender, receiver := newFlowTestPair(t, cipher, stagedOn(4))
  26. delayCrypto(receiver, func(n uint64) {
  27. if n%32 == 0 {
  28. time.Sleep(time.Millisecond)
  29. }
  30. })
  31. receiver.tun.delay = 100 * time.Microsecond
  32. batches, want := flowTestBatches(30, 4, 1, 10)
  33. wire := wireFor(t, sender, batches)
  34. var feed [][]byte
  35. for i, p := range wire {
  36. // Corrupt the tag or the payload
  37. bad := append([]byte(nil), p...)
  38. bad[[]int{len(p) - 1, header.Len + 3}[i%2]] ^= 1
  39. feed = append(feed, bad, p, p)
  40. }
  41. // The jump lands in a batch with fresh data before it, at batch=1000
  42. sender.hostinfo.ConnectionState.messageCounter.Add(2 * ReplayWindow)
  43. feed = append(append(feed, sendControl(sender, header.Test, header.TestReply)), wire...)
  44. forged := func(i int) netip.AddrPort {
  45. if i < 3*len(wire) && i%3 == 0 {
  46. return netip.MustParseAddrPort("198.51.100.9:4242")
  47. }
  48. return flowTestUnder
  49. }
  50. rx0 := rxBatches.Count()
  51. conn := &rxConn{wire: feed, batchLen: batchLen, from: forged}
  52. receiver.receive(conn)
  53. require.Positive(t, rxBatches.Count()-rx0)
  54. require.Equal(t, (len(feed)+batchLen-1)/batchLen, conn.swaps, "every batch is handed off")
  55. require.Equal(t, want, receiver.tun.segments(t), "every packet exactly once, in order")
  56. require.Equal(t, flowTestUnder, receiver.hostinfo.GetRemote())
  57. for _, p := range wire {
  58. h := &header.H{}
  59. require.NoError(t, h.Parse(p))
  60. require.False(t, receiver.hostinfo.ConnectionState.window.Check(receiver.f.l, h.MessageCounter), "counter %d must be marked seen", h.MessageCounter)
  61. }
  62. })
  63. }
  64. }
  65. }
  66. // TestFlowStagedRXClose: a CloseTunnel in the middle of a batch is handled in its place, by the writer. The data after
  67. // it in the batch is still delivered from the batch's hostmap cache, as inline receive does.
  68. func TestFlowStagedRXClose(t *testing.T) {
  69. defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
  70. sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
  71. batches, want := flowTestBatches(4, 4, 1, 8)
  72. wire := wireFor(t, sender, batches)
  73. half := len(wire) / 2
  74. feed := append(append(append([][]byte{}, wire[:half]...), sendControl(sender, header.CloseTunnel, 0)), wire[half:]...)
  75. receiver.receive(&rxConn{wire: feed, batchLen: len(feed)})
  76. require.Equal(t, want, receiver.tun.segments(t))
  77. require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
  78. }
  79. // sendControl returns the wire packet of a control message from sender.
  80. func sendControl(sender *flowTestPeer, typ header.MessageType, st header.MessageSubType) []byte {
  81. sender.f.sendNoMetrics(typ, st, sender.hostinfo.ConnectionState, sender.hostinfo, flowTestUnder, nil, make([]byte, 12), make([]byte, mtu), 0)
  82. wire := sender.conn.captured()
  83. sender.conn.pkts, sender.conn.addrs = nil, nil
  84. return wire[len(wire)-1]
  85. }
  86. // receivePaths is inline, staged and, with the threshold, adaptive receive.
  87. func receivePaths() []stagedConfig {
  88. return []stagedConfig{{}, stagedOn(2)}
  89. }
  90. // TestFlowStagedRXRecvError feeds a RecvError that deletes the tunnel, then a known replay and new data for it, in one
  91. // batch. Every receive path must drop the data through its own view of the hostmap, without touching the replay window,
  92. // and answer each packet with a RecvError, as inline receive does, without decrypting the replay again.
  93. func TestFlowStagedRXRecvError(t *testing.T) {
  94. for _, sc := range receivePaths() {
  95. t.Run(stagedName(sc), func(t *testing.T) {
  96. sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
  97. receiver.f.messageMetrics = newMessageMetrics()
  98. receiver.f.acceptRecvErrorConfig = recvErrorAlways
  99. receiver.f.sendRecvErrorConfig = recvErrorAlways
  100. batches, want := flowTestBatches(1, 1, 1, 33)
  101. wire := wireFor(t, sender, batches)
  102. rxc := newRxContext(receiver.f, 0)
  103. receiver.f.readOutsidePackets(ViaSender{UdpAddr: flowTestUnder}, append([]byte(nil), wire[0]...), rxc)
  104. receiver.f.flushOutside(rxc)
  105. h := &header.H{}
  106. require.NoError(t, h.Parse(wire[0]))
  107. replay := h.MessageCounter
  108. var decrypts atomic.Int64
  109. delayCrypto(receiver, func(n uint64) {
  110. if n == replay {
  111. decrypts.Add(1)
  112. }
  113. })
  114. ctl := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, receiver.hostinfo.remoteIndexId, 0)
  115. conn := &rxConn{wire: append([][]byte{ctl}, wire...), batchLen: len(wire) + 1}
  116. receiver.receive(conn)
  117. require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
  118. require.Equal(t, want[:1], receiver.tun.segments(t))
  119. require.Zero(t, decrypts.Load(), "known replays must not be decrypted again")
  120. replies := conn.captured()
  121. require.Len(t, replies, len(wire))
  122. for i, reply := range replies {
  123. require.NoError(t, h.Parse(reply))
  124. require.Equal(t, header.RecvError, h.Type)
  125. require.NoError(t, h.Parse(wire[i]))
  126. require.True(t, i == 0 || receiver.hostinfo.ConnectionState.window.Check(nil, h.MessageCounter), "dropped data must not update replay state")
  127. }
  128. })
  129. }
  130. }
  131. // TestFlowStagedRXReplacedTunnel classifies a data packet, then a close and a new handshake replace its tunnel at the
  132. // same index before the writer commits it, as when the listener runs ahead: it must be dropped untouched.
  133. func TestFlowStagedRXReplacedTunnel(t *testing.T) {
  134. sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
  135. receiver.f.messageMetrics = newMessageMetrics()
  136. batches, _ := flowTestBatches(1, 1, 1, 1)
  137. wire := wireFor(t, sender, batches)
  138. closePacket := sendControl(sender, header.CloseTunnel, 0)
  139. p := &stagedRx{f: receiver.f, h: &header.H{}, hostmapCache: map[uint32]*HostInfo{}}
  140. item := rxItem{packet: wire[0], via: flowTestUnder}
  141. p.classify(&item)
  142. require.NotNil(t, item.ci)
  143. rxc := newRxContext(receiver.f, 0)
  144. p.process(&rxBatch{items: []rxItem{{packet: closePacket, via: flowTestUnder}}}, rxc)
  145. require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
  146. _, replacement := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
  147. receiver.f.hostMap.Lock()
  148. receiver.f.hostMap.unlockedAddHostInfo(replacement.hostinfo, receiver.f)
  149. receiver.f.hostMap.Unlock()
  150. p.process(&rxBatch{items: []rxItem{item}}, rxc)
  151. require.Empty(t, receiver.tun.writes)
  152. require.True(t, item.ci.window.Check(nil, item.counter))
  153. require.True(t, replacement.hostinfo.ConnectionState.window.Check(nil, item.counter))
  154. }
  155. // TestFlowStagedRXRealSocket exercises buffer handoff through the real Linux UDP receive loop.
  156. func TestFlowStagedRXRealSocket(t *testing.T) {
  157. defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
  158. sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(3))
  159. batches, want := flowTestBatches(60, 4, 1, 8)
  160. wire := wireFor(t, sender, batches)
  161. l := receiver.f.l
  162. conn, err := udp.NewListener(l, udp.Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Batch: 16, Offloads: true})
  163. require.NoError(t, err)
  164. addr, err := conn.LocalAddr()
  165. require.NoError(t, err)
  166. out, err := udp.NewListener(l, udp.Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Batch: 16, Offloads: true})
  167. require.NoError(t, err)
  168. defer out.Close()
  169. // The sender's address is the tunnel's remote, so no roaming
  170. from, err := out.LocalAddr()
  171. require.NoError(t, err)
  172. receiver.hostinfo.remote.Store(&from)
  173. done := make(chan struct{})
  174. go func() { receiver.receive(conn); close(done) }()
  175. // Send in bursts small enough for the default socket buffer
  176. for off := 0; off < len(wire); off += 32 {
  177. end := min(off+32, len(wire))
  178. addrs := make([]netip.AddrPort, end-off)
  179. for i := range addrs {
  180. addrs[i] = addr
  181. }
  182. _, err := out.WriteBatch(wire[off:end], addrs)
  183. require.NoError(t, err)
  184. require.Eventually(t, func() bool { return len(receiver.tun.segments(t)) >= end }, 5*time.Second, 100*time.Microsecond)
  185. }
  186. receiver.f.closed.Store(true)
  187. require.NoError(t, conn.Close())
  188. <-done
  189. require.Equal(t, want, receiver.tun.segments(t))
  190. }
  191. // TestFlowStagedRXCloseFlushesPartial: packets the listener holds in a batch it never got to end when the conn fails
  192. // are still committed, in order, on a live interface.
  193. func TestFlowStagedRXCloseFlushesPartial(t *testing.T) {
  194. defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
  195. sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
  196. batches, want := flowTestBatches(11, 4, 1, 8)
  197. wire := wireFor(t, sender, batches)
  198. p := newStagedRx(receiver.f, 0, newRxContext(receiver.f, 0))
  199. for i, packet := range wire {
  200. p.deliver(flowTestUnder, packet)
  201. if (i+1)%64 == 0 {
  202. p.endBatch()
  203. }
  204. }
  205. p.close()
  206. require.Equal(t, want, receiver.tun.segments(t))
  207. }