handshake_ix.go 14 KB

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