outside.go 16 KB

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