outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. f.decryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache)
  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, addr)
  93. f.connectionManager.In(hostinfo.localIndexId)
  94. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  95. if !ok {
  96. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  97. // its internal mapping. This should never happen.
  98. hostinfo.logger(f.l).WithFields(logrus.Fields{"vpnIp": hostinfo.vpnIp, "remoteIndex": h.RemoteIndex}).Error("HostInfo missing remote relay index")
  99. return
  100. }
  101. switch relay.Type {
  102. case TerminalType:
  103. // If I am the target of this relay, process the unwrapped packet
  104. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  105. f.readOutsidePackets(nil, &ViaSender{relayHI: hostinfo, remoteIdx: relay.RemoteIndex, relay: relay}, out[:0], signedPayload, h, fwPacket, lhf, nb, q, localCache)
  106. return
  107. case ForwardingType:
  108. // Find the target HostInfo relay object
  109. targetHI, err := f.hostMap.QueryVpnIp(relay.PeerIp)
  110. if err != nil {
  111. hostinfo.logger(f.l).WithField("relayTo", relay.PeerIp).WithError(err).Info("Failed to find target host info by ip")
  112. return
  113. }
  114. // find the target Relay info object
  115. targetRelay, ok := targetHI.relayState.QueryRelayForByIp(hostinfo.vpnIp)
  116. if !ok {
  117. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerIp, "relayFrom": hostinfo.vpnIp}).Info("Failed to find relay in hostinfo")
  118. return
  119. }
  120. // If that relay is Established, forward the payload through it
  121. if targetRelay.State == Established {
  122. switch targetRelay.Type {
  123. case ForwardingType:
  124. // Forward this packet through the relay tunnel
  125. // Find the target HostInfo
  126. f.SendVia(targetHI, targetRelay, signedPayload, nb, out, false)
  127. return
  128. case TerminalType:
  129. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  130. }
  131. } else {
  132. hostinfo.logger(f.l).WithFields(logrus.Fields{"relayTo": relay.PeerIp, "relayFrom": hostinfo.vpnIp, "targetRelayState": targetRelay.State}).Info("Unexpected target relay state")
  133. return
  134. }
  135. }
  136. }
  137. case header.LightHouse:
  138. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  139. if !f.handleEncrypted(ci, addr, h) {
  140. return
  141. }
  142. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  143. if err != nil {
  144. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  145. WithField("packet", packet).
  146. Error("Failed to decrypt lighthouse packet")
  147. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  148. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  149. return
  150. }
  151. lhf(addr, hostinfo.vpnIp, d)
  152. // Fallthrough to the bottom to record incoming traffic
  153. case header.Test:
  154. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  155. if !f.handleEncrypted(ci, addr, h) {
  156. return
  157. }
  158. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  159. if err != nil {
  160. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  161. WithField("packet", packet).
  162. Error("Failed to decrypt test packet")
  163. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  164. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  165. return
  166. }
  167. if h.Subtype == header.TestRequest {
  168. // This testRequest might be from TryPromoteBest, so we should roam
  169. // to the new IP address before responding
  170. f.handleHostRoaming(hostinfo, addr)
  171. f.send(header.Test, header.TestReply, ci, hostinfo, d, nb, out)
  172. }
  173. // Fallthrough to the bottom to record incoming traffic
  174. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  175. // are unauthenticated
  176. case header.Handshake:
  177. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  178. HandleIncomingHandshake(f, addr, via, packet, h, hostinfo)
  179. return
  180. case header.RecvError:
  181. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  182. f.handleRecvError(addr, h)
  183. return
  184. case header.CloseTunnel:
  185. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  186. if !f.handleEncrypted(ci, addr, h) {
  187. return
  188. }
  189. hostinfo.logger(f.l).WithField("udpAddr", addr).
  190. Info("Close tunnel received, tearing down.")
  191. f.closeTunnel(hostinfo)
  192. return
  193. case header.Control:
  194. if !f.handleEncrypted(ci, addr, h) {
  195. return
  196. }
  197. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  198. if err != nil {
  199. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  200. WithField("packet", packet).
  201. Error("Failed to decrypt Control packet")
  202. return
  203. }
  204. m := &NebulaControl{}
  205. err = m.Unmarshal(d)
  206. if err != nil {
  207. hostinfo.logger(f.l).WithError(err).Error("Failed to unmarshal control message")
  208. break
  209. }
  210. f.relayManager.HandleControlMsg(hostinfo, m, f)
  211. default:
  212. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  213. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", addr)
  214. return
  215. }
  216. f.handleHostRoaming(hostinfo, addr)
  217. f.connectionManager.In(hostinfo.localIndexId)
  218. }
  219. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  220. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  221. final := f.hostMap.DeleteHostInfo(hostInfo)
  222. if final {
  223. // We no longer have any tunnels with this vpn ip, clear learned lighthouse state to lower memory usage
  224. f.lightHouse.DeleteVpnIp(hostInfo.vpnIp)
  225. }
  226. }
  227. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  228. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  229. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  230. }
  231. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, addr *udp.Addr) {
  232. if addr != nil && !hostinfo.remote.Equals(addr) {
  233. if !f.lightHouse.GetRemoteAllowList().Allow(hostinfo.vpnIp, addr.IP) {
  234. hostinfo.logger(f.l).WithField("newAddr", addr).Debug("lighthouse.remote_allow_list denied roaming")
  235. return
  236. }
  237. if !hostinfo.lastRoam.IsZero() && addr.Equals(hostinfo.lastRoamRemote) && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  238. if f.l.Level >= logrus.DebugLevel {
  239. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  240. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  241. }
  242. return
  243. }
  244. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  245. Info("Host roamed to new udp ip/port.")
  246. hostinfo.lastRoam = time.Now()
  247. hostinfo.lastRoamRemote = hostinfo.remote
  248. hostinfo.SetRemote(addr)
  249. }
  250. }
  251. func (f *Interface) handleEncrypted(ci *ConnectionState, addr *udp.Addr, h *header.H) bool {
  252. // If connectionstate exists and the replay protector allows, process packet
  253. // Else, send recv errors for 300 seconds after a restart to allow fast reconnection.
  254. if ci == nil || !ci.window.Check(f.l, h.MessageCounter) {
  255. if addr != nil {
  256. f.maybeSendRecvError(addr, h.RemoteIndex)
  257. return false
  258. } else {
  259. return false
  260. }
  261. }
  262. return true
  263. }
  264. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  265. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  266. // Do we at least have an ipv4 header worth of data?
  267. if len(data) < ipv4.HeaderLen {
  268. return fmt.Errorf("packet is less than %v bytes", ipv4.HeaderLen)
  269. }
  270. // Is it an ipv4 packet?
  271. if int((data[0]>>4)&0x0f) != 4 {
  272. return fmt.Errorf("packet is not ipv4, type: %v", int((data[0]>>4)&0x0f))
  273. }
  274. // Adjust our start position based on the advertised ip header length
  275. ihl := int(data[0]&0x0f) << 2
  276. // Well formed ip header length?
  277. if ihl < ipv4.HeaderLen {
  278. return fmt.Errorf("packet had an invalid header length: %v", ihl)
  279. }
  280. // Check if this is the second or further fragment of a fragmented packet.
  281. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  282. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  283. // Firewall handles protocol checks
  284. fp.Protocol = data[9]
  285. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  286. minLen := ihl
  287. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  288. minLen += minFwPacketLen
  289. }
  290. if len(data) < minLen {
  291. return fmt.Errorf("packet is less than %v bytes, ip header len: %v", minLen, ihl)
  292. }
  293. // Firewall packets are locally oriented
  294. if incoming {
  295. fp.RemoteIP = iputil.Ip2VpnIp(data[12:16])
  296. fp.LocalIP = iputil.Ip2VpnIp(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. fp.LocalIP = iputil.Ip2VpnIp(data[12:16])
  306. fp.RemoteIP = iputil.Ip2VpnIp(data[16:20])
  307. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  308. fp.RemotePort = 0
  309. fp.LocalPort = 0
  310. } else {
  311. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  312. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  313. }
  314. }
  315. return nil
  316. }
  317. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  318. var err error
  319. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  320. if err != nil {
  321. return nil, err
  322. }
  323. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  324. hostinfo.logger(f.l).WithField("header", h).
  325. Debugln("dropping out of window packet")
  326. return nil, errors.New("out of window packet")
  327. }
  328. return out, nil
  329. }
  330. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) {
  331. var err error
  332. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  333. if err != nil {
  334. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  335. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  336. //f.sendRecvError(hostinfo.remote, header.RemoteIndex)
  337. return
  338. }
  339. err = newPacket(out, true, fwPacket)
  340. if err != nil {
  341. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  342. Warnf("Error while validating inbound packet")
  343. return
  344. }
  345. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  346. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  347. Debugln("dropping out of window packet")
  348. return
  349. }
  350. dropReason := f.firewall.Drop(out, *fwPacket, true, hostinfo, f.caPool, localCache)
  351. if dropReason != nil {
  352. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, out, 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
  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. }
  366. func (f *Interface) maybeSendRecvError(endpoint *udp.Addr, index uint32) {
  367. if f.sendRecvErrorConfig.ShouldSendRecvError(endpoint.IP) {
  368. f.sendRecvError(endpoint, index)
  369. }
  370. }
  371. func (f *Interface) sendRecvError(endpoint *udp.Addr, index uint32) {
  372. f.messageMetrics.Tx(header.RecvError, 0, 1)
  373. //TODO: this should be a signed message so we can trust that we should drop the index
  374. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  375. f.outside.WriteTo(b, endpoint)
  376. if f.l.Level >= logrus.DebugLevel {
  377. f.l.WithField("index", index).
  378. WithField("udpAddr", endpoint).
  379. Debug("Recv error sent")
  380. }
  381. }
  382. func (f *Interface) handleRecvError(addr *udp.Addr, h *header.H) {
  383. if f.l.Level >= logrus.DebugLevel {
  384. f.l.WithField("index", h.RemoteIndex).
  385. WithField("udpAddr", addr).
  386. Debug("Recv error received")
  387. }
  388. // First, clean up in the pending hostmap
  389. f.handshakeManager.pendingHostMap.DeleteReverseIndex(h.RemoteIndex)
  390. hostinfo, err := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  391. if err != nil {
  392. f.l.Debugln(err, ": ", h.RemoteIndex)
  393. return
  394. }
  395. hostinfo.Lock()
  396. defer hostinfo.Unlock()
  397. if !hostinfo.RecvErrorExceeded() {
  398. return
  399. }
  400. if hostinfo.remote != nil && !hostinfo.remote.Equals(addr) {
  401. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  402. return
  403. }
  404. f.closeTunnel(hostinfo)
  405. // We also delete it from pending hostmap to allow for
  406. // fast reconnect.
  407. f.handshakeManager.DeleteHostInfo(hostinfo)
  408. }
  409. /*
  410. func (f *Interface) sendMeta(ci *ConnectionState, endpoint *net.UDPAddr, meta *NebulaMeta) {
  411. if ci.eKey != nil {
  412. //TODO: log error?
  413. return
  414. }
  415. msg, err := proto.Marshal(meta)
  416. if err != nil {
  417. l.Debugln("failed to encode header")
  418. }
  419. c := ci.messageCounter
  420. b := HeaderEncode(nil, Version, uint8(metadata), 0, hostinfo.remoteIndexId, c)
  421. ci.messageCounter++
  422. msg := ci.eKey.EncryptDanger(b, nil, msg, c)
  423. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  424. f.outside.WriteTo(msg, endpoint)
  425. }
  426. */
  427. func RecombineCertAndValidate(h *noise.HandshakeState, rawCertBytes []byte, caPool *cert.NebulaCAPool) (*cert.NebulaCertificate, error) {
  428. pk := h.PeerStatic()
  429. if pk == nil {
  430. return nil, errors.New("no peer static key was present")
  431. }
  432. if rawCertBytes == nil {
  433. return nil, errors.New("provided payload was empty")
  434. }
  435. r := &cert.RawNebulaCertificate{}
  436. err := proto.Unmarshal(rawCertBytes, r)
  437. if err != nil {
  438. return nil, fmt.Errorf("error unmarshaling cert: %s", err)
  439. }
  440. // If the Details are nil, just exit to avoid crashing
  441. if r.Details == nil {
  442. return nil, fmt.Errorf("certificate did not contain any details")
  443. }
  444. r.Details.PublicKey = pk
  445. recombined, err := proto.Marshal(r)
  446. if err != nil {
  447. return nil, fmt.Errorf("error while recombining certificate: %s", err)
  448. }
  449. c, _ := cert.UnmarshalNebulaCertificate(recombined)
  450. isValid, err := c.Verify(time.Now(), caPool)
  451. if err != nil {
  452. return c, fmt.Errorf("certificate validation failed: %s", err)
  453. } else if !isValid {
  454. // This case should never happen but here's to defensive programming!
  455. return c, errors.New("certificate validation failed but did not return an error")
  456. }
  457. return c, nil
  458. }