lighthouse.go 9.8 KB

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