handshake_ix.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package nebula
  2. import (
  3. "sync/atomic"
  4. "time"
  5. "github.com/flynn/noise"
  6. "github.com/golang/protobuf/proto"
  7. )
  8. // NOISE IX Handshakes
  9. // This function constructs a handshake packet, but does not actually send it
  10. // Sending is done by the handshake manager
  11. func ixHandshakeStage0(f *Interface, vpnIp uint32, hostinfo *HostInfo) {
  12. // This queries the lighthouse if we don't know a remote for the host
  13. // We do it here to provoke the lighthouse to preempt our timer wheel and trigger the stage 1 packet to send
  14. // more quickly, effect is a quicker handshake.
  15. if hostinfo.remote == nil {
  16. f.lightHouse.QueryServer(vpnIp, f)
  17. }
  18. err := f.handshakeManager.AddIndexHostInfo(hostinfo)
  19. if err != nil {
  20. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  21. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to generate index")
  22. return
  23. }
  24. ci := hostinfo.ConnectionState
  25. hsProto := &NebulaHandshakeDetails{
  26. InitiatorIndex: hostinfo.localIndexId,
  27. Time: uint64(time.Now().Unix()),
  28. Cert: ci.certState.rawCertificateNoKey,
  29. }
  30. hsBytes := []byte{}
  31. hs := &NebulaHandshake{
  32. Details: hsProto,
  33. }
  34. hsBytes, err = proto.Marshal(hs)
  35. if err != nil {
  36. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  37. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  38. return
  39. }
  40. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, 0, 1)
  41. atomic.AddUint64(&ci.atomicMessageCounter, 1)
  42. msg, _, _, err := ci.H.WriteMessage(header, hsBytes)
  43. if err != nil {
  44. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  45. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  46. return
  47. }
  48. // We are sending handshake packet 1, so we don't expect to receive
  49. // handshake packet 1 from the responder
  50. ci.window.Update(f.l, 1)
  51. hostinfo.HandshakePacket[0] = msg
  52. hostinfo.HandshakeReady = true
  53. hostinfo.handshakeStart = time.Now()
  54. }
  55. func ixHandshakeStage1(f *Interface, addr *udpAddr, packet []byte, h *Header) {
  56. ci := f.newConnectionState(f.l, false, noise.HandshakeIX, []byte{}, 0)
  57. // Mark packet 1 as seen so it doesn't show up as missed
  58. ci.window.Update(f.l, 1)
  59. msg, _, _, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  60. if err != nil {
  61. f.l.WithError(err).WithField("udpAddr", addr).
  62. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.ReadMessage")
  63. return
  64. }
  65. hs := &NebulaHandshake{}
  66. err = proto.Unmarshal(msg, hs)
  67. /*
  68. l.Debugln("GOT INDEX: ", hs.Details.InitiatorIndex)
  69. */
  70. if err != nil || hs.Details == nil {
  71. f.l.WithError(err).WithField("udpAddr", addr).
  72. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  73. return
  74. }
  75. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert, f.caPool)
  76. if err != nil {
  77. f.l.WithError(err).WithField("udpAddr", addr).
  78. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cert", remoteCert).
  79. Info("Invalid certificate from host")
  80. return
  81. }
  82. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  83. certName := remoteCert.Details.Name
  84. fingerprint, _ := remoteCert.Sha256Sum()
  85. if vpnIP == ip2int(f.certState.certificate.Details.Ips[0].IP) {
  86. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  87. WithField("certName", certName).
  88. WithField("fingerprint", fingerprint).
  89. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Refusing to handshake with myself")
  90. return
  91. }
  92. myIndex, err := generateIndex(f.l)
  93. if err != nil {
  94. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  95. WithField("certName", certName).
  96. WithField("fingerprint", fingerprint).
  97. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to generate index")
  98. return
  99. }
  100. hostinfo := &HostInfo{
  101. ConnectionState: ci,
  102. localIndexId: myIndex,
  103. remoteIndexId: hs.Details.InitiatorIndex,
  104. hostId: vpnIP,
  105. HandshakePacket: make(map[uint8][]byte, 0),
  106. }
  107. hostinfo.Lock()
  108. defer hostinfo.Unlock()
  109. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  110. WithField("certName", certName).
  111. WithField("fingerprint", fingerprint).
  112. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  113. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  114. Info("Handshake message received")
  115. hs.Details.ResponderIndex = myIndex
  116. hs.Details.Cert = ci.certState.rawCertificateNoKey
  117. hsBytes, err := proto.Marshal(hs)
  118. if err != nil {
  119. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  120. WithField("certName", certName).
  121. WithField("fingerprint", fingerprint).
  122. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  123. return
  124. }
  125. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, hs.Details.InitiatorIndex, 2)
  126. msg, dKey, eKey, err := ci.H.WriteMessage(header, hsBytes)
  127. if err != nil {
  128. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  129. WithField("certName", certName).
  130. WithField("fingerprint", fingerprint).
  131. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  132. return
  133. } else if dKey == nil || eKey == nil {
  134. f.l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  135. WithField("certName", certName).
  136. WithField("fingerprint", fingerprint).
  137. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Noise did not arrive at a key")
  138. return
  139. }
  140. hostinfo.HandshakePacket[0] = make([]byte, len(packet[HeaderLen:]))
  141. copy(hostinfo.HandshakePacket[0], packet[HeaderLen:])
  142. // Regardless of whether you are the sender or receiver, you should arrive here
  143. // and complete standing up the connection.
  144. hostinfo.HandshakePacket[2] = make([]byte, len(msg))
  145. copy(hostinfo.HandshakePacket[2], msg)
  146. // We are sending handshake packet 2, so we don't expect to receive
  147. // handshake packet 2 from the initiator.
  148. ci.window.Update(f.l, 2)
  149. ci.peerCert = remoteCert
  150. ci.dKey = NewNebulaCipherState(dKey)
  151. ci.eKey = NewNebulaCipherState(eKey)
  152. hostinfo.remotes = f.lightHouse.QueryCache(vpnIP)
  153. hostinfo.SetRemote(addr)
  154. hostinfo.CreateRemoteCIDR(remoteCert)
  155. // Only overwrite existing record if we should win the handshake race
  156. overwrite := vpnIP > ip2int(f.certState.certificate.Details.Ips[0].IP)
  157. existing, err := f.handshakeManager.CheckAndComplete(hostinfo, 0, overwrite, f)
  158. if err != nil {
  159. switch err {
  160. case ErrAlreadySeen:
  161. msg = existing.HandshakePacket[2]
  162. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  163. err := f.outside.WriteTo(msg, addr)
  164. if err != nil {
  165. f.l.WithField("vpnIp", IntIp(existing.hostId)).WithField("udpAddr", addr).
  166. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  167. WithError(err).Error("Failed to send handshake message")
  168. } else {
  169. f.l.WithField("vpnIp", IntIp(existing.hostId)).WithField("udpAddr", addr).
  170. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  171. Info("Handshake message sent")
  172. }
  173. return
  174. case ErrExistingHostInfo:
  175. // This means there was an existing tunnel and we didn't win
  176. // handshake avoidance
  177. //TODO: sprinkle the new protobuf stuff in here, send a reply to get the recv_errors flowing
  178. //TODO: if not new send a test packet like old
  179. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  180. WithField("certName", certName).
  181. WithField("fingerprint", fingerprint).
  182. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  183. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  184. Info("Prevented a handshake race")
  185. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  186. f.SendMessageToVpnIp(test, testRequest, vpnIP, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  187. return
  188. case ErrLocalIndexCollision:
  189. // This means we failed to insert because of collision on localIndexId. Just let the next handshake packet retry
  190. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  191. WithField("certName", certName).
  192. WithField("fingerprint", fingerprint).
  193. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  194. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  195. WithField("localIndex", hostinfo.localIndexId).WithField("collision", IntIp(existing.hostId)).
  196. Error("Failed to add HostInfo due to localIndex collision")
  197. return
  198. case ErrExistingHandshake:
  199. // We have a race where both parties think they are an initiator and this tunnel lost, let the other one finish
  200. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  201. WithField("certName", certName).
  202. WithField("fingerprint", fingerprint).
  203. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  204. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  205. Error("Prevented a pending handshake race")
  206. return
  207. default:
  208. // Shouldn't happen, but just in case someone adds a new error type to CheckAndComplete
  209. // And we forget to update it here
  210. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  211. WithField("certName", certName).
  212. WithField("fingerprint", fingerprint).
  213. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  214. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  215. Error("Failed to add HostInfo to HostMap")
  216. return
  217. }
  218. }
  219. // Do the send
  220. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  221. err = f.outside.WriteTo(msg, addr)
  222. if err != nil {
  223. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  224. WithField("certName", certName).
  225. WithField("fingerprint", fingerprint).
  226. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  227. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  228. WithError(err).Error("Failed to send handshake")
  229. } else {
  230. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  231. WithField("certName", certName).
  232. WithField("fingerprint", fingerprint).
  233. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  234. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  235. Info("Handshake message sent")
  236. }
  237. hostinfo.handshakeComplete(f.l)
  238. return
  239. }
  240. func ixHandshakeStage2(f *Interface, addr *udpAddr, hostinfo *HostInfo, packet []byte, h *Header) bool {
  241. if hostinfo == nil {
  242. // Nothing here to tear down, got a bogus stage 2 packet
  243. return true
  244. }
  245. hostinfo.Lock()
  246. defer hostinfo.Unlock()
  247. ci := hostinfo.ConnectionState
  248. if ci.ready {
  249. f.l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  250. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  251. Info("Handshake is already complete")
  252. //TODO: evaluate addr for preference, if we handshook with a less preferred addr we can correct quickly here
  253. // We already have a complete tunnel, there is nothing that can be done by processing further stage 1 packets
  254. return false
  255. }
  256. msg, eKey, dKey, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  257. if err != nil {
  258. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  259. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  260. Error("Failed to call noise.ReadMessage")
  261. // We don't want to tear down the connection on a bad ReadMessage because it could be an attacker trying
  262. // to DOS us. Every other error condition after should to allow a possible good handshake to complete in the
  263. // near future
  264. return false
  265. } else if dKey == nil || eKey == nil {
  266. f.l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  267. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  268. Error("Noise did not arrive at a key")
  269. // This should be impossible in IX but just in case, if we get here then there is no chance to recover
  270. // the handshake state machine. Tear it down
  271. return true
  272. }
  273. hs := &NebulaHandshake{}
  274. err = proto.Unmarshal(msg, hs)
  275. if err != nil || hs.Details == nil {
  276. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  277. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  278. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  279. return true
  280. }
  281. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert, f.caPool)
  282. if err != nil {
  283. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  284. WithField("cert", remoteCert).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  285. Error("Invalid certificate from host")
  286. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  287. return true
  288. }
  289. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  290. certName := remoteCert.Details.Name
  291. fingerprint, _ := remoteCert.Sha256Sum()
  292. // Ensure the right host responded
  293. if vpnIP != hostinfo.hostId {
  294. f.l.WithField("intendedVpnIp", IntIp(hostinfo.hostId)).WithField("haveVpnIp", IntIp(vpnIP)).
  295. WithField("udpAddr", addr).WithField("certName", certName).
  296. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  297. Info("Incorrect host responded to handshake")
  298. // Release our old handshake from pending, it should not continue
  299. f.handshakeManager.pendingHostMap.DeleteHostInfo(hostinfo)
  300. // Create a new hostinfo/handshake for the intended vpn ip
  301. //TODO: this adds it to the timer wheel in a way that aggressively retries
  302. newHostInfo := f.getOrHandshake(hostinfo.hostId)
  303. newHostInfo.Lock()
  304. // Block the current used address
  305. newHostInfo.remotes = hostinfo.remotes
  306. newHostInfo.remotes.BlockRemote(addr)
  307. // Get the correct remote list for the host we did handshake with
  308. hostinfo.remotes = f.lightHouse.QueryCache(vpnIP)
  309. f.l.WithField("blockedUdpAddrs", newHostInfo.remotes.CopyBlockedRemotes()).WithField("vpnIp", IntIp(vpnIP)).
  310. WithField("remotes", newHostInfo.remotes.CopyAddrs(f.hostMap.preferredRanges)).
  311. Info("Blocked addresses for handshakes")
  312. // Swap the packet store to benefit the original intended recipient
  313. hostinfo.ConnectionState.queueLock.Lock()
  314. newHostInfo.packetStore = hostinfo.packetStore
  315. hostinfo.packetStore = []*cachedPacket{}
  316. hostinfo.ConnectionState.queueLock.Unlock()
  317. // Finally, put the correct vpn ip in the host info, tell them to close the tunnel, and return true to tear down
  318. hostinfo.hostId = vpnIP
  319. f.sendCloseTunnel(hostinfo)
  320. newHostInfo.Unlock()
  321. return true
  322. }
  323. // Mark packet 2 as seen so it doesn't show up as missed
  324. ci.window.Update(f.l, 2)
  325. duration := time.Since(hostinfo.handshakeStart).Nanoseconds()
  326. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  327. WithField("certName", certName).
  328. WithField("fingerprint", fingerprint).
  329. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  330. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  331. WithField("durationNs", duration).
  332. Info("Handshake message received")
  333. hostinfo.remoteIndexId = hs.Details.ResponderIndex
  334. hs.Details.Cert = ci.certState.rawCertificateNoKey
  335. // Store their cert and our symmetric keys
  336. ci.peerCert = remoteCert
  337. ci.dKey = NewNebulaCipherState(dKey)
  338. ci.eKey = NewNebulaCipherState(eKey)
  339. // Make sure the current udpAddr being used is set for responding
  340. hostinfo.SetRemote(addr)
  341. // Build up the radix for the firewall if we have subnets in the cert
  342. hostinfo.CreateRemoteCIDR(remoteCert)
  343. // Complete our handshake and update metrics, this will replace any existing tunnels for this vpnIp
  344. //TODO: Complete here does not do a race avoidance, it will just take the new tunnel. Is this ok?
  345. f.handshakeManager.Complete(hostinfo, f)
  346. hostinfo.handshakeComplete(f.l)
  347. f.metricHandshakes.Update(duration)
  348. return false
  349. }