helpers_test.go 8.5 KB

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