outside.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "time"
  7. "github.com/flynn/noise"
  8. "github.com/golang/protobuf/proto"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/firewall"
  12. "github.com/slackhq/nebula/header"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/udp"
  15. "golang.org/x/net/ipv4"
  16. )
  17. const (
  18. minFwPacketLen = 4
  19. )
  20. func (f *Interface) readOutsidePackets(addr *udp.Addr, 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. // verify if we've seen this index before, otherwise respond to the handshake initiation
  33. hostinfo, err := f.hostMap.QueryIndex(h.RemoteIndex)
  34. var ci *ConnectionState
  35. if err == nil {
  36. ci = hostinfo.ConnectionState
  37. }
  38. switch h.Type {
  39. case header.Message:
  40. if !f.handleEncrypted(ci, addr, h) {
  41. return
  42. }
  43. f.decryptToTun(hostinfo, h.MessageCounter, out, packet, fwPacket, nb, q, localCache)
  44. // Fallthrough to the bottom to record incoming traffic
  45. case header.LightHouse:
  46. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  47. if !f.handleEncrypted(ci, addr, h) {
  48. return
  49. }
  50. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  51. if err != nil {
  52. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  53. WithField("packet", packet).
  54. Error("Failed to decrypt lighthouse packet")
  55. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  56. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  57. return
  58. }
  59. lhf(addr, hostinfo.vpnIp, d, f)
  60. // Fallthrough to the bottom to record incoming traffic
  61. case header.Test:
  62. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  63. if !f.handleEncrypted(ci, addr, h) {
  64. return
  65. }
  66. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  67. if err != nil {
  68. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", addr).
  69. WithField("packet", packet).
  70. Error("Failed to decrypt test packet")
  71. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  72. //f.sendRecvError(net.Addr(addr), header.RemoteIndex)
  73. return
  74. }
  75. if h.Subtype == header.TestRequest {
  76. // This testRequest might be from TryPromoteBest, so we should roam
  77. // to the new IP address before responding
  78. f.handleHostRoaming(hostinfo, addr)
  79. f.send(header.Test, header.TestReply, ci, hostinfo, hostinfo.remote, d, nb, out)
  80. }
  81. // Fallthrough to the bottom to record incoming traffic
  82. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  83. // are unauthenticated
  84. case header.Handshake:
  85. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  86. HandleIncomingHandshake(f, addr, packet, h, hostinfo)
  87. return
  88. case header.RecvError:
  89. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  90. f.handleRecvError(addr, h)
  91. return
  92. case header.CloseTunnel:
  93. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  94. if !f.handleEncrypted(ci, addr, h) {
  95. return
  96. }
  97. hostinfo.logger(f.l).WithField("udpAddr", addr).
  98. Info("Close tunnel received, tearing down.")
  99. f.closeTunnel(hostinfo, false)
  100. return
  101. default:
  102. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  103. hostinfo.logger(f.l).Debugf("Unexpected packet received from %s", addr)
  104. return
  105. }
  106. f.handleHostRoaming(hostinfo, addr)
  107. f.connectionManager.In(hostinfo.vpnIp)
  108. }
  109. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  110. func (f *Interface) closeTunnel(hostInfo *HostInfo, hasHostMapLock bool) {
  111. //TODO: this would be better as a single function in ConnectionManager that handled locks appropriately
  112. f.connectionManager.ClearIP(hostInfo.vpnIp)
  113. f.connectionManager.ClearPendingDeletion(hostInfo.vpnIp)
  114. f.lightHouse.DeleteVpnIp(hostInfo.vpnIp)
  115. if hasHostMapLock {
  116. f.hostMap.unlockedDeleteHostInfo(hostInfo)
  117. } else {
  118. f.hostMap.DeleteHostInfo(hostInfo)
  119. }
  120. }
  121. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  122. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  123. f.send(header.CloseTunnel, 0, h.ConnectionState, h, h.remote, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  124. }
  125. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, addr *udp.Addr) {
  126. if !hostinfo.remote.Equals(addr) {
  127. if !f.lightHouse.remoteAllowList.Allow(hostinfo.vpnIp, addr.IP) {
  128. hostinfo.logger(f.l).WithField("newAddr", addr).Debug("lighthouse.remote_allow_list denied roaming")
  129. return
  130. }
  131. if !hostinfo.lastRoam.IsZero() && addr.Equals(hostinfo.lastRoamRemote) && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  132. if f.l.Level >= logrus.DebugLevel {
  133. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  134. Debugf("Suppressing roam back to previous remote for %d seconds", RoamingSuppressSeconds)
  135. }
  136. return
  137. }
  138. hostinfo.logger(f.l).WithField("udpAddr", hostinfo.remote).WithField("newAddr", addr).
  139. Info("Host roamed to new udp ip/port.")
  140. hostinfo.lastRoam = time.Now()
  141. remoteCopy := *hostinfo.remote
  142. hostinfo.lastRoamRemote = &remoteCopy
  143. hostinfo.SetRemote(addr)
  144. }
  145. }
  146. func (f *Interface) handleEncrypted(ci *ConnectionState, addr *udp.Addr, h *header.H) bool {
  147. // If connectionstate exists and the replay protector allows, process packet
  148. // Else, send recv errors for 300 seconds after a restart to allow fast reconnection.
  149. if ci == nil || !ci.window.Check(f.l, h.MessageCounter) {
  150. f.sendRecvError(addr, h.RemoteIndex)
  151. return false
  152. }
  153. return true
  154. }
  155. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  156. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  157. // Do we at least have an ipv4 header worth of data?
  158. if len(data) < ipv4.HeaderLen {
  159. return fmt.Errorf("packet is less than %v bytes", ipv4.HeaderLen)
  160. }
  161. // Is it an ipv4 packet?
  162. if int((data[0]>>4)&0x0f) != 4 {
  163. return fmt.Errorf("packet is not ipv4, type: %v", int((data[0]>>4)&0x0f))
  164. }
  165. // Adjust our start position based on the advertised ip header length
  166. ihl := int(data[0]&0x0f) << 2
  167. // Well formed ip header length?
  168. if ihl < ipv4.HeaderLen {
  169. return fmt.Errorf("packet had an invalid header length: %v", ihl)
  170. }
  171. // Check if this is the second or further fragment of a fragmented packet.
  172. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  173. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  174. // Firewall handles protocol checks
  175. fp.Protocol = data[9]
  176. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  177. minLen := ihl
  178. if !fp.Fragment && fp.Protocol != firewall.ProtoICMP {
  179. minLen += minFwPacketLen
  180. }
  181. if len(data) < minLen {
  182. return fmt.Errorf("packet is less than %v bytes, ip header len: %v", minLen, ihl)
  183. }
  184. // Firewall packets are locally oriented
  185. if incoming {
  186. fp.RemoteIP = iputil.Ip2VpnIp(data[12:16])
  187. fp.LocalIP = iputil.Ip2VpnIp(data[16:20])
  188. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  189. fp.RemotePort = 0
  190. fp.LocalPort = 0
  191. } else {
  192. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  193. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  194. }
  195. } else {
  196. fp.LocalIP = iputil.Ip2VpnIp(data[12:16])
  197. fp.RemoteIP = iputil.Ip2VpnIp(data[16:20])
  198. if fp.Fragment || fp.Protocol == firewall.ProtoICMP {
  199. fp.RemotePort = 0
  200. fp.LocalPort = 0
  201. } else {
  202. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2])
  203. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4])
  204. }
  205. }
  206. return nil
  207. }
  208. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  209. var err error
  210. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  211. if err != nil {
  212. return nil, err
  213. }
  214. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  215. hostinfo.logger(f.l).WithField("header", h).
  216. Debugln("dropping out of window packet")
  217. return nil, errors.New("out of window packet")
  218. }
  219. return out, nil
  220. }
  221. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) {
  222. var err error
  223. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  224. if err != nil {
  225. hostinfo.logger(f.l).WithError(err).Error("Failed to decrypt packet")
  226. //TODO: maybe after build 64 is out? 06/14/2018 - NB
  227. //f.sendRecvError(hostinfo.remote, header.RemoteIndex)
  228. return
  229. }
  230. err = newPacket(out, true, fwPacket)
  231. if err != nil {
  232. hostinfo.logger(f.l).WithError(err).WithField("packet", out).
  233. Warnf("Error while validating inbound packet")
  234. return
  235. }
  236. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  237. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  238. Debugln("dropping out of window packet")
  239. return
  240. }
  241. dropReason := f.firewall.Drop(out, *fwPacket, true, hostinfo, f.caPool, localCache)
  242. if dropReason != nil {
  243. if f.l.Level >= logrus.DebugLevel {
  244. hostinfo.logger(f.l).WithField("fwPacket", fwPacket).
  245. WithField("reason", dropReason).
  246. Debugln("dropping inbound packet")
  247. }
  248. return
  249. }
  250. f.connectionManager.In(hostinfo.vpnIp)
  251. _, err = f.readers[q].Write(out)
  252. if err != nil {
  253. f.l.WithError(err).Error("Failed to write to tun")
  254. }
  255. }
  256. func (f *Interface) sendRecvError(endpoint *udp.Addr, index uint32) {
  257. f.messageMetrics.Tx(header.RecvError, 0, 1)
  258. //TODO: this should be a signed message so we can trust that we should drop the index
  259. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  260. f.outside.WriteTo(b, endpoint)
  261. if f.l.Level >= logrus.DebugLevel {
  262. f.l.WithField("index", index).
  263. WithField("udpAddr", endpoint).
  264. Debug("Recv error sent")
  265. }
  266. }
  267. func (f *Interface) handleRecvError(addr *udp.Addr, h *header.H) {
  268. if f.l.Level >= logrus.DebugLevel {
  269. f.l.WithField("index", h.RemoteIndex).
  270. WithField("udpAddr", addr).
  271. Debug("Recv error received")
  272. }
  273. // First, clean up in the pending hostmap
  274. f.handshakeManager.pendingHostMap.DeleteReverseIndex(h.RemoteIndex)
  275. hostinfo, err := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  276. if err != nil {
  277. f.l.Debugln(err, ": ", h.RemoteIndex)
  278. return
  279. }
  280. hostinfo.Lock()
  281. defer hostinfo.Unlock()
  282. if !hostinfo.RecvErrorExceeded() {
  283. return
  284. }
  285. if hostinfo.remote != nil && !hostinfo.remote.Equals(addr) {
  286. f.l.Infoln("Someone spoofing recv_errors? ", addr, hostinfo.remote)
  287. return
  288. }
  289. // We delete this host from the main hostmap
  290. f.hostMap.DeleteHostInfo(hostinfo)
  291. // We also delete it from pending to allow for
  292. // fast reconnect. We must null the connectionstate
  293. // or a counter reuse may happen
  294. hostinfo.ConnectionState = nil
  295. f.handshakeManager.DeleteHostInfo(hostinfo)
  296. }
  297. /*
  298. func (f *Interface) sendMeta(ci *ConnectionState, endpoint *net.UDPAddr, meta *NebulaMeta) {
  299. if ci.eKey != nil {
  300. //TODO: log error?
  301. return
  302. }
  303. msg, err := proto.Marshal(meta)
  304. if err != nil {
  305. l.Debugln("failed to encode header")
  306. }
  307. c := ci.messageCounter
  308. b := HeaderEncode(nil, Version, uint8(metadata), 0, hostinfo.remoteIndexId, c)
  309. ci.messageCounter++
  310. msg := ci.eKey.EncryptDanger(b, nil, msg, c)
  311. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  312. f.outside.WriteTo(msg, endpoint)
  313. }
  314. */
  315. func RecombineCertAndValidate(h *noise.HandshakeState, rawCertBytes []byte, caPool *cert.NebulaCAPool) (*cert.NebulaCertificate, error) {
  316. pk := h.PeerStatic()
  317. if pk == nil {
  318. return nil, errors.New("no peer static key was present")
  319. }
  320. if rawCertBytes == nil {
  321. return nil, errors.New("provided payload was empty")
  322. }
  323. r := &cert.RawNebulaCertificate{}
  324. err := proto.Unmarshal(rawCertBytes, r)
  325. if err != nil {
  326. return nil, fmt.Errorf("error unmarshaling cert: %s", err)
  327. }
  328. // If the Details are nil, just exit to avoid crashing
  329. if r.Details == nil {
  330. return nil, fmt.Errorf("certificate did not contain any details")
  331. }
  332. r.Details.PublicKey = pk
  333. recombined, err := proto.Marshal(r)
  334. if err != nil {
  335. return nil, fmt.Errorf("error while recombining certificate: %s", err)
  336. }
  337. c, _ := cert.UnmarshalNebulaCertificate(recombined)
  338. isValid, err := c.Verify(time.Now(), caPool)
  339. if err != nil {
  340. return c, fmt.Errorf("certificate validation failed: %s", err)
  341. } else if !isValid {
  342. // This case should never happen but here's to defensive programming!
  343. return c, errors.New("certificate validation failed but did not return an error")
  344. }
  345. return c, nil
  346. }