outside.go 17 KB

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