outside.go 17 KB

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