lighthouse.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. package nebula
  2. import (
  3. "fmt"
  4. "net"
  5. "sync"
  6. "time"
  7. "github.com/golang/protobuf/proto"
  8. "github.com/slackhq/nebula/cert"
  9. )
  10. type LightHouse struct {
  11. sync.RWMutex //Because we concurrently read and write to our maps
  12. amLighthouse bool
  13. myIp uint32
  14. punchConn *udpConn
  15. // Local cache of answers from light houses
  16. addrMap map[uint32][]udpAddr
  17. // filters remote addresses allowed for each host
  18. // - When we are a lighthouse, this filters what addresses we store and
  19. // respond with.
  20. // - When we are not a lighthouse, this filters which addresses we accept
  21. // from lighthouses.
  22. remoteAllowList *AllowList
  23. // filters local addresses that we advertise to lighthouses
  24. localAllowList *AllowList
  25. // staticList exists to avoid having a bool in each addrMap entry
  26. // since static should be rare
  27. staticList map[uint32]struct{}
  28. lighthouses map[uint32]struct{}
  29. interval int
  30. nebulaPort int
  31. punchBack bool
  32. punchDelay time.Duration
  33. }
  34. type EncWriter interface {
  35. SendMessageToVpnIp(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  36. SendMessageToAll(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  37. }
  38. func NewLightHouse(amLighthouse bool, myIp uint32, ips []uint32, interval int, nebulaPort int, pc *udpConn, punchBack bool, punchDelay time.Duration) *LightHouse {
  39. h := LightHouse{
  40. amLighthouse: amLighthouse,
  41. myIp: myIp,
  42. addrMap: make(map[uint32][]udpAddr),
  43. nebulaPort: nebulaPort,
  44. lighthouses: make(map[uint32]struct{}),
  45. staticList: make(map[uint32]struct{}),
  46. interval: interval,
  47. punchConn: pc,
  48. punchBack: punchBack,
  49. punchDelay: punchDelay,
  50. }
  51. for _, ip := range ips {
  52. h.lighthouses[ip] = struct{}{}
  53. }
  54. return &h
  55. }
  56. func (lh *LightHouse) SetRemoteAllowList(allowList *AllowList) {
  57. lh.Lock()
  58. defer lh.Unlock()
  59. lh.remoteAllowList = allowList
  60. }
  61. func (lh *LightHouse) SetLocalAllowList(allowList *AllowList) {
  62. lh.Lock()
  63. defer lh.Unlock()
  64. lh.localAllowList = allowList
  65. }
  66. func (lh *LightHouse) ValidateLHStaticEntries() error {
  67. for lhIP, _ := range lh.lighthouses {
  68. if _, ok := lh.staticList[lhIP]; !ok {
  69. return fmt.Errorf("Lighthouse %s does not have a static_host_map entry", IntIp(lhIP))
  70. }
  71. }
  72. return nil
  73. }
  74. func (lh *LightHouse) Query(ip uint32, f EncWriter) ([]udpAddr, error) {
  75. if !lh.IsLighthouseIP(ip) {
  76. lh.QueryServer(ip, f)
  77. }
  78. lh.RLock()
  79. if v, ok := lh.addrMap[ip]; ok {
  80. lh.RUnlock()
  81. return v, nil
  82. }
  83. lh.RUnlock()
  84. return nil, fmt.Errorf("host %s not known, queries sent to lighthouses", IntIp(ip))
  85. }
  86. // This is asynchronous so no reply should be expected
  87. func (lh *LightHouse) QueryServer(ip uint32, f EncWriter) {
  88. if !lh.amLighthouse {
  89. // Send a query to the lighthouses and hope for the best next time
  90. query, err := proto.Marshal(NewLhQueryByInt(ip))
  91. if err != nil {
  92. l.WithError(err).WithField("vpnIp", IntIp(ip)).Error("Failed to marshal lighthouse query payload")
  93. return
  94. }
  95. nb := make([]byte, 12, 12)
  96. out := make([]byte, mtu)
  97. for n := range lh.lighthouses {
  98. f.SendMessageToVpnIp(lightHouse, 0, n, query, nb, out)
  99. }
  100. }
  101. }
  102. // Query our local lighthouse cached results
  103. func (lh *LightHouse) QueryCache(ip uint32) []udpAddr {
  104. lh.RLock()
  105. if v, ok := lh.addrMap[ip]; ok {
  106. lh.RUnlock()
  107. return v
  108. }
  109. lh.RUnlock()
  110. return nil
  111. }
  112. func (lh *LightHouse) DeleteVpnIP(vpnIP uint32) {
  113. // First we check the static mapping
  114. // and do nothing if it is there
  115. if _, ok := lh.staticList[vpnIP]; ok {
  116. return
  117. }
  118. lh.Lock()
  119. //l.Debugln(lh.addrMap)
  120. delete(lh.addrMap, vpnIP)
  121. l.Debugf("deleting %s from lighthouse.", IntIp(vpnIP))
  122. lh.Unlock()
  123. }
  124. func (lh *LightHouse) AddRemote(vpnIP uint32, toIp *udpAddr, static bool) {
  125. // First we check if the sender thinks this is a static entry
  126. // and do nothing if it is not, but should be considered static
  127. if static == false {
  128. if _, ok := lh.staticList[vpnIP]; ok {
  129. return
  130. }
  131. }
  132. lh.Lock()
  133. for _, v := range lh.addrMap[vpnIP] {
  134. if v.Equals(toIp) {
  135. lh.Unlock()
  136. return
  137. }
  138. }
  139. allow := lh.remoteAllowList.Allow(udp2ipInt(toIp))
  140. l.WithField("remoteIp", toIp).WithField("allow", allow).Debug("remoteAllowList.Allow")
  141. if !allow {
  142. return
  143. }
  144. //l.Debugf("Adding reply of %s as %s\n", IntIp(vpnIP), toIp)
  145. if static {
  146. lh.staticList[vpnIP] = struct{}{}
  147. }
  148. lh.addrMap[vpnIP] = append(lh.addrMap[vpnIP], *toIp)
  149. lh.Unlock()
  150. }
  151. func (lh *LightHouse) AddRemoteAndReset(vpnIP uint32, toIp *udpAddr) {
  152. if lh.amLighthouse {
  153. lh.DeleteVpnIP(vpnIP)
  154. lh.AddRemote(vpnIP, toIp, false)
  155. }
  156. }
  157. func (lh *LightHouse) IsLighthouseIP(vpnIP uint32) bool {
  158. if _, ok := lh.lighthouses[vpnIP]; ok {
  159. return true
  160. }
  161. return false
  162. }
  163. // Quick generators for protobuf
  164. func NewLhQueryByIpString(VpnIp string) *NebulaMeta {
  165. return NewLhQueryByInt(ip2int(net.ParseIP(VpnIp)))
  166. }
  167. func NewLhQueryByInt(VpnIp uint32) *NebulaMeta {
  168. return &NebulaMeta{
  169. Type: NebulaMeta_HostQuery,
  170. Details: &NebulaMetaDetails{
  171. VpnIp: VpnIp,
  172. },
  173. }
  174. }
  175. func NewLhWhoami() *NebulaMeta {
  176. return &NebulaMeta{
  177. Type: NebulaMeta_HostWhoami,
  178. Details: &NebulaMetaDetails{},
  179. }
  180. }
  181. // End Quick generators for protobuf
  182. func NewIpAndPortFromUDPAddr(addr udpAddr) *IpAndPort {
  183. return &IpAndPort{Ip: udp2ipInt(&addr), Port: uint32(addr.Port)}
  184. }
  185. func NewIpAndPortsFromNetIps(ips []udpAddr) *[]*IpAndPort {
  186. var iap []*IpAndPort
  187. for _, e := range ips {
  188. // Only add IPs that aren't my VPN/tun IP
  189. iap = append(iap, NewIpAndPortFromUDPAddr(e))
  190. }
  191. return &iap
  192. }
  193. func (lh *LightHouse) LhUpdateWorker(f EncWriter) {
  194. if lh.amLighthouse || lh.interval == 0 {
  195. return
  196. }
  197. for {
  198. ipp := []*IpAndPort{}
  199. for _, e := range *localIps(lh.localAllowList) {
  200. // Only add IPs that aren't my VPN/tun IP
  201. if ip2int(e) != lh.myIp {
  202. ipp = append(ipp, &IpAndPort{Ip: ip2int(e), Port: uint32(lh.nebulaPort)})
  203. //fmt.Println(e)
  204. }
  205. }
  206. m := &NebulaMeta{
  207. Type: NebulaMeta_HostUpdateNotification,
  208. Details: &NebulaMetaDetails{
  209. VpnIp: lh.myIp,
  210. IpAndPorts: ipp,
  211. },
  212. }
  213. nb := make([]byte, 12, 12)
  214. out := make([]byte, mtu)
  215. for vpnIp := range lh.lighthouses {
  216. mm, err := proto.Marshal(m)
  217. if err != nil {
  218. l.Debugf("Invalid marshal to update")
  219. }
  220. //l.Error("LIGHTHOUSE PACKET SEND", mm)
  221. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, mm, nb, out)
  222. }
  223. time.Sleep(time.Second * time.Duration(lh.interval))
  224. }
  225. }
  226. func (lh *LightHouse) HandleRequest(rAddr *udpAddr, vpnIp uint32, p []byte, c *cert.NebulaCertificate, f EncWriter) {
  227. n := &NebulaMeta{}
  228. err := proto.Unmarshal(p, n)
  229. if err != nil {
  230. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  231. Error("Failed to unmarshal lighthouse packet")
  232. //TODO: send recv_error?
  233. return
  234. }
  235. if n.Details == nil {
  236. l.WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  237. Error("Invalid lighthouse update")
  238. //TODO: send recv_error?
  239. return
  240. }
  241. switch n.Type {
  242. case NebulaMeta_HostQuery:
  243. // Exit if we don't answer queries
  244. if !lh.amLighthouse {
  245. l.Debugln("I don't answer queries, but received from: ", rAddr)
  246. return
  247. }
  248. //l.Debugln("Got Query")
  249. ips, err := lh.Query(n.Details.VpnIp, f)
  250. if err != nil {
  251. //l.Debugf("Can't answer query %s from %s because error: %s", IntIp(n.Details.VpnIp), rAddr, err)
  252. return
  253. } else {
  254. iap := NewIpAndPortsFromNetIps(ips)
  255. answer := &NebulaMeta{
  256. Type: NebulaMeta_HostQueryReply,
  257. Details: &NebulaMetaDetails{
  258. VpnIp: n.Details.VpnIp,
  259. IpAndPorts: *iap,
  260. },
  261. }
  262. reply, err := proto.Marshal(answer)
  263. if err != nil {
  264. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).Error("Failed to marshal lighthouse host query reply")
  265. return
  266. }
  267. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, reply, make([]byte, 12, 12), make([]byte, mtu))
  268. // This signals the other side to punch some zero byte udp packets
  269. ips, err = lh.Query(vpnIp, f)
  270. if err != nil {
  271. l.WithField("vpnIp", IntIp(vpnIp)).Debugln("Can't notify host to punch")
  272. return
  273. } else {
  274. //l.Debugln("Notify host to punch", iap)
  275. iap = NewIpAndPortsFromNetIps(ips)
  276. answer = &NebulaMeta{
  277. Type: NebulaMeta_HostPunchNotification,
  278. Details: &NebulaMetaDetails{
  279. VpnIp: vpnIp,
  280. IpAndPorts: *iap,
  281. },
  282. }
  283. reply, _ := proto.Marshal(answer)
  284. f.SendMessageToVpnIp(lightHouse, 0, n.Details.VpnIp, reply, make([]byte, 12, 12), make([]byte, mtu))
  285. }
  286. //fmt.Println(reply, remoteaddr)
  287. }
  288. case NebulaMeta_HostQueryReply:
  289. if !lh.IsLighthouseIP(vpnIp) {
  290. return
  291. }
  292. for _, a := range n.Details.IpAndPorts {
  293. //first := n.Details.IpAndPorts[0]
  294. ans := NewUDPAddr(a.Ip, uint16(a.Port))
  295. lh.AddRemote(n.Details.VpnIp, ans, false)
  296. }
  297. case NebulaMeta_HostUpdateNotification:
  298. //Simple check that the host sent this not someone else
  299. if n.Details.VpnIp != vpnIp {
  300. l.WithField("vpnIp", IntIp(vpnIp)).WithField("answer", IntIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  301. return
  302. }
  303. for _, a := range n.Details.IpAndPorts {
  304. ans := NewUDPAddr(a.Ip, uint16(a.Port))
  305. lh.AddRemote(n.Details.VpnIp, ans, false)
  306. }
  307. case NebulaMeta_HostMovedNotification:
  308. case NebulaMeta_HostPunchNotification:
  309. if !lh.IsLighthouseIP(vpnIp) {
  310. return
  311. }
  312. empty := []byte{0}
  313. for _, a := range n.Details.IpAndPorts {
  314. vpnPeer := NewUDPAddr(a.Ip, uint16(a.Port))
  315. go func() {
  316. time.Sleep(lh.punchDelay)
  317. lh.punchConn.WriteTo(empty, vpnPeer)
  318. }()
  319. l.Debugf("Punching %s on %d for %s", IntIp(a.Ip), a.Port, IntIp(n.Details.VpnIp))
  320. }
  321. // This sends a nebula test packet to the host trying to contact us. In the case
  322. // of a double nat or other difficult scenario, this may help establish
  323. // a tunnel.
  324. if lh.punchBack {
  325. go func() {
  326. time.Sleep(time.Second * 5)
  327. l.Debugf("Sending a nebula test packet to vpn ip %s", IntIp(n.Details.VpnIp))
  328. f.SendMessageToVpnIp(test, testRequest, n.Details.VpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  329. }()
  330. }
  331. }
  332. }
  333. /*
  334. func (f *Interface) sendPathCheck(ci *ConnectionState, endpoint *net.UDPAddr, counter int) {
  335. c := ci.messageCounter
  336. b := HeaderEncode(nil, Version, uint8(path_check), 0, ci.remoteIndex, c)
  337. ci.messageCounter++
  338. if ci.eKey != nil {
  339. msg := ci.eKey.EncryptDanger(b, nil, []byte(strconv.Itoa(counter)), c)
  340. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  341. f.outside.WriteTo(msg, endpoint)
  342. l.Debugf("path_check sent, remote index: %d, pathCounter %d", ci.remoteIndex, counter)
  343. }
  344. }
  345. func (f *Interface) sendPathCheckReply(ci *ConnectionState, endpoint *net.UDPAddr, counter []byte) {
  346. c := ci.messageCounter
  347. b := HeaderEncode(nil, Version, uint8(path_check_reply), 0, ci.remoteIndex, c)
  348. ci.messageCounter++
  349. if ci.eKey != nil {
  350. msg := ci.eKey.EncryptDanger(b, nil, counter, c)
  351. f.outside.WriteTo(msg, endpoint)
  352. l.Debugln("path_check sent, remote index: ", ci.remoteIndex)
  353. }
  354. }
  355. */