handshake_ix.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. package nebula
  2. import (
  3. "net/netip"
  4. "slices"
  5. "time"
  6. "github.com/flynn/noise"
  7. "github.com/sirupsen/logrus"
  8. "github.com/slackhq/nebula/cert"
  9. "github.com/slackhq/nebula/header"
  10. )
  11. // NOISE IX Handshakes
  12. // This function constructs a handshake packet, but does not actually send it
  13. // Sending is done by the handshake manager
  14. func ixHandshakeStage0(f *Interface, hh *HandshakeHostInfo) bool {
  15. err := f.handshakeManager.allocateIndex(hh)
  16. if err != nil {
  17. f.l.WithError(err).WithField("vpnAddrs", hh.hostinfo.vpnAddrs).
  18. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to generate index")
  19. return false
  20. }
  21. // If we're connecting to a v6 address we must use a v2 cert
  22. cs := f.pki.getCertState()
  23. v := cs.defaultVersion
  24. for _, a := range hh.hostinfo.vpnAddrs {
  25. if a.Is6() {
  26. v = cert.Version2
  27. break
  28. }
  29. }
  30. crt := cs.getCertificate(v)
  31. if crt == nil {
  32. f.l.WithField("vpnAddrs", hh.hostinfo.vpnAddrs).
  33. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).
  34. WithField("certVersion", v).
  35. Error("Unable to handshake with host because no certificate is available")
  36. return false
  37. }
  38. crtHs := cs.getHandshakeBytes(v)
  39. if crtHs == nil {
  40. f.l.WithField("vpnAddrs", hh.hostinfo.vpnAddrs).
  41. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).
  42. WithField("certVersion", v).
  43. Error("Unable to handshake with host because no certificate handshake bytes is available")
  44. }
  45. ci, err := NewConnectionState(f.l, cs, crt, true, noise.HandshakeIX)
  46. if err != nil {
  47. f.l.WithError(err).WithField("vpnAddrs", hh.hostinfo.vpnAddrs).
  48. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).
  49. WithField("certVersion", v).
  50. Error("Failed to create connection state")
  51. return false
  52. }
  53. hh.hostinfo.ConnectionState = ci
  54. hs := &NebulaHandshake{
  55. Details: &NebulaHandshakeDetails{
  56. InitiatorIndex: hh.hostinfo.localIndexId,
  57. Time: uint64(time.Now().UnixNano()),
  58. Cert: crtHs,
  59. CertVersion: uint32(v),
  60. },
  61. }
  62. hsBytes, err := hs.Marshal()
  63. if err != nil {
  64. f.l.WithError(err).WithField("vpnAddrs", hh.hostinfo.vpnAddrs).WithField("certVersion", v).
  65. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  66. return false
  67. }
  68. h := header.Encode(make([]byte, header.Len), header.Version, header.Handshake, header.HandshakeIXPSK0, 0, 1)
  69. msg, _, _, err := ci.H.WriteMessage(h, hsBytes)
  70. if err != nil {
  71. f.l.WithError(err).WithField("vpnAddrs", hh.hostinfo.vpnAddrs).
  72. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  73. return false
  74. }
  75. // We are sending handshake packet 1, so we don't expect to receive
  76. // handshake packet 1 from the responder
  77. ci.window.Update(f.l, 1)
  78. hh.hostinfo.HandshakePacket[0] = msg
  79. hh.ready = true
  80. return true
  81. }
  82. func ixHandshakeStage1(f *Interface, addr netip.AddrPort, via *ViaSender, packet []byte, h *header.H) {
  83. cs := f.pki.getCertState()
  84. crt := cs.GetDefaultCertificate()
  85. if crt == nil {
  86. f.l.WithField("udpAddr", addr).
  87. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).
  88. WithField("certVersion", cs.defaultVersion).
  89. Error("Unable to handshake with host because no certificate is available")
  90. }
  91. ci, err := NewConnectionState(f.l, cs, crt, false, noise.HandshakeIX)
  92. if err != nil {
  93. f.l.WithError(err).WithField("udpAddr", addr).
  94. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  95. Error("Failed to create connection state")
  96. return
  97. }
  98. // Mark packet 1 as seen so it doesn't show up as missed
  99. ci.window.Update(f.l, 1)
  100. msg, _, _, err := ci.H.ReadMessage(nil, packet[header.Len:])
  101. if err != nil {
  102. f.l.WithError(err).WithField("udpAddr", addr).
  103. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  104. Error("Failed to call noise.ReadMessage")
  105. return
  106. }
  107. hs := &NebulaHandshake{}
  108. err = hs.Unmarshal(msg)
  109. if err != nil || hs.Details == nil {
  110. f.l.WithError(err).WithField("udpAddr", addr).
  111. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  112. Error("Failed unmarshal handshake message")
  113. return
  114. }
  115. remoteCert, err := cert.RecombineAndValidate(cert.Version(hs.Details.CertVersion), hs.Details.Cert, ci.H.PeerStatic(), ci.Curve(), f.pki.GetCAPool())
  116. if err != nil {
  117. e := f.l.WithError(err).WithField("udpAddr", addr).
  118. WithField("handshake", m{"stage": 1, "style": "ix_psk0"})
  119. if f.l.Level > logrus.DebugLevel {
  120. e = e.WithField("cert", remoteCert)
  121. }
  122. e.Info("Invalid certificate from host")
  123. return
  124. }
  125. if remoteCert.Certificate.Version() != ci.myCert.Version() {
  126. // We started off using the wrong certificate version, lets see if we can match the version that was sent to us
  127. rc := cs.getCertificate(remoteCert.Certificate.Version())
  128. if rc == nil {
  129. f.l.WithError(err).WithField("udpAddr", addr).
  130. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cert", remoteCert).
  131. Info("Unable to handshake with host due to missing certificate version")
  132. return
  133. }
  134. // Record the certificate we are actually using
  135. ci.myCert = rc
  136. }
  137. if len(remoteCert.Certificate.Networks()) == 0 {
  138. e := f.l.WithError(err).WithField("udpAddr", addr).
  139. WithField("handshake", m{"stage": 1, "style": "ix_psk0"})
  140. if f.l.Level > logrus.DebugLevel {
  141. e = e.WithField("cert", remoteCert)
  142. }
  143. e.Info("Invalid vpn ip from host")
  144. return
  145. }
  146. var vpnAddrs []netip.Addr
  147. var filteredNetworks []netip.Prefix
  148. certName := remoteCert.Certificate.Name()
  149. fingerprint := remoteCert.Fingerprint
  150. issuer := remoteCert.Certificate.Issuer()
  151. for _, network := range remoteCert.Certificate.Networks() {
  152. vpnAddr := network.Addr()
  153. _, found := f.myVpnAddrsTable.Lookup(vpnAddr)
  154. if found {
  155. f.l.WithField("vpnAddr", vpnAddr).WithField("udpAddr", addr).
  156. WithField("certName", certName).
  157. WithField("fingerprint", fingerprint).
  158. WithField("issuer", issuer).
  159. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Refusing to handshake with myself")
  160. return
  161. }
  162. // vpnAddrs outside our vpn networks are of no use to us, filter them out
  163. if _, ok := f.myVpnNetworksTable.Lookup(vpnAddr); !ok {
  164. continue
  165. }
  166. filteredNetworks = append(filteredNetworks, network)
  167. vpnAddrs = append(vpnAddrs, vpnAddr)
  168. }
  169. if len(vpnAddrs) == 0 {
  170. f.l.WithError(err).WithField("udpAddr", addr).
  171. WithField("certName", certName).
  172. WithField("fingerprint", fingerprint).
  173. WithField("issuer", issuer).
  174. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("No usable vpn addresses from host, refusing handshake")
  175. return
  176. }
  177. if addr.IsValid() {
  178. // addr can be invalid when the tunnel is being relayed.
  179. // We only want to apply the remote allow list for direct tunnels here
  180. if !f.lightHouse.GetRemoteAllowList().AllowAll(vpnAddrs, addr.Addr()) {
  181. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  182. return
  183. }
  184. }
  185. myIndex, err := generateIndex(f.l)
  186. if err != nil {
  187. f.l.WithError(err).WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  188. WithField("certName", certName).
  189. WithField("fingerprint", fingerprint).
  190. WithField("issuer", issuer).
  191. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to generate index")
  192. return
  193. }
  194. hostinfo := &HostInfo{
  195. ConnectionState: ci,
  196. localIndexId: myIndex,
  197. remoteIndexId: hs.Details.InitiatorIndex,
  198. vpnAddrs: vpnAddrs,
  199. HandshakePacket: make(map[uint8][]byte, 0),
  200. lastHandshakeTime: hs.Details.Time,
  201. relayState: RelayState{
  202. relays: map[netip.Addr]struct{}{},
  203. relayForByAddr: map[netip.Addr]*Relay{},
  204. relayForByIdx: map[uint32]*Relay{},
  205. },
  206. }
  207. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  208. WithField("certName", certName).
  209. WithField("fingerprint", fingerprint).
  210. WithField("issuer", issuer).
  211. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  212. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  213. Info("Handshake message received")
  214. hs.Details.ResponderIndex = myIndex
  215. hs.Details.Cert = cs.getHandshakeBytes(ci.myCert.Version())
  216. if hs.Details.Cert == nil {
  217. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  218. WithField("certName", certName).
  219. WithField("fingerprint", fingerprint).
  220. WithField("issuer", issuer).
  221. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  222. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  223. WithField("certVersion", ci.myCert.Version()).
  224. Error("Unable to handshake with host because no certificate handshake bytes is available")
  225. return
  226. }
  227. hs.Details.CertVersion = uint32(ci.myCert.Version())
  228. // Update the time in case their clock is way off from ours
  229. hs.Details.Time = uint64(time.Now().UnixNano())
  230. hsBytes, err := hs.Marshal()
  231. if err != nil {
  232. f.l.WithError(err).WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  233. WithField("certName", certName).
  234. WithField("fingerprint", fingerprint).
  235. WithField("issuer", issuer).
  236. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  237. return
  238. }
  239. nh := header.Encode(make([]byte, header.Len), header.Version, header.Handshake, header.HandshakeIXPSK0, hs.Details.InitiatorIndex, 2)
  240. msg, dKey, eKey, err := ci.H.WriteMessage(nh, hsBytes)
  241. if err != nil {
  242. f.l.WithError(err).WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  243. WithField("certName", certName).
  244. WithField("fingerprint", fingerprint).
  245. WithField("issuer", issuer).
  246. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  247. return
  248. } else if dKey == nil || eKey == nil {
  249. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  250. WithField("certName", certName).
  251. WithField("fingerprint", fingerprint).
  252. WithField("issuer", issuer).
  253. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Noise did not arrive at a key")
  254. return
  255. }
  256. hostinfo.HandshakePacket[0] = make([]byte, len(packet[header.Len:]))
  257. copy(hostinfo.HandshakePacket[0], packet[header.Len:])
  258. // Regardless of whether you are the sender or receiver, you should arrive here
  259. // and complete standing up the connection.
  260. hostinfo.HandshakePacket[2] = make([]byte, len(msg))
  261. copy(hostinfo.HandshakePacket[2], msg)
  262. // We are sending handshake packet 2, so we don't expect to receive
  263. // handshake packet 2 from the initiator.
  264. ci.window.Update(f.l, 2)
  265. ci.peerCert = remoteCert
  266. ci.dKey = NewNebulaCipherState(dKey)
  267. ci.eKey = NewNebulaCipherState(eKey)
  268. hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
  269. hostinfo.SetRemote(addr)
  270. hostinfo.buildNetworks(filteredNetworks, remoteCert.Certificate.UnsafeNetworks())
  271. existing, err := f.handshakeManager.CheckAndComplete(hostinfo, 0, f)
  272. if err != nil {
  273. switch err {
  274. case ErrAlreadySeen:
  275. // Update remote if preferred
  276. if existing.SetRemoteIfPreferred(f.hostMap, addr) {
  277. // Send a test packet to ensure the other side has also switched to
  278. // the preferred remote
  279. f.SendMessageToVpnAddr(header.Test, header.TestRequest, vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  280. }
  281. msg = existing.HandshakePacket[2]
  282. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  283. if addr.IsValid() {
  284. err := f.outside.WriteTo(msg, addr)
  285. if err != nil {
  286. f.l.WithField("vpnAddrs", existing.vpnAddrs).WithField("udpAddr", addr).
  287. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  288. WithError(err).Error("Failed to send handshake message")
  289. } else {
  290. f.l.WithField("vpnAddrs", existing.vpnAddrs).WithField("udpAddr", addr).
  291. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  292. Info("Handshake message sent")
  293. }
  294. return
  295. } else {
  296. if via == nil {
  297. f.l.Error("Handshake send failed: both addr and via are nil.")
  298. return
  299. }
  300. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  301. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  302. f.l.WithField("vpnAddrs", existing.vpnAddrs).WithField("relay", via.relayHI.vpnAddrs[0]).
  303. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  304. Info("Handshake message sent")
  305. return
  306. }
  307. case ErrExistingHostInfo:
  308. // This means there was an existing tunnel and this handshake was older than the one we are currently based on
  309. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  310. WithField("certName", certName).
  311. WithField("oldHandshakeTime", existing.lastHandshakeTime).
  312. WithField("newHandshakeTime", hostinfo.lastHandshakeTime).
  313. WithField("fingerprint", fingerprint).
  314. WithField("issuer", issuer).
  315. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  316. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  317. Info("Handshake too old")
  318. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  319. f.SendMessageToVpnAddr(header.Test, header.TestRequest, vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  320. return
  321. case ErrLocalIndexCollision:
  322. // This means we failed to insert because of collision on localIndexId. Just let the next handshake packet retry
  323. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  324. WithField("certName", certName).
  325. WithField("fingerprint", fingerprint).
  326. WithField("issuer", issuer).
  327. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  328. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  329. WithField("localIndex", hostinfo.localIndexId).WithField("collision", existing.vpnAddrs).
  330. Error("Failed to add HostInfo due to localIndex collision")
  331. return
  332. default:
  333. // Shouldn't happen, but just in case someone adds a new error type to CheckAndComplete
  334. // And we forget to update it here
  335. f.l.WithError(err).WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  336. WithField("certName", certName).
  337. WithField("fingerprint", fingerprint).
  338. WithField("issuer", issuer).
  339. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  340. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  341. Error("Failed to add HostInfo to HostMap")
  342. return
  343. }
  344. }
  345. // Do the send
  346. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  347. if addr.IsValid() {
  348. err = f.outside.WriteTo(msg, addr)
  349. if err != nil {
  350. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  351. WithField("certName", certName).
  352. WithField("fingerprint", fingerprint).
  353. WithField("issuer", issuer).
  354. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  355. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  356. WithError(err).Error("Failed to send handshake")
  357. } else {
  358. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  359. WithField("certName", certName).
  360. WithField("fingerprint", fingerprint).
  361. WithField("issuer", issuer).
  362. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  363. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  364. Info("Handshake message sent")
  365. }
  366. } else {
  367. if via == nil {
  368. f.l.Error("Handshake send failed: both addr and via are nil.")
  369. return
  370. }
  371. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  372. // I successfully received a handshake. Just in case I marked this tunnel as 'Disestablished', ensure
  373. // it's correctly marked as working.
  374. via.relayHI.relayState.UpdateRelayForByIdxState(via.remoteIdx, Established)
  375. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  376. f.l.WithField("vpnAddrs", vpnAddrs).WithField("relay", via.relayHI.vpnAddrs[0]).
  377. WithField("certName", certName).
  378. WithField("fingerprint", fingerprint).
  379. WithField("issuer", issuer).
  380. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  381. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  382. Info("Handshake message sent")
  383. }
  384. f.connectionManager.AddTrafficWatch(hostinfo.localIndexId)
  385. hostinfo.remotes.ResetBlockedRemotes()
  386. return
  387. }
  388. func ixHandshakeStage2(f *Interface, addr netip.AddrPort, via *ViaSender, hh *HandshakeHostInfo, packet []byte, h *header.H) bool {
  389. if hh == nil {
  390. // Nothing here to tear down, got a bogus stage 2 packet
  391. return true
  392. }
  393. hh.Lock()
  394. defer hh.Unlock()
  395. hostinfo := hh.hostinfo
  396. if addr.IsValid() {
  397. // The vpnAddr we know about is the one we tried to handshake with, use it to apply the remote allow list.
  398. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, addr.Addr()) {
  399. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  400. return false
  401. }
  402. }
  403. ci := hostinfo.ConnectionState
  404. msg, eKey, dKey, err := ci.H.ReadMessage(nil, packet[header.Len:])
  405. if err != nil {
  406. f.l.WithError(err).WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  407. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  408. Error("Failed to call noise.ReadMessage")
  409. // We don't want to tear down the connection on a bad ReadMessage because it could be an attacker trying
  410. // to DOS us. Every other error condition after should to allow a possible good handshake to complete in the
  411. // near future
  412. return false
  413. } else if dKey == nil || eKey == nil {
  414. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  415. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  416. Error("Noise did not arrive at a key")
  417. // This should be impossible in IX but just in case, if we get here then there is no chance to recover
  418. // the handshake state machine. Tear it down
  419. return true
  420. }
  421. hs := &NebulaHandshake{}
  422. err = hs.Unmarshal(msg)
  423. if err != nil || hs.Details == nil {
  424. f.l.WithError(err).WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  425. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  426. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  427. return true
  428. }
  429. remoteCert, err := cert.RecombineAndValidate(cert.Version(hs.Details.CertVersion), hs.Details.Cert, ci.H.PeerStatic(), ci.Curve(), f.pki.GetCAPool())
  430. if err != nil {
  431. e := f.l.WithError(err).WithField("vpnAddrs", hostinfo.vpnAddrs).WithField("udpAddr", addr).
  432. WithField("handshake", m{"stage": 2, "style": "ix_psk0"})
  433. if f.l.Level > logrus.DebugLevel {
  434. e = e.WithField("cert", remoteCert)
  435. }
  436. e.Error("Invalid certificate from host")
  437. // The handshake state machine is complete, if things break now there is no chance to recover. Tear down and start again
  438. return true
  439. }
  440. if len(remoteCert.Certificate.Networks()) == 0 {
  441. e := f.l.WithError(err).WithField("udpAddr", addr).
  442. WithField("handshake", m{"stage": 2, "style": "ix_psk0"})
  443. if f.l.Level > logrus.DebugLevel {
  444. e = e.WithField("cert", remoteCert)
  445. }
  446. e.Info("Empty networks from host")
  447. return true
  448. }
  449. vpnNetworks := remoteCert.Certificate.Networks()
  450. certName := remoteCert.Certificate.Name()
  451. fingerprint := remoteCert.Fingerprint
  452. issuer := remoteCert.Certificate.Issuer()
  453. hostinfo.remoteIndexId = hs.Details.ResponderIndex
  454. hostinfo.lastHandshakeTime = hs.Details.Time
  455. // Store their cert and our symmetric keys
  456. ci.peerCert = remoteCert
  457. ci.dKey = NewNebulaCipherState(dKey)
  458. ci.eKey = NewNebulaCipherState(eKey)
  459. // Make sure the current udpAddr being used is set for responding
  460. if addr.IsValid() {
  461. hostinfo.SetRemote(addr)
  462. } else {
  463. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  464. }
  465. var vpnAddrs []netip.Addr
  466. var filteredNetworks []netip.Prefix
  467. for _, network := range vpnNetworks {
  468. // vpnAddrs outside our vpn networks are of no use to us, filter them out
  469. vpnAddr := network.Addr()
  470. if _, ok := f.myVpnNetworksTable.Lookup(vpnAddr); !ok {
  471. continue
  472. }
  473. filteredNetworks = append(filteredNetworks, network)
  474. vpnAddrs = append(vpnAddrs, vpnAddr)
  475. }
  476. if len(vpnAddrs) == 0 {
  477. f.l.WithError(err).WithField("udpAddr", addr).
  478. WithField("certName", certName).
  479. WithField("fingerprint", fingerprint).
  480. WithField("issuer", issuer).
  481. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("No usable vpn addresses from host, refusing handshake")
  482. return true
  483. }
  484. // Ensure the right host responded
  485. if !slices.Contains(vpnAddrs, hostinfo.vpnAddrs[0]) {
  486. f.l.WithField("intendedVpnAddrs", hostinfo.vpnAddrs).WithField("haveVpnNetworks", vpnNetworks).
  487. WithField("udpAddr", addr).WithField("certName", certName).
  488. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  489. Info("Incorrect host responded to handshake")
  490. // Release our old handshake from pending, it should not continue
  491. f.handshakeManager.DeleteHostInfo(hostinfo)
  492. // Create a new hostinfo/handshake for the intended vpn ip
  493. f.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
  494. // Block the current used address
  495. newHH.hostinfo.remotes = hostinfo.remotes
  496. newHH.hostinfo.remotes.BlockRemote(addr)
  497. f.l.WithField("blockedUdpAddrs", newHH.hostinfo.remotes.CopyBlockedRemotes()).
  498. WithField("vpnNetworks", vpnNetworks).
  499. WithField("remotes", newHH.hostinfo.remotes.CopyAddrs(f.hostMap.GetPreferredRanges())).
  500. Info("Blocked addresses for handshakes")
  501. // Swap the packet store to benefit the original intended recipient
  502. newHH.packetStore = hh.packetStore
  503. hh.packetStore = []*cachedPacket{}
  504. // Finally, put the correct vpn addrs in the host info, tell them to close the tunnel, and return true to tear down
  505. hostinfo.vpnAddrs = vpnAddrs
  506. f.sendCloseTunnel(hostinfo)
  507. })
  508. return true
  509. }
  510. // Mark packet 2 as seen so it doesn't show up as missed
  511. ci.window.Update(f.l, 2)
  512. duration := time.Since(hh.startTime).Nanoseconds()
  513. f.l.WithField("vpnAddrs", vpnAddrs).WithField("udpAddr", addr).
  514. WithField("certName", certName).
  515. WithField("fingerprint", fingerprint).
  516. WithField("issuer", issuer).
  517. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  518. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  519. WithField("durationNs", duration).
  520. WithField("sentCachedPackets", len(hh.packetStore)).
  521. Info("Handshake message received")
  522. // Build up the radix for the firewall if we have subnets in the cert
  523. hostinfo.vpnAddrs = vpnAddrs
  524. hostinfo.buildNetworks(filteredNetworks, remoteCert.Certificate.UnsafeNetworks())
  525. // Complete our handshake and update metrics, this will replace any existing tunnels for the vpnAddrs here
  526. f.handshakeManager.Complete(hostinfo, f)
  527. f.connectionManager.AddTrafficWatch(hostinfo.localIndexId)
  528. if f.l.Level >= logrus.DebugLevel {
  529. hostinfo.logger(f.l).Debugf("Sending %d stored packets", len(hh.packetStore))
  530. }
  531. if len(hh.packetStore) > 0 {
  532. nb := make([]byte, 12, 12)
  533. out := make([]byte, mtu)
  534. for _, cp := range hh.packetStore {
  535. cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
  536. }
  537. f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
  538. }
  539. hostinfo.remotes.ResetBlockedRemotes()
  540. f.metricHandshakes.Update(duration)
  541. return false
  542. }