lighthouse.go 9.8 KB

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