handshake_ix.go 25 KB

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