outside.go 17 KB

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