outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. // don't keep Rx metrics for message type, since you can see those in the tun metrics
  47. if h.Type != header.Message {
  48. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  49. }
  50. // Unencrypted packets
  51. switch h.Type {
  52. case header.Message:
  53. switch h.Subtype {
  54. case header.MessageRelay:
  55. // The entire body is sent as AD, not encrypted.
  56. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  57. // 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
  58. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  59. // which will gracefully fail in the DecryptDanger call.
  60. if !f.handleEncrypted(ci, via, h) {
  61. return
  62. }
  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, via)
  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. via = ViaSender{
  88. UdpAddr: via.UdpAddr,
  89. relayHI: hostinfo,
  90. remoteIdx: relay.RemoteIndex,
  91. relay: relay,
  92. IsRelayed: true,
  93. }
  94. f.readOutsidePackets(via, out[:0], signedPayload, h, fwPacket, lhf, nb, q, localCache)
  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. case TerminalType:
  110. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  111. }
  112. } else {
  113. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerAddr, "relayFrom": hostinfo.vpnAddrs[0], "targetRelayState": targetRelay.State}).Info("Unexpected target relay state")
  114. }
  115. }
  116. return
  117. }
  118. case header.Handshake:
  119. f.handshakeManager.HandleIncoming(via, packet, h)
  120. return
  121. case header.RecvError:
  122. f.handleRecvError(via.UdpAddr, h)
  123. return
  124. }
  125. // All remaining packets are encrypted
  126. if !f.handleEncrypted(ci, via, h) {
  127. return
  128. }
  129. out, err = f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  130. if err != nil {
  131. hostinfo.logger(f.l).WithError(err).WithField("from", via).
  132. WithField("packet", packet).
  133. Error("Failed to decrypt packet")
  134. return
  135. }
  136. switch h.Type {
  137. case header.Message:
  138. switch h.Subtype {
  139. case header.MessageNone:
  140. if !f.sendDecryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache) {
  141. return
  142. }
  143. default:
  144. hostinfo.logger(f.l).Debugf("Unexpected message subtype received from %s", via)
  145. return
  146. }
  147. case header.LightHouse:
  148. //TODO: assert via is not relayed
  149. lhf.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, out, f)
  150. case header.Test:
  151. if h.Subtype == header.TestRequest {
  152. // This testRequest might be from TryPromoteBest, so we should roam
  153. // to the new IP address before responding
  154. f.handleHostRoaming(hostinfo, via)
  155. f.send(header.Test, header.TestReply, ci, hostinfo, out, nb, out)
  156. }
  157. case header.CloseTunnel:
  158. hostinfo.logger(f.l).WithField("from", via).
  159. Info("Close tunnel received, tearing down.")
  160. f.closeTunnel(hostinfo)
  161. return
  162. case header.Control:
  163. f.relayManager.HandleControlMsg(hostinfo, out, f)
  164. default:
  165. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", via)
  166. return
  167. }
  168. f.handleHostRoaming(hostinfo, via)
  169. f.connectionManager.In(hostinfo)
  170. }
  171. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  172. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  173. final := f.hostMap.DeleteHostInfo(hostInfo)
  174. if final {
  175. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  176. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  177. }
  178. }
  179. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  180. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  181. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  182. }
  183. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  184. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  185. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  186. hostinfo.logger(f.l).WithField("newAddr", via.UdpAddr).Debug("lighthouse.remote_allow_list denied roaming")
  187. return
  188. }
  189. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  190. if f.l.Level >= logrus.DebugLevel {
  191. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  192. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  193. }
  194. return
  195. }
  196. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", via.UdpAddr).
  197. Info("Host roamed to new udp ip/port.")
  198. hostinfo.lastRoam = time.Now()
  199. hostinfo.lastRoamRemote = hostinfo.remote
  200. hostinfo.SetRemote(via.UdpAddr)
  201. }
  202. }
  203. // handleEncrypted returns true if a packet should be processed, false otherwise
  204. func (f *Interface) handleEncrypted(ci *ConnectionState, via ViaSender, h *header.H) bool {
  205. // If connectionstate does not exist, send a recv error, if possible, to encourage a fast reconnect
  206. if ci == nil {
  207. if !via.IsRelayed {
  208. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  209. }
  210. return false
  211. }
  212. // If the window check fails, refuse to process the packet, but don't send a recv error
  213. if !ci.window.Check(f.l, h.MessageCounter) {
  214. return false
  215. }
  216. return true
  217. }
  218. var (
  219. ErrPacketTooShort = errors.New("packet is too short")
  220. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  221. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  222. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  223. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  224. ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
  225. )
  226. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  227. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  228. if len(data) < 1 {
  229. return ErrPacketTooShort
  230. }
  231. version := int((data[0] >> 4) & 0x0f)
  232. switch version {
  233. case ipv4.Version:
  234. return parseV4(data, incoming, fp)
  235. case ipv6.Version:
  236. return parseV6(data, incoming, fp)
  237. }
  238. return ErrUnknownIPVersion
  239. }
  240. func parseV6(data []byte, incoming bool, fp *firewall.Packet) error {
  241. dataLen := len(data)
  242. if dataLen < ipv6.HeaderLen {
  243. return ErrIPv6PacketTooShort
  244. }
  245. if incoming {
  246. fp.RemoteAddr, _ = netip.AddrFromSlice(data[8:24])
  247. fp.LocalAddr, _ = netip.AddrFromSlice(data[24:40])
  248. } else {
  249. fp.LocalAddr, _ = netip.AddrFromSlice(data[8:24])
  250. fp.RemoteAddr, _ = netip.AddrFromSlice(data[24:40])
  251. }
  252. protoAt := 6 // NextHeader is at 6 bytes into the ipv6 header
  253. offset := ipv6.HeaderLen // Start at the end of the ipv6 header
  254. next := 0
  255. for {
  256. if protoAt >= dataLen {
  257. break
  258. }
  259. proto := layers.IPProtocol(data[protoAt])
  260. switch proto {
  261. case layers.IPProtocolESP, layers.IPProtocolNoNextHeader:
  262. fp.Protocol = uint8(proto)
  263. fp.RemotePort = 0
  264. fp.LocalPort = 0
  265. fp.Fragment = false
  266. return nil
  267. case layers.IPProtocolICMPv6:
  268. if dataLen < offset+6 {
  269. return ErrIPv6PacketTooShort
  270. }
  271. fp.Protocol = uint8(proto)
  272. fp.LocalPort = 0 //incoming vs outgoing doesn't matter for icmpv6
  273. icmptype := data[offset+1]
  274. switch icmptype {
  275. case layers.ICMPv6TypeEchoRequest, layers.ICMPv6TypeEchoReply:
  276. fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier
  277. default:
  278. fp.RemotePort = 0
  279. }
  280. fp.Fragment = false
  281. return nil
  282. case layers.IPProtocolTCP, layers.IPProtocolUDP:
  283. if dataLen < offset+4 {
  284. return ErrIPv6PacketTooShort
  285. }
  286. fp.Protocol = uint8(proto)
  287. if incoming {
  288. fp.RemotePort = binary.BigEndian.Uint16(data[offset : offset+2])
  289. fp.LocalPort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  290. } else {
  291. fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
  292. fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  293. }
  294. fp.Fragment = false
  295. return nil
  296. case layers.IPProtocolIPv6Fragment:
  297. // Fragment header is 8 bytes, need at least offset+4 to read the offset field
  298. if dataLen < offset+8 {
  299. return ErrIPv6PacketTooShort
  300. }
  301. // Check if this is the first fragment
  302. fragmentOffset := binary.BigEndian.Uint16(data[offset+2:offset+4]) &^ uint16(0x7) // Remove the reserved and M flag bits
  303. if fragmentOffset != 0 {
  304. // Non-first fragment, use what we have now and stop processing
  305. fp.Protocol = data[offset]
  306. fp.Fragment = true
  307. fp.RemotePort = 0
  308. fp.LocalPort = 0
  309. return nil
  310. }
  311. // The next loop should be the transport layer since we are the first fragment
  312. next = 8 // Fragment headers are always 8 bytes
  313. case layers.IPProtocolAH:
  314. // Auth headers, used by IPSec, have a different meaning for header length
  315. if dataLen <= offset+1 {
  316. break
  317. }
  318. next = int(data[offset+1]+2) << 2
  319. default:
  320. // Normal ipv6 header length processing
  321. if dataLen <= offset+1 {
  322. break
  323. }
  324. next = int(data[offset+1]+1) << 3
  325. }
  326. if next <= 0 {
  327. // Safety check, each ipv6 header has to be at least 8 bytes
  328. next = 8
  329. }
  330. protoAt = offset
  331. offset = offset + next
  332. }
  333. return ErrIPv6CouldNotFindPayload
  334. }
  335. func parseV4(data []byte, incoming bool, fp *firewall.Packet) error {
  336. // Do we at least have an ipv4 header worth of data?
  337. if len(data) < ipv4.HeaderLen {
  338. return ErrIPv4PacketTooShort
  339. }
  340. // Adjust our start position based on the advertised ip header length
  341. ihl := int(data[0]&0x0f) << 2
  342. // Well-formed ip header length?
  343. if ihl < ipv4.HeaderLen {
  344. return ErrIPv4InvalidHeaderLength
  345. }
  346. // Check if this is the second or further fragment of a fragmented packet.
  347. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  348. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  349. // Firewall handles protocol checks
  350. fp.Protocol = data[9]
  351. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  352. minLen := ihl
  353. if !fp.Fragment {
  354. if fp.Protocol == firewall.ProtoICMP {
  355. minLen += minFwPacketLen + 2
  356. } else {
  357. minLen += minFwPacketLen
  358. }
  359. }
  360. if len(data) < minLen {
  361. return ErrIPv4InvalidHeaderLength
  362. }
  363. if incoming { // Firewall packets are locally oriented
  364. fp.RemoteAddr, _ = netip.AddrFromSlice(data[12:16])
  365. fp.LocalAddr, _ = netip.AddrFromSlice(data[16:20])
  366. } else {
  367. fp.LocalAddr, _ = netip.AddrFromSlice(data[12:16])
  368. fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
  369. }
  370. if fp.Fragment {
  371. fp.RemotePort = 0
  372. fp.LocalPort = 0
  373. } else if fp.Protocol == firewall.ProtoICMP { //note that orientation doesn't matter on ICMP
  374. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier
  375. fp.LocalPort = 0 //code would be uint16(data[ihl+1])
  376. } else if incoming {
  377. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  378. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  379. } else {
  380. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  381. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  382. }
  383. return nil
  384. }
  385. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  386. var err error
  387. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  388. if err != nil {
  389. return nil, err
  390. }
  391. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  392. hostinfo.logger(f.l).WithField("header", h).
  393. Debugln("dropping out of window packet")
  394. return nil, errors.New("out of window packet")
  395. }
  396. return out, nil
  397. }
  398. func (f *Interface) sendDecryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) bool {
  399. var err error
  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. dropReason := f.firewall.Drop(*fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  407. if dropReason != nil {
  408. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  409. // This gives us a buffer to build the reject packet in
  410. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  411. if f.l.Level >= logrus.DebugLevel {
  412. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  413. WithField("reason", dropReason).
  414. Debugln("dropping inbound packet")
  415. }
  416. return false
  417. }
  418. f.connectionManager.In(hostinfo)
  419. _, err = f.readers[q].Write(out)
  420. if err != nil {
  421. f.l.WithError(err).Error("Failed to write to tun")
  422. }
  423. return true
  424. }
  425. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  426. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  427. f.sendRecvError(endpoint, index)
  428. }
  429. }
  430. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  431. f.messageMetrics.Tx(header.RecvError, 0, 1)
  432. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  433. _ = f.outside.WriteTo(b, endpoint)
  434. if f.l.Level >= logrus.DebugLevel {
  435. f.l.WithField("index", index).
  436. WithField("udpAddr", endpoint).
  437. Debug("Recv error sent")
  438. }
  439. }
  440. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  441. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  442. f.l.WithField("index", h.RemoteIndex).
  443. WithField("udpAddr", addr).
  444. Debug("Recv error received, ignoring")
  445. return
  446. }
  447. if f.l.Level >= logrus.DebugLevel {
  448. f.l.WithField("index", h.RemoteIndex).
  449. WithField("udpAddr", addr).
  450. Debug("Recv error received")
  451. }
  452. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  453. if hostinfo == nil {
  454. f.l.WithField("remoteIndex", h.RemoteIndex).Debugln("Did not find remote index in main hostmap")
  455. return
  456. }
  457. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  458. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  459. return
  460. }
  461. f.closeTunnel(hostinfo)
  462. // We also delete it from pending hostmap to allow for fast reconnect.
  463. f.handshakeManager.DeleteHostInfo(hostinfo)
  464. }