handshake_ix.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package nebula
  2. import (
  3. "time"
  4. "github.com/flynn/noise"
  5. "github.com/sirupsen/logrus"
  6. "github.com/slackhq/nebula/header"
  7. "github.com/slackhq/nebula/iputil"
  8. "github.com/slackhq/nebula/udp"
  9. )
  10. // NOISE IX Handshakes
  11. // This function constructs a handshake packet, but does not actually send it
  12. // Sending is done by the handshake manager
  13. func ixHandshakeStage0(f *Interface, hh *HandshakeHostInfo) bool {
  14. err := f.handshakeManager.allocateIndex(hh)
  15. if err != nil {
  16. f.l.WithError(err).WithField("vpnIp", hh.hostinfo.vpnIp).
  17. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to generate index")
  18. return false
  19. }
  20. certState := f.pki.GetCertState()
  21. ci := NewConnectionState(f.l, f.cipher, certState, true, noise.HandshakeIX, []byte{}, 0)
  22. hh.hostinfo.ConnectionState = ci
  23. hsProto := &NebulaHandshakeDetails{
  24. InitiatorIndex: hh.hostinfo.localIndexId,
  25. Time: uint64(time.Now().UnixNano()),
  26. Cert: certState.RawCertificateNoKey,
  27. }
  28. hsBytes := []byte{}
  29. hs := &NebulaHandshake{
  30. Details: hsProto,
  31. }
  32. hsBytes, err = hs.Marshal()
  33. if err != nil {
  34. f.l.WithError(err).WithField("vpnIp", hh.hostinfo.vpnIp).
  35. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  36. return false
  37. }
  38. h := header.Encode(make([]byte, header.Len), header.Version, header.Handshake, header.HandshakeIXPSK0, 0, 1)
  39. ci.messageCounter.Add(1)
  40. msg, _, _, err := ci.H.WriteMessage(h, hsBytes)
  41. if err != nil {
  42. f.l.WithError(err).WithField("vpnIp", hh.hostinfo.vpnIp).
  43. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  44. return false
  45. }
  46. // We are sending handshake packet 1, so we don't expect to receive
  47. // handshake packet 1 from the responder
  48. ci.window.Update(f.l, 1)
  49. hh.hostinfo.HandshakePacket[0] = msg
  50. hh.ready = true
  51. return true
  52. }
  53. func ixHandshakeStage1(f *Interface, addr *udp.Addr, via *ViaSender, packet []byte, h *header.H) {
  54. certState := f.pki.GetCertState()
  55. ci := NewConnectionState(f.l, f.cipher, certState, false, noise.HandshakeIX, []byte{}, 0)
  56. // Mark packet 1 as seen so it doesn't show up as missed
  57. ci.window.Update(f.l, 1)
  58. msg, _, _, err := ci.H.ReadMessage(nil, packet[header.Len:])
  59. if err != nil {
  60. f.l.WithError(err).WithField("udpAddr", addr).
  61. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.ReadMessage")
  62. return
  63. }
  64. hs := &NebulaHandshake{}
  65. err = hs.Unmarshal(msg)
  66. /*
  67. l.Debugln("GOT INDEX: ", hs.Details.InitiatorIndex)
  68. */
  69. if err != nil || hs.Details == nil {
  70. f.l.WithError(err).WithField("udpAddr", addr).
  71. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  72. return
  73. }
  74. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert, f.pki.GetCAPool())
  75. if err != nil {
  76. f.l.WithError(err).WithField("udpAddr", addr).
  77. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cert", remoteCert).
  78. Info("Invalid certificate from host")
  79. return
  80. }
  81. vpnIp := iputil.Ip2VpnIp(remoteCert.Details.Ips[0].IP)
  82. certName := remoteCert.Details.Name
  83. fingerprint, _ := remoteCert.Sha256Sum()
  84. issuer := remoteCert.Details.Issuer
  85. if vpnIp == f.myVpnIp {
  86. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  87. WithField("certName", certName).
  88. WithField("fingerprint", fingerprint).
  89. WithField("issuer", issuer).
  90. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Refusing to handshake with myself")
  91. return
  92. }
  93. if addr != nil {
  94. if !f.lightHouse.GetRemoteAllowList().Allow(vpnIp, addr.IP) {
  95. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  96. return
  97. }
  98. }
  99. myIndex, err := generateIndex(f.l)
  100. if err != nil {
  101. f.l.WithError(err).WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  102. WithField("certName", certName).
  103. WithField("fingerprint", fingerprint).
  104. WithField("issuer", issuer).
  105. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to generate index")
  106. return
  107. }
  108. hostinfo := &HostInfo{
  109. ConnectionState: ci,
  110. localIndexId: myIndex,
  111. remoteIndexId: hs.Details.InitiatorIndex,
  112. vpnIp: vpnIp,
  113. HandshakePacket: make(map[uint8][]byte, 0),
  114. lastHandshakeTime: hs.Details.Time,
  115. relayState: RelayState{
  116. relays: map[iputil.VpnIp]struct{}{},
  117. relayForByIp: map[iputil.VpnIp]*Relay{},
  118. relayForByIdx: map[uint32]*Relay{},
  119. },
  120. }
  121. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  122. WithField("certName", certName).
  123. WithField("fingerprint", fingerprint).
  124. WithField("issuer", issuer).
  125. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  126. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  127. Info("Handshake message received")
  128. hs.Details.ResponderIndex = myIndex
  129. hs.Details.Cert = certState.RawCertificateNoKey
  130. // Update the time in case their clock is way off from ours
  131. hs.Details.Time = uint64(time.Now().UnixNano())
  132. hsBytes, err := hs.Marshal()
  133. if err != nil {
  134. f.l.WithError(err).WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  135. WithField("certName", certName).
  136. WithField("fingerprint", fingerprint).
  137. WithField("issuer", issuer).
  138. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  139. return
  140. }
  141. nh := header.Encode(make([]byte, header.Len), header.Version, header.Handshake, header.HandshakeIXPSK0, hs.Details.InitiatorIndex, 2)
  142. msg, dKey, eKey, err := ci.H.WriteMessage(nh, hsBytes)
  143. if err != nil {
  144. f.l.WithError(err).WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  145. WithField("certName", certName).
  146. WithField("fingerprint", fingerprint).
  147. WithField("issuer", issuer).
  148. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  149. return
  150. } else if dKey == nil || eKey == nil {
  151. f.l.WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  152. WithField("certName", certName).
  153. WithField("fingerprint", fingerprint).
  154. WithField("issuer", issuer).
  155. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Noise did not arrive at a key")
  156. return
  157. }
  158. hostinfo.HandshakePacket[0] = make([]byte, len(packet[header.Len:]))
  159. copy(hostinfo.HandshakePacket[0], packet[header.Len:])
  160. // Regardless of whether you are the sender or receiver, you should arrive here
  161. // and complete standing up the connection.
  162. hostinfo.HandshakePacket[2] = make([]byte, len(msg))
  163. copy(hostinfo.HandshakePacket[2], msg)
  164. // We are sending handshake packet 2, so we don't expect to receive
  165. // handshake packet 2 from the initiator.
  166. ci.window.Update(f.l, 2)
  167. ci.peerCert = remoteCert
  168. ci.dKey = NewNebulaCipherState(dKey)
  169. ci.eKey = NewNebulaCipherState(eKey)
  170. hostinfo.remotes = f.lightHouse.QueryCache(vpnIp)
  171. hostinfo.SetRemote(addr)
  172. hostinfo.CreateRemoteCIDR(remoteCert)
  173. existing, err := f.handshakeManager.CheckAndComplete(hostinfo, 0, f)
  174. if err != nil {
  175. switch err {
  176. case ErrAlreadySeen:
  177. // Update remote if preferred
  178. if existing.SetRemoteIfPreferred(f.hostMap, addr) {
  179. // Send a test packet to ensure the other side has also switched to
  180. // the preferred remote
  181. f.SendMessageToVpnIp(header.Test, header.TestRequest, vpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  182. }
  183. msg = existing.HandshakePacket[2]
  184. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  185. if addr != nil {
  186. err := f.outside.WriteTo(msg, addr)
  187. if err != nil {
  188. f.l.WithField("vpnIp", existing.vpnIp).WithField("udpAddr", addr).
  189. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  190. WithError(err).Error("Failed to send handshake message")
  191. } else {
  192. f.l.WithField("vpnIp", existing.vpnIp).WithField("udpAddr", addr).
  193. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  194. Info("Handshake message sent")
  195. }
  196. return
  197. } else {
  198. if via == nil {
  199. f.l.Error("Handshake send failed: both addr and via are nil.")
  200. return
  201. }
  202. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnIp)
  203. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  204. f.l.WithField("vpnIp", existing.vpnIp).WithField("relay", via.relayHI.vpnIp).
  205. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  206. Info("Handshake message sent")
  207. return
  208. }
  209. case ErrExistingHostInfo:
  210. // This means there was an existing tunnel and this handshake was older than the one we are currently based on
  211. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  212. WithField("certName", certName).
  213. WithField("oldHandshakeTime", existing.lastHandshakeTime).
  214. WithField("newHandshakeTime", hostinfo.lastHandshakeTime).
  215. WithField("fingerprint", fingerprint).
  216. WithField("issuer", issuer).
  217. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  218. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  219. Info("Handshake too old")
  220. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  221. f.SendMessageToVpnIp(header.Test, header.TestRequest, vpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  222. return
  223. case ErrLocalIndexCollision:
  224. // This means we failed to insert because of collision on localIndexId. Just let the next handshake packet retry
  225. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  226. WithField("certName", certName).
  227. WithField("fingerprint", fingerprint).
  228. WithField("issuer", issuer).
  229. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  230. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  231. WithField("localIndex", hostinfo.localIndexId).WithField("collision", existing.vpnIp).
  232. Error("Failed to add HostInfo due to localIndex collision")
  233. return
  234. default:
  235. // Shouldn't happen, but just in case someone adds a new error type to CheckAndComplete
  236. // And we forget to update it here
  237. f.l.WithError(err).WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  238. WithField("certName", certName).
  239. WithField("fingerprint", fingerprint).
  240. WithField("issuer", issuer).
  241. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  242. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  243. Error("Failed to add HostInfo to HostMap")
  244. return
  245. }
  246. }
  247. // Do the send
  248. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  249. if addr != nil {
  250. err = f.outside.WriteTo(msg, addr)
  251. if err != nil {
  252. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  253. WithField("certName", certName).
  254. WithField("fingerprint", fingerprint).
  255. WithField("issuer", issuer).
  256. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  257. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  258. WithError(err).Error("Failed to send handshake")
  259. } else {
  260. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  261. WithField("certName", certName).
  262. WithField("fingerprint", fingerprint).
  263. WithField("issuer", issuer).
  264. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  265. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  266. Info("Handshake message sent")
  267. }
  268. } else {
  269. if via == nil {
  270. f.l.Error("Handshake send failed: both addr and via are nil.")
  271. return
  272. }
  273. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnIp)
  274. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  275. f.l.WithField("vpnIp", vpnIp).WithField("relay", via.relayHI.vpnIp).
  276. WithField("certName", certName).
  277. WithField("fingerprint", fingerprint).
  278. WithField("issuer", issuer).
  279. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  280. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  281. Info("Handshake message sent")
  282. }
  283. f.connectionManager.AddTrafficWatch(hostinfo.localIndexId)
  284. hostinfo.ConnectionState.messageCounter.Store(2)
  285. hostinfo.remotes.ResetBlockedRemotes()
  286. return
  287. }
  288. func ixHandshakeStage2(f *Interface, addr *udp.Addr, via *ViaSender, hh *HandshakeHostInfo, packet []byte, h *header.H) bool {
  289. if hh == nil {
  290. // Nothing here to tear down, got a bogus stage 2 packet
  291. return true
  292. }
  293. hh.Lock()
  294. defer hh.Unlock()
  295. hostinfo := hh.hostinfo
  296. if addr != nil {
  297. if !f.lightHouse.GetRemoteAllowList().Allow(hostinfo.vpnIp, addr.IP) {
  298. f.l.WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  299. return false
  300. }
  301. }
  302. ci := hostinfo.ConnectionState
  303. msg, eKey, dKey, err := ci.H.ReadMessage(nil, packet[header.Len:])
  304. if err != nil {
  305. f.l.WithError(err).WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  306. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  307. Error("Failed to call noise.ReadMessage")
  308. // We don't want to tear down the connection on a bad ReadMessage because it could be an attacker trying
  309. // to DOS us. Every other error condition after should to allow a possible good handshake to complete in the
  310. // near future
  311. return false
  312. } else if dKey == nil || eKey == nil {
  313. f.l.WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  314. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  315. Error("Noise did not arrive at a key")
  316. // This should be impossible in IX but just in case, if we get here then there is no chance to recover
  317. // the handshake state machine. Tear it down
  318. return true
  319. }
  320. hs := &NebulaHandshake{}
  321. err = hs.Unmarshal(msg)
  322. if err != nil || hs.Details == nil {
  323. f.l.WithError(err).WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  324. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  325. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  326. return true
  327. }
  328. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert, f.pki.GetCAPool())
  329. if err != nil {
  330. f.l.WithError(err).WithField("vpnIp", hostinfo.vpnIp).WithField("udpAddr", addr).
  331. WithField("cert", remoteCert).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  332. Error("Invalid certificate from host")
  333. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  334. return true
  335. }
  336. vpnIp := iputil.Ip2VpnIp(remoteCert.Details.Ips[0].IP)
  337. certName := remoteCert.Details.Name
  338. fingerprint, _ := remoteCert.Sha256Sum()
  339. issuer := remoteCert.Details.Issuer
  340. // Ensure the right host responded
  341. if vpnIp != hostinfo.vpnIp {
  342. f.l.WithField("intendedVpnIp", hostinfo.vpnIp).WithField("haveVpnIp", vpnIp).
  343. WithField("udpAddr", addr).WithField("certName", certName).
  344. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  345. Info("Incorrect host responded to handshake")
  346. // Release our old handshake from pending, it should not continue
  347. f.handshakeManager.DeleteHostInfo(hostinfo)
  348. // Create a new hostinfo/handshake for the intended vpn ip
  349. f.handshakeManager.StartHandshake(hostinfo.vpnIp, func(newHH *HandshakeHostInfo) {
  350. //TODO: this doesnt know if its being added or is being used for caching a packet
  351. // Block the current used address
  352. newHH.hostinfo.remotes = hostinfo.remotes
  353. newHH.hostinfo.remotes.BlockRemote(addr)
  354. // Get the correct remote list for the host we did handshake with
  355. hostinfo.remotes = f.lightHouse.QueryCache(vpnIp)
  356. f.l.WithField("blockedUdpAddrs", newHH.hostinfo.remotes.CopyBlockedRemotes()).WithField("vpnIp", vpnIp).
  357. WithField("remotes", newHH.hostinfo.remotes.CopyAddrs(f.hostMap.preferredRanges)).
  358. Info("Blocked addresses for handshakes")
  359. // Swap the packet store to benefit the original intended recipient
  360. newHH.packetStore = hh.packetStore
  361. hh.packetStore = []*cachedPacket{}
  362. // Finally, put the correct vpn ip in the host info, tell them to close the tunnel, and return true to tear down
  363. hostinfo.vpnIp = vpnIp
  364. f.sendCloseTunnel(hostinfo)
  365. })
  366. return true
  367. }
  368. // Mark packet 2 as seen so it doesn't show up as missed
  369. ci.window.Update(f.l, 2)
  370. duration := time.Since(hh.startTime).Nanoseconds()
  371. f.l.WithField("vpnIp", vpnIp).WithField("udpAddr", addr).
  372. WithField("certName", certName).
  373. WithField("fingerprint", fingerprint).
  374. WithField("issuer", issuer).
  375. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  376. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  377. WithField("durationNs", duration).
  378. WithField("sentCachedPackets", len(hh.packetStore)).
  379. Info("Handshake message received")
  380. hostinfo.remoteIndexId = hs.Details.ResponderIndex
  381. hostinfo.lastHandshakeTime = hs.Details.Time
  382. // Store their cert and our symmetric keys
  383. ci.peerCert = remoteCert
  384. ci.dKey = NewNebulaCipherState(dKey)
  385. ci.eKey = NewNebulaCipherState(eKey)
  386. // Make sure the current udpAddr being used is set for responding
  387. if addr != nil {
  388. hostinfo.SetRemote(addr)
  389. } else {
  390. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnIp)
  391. }
  392. // Build up the radix for the firewall if we have subnets in the cert
  393. hostinfo.CreateRemoteCIDR(remoteCert)
  394. // Complete our handshake and update metrics, this will replace any existing tunnels for this vpnIp
  395. f.handshakeManager.Complete(hostinfo, f)
  396. f.connectionManager.AddTrafficWatch(hostinfo.localIndexId)
  397. hostinfo.ConnectionState.messageCounter.Store(2)
  398. if f.l.Level >= logrus.DebugLevel {
  399. hostinfo.logger(f.l).Debugf("Sending %d stored packets", len(hh.packetStore))
  400. }
  401. if len(hh.packetStore) > 0 {
  402. nb := make([]byte, 12, 12)
  403. out := make([]byte, mtu)
  404. for _, cp := range hh.packetStore {
  405. cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
  406. }
  407. f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
  408. }
  409. hostinfo.remotes.ResetBlockedRemotes()
  410. f.metricHandshakes.Update(duration)
  411. return false
  412. }