inside.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package nebula
  2. import (
  3. "github.com/sirupsen/logrus"
  4. "github.com/slackhq/nebula/firewall"
  5. "github.com/slackhq/nebula/header"
  6. "github.com/slackhq/nebula/iputil"
  7. "github.com/slackhq/nebula/noiseutil"
  8. "github.com/slackhq/nebula/udp"
  9. )
  10. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
  11. err := newPacket(packet, false, fwPacket)
  12. if err != nil {
  13. if f.l.Level >= logrus.DebugLevel {
  14. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  15. }
  16. return
  17. }
  18. // Ignore local broadcast packets
  19. if f.dropLocalBroadcast && fwPacket.RemoteIP == f.localBroadcast {
  20. return
  21. }
  22. if fwPacket.RemoteIP == f.myVpnIp {
  23. // Immediately forward packets from self to self.
  24. // This should only happen on Darwin-based and FreeBSD hosts, which
  25. // routes packets from the Nebula IP to the Nebula IP through the Nebula
  26. // TUN device.
  27. if immediatelyForwardToSelf {
  28. _, err := f.readers[q].Write(packet)
  29. if err != nil {
  30. f.l.WithError(err).Error("Failed to forward to tun")
  31. }
  32. }
  33. // Otherwise, drop. On linux, we should never see these packets - Linux
  34. // routes packets from the nebula IP to the nebula IP through the loopback device.
  35. return
  36. }
  37. // Ignore broadcast packets
  38. if f.dropMulticast && isMulticast(fwPacket.RemoteIP) {
  39. return
  40. }
  41. hostinfo, ready := f.getOrHandshake(fwPacket.RemoteIP, func(hh *HandshakeHostInfo) {
  42. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  43. })
  44. if hostinfo == nil {
  45. f.rejectInside(packet, out, q)
  46. if f.l.Level >= logrus.DebugLevel {
  47. f.l.WithField("vpnIp", fwPacket.RemoteIP).
  48. WithField("fwPacket", fwPacket).
  49. Debugln("dropping outbound packet, vpnIp not in our CIDR or in unsafe routes")
  50. }
  51. return
  52. }
  53. if !ready {
  54. return
  55. }
  56. dropReason := f.firewall.Drop(packet, *fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  57. if dropReason == nil {
  58. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, nil, packet, nb, out, q)
  59. } else {
  60. f.rejectInside(packet, out, q)
  61. if f.l.Level >= logrus.DebugLevel {
  62. hostinfo.logger(f.l).
  63. WithField("fwPacket", fwPacket).
  64. WithField("reason", dropReason).
  65. Debugln("dropping outbound packet")
  66. }
  67. }
  68. }
  69. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  70. if !f.firewall.InSendReject {
  71. return
  72. }
  73. out = iputil.CreateRejectPacket(packet, out)
  74. if len(out) == 0 {
  75. return
  76. }
  77. _, err := f.readers[q].Write(out)
  78. if err != nil {
  79. f.l.WithError(err).Error("Failed to write to tun")
  80. }
  81. }
  82. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  83. if !f.firewall.OutSendReject {
  84. return
  85. }
  86. out = iputil.CreateRejectPacket(packet, out)
  87. if len(out) == 0 {
  88. return
  89. }
  90. if len(out) > iputil.MaxRejectPacketSize {
  91. if f.l.GetLevel() >= logrus.InfoLevel {
  92. f.l.
  93. WithField("packet", packet).
  94. WithField("outPacket", out).
  95. Info("rejectOutside: packet too big, not sending")
  96. }
  97. return
  98. }
  99. f.sendNoMetrics(header.Message, 0, ci, hostinfo, nil, out, nb, packet, q)
  100. }
  101. func (f *Interface) Handshake(vpnIp iputil.VpnIp) {
  102. f.getOrHandshake(vpnIp, nil)
  103. }
  104. // getOrHandshake returns nil if the vpnIp is not routable.
  105. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  106. func (f *Interface) getOrHandshake(vpnIp iputil.VpnIp, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  107. if !ipMaskContains(f.lightHouse.myVpnIp, f.lightHouse.myVpnZeros, vpnIp) {
  108. vpnIp = f.inside.RouteFor(vpnIp)
  109. if vpnIp == 0 {
  110. return nil, false
  111. }
  112. }
  113. return f.handshakeManager.GetOrHandshake(vpnIp, cacheCallback)
  114. }
  115. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  116. fp := &firewall.Packet{}
  117. err := newPacket(p, false, fp)
  118. if err != nil {
  119. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  120. return
  121. }
  122. // check if packet is in outbound fw rules
  123. dropReason := f.firewall.Drop(p, *fp, false, hostinfo, f.pki.GetCAPool(), nil)
  124. if dropReason != nil {
  125. if f.l.Level >= logrus.DebugLevel {
  126. f.l.WithField("fwPacket", fp).
  127. WithField("reason", dropReason).
  128. Debugln("dropping cached packet")
  129. }
  130. return
  131. }
  132. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, nil, p, nb, out, 0)
  133. }
  134. // SendMessageToVpnIp handles real ip:port lookup and sends to the current best known address for vpnIp
  135. func (f *Interface) SendMessageToVpnIp(t header.MessageType, st header.MessageSubType, vpnIp iputil.VpnIp, p, nb, out []byte) {
  136. hostInfo, ready := f.getOrHandshake(vpnIp, func(hh *HandshakeHostInfo) {
  137. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  138. })
  139. if hostInfo == nil {
  140. if f.l.Level >= logrus.DebugLevel {
  141. f.l.WithField("vpnIp", vpnIp).
  142. Debugln("dropping SendMessageToVpnIp, vpnIp not in our CIDR or in unsafe routes")
  143. }
  144. return
  145. }
  146. if !ready {
  147. return
  148. }
  149. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  150. }
  151. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  152. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  153. }
  154. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  155. f.messageMetrics.Tx(t, st, 1)
  156. f.sendNoMetrics(t, st, ci, hostinfo, nil, p, nb, out, 0)
  157. }
  158. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte) {
  159. f.messageMetrics.Tx(t, st, 1)
  160. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  161. }
  162. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  163. // to the payload for the ultimate target host, making this a useful method for sending
  164. // handshake messages to peers through relay tunnels.
  165. // via is the HostInfo through which the message is relayed.
  166. // ad is the plaintext data to authenticate, but not encrypt
  167. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  168. // out is a buffer used to store the result of the Encrypt operation
  169. // q indicates which writer to use to send the packet.
  170. func (f *Interface) SendVia(via *HostInfo,
  171. relay *Relay,
  172. ad,
  173. nb,
  174. out []byte,
  175. nocopy bool,
  176. ) {
  177. if noiseutil.EncryptLockNeeded {
  178. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  179. via.ConnectionState.writeLock.Lock()
  180. }
  181. c := via.ConnectionState.messageCounter.Add(1)
  182. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  183. f.connectionManager.Out(via.localIndexId)
  184. // Authenticate the header and payload, but do not encrypt for this message type.
  185. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  186. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  187. if noiseutil.EncryptLockNeeded {
  188. via.ConnectionState.writeLock.Unlock()
  189. }
  190. via.logger(f.l).
  191. WithField("outCap", cap(out)).
  192. WithField("payloadLen", len(ad)).
  193. WithField("headerLen", len(out)).
  194. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  195. Error("SendVia out buffer not large enough for relay")
  196. return
  197. }
  198. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  199. offset := len(out)
  200. out = out[:offset+len(ad)]
  201. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  202. // be copied into 'out'.
  203. if !nocopy {
  204. copy(out[offset:], ad)
  205. }
  206. var err error
  207. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  208. if noiseutil.EncryptLockNeeded {
  209. via.ConnectionState.writeLock.Unlock()
  210. }
  211. if err != nil {
  212. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  213. return
  214. }
  215. err = f.writers[0].WriteTo(out, via.remote)
  216. if err != nil {
  217. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  218. }
  219. f.connectionManager.RelayUsed(relay.LocalIndex)
  220. }
  221. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte, q int) {
  222. if ci.eKey == nil {
  223. //TODO: log warning
  224. return
  225. }
  226. useRelay := remote == nil && hostinfo.remote == nil
  227. fullOut := out
  228. if useRelay {
  229. if len(out) < header.Len {
  230. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  231. // Grow it to make sure the next operation works.
  232. out = out[:header.Len]
  233. }
  234. // Save a header's worth of data at the front of the 'out' buffer.
  235. out = out[header.Len:]
  236. }
  237. if noiseutil.EncryptLockNeeded {
  238. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  239. ci.writeLock.Lock()
  240. }
  241. c := ci.messageCounter.Add(1)
  242. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  243. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  244. f.connectionManager.Out(hostinfo.localIndexId)
  245. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  246. // all our IPs and enable a faster roaming.
  247. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  248. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  249. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  250. f.lightHouse.QueryServer(hostinfo.vpnIp)
  251. hostinfo.lastRebindCount = f.rebindCount
  252. if f.l.Level >= logrus.DebugLevel {
  253. f.l.WithField("vpnIp", hostinfo.vpnIp).Debug("Lighthouse update triggered for punch due to rebind counter")
  254. }
  255. }
  256. var err error
  257. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  258. if noiseutil.EncryptLockNeeded {
  259. ci.writeLock.Unlock()
  260. }
  261. if err != nil {
  262. hostinfo.logger(f.l).WithError(err).
  263. WithField("udpAddr", remote).WithField("counter", c).
  264. WithField("attemptedCounter", c).
  265. Error("Failed to encrypt outgoing packet")
  266. return
  267. }
  268. if remote != nil {
  269. err = f.writers[q].WriteTo(out, remote)
  270. if err != nil {
  271. hostinfo.logger(f.l).WithError(err).
  272. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  273. }
  274. } else if hostinfo.remote != nil {
  275. err = f.writers[q].WriteTo(out, hostinfo.remote)
  276. if err != nil {
  277. hostinfo.logger(f.l).WithError(err).
  278. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  279. }
  280. } else {
  281. // Try to send via a relay
  282. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  283. relayHostInfo, relay, err := f.hostMap.QueryVpnIpRelayFor(hostinfo.vpnIp, relayIP)
  284. if err != nil {
  285. hostinfo.relayState.DeleteRelay(relayIP)
  286. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  287. continue
  288. }
  289. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  290. break
  291. }
  292. }
  293. }
  294. func isMulticast(ip iputil.VpnIp) bool {
  295. // Class D multicast
  296. return (((ip >> 24) & 0xff) & 0xf0) == 0xe0
  297. }