outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.localIndexId)
  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.localIndexId)
  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. func (f *Interface) handleEncrypted(ci *ConnectionState, addr netip.AddrPort, h *header.H) bool {
  249. // If connectionstate exists and the replay protector allows, process packet
  250. // Else, send recv errors for 300 seconds after a restart to allow fast reconnection.
  251. if ci == nil || !ci.window.Check(f.l, h.MessageCounter) {
  252. if addr.IsValid() {
  253. f.maybeSendRecvError(addr, h.RemoteIndex)
  254. return false
  255. } else {
  256. return false
  257. }
  258. }
  259. return true
  260. }
  261. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  262. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  263. // Do we at least have an ipv4 header worth of data?
  264. if len(data) < ipv4.HeaderLen {
  265. return fmt.Errorf("packet is less than %v bytes", ipv4.HeaderLen)
  266. }
  267. // Is it an ipv4 packet?
  268. if int((data[0]>>4)&0x0f) != 4 {
  269. return fmt.Errorf("packet is not ipv4, type: %v", int((data[0]>>4)&0x0f))
  270. }
  271. // Adjust our start position based on the advertised ip header length
  272. ihl := int(data[0]&0x0f) << 2
  273. // Well formed ip header length?
  274. if ihl < ipv4.HeaderLen {
  275. return fmt.Errorf("packet had an invalid header length: %v", ihl)
  276. }
  277. // Check if this is the second or further fragment of a fragmented packet.
  278. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  279. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  280. // Firewall handles protocol checks
  281. fp.Protocol = data[9]
  282. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  283. minLen := ihl
  284. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  285. minLen += minFwPacketLen
  286. }
  287. if len(data) < minLen {
  288. return fmt.Errorf("packet is less than %v bytes, ip header len: %v", minLen, ihl)
  289. }
  290. // Firewall packets are locally oriented
  291. if incoming {
  292. //TODO: IPV6-WORK
  293. fp.RemoteIP, _ = netip.AddrFromSlice(data[12:16])
  294. fp.LocalIP, _ = netip.AddrFromSlice(data[16:20])
  295. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  296. fp.RemotePort = 0
  297. fp.LocalPort = 0
  298. } else {
  299. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  300. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  301. }
  302. } else {
  303. //TODO: IPV6-WORK
  304. fp.LocalIP, _ = netip.AddrFromSlice(data[12:16])
  305. fp.RemoteIP, _ = netip.AddrFromSlice(data[16:20])
  306. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  307. fp.RemotePort = 0
  308. fp.LocalPort = 0
  309. } else {
  310. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  311. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  312. }
  313. }
  314. return nil
  315. }
  316. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  317. var err error
  318. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  319. if err != nil {
  320. return nil, err
  321. }
  322. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  323. hostinfo.logger(f.l).WithField("header", h).
  324. Debugln("dropping out of window packet")
  325. return nil, errors.New("out of window packet")
  326. }
  327. return out, nil
  328. }
  329. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) bool {
  330. var err error
  331. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  332. if err != nil {
  333. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  334. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  335. //f.sendRecvError(hostinfo.remote, header.RemoteIndex)
  336. return false
  337. }
  338. err = newPacket(out, true, fwPacket)
  339. if err != nil {
  340. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  341. Warnf("Error while validating inbound packet")
  342. return false
  343. }
  344. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  345. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  346. Debugln("dropping out of window packet")
  347. return false
  348. }
  349. dropReason := f.firewall.Drop(*fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  350. if dropReason != nil {
  351. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  352. // This gives us a buffer to build the reject packet in
  353. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  354. if f.l.Level >= logrus.DebugLevel {
  355. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  356. WithField("reason", dropReason).
  357. Debugln("dropping inbound packet")
  358. }
  359. return false
  360. }
  361. f.connectionManager.In(hostinfo.localIndexId)
  362. _, err = f.readers[q].Write(out)
  363. if err != nil {
  364. f.l.WithError(err).Error("Failed to write to tun")
  365. }
  366. return true
  367. }
  368. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  369. if f.sendRecvErrorConfig.ShouldSendRecvError(endpoint) {
  370. f.sendRecvError(endpoint, index)
  371. }
  372. }
  373. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  374. f.messageMetrics.Tx(header.RecvError, 0, 1)
  375. //TODO: this should be a signed message so we can trust that we should drop the index
  376. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  377. f.outside.WriteTo(b, endpoint)
  378. if f.l.Level >= logrus.DebugLevel {
  379. f.l.WithField("index", index).
  380. WithField("udpAddr", endpoint).
  381. Debug("Recv error sent")
  382. }
  383. }
  384. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  385. if f.l.Level >= logrus.DebugLevel {
  386. f.l.WithField("index", h.RemoteIndex).
  387. WithField("udpAddr", addr).
  388. Debug("Recv error received")
  389. }
  390. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  391. if hostinfo == nil {
  392. f.l.WithField("remoteIndex", h.RemoteIndex).Debugln("Did not find remote index in main hostmap")
  393. return
  394. }
  395. if !hostinfo.RecvErrorExceeded() {
  396. return
  397. }
  398. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  399. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  400. return
  401. }
  402. f.closeTunnel(hostinfo)
  403. // We also delete it from pending hostmap to allow for fast reconnect.
  404. f.handshakeManager.DeleteHostInfo(hostinfo)
  405. }
  406. /*
  407. func (f *Interface) sendMeta(ci *ConnectionState, endpoint *net.UDPAddr, meta *NebulaMeta) {
  408. if ci.eKey != nil {
  409. //TODO: log error?
  410. return
  411. }
  412. msg, err := proto.Marshal(meta)
  413. if err != nil {
  414. l.Debugln("failed to encode header")
  415. }
  416. c := ci.messageCounter
  417. b := HeaderEncode(nil, Version, uint8(metadata), 0, hostinfo.remoteIndexId, c)
  418. ci.messageCounter++
  419. msg := ci.eKey.EncryptDanger(b, nil, msg, c)
  420. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  421. f.outside.WriteTo(msg, endpoint)
  422. }
  423. */
  424. func RecombineCertAndValidate(h *noise.HandshakeState, rawCertBytes []byte, caPool *cert.NebulaCAPool) (*cert.NebulaCertificate, error) {
  425. pk := h.PeerStatic()
  426. if pk == nil {
  427. return nil, errors.New("no peer static key was present")
  428. }
  429. if rawCertBytes == nil {
  430. return nil, errors.New("provided payload was empty")
  431. }
  432. r := &cert.RawNebulaCertificate{}
  433. err := proto.Unmarshal(rawCertBytes, r)
  434. if err != nil {
  435. return nil, fmt.Errorf("error unmarshaling cert: %s", err)
  436. }
  437. // If the Details are nil, just exit to avoid crashing
  438. if r.Details == nil {
  439. return nil, fmt.Errorf("certificate did not contain any details")
  440. }
  441. r.Details.PublicKey = pk
  442. recombined, err := proto.Marshal(r)
  443. if err != nil {
  444. return nil, fmt.Errorf("error while recombining certificate: %s", err)
  445. }
  446. c, _ := cert.UnmarshalNebulaCertificate(recombined)
  447. isValid, err := c.Verify(time.Now(), caPool)
  448. if err != nil {
  449. return c, fmt.Errorf("certificate validation failed: %s", err)
  450. } else if !isValid {
  451. // This case should never happen but here's to defensive programming!
  452. return c, errors.New("certificate validation failed but did not return an error")
  453. }
  454. return c, nil
  455. }