outside.go 13 KB

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