helpers_test.go 8.5 KB

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