outside.go 17 KB

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