outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "net/netip"
  6. "time"
  7. "github.com/google/gopacket/layers"
  8. "golang.org/x/net/ipv6"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/firewall"
  11. "github.com/slackhq/nebula/header"
  12. "golang.org/x/net/ipv4"
  13. )
  14. const (
  15. minFwPacketLen = 4
  16. )
  17. 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) {
  18. err := h.Parse(packet)
  19. if err != nil {
  20. // Hole punch packets are 0 or 1 byte big, so lets ignore printing those errors
  21. if len(packet) > 1 {
  22. f.l.WithField("packet", packet).Infof("Error while parsing inbound packet from %s: %s", via, err)
  23. }
  24. return
  25. }
  26. //l.Error("in packet ", header, packet[HeaderLen:])
  27. if !via.IsRelayed {
  28. if f.myVpnNetworksTable.Contains(via.UdpAddr.Addr()) {
  29. if f.l.Level >= logrus.DebugLevel {
  30. f.l.WithField("from", via).Debug("Refusing to process double encrypted packet")
  31. }
  32. return
  33. }
  34. }
  35. var hostinfo *HostInfo
  36. // verify if we've seen this index before, otherwise respond to the handshake initiation
  37. if h.Type == header.Message && h.Subtype == header.MessageRelay {
  38. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  39. } else {
  40. hostinfo = f.hostMap.QueryIndex(h.RemoteIndex)
  41. }
  42. var ci *ConnectionState
  43. if hostinfo != nil {
  44. ci = hostinfo.ConnectionState
  45. }
  46. switch h.Type {
  47. case header.Message:
  48. if !f.handleEncrypted(ci, via, h) {
  49. return
  50. }
  51. switch h.Subtype {
  52. case header.MessageNone:
  53. if !f.decryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache) {
  54. return
  55. }
  56. case header.MessageRelay:
  57. // The entire body is sent as AD, not encrypted.
  58. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  59. // 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
  60. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  61. // which will gracefully fail in the DecryptDanger call.
  62. signedPayload := packet[:len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  63. signatureValue := packet[len(packet)-hostinfo.ConnectionState.dKey.Overhead():]
  64. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, signedPayload, signatureValue, h.MessageCounter, nb)
  65. if err != nil {
  66. return
  67. }
  68. // Successfully validated the thing. Get rid of the Relay header.
  69. signedPayload = signedPayload[header.Len:]
  70. // Pull the Roaming parts up here, and return in all call paths.
  71. f.handleHostRoaming(hostinfo, via)
  72. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  73. f.connectionManager.In(hostinfo)
  74. f.connectionManager.RelayUsed(h.RemoteIndex)
  75. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  76. if !ok {
  77. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  78. // its internal mapping. This should never happen.
  79. hostinfo.logger(f.l).WithFields(logrus.Fields{"vpnAddrs": hostinfo.vpnAddrs, "remoteIndex": h.RemoteIndex}).Error("HostInfo missing remote relay index")
  80. return
  81. }
  82. switch relay.Type {
  83. case TerminalType:
  84. // If I am the target of this relay, process the unwrapped packet
  85. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  86. via = ViaSender{
  87. UdpAddr: via.UdpAddr,
  88. relayHI: hostinfo,
  89. remoteIdx: relay.RemoteIndex,
  90. relay: relay,
  91. IsRelayed: true,
  92. }
  93. f.readOutsidePackets(via, out[:0], signedPayload, h, fwPacket, lhf, nb, q, localCache)
  94. return
  95. case ForwardingType:
  96. // Find the target HostInfo relay object
  97. targetHI, targetRelay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relay.PeerAddr)
  98. if err != nil {
  99. hostinfo.logger(f.l).WithField("relayTo", relay.PeerAddr).WithError(err).WithField("hostinfo.vpnAddrs", hostinfo.vpnAddrs).Info("Failed to find target host info by ip")
  100. return
  101. }
  102. // If that relay is Established, forward the payload through it
  103. if targetRelay.State == Established {
  104. switch targetRelay.Type {
  105. case ForwardingType:
  106. // Forward this packet through the relay tunnel
  107. // Find the target HostInfo
  108. f.SendVia(targetHI, targetRelay, signedPayload, nb, out, false)
  109. return
  110. case TerminalType:
  111. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  112. }
  113. } else {
  114. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerAddr, "relayFrom": hostinfo.vpnAddrs[0], "targetRelayState": targetRelay.State}).Info("Unexpected target relay state")
  115. return
  116. }
  117. }
  118. }
  119. case header.LightHouse:
  120. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  121. if !f.handleEncrypted(ci, via, h) {
  122. return
  123. }
  124. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  125. if err != nil {
  126. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  127. WithField("packet", packet).
  128. Error("Failed to decrypt lighthouse packet")
  129. return
  130. }
  131. //TODO: assert via is not relayed
  132. lhf.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, d, f)
  133. // Fallthrough to the bottom to record incoming traffic
  134. case header.Test:
  135. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  136. if !f.handleEncrypted(ci, via, h) {
  137. return
  138. }
  139. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  140. if err != nil {
  141. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  142. WithField("packet", packet).
  143. Error("Failed to decrypt test packet")
  144. return
  145. }
  146. if h.Subtype == header.TestRequest {
  147. // This testRequest might be from TryPromoteBest, so we should roam
  148. // to the new IP address before responding
  149. f.handleHostRoaming(hostinfo, via)
  150. f.send(header.Test, header.TestReply, ci, hostinfo, d, nb, out)
  151. }
  152. // Fallthrough to the bottom to record incoming traffic
  153. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  154. // are unauthenticated
  155. case header.Handshake:
  156. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  157. f.handshakeManager.HandleIncoming(via, packet, h)
  158. return
  159. case header.RecvError:
  160. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  161. f.handleRecvError(via.UdpAddr, h)
  162. return
  163. case header.CloseTunnel:
  164. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  165. if !f.handleEncrypted(ci, via, h) {
  166. return
  167. }
  168. hostinfo.logger(f.l).WithField("from", via).
  169. Info("Close tunnel received, tearing down.")
  170. f.closeTunnel(hostinfo)
  171. return
  172. case header.Control:
  173. if !f.handleEncrypted(ci, via, h) {
  174. return
  175. }
  176. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  177. if err != nil {
  178. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  179. WithField("packet", packet).
  180. Error("Failed to decrypt Control packet")
  181. return
  182. }
  183. f.relayManager.HandleControlMsg(hostinfo, d, f)
  184. default:
  185. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  186. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", via)
  187. return
  188. }
  189. f.handleHostRoaming(hostinfo, via)
  190. f.connectionManager.In(hostinfo)
  191. }
  192. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  193. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  194. final := f.hostMap.DeleteHostInfo(hostInfo)
  195. if final {
  196. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  197. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  198. }
  199. }
  200. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  201. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  202. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  203. }
  204. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  205. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  206. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  207. hostinfo.logger(f.l).WithField("newAddr", via.UdpAddr).Debug("lighthouse.remote_allow_list denied roaming")
  208. return
  209. }
  210. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  211. if f.l.Level >= logrus.DebugLevel {
  212. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  213. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  214. }
  215. return
  216. }
  217. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  218. Info("Host roamed to new udp ip/port.")
  219. hostinfo.lastRoam = time.Now()
  220. hostinfo.lastRoamRemote = hostinfo.remote
  221. hostinfo.SetRemote(via.UdpAddr)
  222. }
  223. }
  224. // handleEncrypted returns true if a packet should be processed, false otherwise
  225. func (f *Interface) handleEncrypted(ci *ConnectionState, via ViaSender, h *header.H) bool {
  226. // If connectionstate does not exist, send a recv error, if possible, to encourage a fast reconnect
  227. if ci == nil {
  228. if !via.IsRelayed {
  229. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  230. }
  231. return false
  232. }
  233. // If the window check fails, refuse to process the packet, but don't send a recv error
  234. if !ci.window.Check(f.l, h.MessageCounter) {
  235. return false
  236. }
  237. return true
  238. }
  239. var (
  240. ErrPacketTooShort = errors.New("packet is too short")
  241. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  242. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  243. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  244. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  245. ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
  246. )
  247. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  248. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  249. if len(data) < 1 {
  250. return ErrPacketTooShort
  251. }
  252. version := int((data[0] >> 4) & 0x0f)
  253. switch version {
  254. case ipv4.Version:
  255. return parseV4(data, incoming, fp)
  256. case ipv6.Version:
  257. return parseV6(data, incoming, fp)
  258. }
  259. return ErrUnknownIPVersion
  260. }
  261. func parseV6(data []byte, incoming bool, fp *firewall.Packet) error {
  262. dataLen := len(data)
  263. if dataLen < ipv6.HeaderLen {
  264. return ErrIPv6PacketTooShort
  265. }
  266. if incoming {
  267. fp.RemoteAddr, _ = netip.AddrFromSlice(data[8:24])
  268. fp.LocalAddr, _ = netip.AddrFromSlice(data[24:40])
  269. } else {
  270. fp.LocalAddr, _ = netip.AddrFromSlice(data[8:24])
  271. fp.RemoteAddr, _ = netip.AddrFromSlice(data[24:40])
  272. }
  273. protoAt := 6 // NextHeader is at 6 bytes into the ipv6 header
  274. offset := ipv6.HeaderLen // Start at the end of the ipv6 header
  275. next := 0
  276. for {
  277. if protoAt >= dataLen {
  278. break
  279. }
  280. proto := layers.IPProtocol(data[protoAt])
  281. switch proto {
  282. case layers.IPProtocolICMPv6, layers.IPProtocolESP, layers.IPProtocolNoNextHeader:
  283. fp.Protocol = uint8(proto)
  284. fp.RemotePort = 0
  285. fp.LocalPort = 0
  286. fp.Fragment = false
  287. return nil
  288. case layers.IPProtocolTCP, layers.IPProtocolUDP:
  289. if dataLen < offset+4 {
  290. return ErrIPv6PacketTooShort
  291. }
  292. fp.Protocol = uint8(proto)
  293. if incoming {
  294. fp.RemotePort = binary.BigEndian.Uint16(data[offset : offset+2])
  295. fp.LocalPort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  296. } else {
  297. fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
  298. fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  299. }
  300. fp.Fragment = false
  301. return nil
  302. case layers.IPProtocolIPv6Fragment:
  303. // Fragment header is 8 bytes, need at least offset+4 to read the offset field
  304. if dataLen < offset+8 {
  305. return ErrIPv6PacketTooShort
  306. }
  307. // Check if this is the first fragment
  308. fragmentOffset := binary.BigEndian.Uint16(data[offset+2:offset+4]) &^ uint16(0x7) // Remove the reserved and M flag bits
  309. if fragmentOffset != 0 {
  310. // Non-first fragment, use what we have now and stop processing
  311. fp.Protocol = data[offset]
  312. fp.Fragment = true
  313. fp.RemotePort = 0
  314. fp.LocalPort = 0
  315. return nil
  316. }
  317. // The next loop should be the transport layer since we are the first fragment
  318. next = 8 // Fragment headers are always 8 bytes
  319. case layers.IPProtocolAH:
  320. // Auth headers, used by IPSec, have a different meaning for header length
  321. if dataLen <= offset+1 {
  322. break
  323. }
  324. next = int(data[offset+1]+2) << 2
  325. default:
  326. // Normal ipv6 header length processing
  327. if dataLen <= offset+1 {
  328. break
  329. }
  330. next = int(data[offset+1]+1) << 3
  331. }
  332. if next <= 0 {
  333. // Safety check, each ipv6 header has to be at least 8 bytes
  334. next = 8
  335. }
  336. protoAt = offset
  337. offset = offset + next
  338. }
  339. return ErrIPv6CouldNotFindPayload
  340. }
  341. func parseV4(data []byte, incoming bool, fp *firewall.Packet) error {
  342. // Do we at least have an ipv4 header worth of data?
  343. if len(data) < ipv4.HeaderLen {
  344. return ErrIPv4PacketTooShort
  345. }
  346. // Adjust our start position based on the advertised ip header length
  347. ihl := int(data[0]&0x0f) << 2
  348. // Well-formed ip header length?
  349. if ihl < ipv4.HeaderLen {
  350. return ErrIPv4InvalidHeaderLength
  351. }
  352. // Check if this is the second or further fragment of a fragmented packet.
  353. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  354. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  355. // Firewall handles protocol checks
  356. fp.Protocol = data[9]
  357. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  358. minLen := ihl
  359. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  360. minLen += minFwPacketLen
  361. }
  362. if len(data) < minLen {
  363. return ErrIPv4InvalidHeaderLength
  364. }
  365. // Firewall packets are locally oriented
  366. if incoming {
  367. fp.RemoteAddr, _ = netip.AddrFromSlice(data[12:16])
  368. fp.LocalAddr, _ = netip.AddrFromSlice(data[16:20])
  369. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  370. fp.RemotePort = 0
  371. fp.LocalPort = 0
  372. } else {
  373. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  374. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  375. }
  376. } else {
  377. fp.LocalAddr, _ = netip.AddrFromSlice(data[12:16])
  378. fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
  379. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  380. fp.RemotePort = 0
  381. fp.LocalPort = 0
  382. } else {
  383. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  384. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  385. }
  386. }
  387. return nil
  388. }
  389. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  390. var err error
  391. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  392. if err != nil {
  393. return nil, err
  394. }
  395. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  396. hostinfo.logger(f.l).WithField("header", h).
  397. Debugln("dropping out of window packet")
  398. return nil, errors.New("out of window packet")
  399. }
  400. return out, nil
  401. }
  402. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) bool {
  403. var err error
  404. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  405. if err != nil {
  406. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  407. return false
  408. }
  409. err = newPacket(out, true, fwPacket)
  410. if err != nil {
  411. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  412. Warnf("Error while validating inbound packet")
  413. return false
  414. }
  415. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  416. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  417. Debugln("dropping out of window packet")
  418. return false
  419. }
  420. dropReason := f.firewall.Drop(*fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  421. if dropReason != nil {
  422. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  423. // This gives us a buffer to build the reject packet in
  424. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  425. if f.l.Level >= logrus.DebugLevel {
  426. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  427. WithField("reason", dropReason).
  428. Debugln("dropping inbound packet")
  429. }
  430. return false
  431. }
  432. f.connectionManager.In(hostinfo)
  433. _, err = f.readers[q].Write(out)
  434. if err != nil {
  435. f.l.WithError(err).Error("Failed to write to tun")
  436. }
  437. return true
  438. }
  439. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  440. if f.sendRecvErrorConfig.ShouldSendRecvError(endpoint) {
  441. f.sendRecvError(endpoint, index)
  442. }
  443. }
  444. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  445. f.messageMetrics.Tx(header.RecvError, 0, 1)
  446. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  447. _ = f.outside.WriteTo(b, endpoint)
  448. if f.l.Level >= logrus.DebugLevel {
  449. f.l.WithField("index", index).
  450. WithField("udpAddr", endpoint).
  451. Debug("Recv error sent")
  452. }
  453. }
  454. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  455. if f.l.Level >= logrus.DebugLevel {
  456. f.l.WithField("index", h.RemoteIndex).
  457. WithField("udpAddr", addr).
  458. Debug("Recv error received")
  459. }
  460. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  461. if hostinfo == nil {
  462. f.l.WithField("remoteIndex", h.RemoteIndex).Debugln("Did not find remote index in main hostmap")
  463. return
  464. }
  465. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  466. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  467. return
  468. }
  469. f.closeTunnel(hostinfo)
  470. // We also delete it from pending hostmap to allow for fast reconnect.
  471. f.handshakeManager.DeleteHostInfo(hostinfo)
  472. }