2
0

handshake_ix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package nebula
  2. import (
  3. "bytes"
  4. "sync/atomic"
  5. "time"
  6. "github.com/flynn/noise"
  7. "github.com/golang/protobuf/proto"
  8. )
  9. // NOISE IX Handshakes
  10. // This function constructs a handshake packet, but does not actually send it
  11. // Sending is done by the handshake manager
  12. func ixHandshakeStage0(f *Interface, vpnIp uint32, hostinfo *HostInfo) {
  13. // This queries the lighthouse if we don't know a remote for the host
  14. if hostinfo.remote == nil {
  15. ips, err := f.lightHouse.Query(vpnIp, f)
  16. if err != nil {
  17. //l.Debugln(err)
  18. }
  19. for _, ip := range ips {
  20. hostinfo.AddRemote(ip)
  21. }
  22. }
  23. myIndex, err := generateIndex()
  24. if err != nil {
  25. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  26. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to generate index")
  27. return
  28. }
  29. ci := hostinfo.ConnectionState
  30. f.handshakeManager.AddIndexHostInfo(myIndex, hostinfo)
  31. hsProto := &NebulaHandshakeDetails{
  32. InitiatorIndex: myIndex,
  33. Time: uint64(time.Now().Unix()),
  34. Cert: ci.certState.rawCertificateNoKey,
  35. }
  36. hsBytes := []byte{}
  37. hs := &NebulaHandshake{
  38. Details: hsProto,
  39. }
  40. hsBytes, err = proto.Marshal(hs)
  41. if err != nil {
  42. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  43. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  44. return
  45. }
  46. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, 0, 1)
  47. atomic.AddUint64(ci.messageCounter, 1)
  48. msg, _, _, err := ci.H.WriteMessage(header, hsBytes)
  49. if err != nil {
  50. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  51. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  52. return
  53. }
  54. // We are sending handshake packet 1, so we don't expect to receive
  55. // handshake packet 1 from the responder
  56. ci.window.Update(1)
  57. hostinfo.HandshakePacket[0] = msg
  58. hostinfo.HandshakeReady = true
  59. hostinfo.handshakeStart = time.Now()
  60. }
  61. func ixHandshakeStage1(f *Interface, addr *udpAddr, hostinfo *HostInfo, packet []byte, h *Header) bool {
  62. var ip uint32
  63. if h.RemoteIndex == 0 {
  64. ci := f.newConnectionState(false, noise.HandshakeIX, []byte{}, 0)
  65. // Mark packet 1 as seen so it doesn't show up as missed
  66. ci.window.Update(1)
  67. msg, _, _, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  68. if err != nil {
  69. l.WithError(err).WithField("udpAddr", addr).
  70. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.ReadMessage")
  71. return true
  72. }
  73. hs := &NebulaHandshake{}
  74. err = proto.Unmarshal(msg, hs)
  75. /*
  76. l.Debugln("GOT INDEX: ", hs.Details.InitiatorIndex)
  77. */
  78. if err != nil || hs.Details == nil {
  79. l.WithError(err).WithField("udpAddr", addr).
  80. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  81. return true
  82. }
  83. hostinfo, _ := f.handshakeManager.pendingHostMap.QueryReverseIndex(hs.Details.InitiatorIndex)
  84. if hostinfo != nil && bytes.Equal(hostinfo.HandshakePacket[0], packet[HeaderLen:]) {
  85. if msg, ok := hostinfo.HandshakePacket[2]; ok {
  86. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  87. err := f.outside.WriteTo(msg, addr)
  88. if err != nil {
  89. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  90. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  91. WithError(err).Error("Failed to send handshake message")
  92. } else {
  93. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  94. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  95. Info("Handshake message sent")
  96. }
  97. return false
  98. }
  99. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  100. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cached", true).
  101. WithField("packets", hostinfo.HandshakePacket).
  102. Error("Seen this handshake packet already but don't have a cached packet to return")
  103. }
  104. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert)
  105. if err != nil {
  106. l.WithError(err).WithField("udpAddr", addr).
  107. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cert", remoteCert).
  108. Info("Invalid certificate from host")
  109. return true
  110. }
  111. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  112. certName := remoteCert.Details.Name
  113. fingerprint, _ := remoteCert.Sha256Sum()
  114. myIndex, err := generateIndex()
  115. if err != nil {
  116. l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  117. WithField("certName", certName).
  118. WithField("fingerprint", fingerprint).
  119. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to generate index")
  120. return true
  121. }
  122. hostinfo, err = f.handshakeManager.AddIndex(myIndex, ci)
  123. if err != nil {
  124. l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  125. WithField("certName", certName).
  126. WithField("fingerprint", fingerprint).
  127. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Error adding index to connection manager")
  128. return true
  129. }
  130. l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  131. WithField("certName", certName).
  132. WithField("fingerprint", fingerprint).
  133. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  134. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  135. Info("Handshake message received")
  136. hostinfo.remoteIndexId = hs.Details.InitiatorIndex
  137. hs.Details.ResponderIndex = myIndex
  138. hs.Details.Cert = ci.certState.rawCertificateNoKey
  139. hsBytes, err := proto.Marshal(hs)
  140. if err != nil {
  141. l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  142. WithField("certName", certName).
  143. WithField("fingerprint", fingerprint).
  144. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  145. return true
  146. }
  147. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, hs.Details.InitiatorIndex, 2)
  148. msg, dKey, eKey, err := ci.H.WriteMessage(header, hsBytes)
  149. if err != nil {
  150. l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  151. WithField("certName", certName).
  152. WithField("fingerprint", fingerprint).
  153. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  154. return true
  155. }
  156. if f.hostMap.CheckHandshakeCompleteIP(vpnIP) && vpnIP < ip2int(f.certState.certificate.Details.Ips[0].IP) {
  157. l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  158. WithField("certName", certName).
  159. WithField("fingerprint", fingerprint).
  160. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  161. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  162. Info("Prevented a handshake race")
  163. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  164. f.SendMessageToVpnIp(test, testRequest, vpnIP, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  165. return true
  166. }
  167. hostinfo.HandshakePacket[0] = make([]byte, len(packet[HeaderLen:]))
  168. copy(hostinfo.HandshakePacket[0], packet[HeaderLen:])
  169. // Regardless of whether you are the sender or receiver, you should arrive here
  170. // and complete standing up the connection.
  171. if dKey != nil && eKey != nil {
  172. hostinfo.HandshakePacket[2] = make([]byte, len(msg))
  173. copy(hostinfo.HandshakePacket[2], msg)
  174. // We are sending handshake packet 2, so we don't expect to receive
  175. // handshake packet 2 from the initiator.
  176. ci.window.Update(2)
  177. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  178. err := f.outside.WriteTo(msg, addr)
  179. if err != nil {
  180. l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  181. WithField("certName", certName).
  182. WithField("fingerprint", fingerprint).
  183. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  184. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  185. WithError(err).Error("Failed to send handshake")
  186. } else {
  187. l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  188. WithField("certName", certName).
  189. WithField("fingerprint", fingerprint).
  190. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  191. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  192. Info("Handshake message sent")
  193. }
  194. ip = ip2int(remoteCert.Details.Ips[0].IP)
  195. ci.peerCert = remoteCert
  196. ci.dKey = NewNebulaCipherState(dKey)
  197. ci.eKey = NewNebulaCipherState(eKey)
  198. //l.Debugln("got symmetric pairs")
  199. //hostinfo.ClearRemotes()
  200. hostinfo.AddRemote(*addr)
  201. hostinfo.CreateRemoteCIDR(remoteCert)
  202. f.lightHouse.AddRemoteAndReset(ip, addr)
  203. if f.serveDns {
  204. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  205. }
  206. ho, err := f.hostMap.QueryVpnIP(vpnIP)
  207. if err == nil && ho.localIndexId != 0 {
  208. l.WithField("vpnIp", vpnIP).
  209. WithField("certName", certName).
  210. WithField("fingerprint", fingerprint).
  211. WithField("action", "removing stale index").
  212. WithField("index", ho.localIndexId).
  213. Debug("Handshake processing")
  214. f.hostMap.DeleteIndex(ho.localIndexId)
  215. }
  216. f.hostMap.AddIndexHostInfo(hostinfo.localIndexId, hostinfo)
  217. f.hostMap.AddVpnIPHostInfo(vpnIP, hostinfo)
  218. hostinfo.handshakeComplete()
  219. } else {
  220. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  221. WithField("certName", certName).
  222. WithField("fingerprint", fingerprint).
  223. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  224. Error("Noise did not arrive at a key")
  225. return true
  226. }
  227. }
  228. f.hostMap.AddRemote(ip, addr)
  229. return false
  230. }
  231. func ixHandshakeStage2(f *Interface, addr *udpAddr, hostinfo *HostInfo, packet []byte, h *Header) bool {
  232. if hostinfo == nil {
  233. return true
  234. }
  235. if bytes.Equal(hostinfo.HandshakePacket[2], packet[HeaderLen:]) {
  236. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  237. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  238. Error("Already seen this handshake packet")
  239. return false
  240. }
  241. ci := hostinfo.ConnectionState
  242. // Mark packet 2 as seen so it doesn't show up as missed
  243. ci.window.Update(2)
  244. hostinfo.HandshakePacket[2] = make([]byte, len(packet[HeaderLen:]))
  245. copy(hostinfo.HandshakePacket[2], packet[HeaderLen:])
  246. msg, eKey, dKey, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  247. if err != nil {
  248. l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  249. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  250. Error("Failed to call noise.ReadMessage")
  251. // We don't want to tear down the connection on a bad ReadMessage because it could be an attacker trying
  252. // to DOS us. Every other error condition after should to allow a possible good handshake to complete in the
  253. // near future
  254. return false
  255. }
  256. hs := &NebulaHandshake{}
  257. err = proto.Unmarshal(msg, hs)
  258. if err != nil || hs.Details == nil {
  259. l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  260. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  261. return true
  262. }
  263. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert)
  264. if err != nil {
  265. l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  266. WithField("cert", remoteCert).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  267. Error("Invalid certificate from host")
  268. return true
  269. }
  270. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  271. certName := remoteCert.Details.Name
  272. fingerprint, _ := remoteCert.Sha256Sum()
  273. duration := time.Since(hostinfo.handshakeStart).Nanoseconds()
  274. l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  275. WithField("certName", certName).
  276. WithField("fingerprint", fingerprint).
  277. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  278. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  279. WithField("durationNs", duration).
  280. Info("Handshake message received")
  281. //ci.remoteIndex = hs.ResponderIndex
  282. hostinfo.remoteIndexId = hs.Details.ResponderIndex
  283. hs.Details.Cert = ci.certState.rawCertificateNoKey
  284. /*
  285. hsBytes, err := proto.Marshal(hs)
  286. if err != nil {
  287. l.Debugln("Failed to marshal handshake: ", err)
  288. return
  289. }
  290. */
  291. // Regardless of whether you are the sender or receiver, you should arrive here
  292. // and complete standing up the connection.
  293. if dKey != nil && eKey != nil {
  294. ip := ip2int(remoteCert.Details.Ips[0].IP)
  295. ci.peerCert = remoteCert
  296. ci.dKey = NewNebulaCipherState(dKey)
  297. ci.eKey = NewNebulaCipherState(eKey)
  298. //l.Debugln("got symmetric pairs")
  299. //hostinfo.ClearRemotes()
  300. f.hostMap.AddRemote(ip, addr)
  301. hostinfo.CreateRemoteCIDR(remoteCert)
  302. f.lightHouse.AddRemoteAndReset(ip, addr)
  303. if f.serveDns {
  304. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  305. }
  306. ho, err := f.hostMap.QueryVpnIP(vpnIP)
  307. if err == nil && ho.localIndexId != 0 {
  308. l.WithField("vpnIp", vpnIP).
  309. WithField("certName", certName).
  310. WithField("fingerprint", fingerprint).
  311. WithField("action", "removing stale index").
  312. WithField("index", ho.localIndexId).
  313. Debug("Handshake processing")
  314. f.hostMap.DeleteIndex(ho.localIndexId)
  315. }
  316. f.hostMap.AddVpnIPHostInfo(vpnIP, hostinfo)
  317. f.hostMap.AddIndexHostInfo(hostinfo.localIndexId, hostinfo)
  318. hostinfo.handshakeComplete()
  319. f.metricHandshakes.Update(duration)
  320. } else {
  321. l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  322. WithField("certName", certName).
  323. WithField("fingerprint", fingerprint).
  324. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  325. Error("Noise did not arrive at a key")
  326. return true
  327. }
  328. return false
  329. }