trust.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. if !m.Enabled() {
  14. return ""
  15. }
  16. ca := m.CA()
  17. if ca == nil || ca.Leaf() == nil {
  18. return ""
  19. }
  20. leaf := ca.Leaf()
  21. host := urlHost(base)
  22. if host == "" {
  23. host = hostOnly(base)
  24. }
  25. // A loopback address names the server only to itself; the router, or
  26. // any other device given this URL, would dial its own loopback.
  27. if !leafNames(leaf.DNSNames, leaf.IPAddresses, host) || isLoopbackHost(host) {
  28. host = firstReachable(leaf.IPAddresses)
  29. }
  30. if host == "" {
  31. return ""
  32. }
  33. return "https://" + net.JoinHostPort(host, strconv.Itoa(m.currentPort()))
  34. }
  35. // AgentTrust is how an agent (re)installed with base as its server should
  36. // reach this server. With HTTPS on, it moves to the HTTPS address, pins the
  37. // root and verifies its downloads against it. Otherwise an https base keeps
  38. // working with legacyFP (the pin of a self-signed or user certificate), and
  39. // a plain one is left as it is.
  40. func AgentTrust(m *Manager, legacyFP func() string, base string) reinstall.Trust {
  41. if m != nil {
  42. if url := m.HTTPSURL(base); url != "" {
  43. ca := m.CA()
  44. return reinstall.Trust{ServerURL: url, ServerFP: ca.Fingerprint(), CAPEM: ca.RootPEM()}
  45. }
  46. }
  47. if strings.HasPrefix(base, "https://") && legacyFP != nil {
  48. return reinstall.Trust{ServerFP: legacyFP()}
  49. }
  50. return reinstall.Trust{}
  51. }
  52. func isLoopbackHost(host string) bool {
  53. if ip := net.ParseIP(host); ip != nil {
  54. return ip.IsLoopback()
  55. }
  56. return host == "localhost"
  57. }