outside.go 17 KB

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