outside.go 17 KB

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