helpers_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //go:build e2e_testing
  2. // +build e2e_testing
  3. package e2e
  4. import (
  5. "crypto/rand"
  6. "fmt"
  7. "io"
  8. "net"
  9. "os"
  10. "testing"
  11. "time"
  12. "github.com/google/gopacket"
  13. "github.com/google/gopacket/layers"
  14. "github.com/imdario/mergo"
  15. "github.com/sirupsen/logrus"
  16. "github.com/slackhq/nebula"
  17. "github.com/slackhq/nebula/cert"
  18. "github.com/slackhq/nebula/config"
  19. "github.com/slackhq/nebula/e2e/router"
  20. "github.com/slackhq/nebula/iputil"
  21. "github.com/stretchr/testify/assert"
  22. "golang.org/x/crypto/curve25519"
  23. "golang.org/x/crypto/ed25519"
  24. "gopkg.in/yaml.v2"
  25. )
  26. type m map[string]interface{}
  27. // newSimpleServer creates a nebula instance with many assumptions
  28. func newSimpleServer(caCrt *cert.NebulaCertificate, caKey []byte, name string, udpIp net.IP, overrides m) (*nebula.Control, net.IP, *net.UDPAddr) {
  29. l := NewTestLogger()
  30. vpnIpNet := &net.IPNet{IP: make([]byte, len(udpIp)), Mask: net.IPMask{255, 255, 255, 0}}
  31. copy(vpnIpNet.IP, udpIp)
  32. vpnIpNet.IP[1] += 128
  33. udpAddr := net.UDPAddr{
  34. IP: udpIp,
  35. Port: 4242,
  36. }
  37. _, _, myPrivKey, myPEM := newTestCert(caCrt, caKey, name, time.Now(), time.Now().Add(5*time.Minute), vpnIpNet, nil, []string{})
  38. caB, err := caCrt.MarshalToPEM()
  39. if err != nil {
  40. panic(err)
  41. }
  42. mc := m{
  43. "pki": m{
  44. "ca": string(caB),
  45. "cert": string(myPEM),
  46. "key": string(myPrivKey),
  47. },
  48. //"tun": m{"disabled": true},
  49. "firewall": m{
  50. "outbound": []m{{
  51. "proto": "any",
  52. "port": "any",
  53. "host": "any",
  54. }},
  55. "inbound": []m{{
  56. "proto": "any",
  57. "port": "any",
  58. "host": "any",
  59. }},
  60. },
  61. //"handshakes": m{
  62. // "try_interval": "1s",
  63. //},
  64. "listen": m{
  65. "host": udpAddr.IP.String(),
  66. "port": udpAddr.Port,
  67. },
  68. "logging": m{
  69. "timestamp_format": fmt.Sprintf("%v 15:04:05.000000", name),
  70. "level": l.Level.String(),
  71. },
  72. }
  73. if overrides != nil {
  74. err = mergo.Merge(&overrides, mc, mergo.WithAppendSlice)
  75. if err != nil {
  76. panic(err)
  77. }
  78. mc = overrides
  79. }
  80. cb, err := yaml.Marshal(mc)
  81. if err != nil {
  82. panic(err)
  83. }
  84. c := config.NewC(l)
  85. c.LoadString(string(cb))
  86. control, err := nebula.Main(c, false, "e2e-test", l, nil)
  87. if err != nil {
  88. panic(err)
  89. }
  90. return control, vpnIpNet.IP, &udpAddr
  91. }
  92. // newTestCaCert will generate a CA cert
  93. func newTestCaCert(before, after time.Time, ips, subnets []*net.IPNet, groups []string) (*cert.NebulaCertificate, []byte, []byte, []byte) {
  94. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  95. if before.IsZero() {
  96. before = time.Now().Add(time.Second * -60).Round(time.Second)
  97. }
  98. if after.IsZero() {
  99. after = time.Now().Add(time.Second * 60).Round(time.Second)
  100. }
  101. nc := &cert.NebulaCertificate{
  102. Details: cert.NebulaCertificateDetails{
  103. Name: "test ca",
  104. NotBefore: time.Unix(before.Unix(), 0),
  105. NotAfter: time.Unix(after.Unix(), 0),
  106. PublicKey: pub,
  107. IsCA: true,
  108. InvertedGroups: make(map[string]struct{}),
  109. },
  110. }
  111. if len(ips) > 0 {
  112. nc.Details.Ips = ips
  113. }
  114. if len(subnets) > 0 {
  115. nc.Details.Subnets = subnets
  116. }
  117. if len(groups) > 0 {
  118. nc.Details.Groups = groups
  119. }
  120. err = nc.Sign(priv)
  121. if err != nil {
  122. panic(err)
  123. }
  124. pem, err := nc.MarshalToPEM()
  125. if err != nil {
  126. panic(err)
  127. }
  128. return nc, pub, priv, pem
  129. }
  130. // newTestCert will generate a signed certificate with the provided details.
  131. // Expiry times are defaulted if you do not pass them in
  132. func newTestCert(ca *cert.NebulaCertificate, key []byte, name string, before, after time.Time, ip *net.IPNet, subnets []*net.IPNet, groups []string) (*cert.NebulaCertificate, []byte, []byte, []byte) {
  133. issuer, err := ca.Sha256Sum()
  134. if err != nil {
  135. panic(err)
  136. }
  137. if before.IsZero() {
  138. before = time.Now().Add(time.Second * -60).Round(time.Second)
  139. }
  140. if after.IsZero() {
  141. after = time.Now().Add(time.Second * 60).Round(time.Second)
  142. }
  143. pub, rawPriv := x25519Keypair()
  144. nc := &cert.NebulaCertificate{
  145. Details: cert.NebulaCertificateDetails{
  146. Name: name,
  147. Ips: []*net.IPNet{ip},
  148. Subnets: subnets,
  149. Groups: groups,
  150. NotBefore: time.Unix(before.Unix(), 0),
  151. NotAfter: time.Unix(after.Unix(), 0),
  152. PublicKey: pub,
  153. IsCA: false,
  154. Issuer: issuer,
  155. InvertedGroups: make(map[string]struct{}),
  156. },
  157. }
  158. err = nc.Sign(key)
  159. if err != nil {
  160. panic(err)
  161. }
  162. pem, err := nc.MarshalToPEM()
  163. if err != nil {
  164. panic(err)
  165. }
  166. return nc, pub, cert.MarshalX25519PrivateKey(rawPriv), pem
  167. }
  168. func x25519Keypair() ([]byte, []byte) {
  169. privkey := make([]byte, 32)
  170. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  171. panic(err)
  172. }
  173. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  174. if err != nil {
  175. panic(err)
  176. }
  177. return pubkey, privkey
  178. }
  179. type doneCb func()
  180. func deadline(t *testing.T, seconds time.Duration) doneCb {
  181. timeout := time.After(seconds * time.Second)
  182. done := make(chan bool)
  183. go func() {
  184. select {
  185. case <-timeout:
  186. t.Fatal("Test did not finish in time")
  187. case <-done:
  188. }
  189. }()
  190. return func() {
  191. done <- true
  192. }
  193. }
  194. func assertTunnel(t *testing.T, vpnIpA, vpnIpB net.IP, controlA, controlB *nebula.Control, r *router.R) {
  195. // Send a packet from them to me
  196. controlB.InjectTunUDPPacket(vpnIpA, 80, 90, []byte("Hi from B"))
  197. bPacket := r.RouteUntilTxTun(controlB, controlA)
  198. assertUdpPacket(t, []byte("Hi from B"), bPacket, vpnIpB, vpnIpA, 90, 80)
  199. // And once more from me to them
  200. controlA.InjectTunUDPPacket(vpnIpB, 80, 90, []byte("Hello from A"))
  201. aPacket := r.RouteUntilTxTun(controlA, controlB)
  202. assertUdpPacket(t, []byte("Hello from A"), aPacket, vpnIpA, vpnIpB, 90, 80)
  203. }
  204. func assertHostInfoPair(t *testing.T, addrA, addrB *net.UDPAddr, vpnIpA, vpnIpB net.IP, controlA, controlB *nebula.Control) {
  205. // Get both host infos
  206. hBinA := controlA.GetHostInfoByVpnIp(iputil.Ip2VpnIp(vpnIpB), false)
  207. assert.NotNil(t, hBinA, "Host B was not found by vpnIp in controlA")
  208. hAinB := controlB.GetHostInfoByVpnIp(iputil.Ip2VpnIp(vpnIpA), false)
  209. assert.NotNil(t, hAinB, "Host A was not found by vpnIp in controlB")
  210. // Check that both vpn and real addr are correct
  211. assert.Equal(t, vpnIpB, hBinA.VpnIp, "Host B VpnIp is wrong in control A")
  212. assert.Equal(t, vpnIpA, hAinB.VpnIp, "Host A VpnIp is wrong in control B")
  213. assert.Equal(t, addrB.IP.To16(), hBinA.CurrentRemote.IP.To16(), "Host B remote ip is wrong in control A")
  214. assert.Equal(t, addrA.IP.To16(), hAinB.CurrentRemote.IP.To16(), "Host A remote ip is wrong in control B")
  215. assert.Equal(t, addrB.Port, int(hBinA.CurrentRemote.Port), "Host B remote port is wrong in control A")
  216. assert.Equal(t, addrA.Port, int(hAinB.CurrentRemote.Port), "Host A remote port is wrong in control B")
  217. // Check that our indexes match
  218. assert.Equal(t, hBinA.LocalIndex, hAinB.RemoteIndex, "Host B local index does not match host A remote index")
  219. assert.Equal(t, hBinA.RemoteIndex, hAinB.LocalIndex, "Host B remote index does not match host A local index")
  220. //TODO: Would be nice to assert this memory
  221. //checkIndexes := func(name string, hm *HostMap, hi *HostInfo) {
  222. // hBbyIndex := hmA.Indexes[hBinA.localIndexId]
  223. // assert.NotNil(t, hBbyIndex, "Could not host info by local index in %s", name)
  224. // assert.Equal(t, &hBbyIndex, &hBinA, "%s Indexes map did not point to the right host info", name)
  225. //
  226. // //TODO: remote indexes are susceptible to collision
  227. // hBbyRemoteIndex := hmA.RemoteIndexes[hBinA.remoteIndexId]
  228. // assert.NotNil(t, hBbyIndex, "Could not host info by remote index in %s", name)
  229. // assert.Equal(t, &hBbyRemoteIndex, &hBinA, "%s RemoteIndexes did not point to the right host info", name)
  230. //}
  231. //
  232. //// Check hostmap indexes too
  233. //checkIndexes("hmA", hmA, hBinA)
  234. //checkIndexes("hmB", hmB, hAinB)
  235. }
  236. func assertUdpPacket(t *testing.T, expected, b []byte, fromIp, toIp net.IP, fromPort, toPort uint16) {
  237. packet := gopacket.NewPacket(b, layers.LayerTypeIPv4, gopacket.Lazy)
  238. v4 := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
  239. assert.NotNil(t, v4, "No ipv4 data found")
  240. assert.Equal(t, fromIp, v4.SrcIP, "Source ip was incorrect")
  241. assert.Equal(t, toIp, v4.DstIP, "Dest ip was incorrect")
  242. udp := packet.Layer(layers.LayerTypeUDP).(*layers.UDP)
  243. assert.NotNil(t, udp, "No udp data found")
  244. assert.Equal(t, fromPort, uint16(udp.SrcPort), "Source port was incorrect")
  245. assert.Equal(t, toPort, uint16(udp.DstPort), "Dest port was incorrect")
  246. data := packet.ApplicationLayer()
  247. assert.NotNil(t, data)
  248. assert.Equal(t, expected, data.Payload(), "Data was incorrect")
  249. }
  250. func NewTestLogger() *logrus.Logger {
  251. l := logrus.New()
  252. v := os.Getenv("TEST_LOGS")
  253. if v == "" {
  254. l.SetOutput(io.Discard)
  255. l.SetLevel(logrus.PanicLevel)
  256. return l
  257. }
  258. switch v {
  259. case "2":
  260. l.SetLevel(logrus.DebugLevel)
  261. case "3":
  262. l.SetLevel(logrus.TraceLevel)
  263. default:
  264. l.SetLevel(logrus.InfoLevel)
  265. }
  266. return l
  267. }