handshake_ix.go 24 KB

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