outside.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package nebula
  2. import (
  3. "errors"
  4. "net/netip"
  5. "time"
  6. "github.com/sirupsen/logrus"
  7. "github.com/slackhq/nebula/firewall"
  8. "github.com/slackhq/nebula/header"
  9. )
  10. func (f *Interface) readOutsidePackets(via ViaSender, out []byte, packet []byte, h *header.H, fwPacket *firewall.Packet, lhf *LightHouseHandler, nb []byte, q int, localCache firewall.ConntrackCache) {
  11. err := h.Parse(packet)
  12. if err != nil {
  13. // Hole punch packets are 0 or 1 byte big, so lets ignore printing those errors
  14. if len(packet) > 1 {
  15. f.l.WithField("packet", packet).Infof("Error while parsing inbound packet from %s: %s", via, err)
  16. }
  17. return
  18. }
  19. //l.Error("in packet ", header, packet[HeaderLen:])
  20. if !via.IsRelayed {
  21. if f.myVpnNetworksTable.Contains(via.UdpAddr.Addr()) {
  22. if f.l.Level >= logrus.DebugLevel {
  23. f.l.WithField("from", via).Debug("Refusing to process double encrypted packet")
  24. }
  25. return
  26. }
  27. }
  28. var hostinfo *HostInfo
  29. // verify if we've seen this index before, otherwise respond to the handshake initiation
  30. if h.Type == header.Message && h.Subtype == header.MessageRelay {
  31. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  32. } else {
  33. hostinfo = f.hostMap.QueryIndex(h.RemoteIndex)
  34. }
  35. var ci *ConnectionState
  36. if hostinfo != nil {
  37. ci = hostinfo.ConnectionState
  38. }
  39. switch h.Type {
  40. case header.Message:
  41. if !f.handleEncrypted(ci, via, h) {
  42. return
  43. }
  44. switch h.Subtype {
  45. case header.MessageNone:
  46. if !f.decryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache) {
  47. return
  48. }
  49. case header.MessageRelay:
  50. // The entire body is sent as AD, not encrypted.
  51. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  52. // The packet is guaranteed to be at least 16 bytes at this point, b/c it got past the h.Parse() call above. If it's
  53. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  54. // which will gracefully fail in the DecryptDanger call.
  55. signedPayload := packet[:len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  56. signatureValue := packet[len(packet)-hostinfo.ConnectionState.dKey.Overhead():]
  57. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, signedPayload, signatureValue, h.MessageCounter, nb)
  58. if err != nil {
  59. return
  60. }
  61. // Successfully validated the thing. Get rid of the Relay header.
  62. signedPayload = signedPayload[header.Len:]
  63. // Pull the Roaming parts up here, and return in all call paths.
  64. f.handleHostRoaming(hostinfo, via)
  65. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  66. f.connectionManager.In(hostinfo)
  67. f.connectionManager.RelayUsed(h.RemoteIndex)
  68. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  69. if !ok {
  70. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  71. // its internal mapping. This should never happen.
  72. hostinfo.logger(f.l).WithFields(logrus.Fields{"vpnAddrs": hostinfo.vpnAddrs, "remoteIndex": h.RemoteIndex}).Error("HostInfo missing remote relay index")
  73. return
  74. }
  75. switch relay.Type {
  76. case TerminalType:
  77. // If I am the target of this relay, process the unwrapped packet
  78. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  79. via = ViaSender{
  80. UdpAddr: via.UdpAddr,
  81. relayHI: hostinfo,
  82. remoteIdx: relay.RemoteIndex,
  83. relay: relay,
  84. IsRelayed: true,
  85. }
  86. f.readOutsidePackets(via, out[:0], signedPayload, h, fwPacket, lhf, nb, q, localCache)
  87. return
  88. case ForwardingType:
  89. // Find the target HostInfo relay object
  90. targetHI, targetRelay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relay.PeerAddr)
  91. if err != nil {
  92. hostinfo.logger(f.l).WithField("relayTo", relay.PeerAddr).WithError(err).WithField("hostinfo.vpnAddrs", hostinfo.vpnAddrs).Info("Failed to find target host info by ip")
  93. return
  94. }
  95. // If that relay is Established, forward the payload through it
  96. if targetRelay.State == Established {
  97. switch targetRelay.Type {
  98. case ForwardingType:
  99. // Forward this packet through the relay tunnel
  100. // Find the target HostInfo
  101. f.SendVia(targetHI, targetRelay, signedPayload, nb, out, false)
  102. return
  103. case TerminalType:
  104. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  105. }
  106. } else {
  107. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerAddr, "relayFrom": hostinfo.vpnAddrs[0], "targetRelayState": targetRelay.State}).Info("Unexpected target relay state")
  108. return
  109. }
  110. }
  111. }
  112. case header.LightHouse:
  113. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  114. if !f.handleEncrypted(ci, via, h) {
  115. return
  116. }
  117. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  118. if err != nil {
  119. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  120. WithField("packet", packet).
  121. Error("Failed to decrypt lighthouse packet")
  122. return
  123. }
  124. //TODO: assert via is not relayed
  125. lhf.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, d, f)
  126. // Fallthrough to the bottom to record incoming traffic
  127. case header.Test:
  128. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  129. if !f.handleEncrypted(ci, via, h) {
  130. return
  131. }
  132. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  133. if err != nil {
  134. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  135. WithField("packet", packet).
  136. Error("Failed to decrypt test packet")
  137. return
  138. }
  139. if h.Subtype == header.TestRequest {
  140. // This testRequest might be from TryPromoteBest, so we should roam
  141. // to the new IP address before responding
  142. f.handleHostRoaming(hostinfo, via)
  143. f.send(header.Test, header.TestReply, ci, hostinfo, d, nb, out)
  144. }
  145. // Fallthrough to the bottom to record incoming traffic
  146. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  147. // are unauthenticated
  148. case header.Handshake:
  149. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  150. f.handshakeManager.HandleIncoming(via, packet, h)
  151. return
  152. case header.RecvError:
  153. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  154. f.handleRecvError(via.UdpAddr, h)
  155. return
  156. case header.CloseTunnel:
  157. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  158. if !f.handleEncrypted(ci, via, h) {
  159. return
  160. }
  161. hostinfo.logger(f.l).WithField("from", via).
  162. Info("Close tunnel received, tearing down.")
  163. f.closeTunnel(hostinfo)
  164. return
  165. case header.Control:
  166. if !f.handleEncrypted(ci, via, h) {
  167. return
  168. }
  169. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  170. if err != nil {
  171. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  172. WithField("packet", packet).
  173. Error("Failed to decrypt Control packet")
  174. return
  175. }
  176. f.relayManager.HandleControlMsg(hostinfo, d, f)
  177. default:
  178. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  179. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", via)
  180. return
  181. }
  182. f.handleHostRoaming(hostinfo, via)
  183. f.connectionManager.In(hostinfo)
  184. }
  185. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  186. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  187. final := f.hostMap.DeleteHostInfo(hostInfo)
  188. if final {
  189. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  190. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  191. }
  192. }
  193. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  194. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  195. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  196. }
  197. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  198. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  199. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  200. hostinfo.logger(f.l).WithField("newAddr", via.UdpAddr).Debug("lighthouse.remote_allow_list denied roaming")
  201. return
  202. }
  203. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  204. if f.l.Level >= logrus.DebugLevel {
  205. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  206. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  207. }
  208. return
  209. }
  210. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  211. Info("Host roamed to new udp ip/port.")
  212. hostinfo.lastRoam = time.Now()
  213. hostinfo.lastRoamRemote = hostinfo.remote
  214. hostinfo.SetRemote(via.UdpAddr)
  215. }
  216. }
  217. // handleEncrypted returns true if a packet should be processed, false otherwise
  218. func (f *Interface) handleEncrypted(ci *ConnectionState, via ViaSender, h *header.H) bool {
  219. // If connectionstate does not exist, send a recv error, if possible, to encourage a fast reconnect
  220. if ci == nil {
  221. if !via.IsRelayed {
  222. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  223. }
  224. return false
  225. }
  226. // If the window check fails, refuse to process the packet, but don't send a recv error
  227. if !ci.window.Check(f.l, h.MessageCounter) {
  228. return false
  229. }
  230. return true
  231. }
  232. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  233. var err error
  234. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  239. hostinfo.logger(f.l).WithField("header", h).
  240. Debugln("dropping out of window packet")
  241. return nil, errors.New("out of window packet")
  242. }
  243. return out, nil
  244. }
  245. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) bool {
  246. var err error
  247. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  248. if err != nil {
  249. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  250. return false
  251. }
  252. err = firewall.NewPacket(out, true, fwPacket)
  253. if err != nil {
  254. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  255. Warnf("Error while validating inbound packet")
  256. return false
  257. }
  258. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  259. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  260. Debugln("dropping out of window packet")
  261. return false
  262. }
  263. dropReason := f.firewall.Drop(*fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  264. if dropReason != nil {
  265. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  266. // This gives us a buffer to build the reject packet in
  267. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  268. if f.l.Level >= logrus.DebugLevel {
  269. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  270. WithField("reason", dropReason).
  271. Debugln("dropping inbound packet")
  272. }
  273. return false
  274. }
  275. f.connectionManager.In(hostinfo)
  276. _, err = f.readers[q].Write(out)
  277. if err != nil {
  278. f.l.WithError(err).Error("Failed to write to tun")
  279. }
  280. return true
  281. }
  282. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  283. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  284. f.sendRecvError(endpoint, index)
  285. }
  286. }
  287. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  288. f.messageMetrics.Tx(header.RecvError, 0, 1)
  289. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  290. _ = f.outside.WriteTo(b, endpoint)
  291. if f.l.Level >= logrus.DebugLevel {
  292. f.l.WithField("index", index).
  293. WithField("udpAddr", endpoint).
  294. Debug("Recv error sent")
  295. }
  296. }
  297. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  298. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  299. f.l.WithField("index", h.RemoteIndex).
  300. WithField("udpAddr", addr).
  301. Debug("Recv error received, ignoring")
  302. return
  303. }
  304. if f.l.Level >= logrus.DebugLevel {
  305. f.l.WithField("index", h.RemoteIndex).
  306. WithField("udpAddr", addr).
  307. Debug("Recv error received")
  308. }
  309. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  310. if hostinfo == nil {
  311. f.l.WithField("remoteIndex", h.RemoteIndex).Debugln("Did not find remote index in main hostmap")
  312. return
  313. }
  314. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  315. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  316. return
  317. }
  318. f.closeTunnel(hostinfo)
  319. // We also delete it from pending hostmap to allow for fast reconnect.
  320. f.handshakeManager.DeleteHostInfo(hostinfo)
  321. }