outside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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.vpnIp)
  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.vpnIp)
  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.ClearIP(hostInfo.vpnIp)
  212. f.connectionManager.ClearPendingDeletion(hostInfo.vpnIp)
  213. f.lightHouse.DeleteVpnIp(hostInfo.vpnIp)
  214. f.hostMap.DeleteHostInfo(hostInfo)
  215. }
  216. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  217. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  218. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  219. }
  220. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, addr *udp.Addr) {
  221. if addr != nil && !hostinfo.remote.Equals(addr) {
  222. if !f.lightHouse.GetRemoteAllowList().Allow(hostinfo.vpnIp, addr.IP) {
  223. hostinfo.logger(f.l).WithField("newAddr", addr).Debug("lighthouse.remote_allow_list denied roaming")
  224. return
  225. }
  226. if !hostinfo.lastRoam.IsZero() && addr.Equals(hostinfo.lastRoamRemote) && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  227. if f.l.Level >= logrus.DebugLevel {
  228. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  229. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  230. }
  231. return
  232. }
  233. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  234. Info("Host roamed to new udp ip/port.")
  235. hostinfo.lastRoam = time.Now()
  236. hostinfo.lastRoamRemote = hostinfo.remote
  237. hostinfo.SetRemote(addr)
  238. }
  239. }
  240. func (f *Interface) handleEncrypted(ci *ConnectionState, addr *udp.Addr, h *header.H) bool {
  241. // If connectionstate exists and the replay protector allows, process packet
  242. // Else, send recv errors for 300 seconds after a restart to allow fast reconnection.
  243. if ci == nil || !ci.window.Check(f.l, h.MessageCounter) {
  244. if addr != nil {
  245. f.maybeSendRecvError(addr, h.RemoteIndex)
  246. return false
  247. } else {
  248. return false
  249. }
  250. }
  251. return true
  252. }
  253. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  254. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  255. // Do we at least have an ipv4 header worth of data?
  256. if len(data) < ipv4.HeaderLen {
  257. return fmt.Errorf("packet is less than %v bytes", ipv4.HeaderLen)
  258. }
  259. // Is it an ipv4 packet?
  260. if int((data[0]>>4)&0x0f) != 4 {
  261. return fmt.Errorf("packet is not ipv4, type: %v", int((data[0]>>4)&0x0f))
  262. }
  263. // Adjust our start position based on the advertised ip header length
  264. ihl := int(data[0]&0x0f) << 2
  265. // Well formed ip header length?
  266. if ihl < ipv4.HeaderLen {
  267. return fmt.Errorf("packet had an invalid header length: %v", ihl)
  268. }
  269. // Check if this is the second or further fragment of a fragmented packet.
  270. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  271. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  272. // Firewall handles protocol checks
  273. fp.Protocol = data[9]
  274. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  275. minLen := ihl
  276. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  277. minLen += minFwPacketLen
  278. }
  279. if len(data) < minLen {
  280. return fmt.Errorf("packet is less than %v bytes, ip header len: %v", minLen, ihl)
  281. }
  282. // Firewall packets are locally oriented
  283. if incoming {
  284. fp.RemoteIP = iputil.Ip2VpnIp(data[12:16])
  285. fp.LocalIP = iputil.Ip2VpnIp(data[16:20])
  286. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  287. fp.RemotePort = 0
  288. fp.LocalPort = 0
  289. } else {
  290. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  291. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  292. }
  293. } else {
  294. fp.LocalIP = iputil.Ip2VpnIp(data[12:16])
  295. fp.RemoteIP = iputil.Ip2VpnIp(data[16:20])
  296. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  297. fp.RemotePort = 0
  298. fp.LocalPort = 0
  299. } else {
  300. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  301. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  302. }
  303. }
  304. return nil
  305. }
  306. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  307. var err error
  308. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  309. if err != nil {
  310. return nil, err
  311. }
  312. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  313. hostinfo.logger(f.l).WithField("header", h).
  314. Debugln("dropping out of window packet")
  315. return nil, errors.New("out of window packet")
  316. }
  317. return out, nil
  318. }
  319. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) {
  320. var err error
  321. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  322. if err != nil {
  323. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  324. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  325. //f.sendRecvError(hostinfo.remote, header.RemoteIndex)
  326. return
  327. }
  328. err = newPacket(out, true, fwPacket)
  329. if err != nil {
  330. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  331. Warnf("Error while validating inbound packet")
  332. return
  333. }
  334. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  335. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  336. Debugln("dropping out of window packet")
  337. return
  338. }
  339. dropReason := f.firewall.Drop(out, *fwPacket, true, hostinfo, f.caPool, localCache)
  340. if dropReason != nil {
  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.vpnIp)
  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. }