handshake_ix.go 25 KB

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