handshake_ix.go 24 KB

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