outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "time"
  7. "github.com/flynn/noise"
  8. "github.com/sirupsen/logrus"
  9. "github.com/slackhq/nebula/cert"
  10. "github.com/slackhq/nebula/firewall"
  11. "github.com/slackhq/nebula/header"
  12. "github.com/slackhq/nebula/iputil"
  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. func readOutsidePackets(f *Interface) udp.EncReader {
  21. return func(
  22. addr *udp.Addr,
  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(addr *udp.Addr, 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", addr, err)
  43. }
  44. return
  45. }
  46. //l.Error("in packet ", header, packet[HeaderLen:])
  47. if addr != nil {
  48. if ip4 := addr.IP.To4(); ip4 != nil {
  49. if ipMaskContains(f.lightHouse.myVpnIp, f.lightHouse.myVpnZeros, iputil.VpnIp(binary.BigEndian.Uint32(ip4))) {
  50. if f.l.Level >= logrus.DebugLevel {
  51. f.l.WithField("udpAddr", addr).Debug("Refusing to process double encrypted packet")
  52. }
  53. return
  54. }
  55. }
  56. }
  57. var hostinfo *HostInfo
  58. // verify if we've seen this index before, otherwise respond to the handshake initiation
  59. if h.Type == header.Message && h.Subtype == header.MessageRelay {
  60. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  61. } else {
  62. hostinfo = f.hostMap.QueryIndex(h.RemoteIndex)
  63. }
  64. var ci *ConnectionState
  65. if hostinfo != nil {
  66. ci = hostinfo.ConnectionState
  67. }
  68. switch h.Type {
  69. case header.Message:
  70. // TODO handleEncrypted sends directly to addr on error. Handle this in the tunneling case.
  71. if !f.handleEncrypted(ci, addr, h) {
  72. return
  73. }
  74. switch h.Subtype {
  75. case header.MessageNone:
  76. if !f.decryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache) {
  77. return
  78. }
  79. case header.MessageRelay:
  80. // The entire body is sent as AD, not encrypted.
  81. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  82. // 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
  83. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  84. // which will gracefully fail in the DecryptDanger call.
  85. signedPayload := packet[:len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  86. signatureValue := packet[len(packet)-hostinfo.ConnectionState.dKey.Overhead():]
  87. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, signedPayload, signatureValue, h.MessageCounter, nb)
  88. if err != nil {
  89. return
  90. }
  91. // Successfully validated the thing. Get rid of the Relay header.
  92. signedPayload = signedPayload[header.Len:]
  93. // Pull the Roaming parts up here, and return in all call paths.
  94. f.handleHostRoaming(hostinfo, addr)
  95. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  96. f.connectionManager.In(hostinfo.localIndexId)
  97. f.connectionManager.RelayUsed(h.RemoteIndex)
  98. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  99. if !ok {
  100. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  101. // its internal mapping. This should never happen.
  102. hostinfo.logger(f.l).WithFields(logrus.Fields{"vpnIp": hostinfo.vpnIp, "remoteIndex": h.RemoteIndex}).Error("HostInfo missing remote relay index")
  103. return
  104. }
  105. switch relay.Type {
  106. case TerminalType:
  107. // If I am the target of this relay, process the unwrapped packet
  108. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  109. f.readOutsidePackets(nil, &ViaSender{relayHI: hostinfo, remoteIdx: relay.RemoteIndex, relay: relay}, out[:0], signedPayload, h, fwPacket, lhf, nb, q, localCache)
  110. return
  111. case ForwardingType:
  112. // Find the target HostInfo relay object
  113. targetHI, targetRelay, err := f.hostMap.QueryVpnIpRelayFor(hostinfo.vpnIp, relay.PeerIp)
  114. if err != nil {
  115. hostinfo.logger(f.l).WithField("relayTo", relay.PeerIp).WithError(err).Info("Failed to find target host info by ip")
  116. return
  117. }
  118. // If that relay is Established, forward the payload through it
  119. if targetRelay.State == Established {
  120. switch targetRelay.Type {
  121. case ForwardingType:
  122. // Forward this packet through the relay tunnel
  123. // Find the target HostInfo
  124. f.SendVia(targetHI, targetRelay, signedPayload, nb, out, false)
  125. return
  126. case TerminalType:
  127. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  128. }
  129. } else {
  130. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerIp, "relayFrom": hostinfo.vpnIp, "targetRelayState": targetRelay.State}).Info("Unexpected target relay state")
  131. return
  132. }
  133. }
  134. }
  135. case header.LightHouse:
  136. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  137. if !f.handleEncrypted(ci, addr, h) {
  138. return
  139. }
  140. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  141. if err != nil {
  142. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  143. WithField("packet", packet).
  144. Error("Failed to decrypt lighthouse packet")
  145. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  146. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  147. return
  148. }
  149. lhf(addr, hostinfo.vpnIp, d)
  150. // Fallthrough to the bottom to record incoming traffic
  151. case header.Test:
  152. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  153. if !f.handleEncrypted(ci, addr, h) {
  154. return
  155. }
  156. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  157. if err != nil {
  158. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  159. WithField("packet", packet).
  160. Error("Failed to decrypt test packet")
  161. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  162. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  163. return
  164. }
  165. if h.Subtype == header.TestRequest {
  166. // This testRequest might be from TryPromoteBest, so we should roam
  167. // to the new IP address before responding
  168. f.handleHostRoaming(hostinfo, addr)
  169. f.send(header.Test, header.TestReply, ci, hostinfo, d, nb, out)
  170. }
  171. // Fallthrough to the bottom to record incoming traffic
  172. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  173. // are unauthenticated
  174. case header.Handshake:
  175. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  176. f.handshakeManager.HandleIncoming(addr, via, packet, h)
  177. return
  178. case header.RecvError:
  179. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  180. f.handleRecvError(addr, h)
  181. return
  182. case header.CloseTunnel:
  183. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  184. if !f.handleEncrypted(ci, addr, h) {
  185. return
  186. }
  187. hostinfo.logger(f.l).WithField("udpAddr", addr).
  188. Info("Close tunnel received, tearing down.")
  189. f.closeTunnel(hostinfo)
  190. return
  191. case header.Control:
  192. if !f.handleEncrypted(ci, addr, h) {
  193. return
  194. }
  195. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  196. if err != nil {
  197. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  198. WithField("packet", packet).
  199. Error("Failed to decrypt Control packet")
  200. return
  201. }
  202. m := &NebulaControl{}
  203. err = m.Unmarshal(d)
  204. if err != nil {
  205. hostinfo.logger(f.l).WithError(err).Error("Failed to unmarshal control message")
  206. break
  207. }
  208. f.relayManager.HandleControlMsg(hostinfo, m, f)
  209. default:
  210. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  211. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", addr)
  212. return
  213. }
  214. f.handleHostRoaming(hostinfo, addr)
  215. f.connectionManager.In(hostinfo.localIndexId)
  216. }
  217. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  218. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  219. final := f.hostMap.DeleteHostInfo(hostInfo)
  220. if final {
  221. // We no longer have any tunnels with this vpn ip, clear learned lighthouse state to lower memory usage
  222. f.lightHouse.DeleteVpnIp(hostInfo.vpnIp)
  223. }
  224. }
  225. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  226. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  227. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  228. }
  229. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, addr *udp.Addr) {
  230. if addr != nil && !hostinfo.remote.Equals(addr) {
  231. if !f.lightHouse.GetRemoteAllowList().Allow(hostinfo.vpnIp, addr.IP) {
  232. hostinfo.logger(f.l).WithField("newAddr", addr).Debug("lighthouse.remote_allow_list denied roaming")
  233. return
  234. }
  235. if !hostinfo.lastRoam.IsZero() && addr.Equals(hostinfo.lastRoamRemote) && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  236. if f.l.Level >= logrus.DebugLevel {
  237. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  238. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  239. }
  240. return
  241. }
  242. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  243. Info("Host roamed to new udp ip/port.")
  244. hostinfo.lastRoam = time.Now()
  245. hostinfo.lastRoamRemote = hostinfo.remote
  246. hostinfo.SetRemote(addr)
  247. }
  248. }
  249. func (f *Interface) handleEncrypted(ci *ConnectionState, addr *udp.Addr, h *header.H) bool {
  250. // If connectionstate exists and the replay protector allows, process packet
  251. // Else, send recv errors for 300 seconds after a restart to allow fast reconnection.
  252. if ci == nil || !ci.window.Check(f.l, h.MessageCounter) {
  253. if addr != nil {
  254. f.maybeSendRecvError(addr, h.RemoteIndex)
  255. return false
  256. } else {
  257. return false
  258. }
  259. }
  260. return true
  261. }
  262. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  263. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  264. // Do we at least have an ipv4 header worth of data?
  265. if len(data) < ipv4.HeaderLen {
  266. return fmt.Errorf("packet is less than %v bytes", ipv4.HeaderLen)
  267. }
  268. // Is it an ipv4 packet?
  269. if int((data[0]>>4)&0x0f) != 4 {
  270. return fmt.Errorf("packet is not ipv4, type: %v", int((data[0]>>4)&0x0f))
  271. }
  272. // Adjust our start position based on the advertised ip header length
  273. ihl := int(data[0]&0x0f) << 2
  274. // Well formed ip header length?
  275. if ihl < ipv4.HeaderLen {
  276. return fmt.Errorf("packet had an invalid header length: %v", ihl)
  277. }
  278. // Check if this is the second or further fragment of a fragmented packet.
  279. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  280. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  281. // Firewall handles protocol checks
  282. fp.Protocol = data[9]
  283. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  284. minLen := ihl
  285. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  286. minLen += minFwPacketLen
  287. }
  288. if len(data) < minLen {
  289. return fmt.Errorf("packet is less than %v bytes, ip header len: %v", minLen, ihl)
  290. }
  291. // Firewall packets are locally oriented
  292. if incoming {
  293. fp.RemoteIP = iputil.Ip2VpnIp(data[12:16])
  294. fp.LocalIP = iputil.Ip2VpnIp(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. fp.LocalIP = iputil.Ip2VpnIp(data[12:16])
  304. fp.RemoteIP = iputil.Ip2VpnIp(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 *udp.Addr, index uint32) {
  368. if f.sendRecvErrorConfig.ShouldSendRecvError(endpoint.IP) {
  369. f.sendRecvError(endpoint, index)
  370. }
  371. }
  372. func (f *Interface) sendRecvError(endpoint *udp.Addr, 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 *udp.Addr, 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 != nil && !hostinfo.remote.Equals(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. }