handshake_ix.go 24 KB

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