handshake_ix.go 24 KB

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