lighthouse.go 9.6 KB

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