handshake_ix.go 28 KB

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