trust.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package tlsmode
  2. import (
  3. "net"
  4. "strconv"
  5. "strings"
  6. "github.com/gnacho/netpulse/server-go/internal/reinstall"
  7. )
  8. // HTTPSURL is base moved to this server's HTTPS port - same host if the
  9. // certificate names it, else one it does - or "" while HTTPS is off. base is
  10. // whatever address routers were given (NETPULSE_PUBLIC_URL, or the one the
  11. // admin browsed to).
  12. func (m *Manager) HTTPSURL(base string) string {
  13. leaf := m.Leaf()
  14. if leaf == nil {
  15. return ""
  16. }
  17. host := urlHost(base)
  18. if host == "" {
  19. host = hostOnly(base)
  20. }
  21. // A loopback address names the server only to itself; the router, or
  22. // any other device given this URL, would dial its own loopback.
  23. if !leafNames(leaf.DNSNames, leaf.IPAddresses, host) || isLoopbackHost(host) {
  24. host = firstReachable(leaf.IPAddresses)
  25. }
  26. if host == "" {
  27. return ""
  28. }
  29. return "https://" + net.JoinHostPort(host, strconv.Itoa(m.currentPort()))
  30. }
  31. // AgentTrust is how an agent (re)installed with base as its server should
  32. // reach this server. With HTTPS on, it moves to the HTTPS address, pins the
  33. // root and verifies its downloads against it. Otherwise an https base keeps
  34. // working with legacyFP (the pin of a self-signed or user certificate), and
  35. // a plain one is left as it is.
  36. func AgentTrust(m *Manager, legacyFP func() string, base string) reinstall.Trust {
  37. if m != nil {
  38. if url := m.HTTPSURL(base); url != "" {
  39. if m.CertSource() == "custom" {
  40. // #1756: a certificate from disk has no root of ours to
  41. // hand out, so the agent pins the leaf itself.
  42. return reinstall.Trust{ServerURL: url, ServerFP: m.Fingerprint()}
  43. }
  44. ca := m.CA()
  45. return reinstall.Trust{ServerURL: url, ServerFP: ca.Fingerprint(), CAPEM: ca.RootPEM()}
  46. }
  47. }
  48. if strings.HasPrefix(base, "https://") && legacyFP != nil {
  49. return reinstall.Trust{ServerFP: legacyFP()}
  50. }
  51. return reinstall.Trust{}
  52. }
  53. func isLoopbackHost(host string) bool {
  54. if ip := net.ParseIP(host); ip != nil {
  55. return ip.IsLoopback()
  56. }
  57. return host == "localhost"
  58. }