3
0

handshake_ix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. err := f.handshakeManager.AddIndexHostInfo(hostinfo)
  24. if err != nil {
  25. f.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. hsProto := &NebulaHandshakeDetails{
  31. InitiatorIndex: hostinfo.localIndexId,
  32. Time: uint64(time.Now().Unix()),
  33. Cert: ci.certState.rawCertificateNoKey,
  34. }
  35. hsBytes := []byte{}
  36. hs := &NebulaHandshake{
  37. Details: hsProto,
  38. }
  39. hsBytes, err = proto.Marshal(hs)
  40. if err != nil {
  41. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  42. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  43. return
  44. }
  45. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, 0, 1)
  46. atomic.AddUint64(&ci.atomicMessageCounter, 1)
  47. msg, _, _, err := ci.H.WriteMessage(header, hsBytes)
  48. if err != nil {
  49. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).
  50. WithField("handshake", m{"stage": 0, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  51. return
  52. }
  53. // We are sending handshake packet 1, so we don't expect to receive
  54. // handshake packet 1 from the responder
  55. ci.window.Update(f.l, 1)
  56. hostinfo.HandshakePacket[0] = msg
  57. hostinfo.HandshakeReady = true
  58. hostinfo.handshakeStart = time.Now()
  59. }
  60. func ixHandshakeStage1(f *Interface, addr *udpAddr, packet []byte, h *Header) {
  61. ci := f.newConnectionState(f.l, false, noise.HandshakeIX, []byte{}, 0)
  62. // Mark packet 1 as seen so it doesn't show up as missed
  63. ci.window.Update(f.l, 1)
  64. msg, _, _, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  65. if err != nil {
  66. f.l.WithError(err).WithField("udpAddr", addr).
  67. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.ReadMessage")
  68. return
  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. f.l.WithError(err).WithField("udpAddr", addr).
  77. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  78. return
  79. }
  80. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert)
  81. if err != nil {
  82. f.l.WithError(err).WithField("udpAddr", addr).
  83. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).WithField("cert", remoteCert).
  84. Info("Invalid certificate from host")
  85. return
  86. }
  87. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  88. certName := remoteCert.Details.Name
  89. fingerprint, _ := remoteCert.Sha256Sum()
  90. if vpnIP == ip2int(f.certState.certificate.Details.Ips[0].IP) {
  91. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  92. WithField("certName", certName).
  93. WithField("fingerprint", fingerprint).
  94. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Refusing to handshake with myself")
  95. return
  96. }
  97. myIndex, err := generateIndex(f.l)
  98. if err != nil {
  99. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  100. WithField("certName", certName).
  101. WithField("fingerprint", fingerprint).
  102. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to generate index")
  103. return
  104. }
  105. hostinfo := &HostInfo{
  106. ConnectionState: ci,
  107. Remotes: []*HostInfoDest{},
  108. localIndexId: myIndex,
  109. remoteIndexId: hs.Details.InitiatorIndex,
  110. hostId: vpnIP,
  111. HandshakePacket: make(map[uint8][]byte, 0),
  112. }
  113. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  114. WithField("certName", certName).
  115. WithField("fingerprint", fingerprint).
  116. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  117. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  118. Info("Handshake message received")
  119. hs.Details.ResponderIndex = myIndex
  120. hs.Details.Cert = ci.certState.rawCertificateNoKey
  121. hsBytes, err := proto.Marshal(hs)
  122. if err != nil {
  123. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  124. WithField("certName", certName).
  125. WithField("fingerprint", fingerprint).
  126. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to marshal handshake message")
  127. return
  128. }
  129. header := HeaderEncode(make([]byte, HeaderLen), Version, uint8(handshake), handshakeIXPSK0, hs.Details.InitiatorIndex, 2)
  130. msg, dKey, eKey, err := ci.H.WriteMessage(header, hsBytes)
  131. if err != nil {
  132. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  133. WithField("certName", certName).
  134. WithField("fingerprint", fingerprint).
  135. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).Error("Failed to call noise.WriteMessage")
  136. return
  137. } else if dKey == nil || eKey == nil {
  138. f.l.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("Noise did not arrive at a key")
  142. return
  143. }
  144. hostinfo.HandshakePacket[0] = make([]byte, len(packet[HeaderLen:]))
  145. copy(hostinfo.HandshakePacket[0], packet[HeaderLen:])
  146. // Regardless of whether you are the sender or receiver, you should arrive here
  147. // and complete standing up the connection.
  148. hostinfo.HandshakePacket[2] = make([]byte, len(msg))
  149. copy(hostinfo.HandshakePacket[2], msg)
  150. // We are sending handshake packet 2, so we don't expect to receive
  151. // handshake packet 2 from the initiator.
  152. ci.window.Update(f.l, 2)
  153. ci.peerCert = remoteCert
  154. ci.dKey = NewNebulaCipherState(dKey)
  155. ci.eKey = NewNebulaCipherState(eKey)
  156. //l.Debugln("got symmetric pairs")
  157. //hostinfo.ClearRemotes()
  158. hostinfo.AddRemote(addr)
  159. hostinfo.ForcePromoteBest(f.hostMap.preferredRanges)
  160. hostinfo.CreateRemoteCIDR(remoteCert)
  161. hostinfo.Lock()
  162. defer hostinfo.Unlock()
  163. // Only overwrite existing record if we should win the handshake race
  164. overwrite := vpnIP > ip2int(f.certState.certificate.Details.Ips[0].IP)
  165. existing, err := f.handshakeManager.CheckAndComplete(hostinfo, 0, overwrite, f)
  166. if err != nil {
  167. switch err {
  168. case ErrAlreadySeen:
  169. msg = existing.HandshakePacket[2]
  170. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  171. err := f.outside.WriteTo(msg, addr)
  172. if err != nil {
  173. f.l.WithField("vpnIp", IntIp(existing.hostId)).WithField("udpAddr", addr).
  174. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  175. WithError(err).Error("Failed to send handshake message")
  176. } else {
  177. f.l.WithField("vpnIp", IntIp(existing.hostId)).WithField("udpAddr", addr).
  178. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("cached", true).
  179. Info("Handshake message sent")
  180. }
  181. return
  182. case ErrExistingHostInfo:
  183. // This means there was an existing tunnel and we didn't win
  184. // handshake avoidance
  185. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  186. WithField("certName", certName).
  187. WithField("fingerprint", fingerprint).
  188. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  189. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  190. Info("Prevented a handshake race")
  191. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  192. f.SendMessageToVpnIp(test, testRequest, vpnIP, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  193. return
  194. case ErrLocalIndexCollision:
  195. // This means we failed to insert because of collision on localIndexId. Just let the next handshake packet retry
  196. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  197. WithField("certName", certName).
  198. WithField("fingerprint", fingerprint).
  199. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  200. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  201. WithField("localIndex", hostinfo.localIndexId).WithField("collision", IntIp(existing.hostId)).
  202. Error("Failed to add HostInfo due to localIndex collision")
  203. return
  204. default:
  205. // Shouldn't happen, but just in case someone adds a new error type to CheckAndComplete
  206. // And we forget to update it here
  207. f.l.WithError(err).WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  208. WithField("certName", certName).
  209. WithField("fingerprint", fingerprint).
  210. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  211. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  212. Error("Failed to add HostInfo to HostMap")
  213. return
  214. }
  215. }
  216. // Do the send
  217. f.messageMetrics.Tx(handshake, NebulaMessageSubType(msg[1]), 1)
  218. err = f.outside.WriteTo(msg, addr)
  219. if err != nil {
  220. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  221. WithField("certName", certName).
  222. WithField("fingerprint", fingerprint).
  223. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  224. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  225. WithError(err).Error("Failed to send handshake")
  226. } else {
  227. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  228. WithField("certName", certName).
  229. WithField("fingerprint", fingerprint).
  230. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  231. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  232. Info("Handshake message sent")
  233. }
  234. hostinfo.handshakeComplete(f.l)
  235. return
  236. }
  237. func ixHandshakeStage2(f *Interface, addr *udpAddr, hostinfo *HostInfo, packet []byte, h *Header) bool {
  238. if hostinfo == nil {
  239. return true
  240. }
  241. hostinfo.Lock()
  242. defer hostinfo.Unlock()
  243. if bytes.Equal(hostinfo.HandshakePacket[2], packet[HeaderLen:]) {
  244. f.l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  245. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  246. Info("Already seen this handshake packet")
  247. return false
  248. }
  249. ci := hostinfo.ConnectionState
  250. // Mark packet 2 as seen so it doesn't show up as missed
  251. ci.window.Update(f.l, 2)
  252. hostinfo.HandshakePacket[2] = make([]byte, len(packet[HeaderLen:]))
  253. copy(hostinfo.HandshakePacket[2], packet[HeaderLen:])
  254. msg, eKey, dKey, err := ci.H.ReadMessage(nil, packet[HeaderLen:])
  255. if err != nil {
  256. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  257. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).WithField("header", h).
  258. Error("Failed to call noise.ReadMessage")
  259. // We don't want to tear down the connection on a bad ReadMessage because it could be an attacker trying
  260. // to DOS us. Every other error condition after should to allow a possible good handshake to complete in the
  261. // near future
  262. return false
  263. } else if dKey == nil || eKey == nil {
  264. f.l.WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  265. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  266. Error("Noise did not arrive at a key")
  267. return true
  268. }
  269. hs := &NebulaHandshake{}
  270. err = proto.Unmarshal(msg, hs)
  271. if err != nil || hs.Details == nil {
  272. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  273. WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).Error("Failed unmarshal handshake message")
  274. return true
  275. }
  276. remoteCert, err := RecombineCertAndValidate(ci.H, hs.Details.Cert)
  277. if err != nil {
  278. f.l.WithError(err).WithField("vpnIp", IntIp(hostinfo.hostId)).WithField("udpAddr", addr).
  279. WithField("cert", remoteCert).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  280. Error("Invalid certificate from host")
  281. return true
  282. }
  283. vpnIP := ip2int(remoteCert.Details.Ips[0].IP)
  284. certName := remoteCert.Details.Name
  285. fingerprint, _ := remoteCert.Sha256Sum()
  286. duration := time.Since(hostinfo.handshakeStart).Nanoseconds()
  287. f.l.WithField("vpnIp", IntIp(vpnIP)).WithField("udpAddr", addr).
  288. WithField("certName", certName).
  289. WithField("fingerprint", fingerprint).
  290. WithField("initiatorIndex", hs.Details.InitiatorIndex).WithField("responderIndex", hs.Details.ResponderIndex).
  291. WithField("remoteIndex", h.RemoteIndex).WithField("handshake", m{"stage": 2, "style": "ix_psk0"}).
  292. WithField("durationNs", duration).
  293. Info("Handshake message received")
  294. //ci.remoteIndex = hs.ResponderIndex
  295. hostinfo.remoteIndexId = hs.Details.ResponderIndex
  296. hs.Details.Cert = ci.certState.rawCertificateNoKey
  297. /*
  298. hsBytes, err := proto.Marshal(hs)
  299. if err != nil {
  300. l.Debugln("Failed to marshal handshake: ", err)
  301. return
  302. }
  303. */
  304. // Regardless of whether you are the sender or receiver, you should arrive here
  305. // and complete standing up the connection.
  306. ci.peerCert = remoteCert
  307. ci.dKey = NewNebulaCipherState(dKey)
  308. ci.eKey = NewNebulaCipherState(eKey)
  309. //l.Debugln("got symmetric pairs")
  310. hostinfo.SetRemote(addr)
  311. hostinfo.CreateRemoteCIDR(remoteCert)
  312. f.handshakeManager.Complete(hostinfo, f)
  313. hostinfo.handshakeComplete(f.l)
  314. f.metricHandshakes.Update(duration)
  315. return false
  316. }