router.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. //go:build e2e_testing
  2. // +build e2e_testing
  3. package router
  4. import (
  5. "context"
  6. "fmt"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "testing"
  15. "time"
  16. "github.com/google/gopacket"
  17. "github.com/google/gopacket/layers"
  18. "github.com/slackhq/nebula"
  19. "github.com/slackhq/nebula/header"
  20. "github.com/slackhq/nebula/iputil"
  21. "github.com/slackhq/nebula/udp"
  22. )
  23. type R struct {
  24. // Simple map of the ip:port registered on a control to the control
  25. // Basically a router, right?
  26. controls map[string]*nebula.Control
  27. // A map for inbound packets for a control that doesn't know about this address
  28. inNat map[string]*nebula.Control
  29. // A last used map, if an inbound packet hit the inNat map then
  30. // all return packets should use the same last used inbound address for the outbound sender
  31. // map[from address + ":" + to address] => ip:port to rewrite in the udp packet to receiver
  32. outNat map[string]net.UDPAddr
  33. // A map of vpn ip to the nebula control it belongs to
  34. vpnControls map[iputil.VpnIp]*nebula.Control
  35. flow []flowEntry
  36. // All interactions are locked to help serialize behavior
  37. sync.Mutex
  38. fn string
  39. cancelRender context.CancelFunc
  40. t testing.TB
  41. }
  42. type flowEntry struct {
  43. note string
  44. packet *packet
  45. }
  46. type packet struct {
  47. from *nebula.Control
  48. to *nebula.Control
  49. packet *udp.Packet
  50. tun bool // a packet pulled off a tun device
  51. rx bool // the packet was received by a udp device
  52. }
  53. func (p *packet) WasReceived() {
  54. if p != nil {
  55. p.rx = true
  56. }
  57. }
  58. type ExitType int
  59. const (
  60. // KeepRouting the function will get called again on the next packet
  61. KeepRouting ExitType = 0
  62. // ExitNow does not route this packet and exits immediately
  63. ExitNow ExitType = 1
  64. // RouteAndExit routes this packet and exits immediately afterwards
  65. RouteAndExit ExitType = 2
  66. )
  67. type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType
  68. // NewR creates a new router to pass packets in a controlled fashion between the provided controllers.
  69. // The packet flow will be recorded in a file within the mermaid directory under the same name as the test.
  70. // Renders will occur automatically, roughly every 100ms, until a call to RenderFlow() is made
  71. func NewR(t testing.TB, controls ...*nebula.Control) *R {
  72. ctx, cancel := context.WithCancel(context.Background())
  73. if err := os.MkdirAll("mermaid", 0755); err != nil {
  74. panic(err)
  75. }
  76. r := &R{
  77. controls: make(map[string]*nebula.Control),
  78. vpnControls: make(map[iputil.VpnIp]*nebula.Control),
  79. inNat: make(map[string]*nebula.Control),
  80. outNat: make(map[string]net.UDPAddr),
  81. flow: []flowEntry{},
  82. fn: filepath.Join("mermaid", fmt.Sprintf("%s.md", t.Name())),
  83. t: t,
  84. cancelRender: cancel,
  85. }
  86. // Try to remove our render file
  87. os.Remove(r.fn)
  88. for _, c := range controls {
  89. addr := c.GetUDPAddr()
  90. if _, ok := r.controls[addr]; ok {
  91. panic("Duplicate listen address: " + addr)
  92. }
  93. r.vpnControls[c.GetVpnIp()] = c
  94. r.controls[addr] = c
  95. }
  96. // Spin the renderer in case we go nuts and the test never completes
  97. go func() {
  98. clockSource := time.NewTicker(time.Millisecond * 100)
  99. defer clockSource.Stop()
  100. for {
  101. select {
  102. case <-ctx.Done():
  103. return
  104. case <-clockSource.C:
  105. r.renderFlow()
  106. }
  107. }
  108. }()
  109. return r
  110. }
  111. // AddRoute will place the nebula controller at the ip and port specified.
  112. // It does not look at the addr attached to the instance.
  113. // If a route is used, this will behave like a NAT for the return path.
  114. // Rewriting the source ip:port to what was last sent to from the origin
  115. func (r *R) AddRoute(ip net.IP, port uint16, c *nebula.Control) {
  116. r.Lock()
  117. defer r.Unlock()
  118. inAddr := net.JoinHostPort(ip.String(), fmt.Sprintf("%v", port))
  119. if _, ok := r.inNat[inAddr]; ok {
  120. panic("Duplicate listen address inNat: " + inAddr)
  121. }
  122. r.inNat[inAddr] = c
  123. }
  124. // RenderFlow renders the packet flow seen up until now and stops further automatic renders from happening.
  125. func (r *R) RenderFlow() {
  126. r.cancelRender()
  127. r.renderFlow()
  128. }
  129. // CancelFlowLogs stops flow logs from being tracked and destroys any logs already collected
  130. func (r *R) CancelFlowLogs() {
  131. r.cancelRender()
  132. r.flow = nil
  133. }
  134. func (r *R) renderFlow() {
  135. if r.flow == nil {
  136. return
  137. }
  138. f, err := os.OpenFile(r.fn, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
  139. if err != nil {
  140. panic(err)
  141. }
  142. var participants = map[string]struct{}{}
  143. var participantsVals []string
  144. fmt.Fprintln(f, "```mermaid")
  145. fmt.Fprintln(f, "sequenceDiagram")
  146. // Assemble participants
  147. for _, e := range r.flow {
  148. if e.packet == nil {
  149. continue
  150. }
  151. addr := e.packet.from.GetUDPAddr()
  152. if _, ok := participants[addr]; ok {
  153. continue
  154. }
  155. participants[addr] = struct{}{}
  156. sanAddr := strings.Replace(addr, ":", "#58;", 1)
  157. participantsVals = append(participantsVals, sanAddr)
  158. fmt.Fprintf(
  159. f, " participant %s as Nebula: %s<br/>UDP: %s\n",
  160. sanAddr, e.packet.from.GetVpnIp(), sanAddr,
  161. )
  162. }
  163. // Print packets
  164. h := &header.H{}
  165. for _, e := range r.flow {
  166. if e.packet == nil {
  167. fmt.Fprintf(f, " note over %s: %s\n", strings.Join(participantsVals, ", "), e.note)
  168. continue
  169. }
  170. p := e.packet
  171. if p.tun {
  172. fmt.Fprintln(f, r.formatUdpPacket(p))
  173. } else {
  174. if err := h.Parse(p.packet.Data); err != nil {
  175. panic(err)
  176. }
  177. line := "--x"
  178. if p.rx {
  179. line = "->>"
  180. }
  181. fmt.Fprintf(f,
  182. " %s%s%s: %s(%s), counter: %v\n",
  183. strings.Replace(p.from.GetUDPAddr(), ":", "#58;", 1),
  184. line,
  185. strings.Replace(p.to.GetUDPAddr(), ":", "#58;", 1),
  186. h.TypeName(), h.SubTypeName(), h.MessageCounter,
  187. )
  188. }
  189. }
  190. fmt.Fprintln(f, "```")
  191. }
  192. // InjectFlow can be used to record packet flow if the test is handling the routing on its own.
  193. // The packet is assumed to have been received
  194. func (r *R) InjectFlow(from, to *nebula.Control, p *udp.Packet) {
  195. r.Lock()
  196. defer r.Unlock()
  197. r.unlockedInjectFlow(from, to, p, false)
  198. }
  199. func (r *R) Log(arg ...any) {
  200. if r.flow == nil {
  201. return
  202. }
  203. r.Lock()
  204. r.flow = append(r.flow, flowEntry{note: fmt.Sprint(arg...)})
  205. r.t.Log(arg...)
  206. r.Unlock()
  207. }
  208. func (r *R) Logf(format string, arg ...any) {
  209. if r.flow == nil {
  210. return
  211. }
  212. r.Lock()
  213. r.flow = append(r.flow, flowEntry{note: fmt.Sprintf(format, arg...)})
  214. r.t.Logf(format, arg...)
  215. r.Unlock()
  216. }
  217. // unlockedInjectFlow is used by the router to record a packet has been transmitted, the packet is returned and
  218. // should be marked as received AFTER it has been placed on the receivers channel.
  219. // If flow logs have been disabled this function will return nil
  220. func (r *R) unlockedInjectFlow(from, to *nebula.Control, p *udp.Packet, tun bool) *packet {
  221. if r.flow == nil {
  222. return nil
  223. }
  224. fp := &packet{
  225. from: from,
  226. to: to,
  227. packet: p.Copy(),
  228. tun: tun,
  229. }
  230. r.flow = append(r.flow, flowEntry{packet: fp})
  231. return fp
  232. }
  233. // OnceFrom will route a single packet from sender then return
  234. // If the router doesn't have the nebula controller for that address, we panic
  235. func (r *R) OnceFrom(sender *nebula.Control) {
  236. r.RouteExitFunc(sender, func(*udp.Packet, *nebula.Control) ExitType {
  237. return RouteAndExit
  238. })
  239. }
  240. // RouteUntilTxTun will route for sender and return when a packet is seen on receivers tun
  241. // If the router doesn't have the nebula controller for that address, we panic
  242. func (r *R) RouteUntilTxTun(sender *nebula.Control, receiver *nebula.Control) []byte {
  243. tunTx := receiver.GetTunTxChan()
  244. udpTx := sender.GetUDPTxChan()
  245. for {
  246. select {
  247. // Maybe we already have something on the tun for us
  248. case b := <-tunTx:
  249. r.Lock()
  250. np := udp.Packet{Data: make([]byte, len(b))}
  251. copy(np.Data, b)
  252. r.unlockedInjectFlow(receiver, receiver, &np, true)
  253. r.Unlock()
  254. return b
  255. // Nope, lets push the sender along
  256. case p := <-udpTx:
  257. outAddr := sender.GetUDPAddr()
  258. r.Lock()
  259. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  260. c := r.getControl(outAddr, inAddr, p)
  261. if c == nil {
  262. r.Unlock()
  263. panic("No control for udp tx")
  264. }
  265. fp := r.unlockedInjectFlow(sender, c, p, false)
  266. c.InjectUDPPacket(p)
  267. fp.WasReceived()
  268. r.Unlock()
  269. }
  270. }
  271. }
  272. // RouteForAllUntilTxTun will route for everyone and return when a packet is seen on receivers tun
  273. // If the router doesn't have the nebula controller for that address, we panic
  274. func (r *R) RouteForAllUntilTxTun(receiver *nebula.Control) []byte {
  275. sc := make([]reflect.SelectCase, len(r.controls)+1)
  276. cm := make([]*nebula.Control, len(r.controls)+1)
  277. i := 0
  278. sc[i] = reflect.SelectCase{
  279. Dir: reflect.SelectRecv,
  280. Chan: reflect.ValueOf(receiver.GetTunTxChan()),
  281. Send: reflect.Value{},
  282. }
  283. cm[i] = receiver
  284. i++
  285. for _, c := range r.controls {
  286. sc[i] = reflect.SelectCase{
  287. Dir: reflect.SelectRecv,
  288. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  289. Send: reflect.Value{},
  290. }
  291. cm[i] = c
  292. i++
  293. }
  294. for {
  295. x, rx, _ := reflect.Select(sc)
  296. r.Lock()
  297. if x == 0 {
  298. // we are the tun tx, we can exit
  299. p := rx.Interface().([]byte)
  300. np := udp.Packet{Data: make([]byte, len(p))}
  301. copy(np.Data, p)
  302. r.unlockedInjectFlow(cm[x], cm[x], &np, true)
  303. r.Unlock()
  304. return p
  305. } else {
  306. // we are a udp tx, route and continue
  307. p := rx.Interface().(*udp.Packet)
  308. outAddr := cm[x].GetUDPAddr()
  309. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  310. c := r.getControl(outAddr, inAddr, p)
  311. if c == nil {
  312. r.Unlock()
  313. panic("No control for udp tx")
  314. }
  315. fp := r.unlockedInjectFlow(cm[x], c, p, false)
  316. c.InjectUDPPacket(p)
  317. fp.WasReceived()
  318. }
  319. r.Unlock()
  320. }
  321. }
  322. // RouteExitFunc will call the whatDo func with each udp packet from sender.
  323. // whatDo can return:
  324. // - exitNow: the packet will not be routed and this call will return immediately
  325. // - routeAndExit: this call will return immediately after routing the last packet from sender
  326. // - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender
  327. func (r *R) RouteExitFunc(sender *nebula.Control, whatDo ExitFunc) {
  328. h := &header.H{}
  329. for {
  330. p := sender.GetFromUDP(true)
  331. r.Lock()
  332. if err := h.Parse(p.Data); err != nil {
  333. panic(err)
  334. }
  335. outAddr := sender.GetUDPAddr()
  336. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  337. receiver := r.getControl(outAddr, inAddr, p)
  338. if receiver == nil {
  339. r.Unlock()
  340. panic("Can't route for host: " + inAddr)
  341. }
  342. e := whatDo(p, receiver)
  343. switch e {
  344. case ExitNow:
  345. r.Unlock()
  346. return
  347. case RouteAndExit:
  348. fp := r.unlockedInjectFlow(sender, receiver, p, false)
  349. receiver.InjectUDPPacket(p)
  350. fp.WasReceived()
  351. r.Unlock()
  352. return
  353. case KeepRouting:
  354. fp := r.unlockedInjectFlow(sender, receiver, p, false)
  355. receiver.InjectUDPPacket(p)
  356. fp.WasReceived()
  357. default:
  358. panic(fmt.Sprintf("Unknown exitFunc return: %v", e))
  359. }
  360. r.Unlock()
  361. }
  362. }
  363. // RouteUntilAfterMsgType will route for sender until a message type is seen and sent from sender
  364. // If the router doesn't have the nebula controller for that address, we panic
  365. func (r *R) RouteUntilAfterMsgType(sender *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
  366. h := &header.H{}
  367. r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType {
  368. if err := h.Parse(p.Data); err != nil {
  369. panic(err)
  370. }
  371. if h.Type == msgType && h.Subtype == subType {
  372. return RouteAndExit
  373. }
  374. return KeepRouting
  375. })
  376. }
  377. func (r *R) RouteForAllUntilAfterMsgTypeTo(receiver *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
  378. h := &header.H{}
  379. r.RouteForAllExitFunc(func(p *udp.Packet, r *nebula.Control) ExitType {
  380. if r != receiver {
  381. return KeepRouting
  382. }
  383. if err := h.Parse(p.Data); err != nil {
  384. panic(err)
  385. }
  386. if h.Type == msgType && h.Subtype == subType {
  387. return RouteAndExit
  388. }
  389. return KeepRouting
  390. })
  391. }
  392. func (r *R) InjectUDPPacket(sender, receiver *nebula.Control, packet *udp.Packet) {
  393. r.Lock()
  394. defer r.Unlock()
  395. fp := r.unlockedInjectFlow(sender, receiver, packet, false)
  396. receiver.InjectUDPPacket(packet)
  397. fp.WasReceived()
  398. }
  399. // RouteForUntilAfterToAddr will route for sender and return only after it sees and sends a packet destined for toAddr
  400. // finish can be any of the exitType values except `keepRouting`, the default value is `routeAndExit`
  401. // If the router doesn't have the nebula controller for that address, we panic
  402. func (r *R) RouteForUntilAfterToAddr(sender *nebula.Control, toAddr *net.UDPAddr, finish ExitType) {
  403. if finish == KeepRouting {
  404. finish = RouteAndExit
  405. }
  406. r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType {
  407. if p.ToIp.Equal(toAddr.IP) && p.ToPort == uint16(toAddr.Port) {
  408. return finish
  409. }
  410. return KeepRouting
  411. })
  412. }
  413. // RouteForAllExitFunc will route for every registered controller and calls the whatDo func with each udp packet from
  414. // whatDo can return:
  415. // - exitNow: the packet will not be routed and this call will return immediately
  416. // - routeAndExit: this call will return immediately after routing the last packet from sender
  417. // - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender
  418. func (r *R) RouteForAllExitFunc(whatDo ExitFunc) {
  419. sc := make([]reflect.SelectCase, len(r.controls))
  420. cm := make([]*nebula.Control, len(r.controls))
  421. i := 0
  422. for _, c := range r.controls {
  423. sc[i] = reflect.SelectCase{
  424. Dir: reflect.SelectRecv,
  425. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  426. Send: reflect.Value{},
  427. }
  428. cm[i] = c
  429. i++
  430. }
  431. for {
  432. x, rx, _ := reflect.Select(sc)
  433. r.Lock()
  434. p := rx.Interface().(*udp.Packet)
  435. outAddr := cm[x].GetUDPAddr()
  436. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  437. receiver := r.getControl(outAddr, inAddr, p)
  438. if receiver == nil {
  439. r.Unlock()
  440. panic("Can't route for host: " + inAddr)
  441. }
  442. e := whatDo(p, receiver)
  443. switch e {
  444. case ExitNow:
  445. r.Unlock()
  446. return
  447. case RouteAndExit:
  448. fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
  449. receiver.InjectUDPPacket(p)
  450. fp.WasReceived()
  451. r.Unlock()
  452. return
  453. case KeepRouting:
  454. fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
  455. receiver.InjectUDPPacket(p)
  456. fp.WasReceived()
  457. default:
  458. panic(fmt.Sprintf("Unknown exitFunc return: %v", e))
  459. }
  460. r.Unlock()
  461. }
  462. }
  463. // FlushAll will route for every registered controller, exiting once there are no packets left to route
  464. func (r *R) FlushAll() {
  465. sc := make([]reflect.SelectCase, len(r.controls))
  466. cm := make([]*nebula.Control, len(r.controls))
  467. i := 0
  468. for _, c := range r.controls {
  469. sc[i] = reflect.SelectCase{
  470. Dir: reflect.SelectRecv,
  471. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  472. Send: reflect.Value{},
  473. }
  474. cm[i] = c
  475. i++
  476. }
  477. // Add a default case to exit when nothing is left to send
  478. sc = append(sc, reflect.SelectCase{
  479. Dir: reflect.SelectDefault,
  480. Chan: reflect.Value{},
  481. Send: reflect.Value{},
  482. })
  483. for {
  484. x, rx, ok := reflect.Select(sc)
  485. if !ok {
  486. return
  487. }
  488. r.Lock()
  489. p := rx.Interface().(*udp.Packet)
  490. outAddr := cm[x].GetUDPAddr()
  491. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  492. receiver := r.getControl(outAddr, inAddr, p)
  493. if receiver == nil {
  494. r.Unlock()
  495. panic("Can't route for host: " + inAddr)
  496. }
  497. r.Unlock()
  498. }
  499. }
  500. // getControl performs or seeds NAT translation and returns the control for toAddr, p from fields may change
  501. // This is an internal router function, the caller must hold the lock
  502. func (r *R) getControl(fromAddr, toAddr string, p *udp.Packet) *nebula.Control {
  503. if newAddr, ok := r.outNat[fromAddr+":"+toAddr]; ok {
  504. p.FromIp = newAddr.IP
  505. p.FromPort = uint16(newAddr.Port)
  506. }
  507. c, ok := r.inNat[toAddr]
  508. if ok {
  509. sHost, sPort, err := net.SplitHostPort(toAddr)
  510. if err != nil {
  511. panic(err)
  512. }
  513. port, err := strconv.Atoi(sPort)
  514. if err != nil {
  515. panic(err)
  516. }
  517. r.outNat[c.GetUDPAddr()+":"+fromAddr] = net.UDPAddr{
  518. IP: net.ParseIP(sHost),
  519. Port: port,
  520. }
  521. return c
  522. }
  523. return r.controls[toAddr]
  524. }
  525. func (r *R) formatUdpPacket(p *packet) string {
  526. packet := gopacket.NewPacket(p.packet.Data, layers.LayerTypeIPv4, gopacket.Lazy)
  527. v4 := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
  528. if v4 == nil {
  529. panic("not an ipv4 packet")
  530. }
  531. from := "unknown"
  532. if c, ok := r.vpnControls[iputil.Ip2VpnIp(v4.SrcIP)]; ok {
  533. from = c.GetUDPAddr()
  534. }
  535. udp := packet.Layer(layers.LayerTypeUDP).(*layers.UDP)
  536. if udp == nil {
  537. panic("not a udp packet")
  538. }
  539. data := packet.ApplicationLayer()
  540. return fmt.Sprintf(
  541. " %s-->>%s: src port: %v<br/>dest port: %v<br/>data: \"%v\"\n",
  542. strings.Replace(from, ":", "#58;", 1),
  543. strings.Replace(p.to.GetUDPAddr(), ":", "#58;", 1),
  544. udp.SrcPort,
  545. udp.DstPort,
  546. string(data.Payload()),
  547. )
  548. }