prove.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package runtime
  2. // FORK: learning the server's key at pairing without trusting whoever
  3. // answers first.
  4. //
  5. // An agent given a pairing token but no pin used to have no way to reach an
  6. // HTTPS server at all: the pin had to be supplied beforehand. ProveServerKey
  7. // closes that gap without falling back to trust on first use. The pairing
  8. // token is a secret the admin copies from the server, so the server can prove
  9. // it knows the token - and bind that proof to the key it is serving - while
  10. // the token itself never travels on the not-yet-authenticated connection:
  11. //
  12. // agent -> POST /api/agents/pair/hello {nonce}
  13. // server -> {server_fp, mac = pairproof.MAC(token, nonce, server_fp)}
  14. //
  15. // The agent accepts server_fp only if the MAC is right AND server_fp is the
  16. // key of a certificate in the chain it was actually shown. A man in the
  17. // middle can relay the hello and obtain the real server's MAC, but for the
  18. // real server's key, which is not in the chain the middle presented.
  19. import (
  20. "crypto/hmac"
  21. "crypto/rand"
  22. "crypto/tls"
  23. "crypto/x509"
  24. "encoding/hex"
  25. "encoding/json"
  26. "errors"
  27. "fmt"
  28. "io"
  29. "net/http"
  30. "net/url"
  31. "strings"
  32. "sync"
  33. "time"
  34. "github.com/gnacho/netpulse/agent/internal/tlspin"
  35. "github.com/gnacho/netpulse/agent/pairproof"
  36. )
  37. // ServerTransport is the transport an embedder should use for its own
  38. // requests to the NetPulse server: the same pinning the agent uses. fps is
  39. // NETPULSE_SERVER_FP - one or more comma-separated pins.
  40. func ServerTransport(serverURL, fps string) (*http.Transport, error) {
  41. return tlspin.BuildTransport(serverURL, fps)
  42. }
  43. // ValidatePins checks a NETPULSE_SERVER_FP value - one or more
  44. // comma-separated SHA-256 fingerprints - as the agent will read it, so a
  45. // setting can be refused when it is entered rather than when the agent
  46. // starts.
  47. func ValidatePins(fps string) error {
  48. _, err := tlspin.ParsePins(fps)
  49. return err
  50. }
  51. // ProveServerKey learns which key the HTTPS server at serverURL serves and
  52. // checks, with the pairing token, that it is the real server's. It returns
  53. // the fingerprint to pin. It never sends the pairing token.
  54. func ProveServerKey(serverURL, pairingToken string) (string, error) {
  55. if !strings.HasPrefix(serverURL, "https://") {
  56. return "", errors.New("the server's key can only be proven over https")
  57. }
  58. if pairingToken == "" {
  59. return "", errors.New("proving the server's key needs the pairing token")
  60. }
  61. var (
  62. mu sync.Mutex
  63. seen []*x509.Certificate
  64. )
  65. t := http.DefaultTransport.(*http.Transport).Clone()
  66. t.DisableKeepAlives = true
  67. t.TLSClientConfig = &tls.Config{
  68. // Nothing is trusted on this connection: it only records the chain,
  69. // and what the server says over it is checked against that chain.
  70. InsecureSkipVerify: true, //nolint:gosec // the chain is checked below, against the MAC
  71. MinVersion: tls.VersionTLS12,
  72. VerifyConnection: func(cs tls.ConnectionState) error {
  73. mu.Lock()
  74. seen = cs.PeerCertificates
  75. mu.Unlock()
  76. return nil
  77. },
  78. }
  79. nonceBytes := make([]byte, 32)
  80. if _, err := rand.Read(nonceBytes); err != nil {
  81. return "", err
  82. }
  83. nonce := hex.EncodeToString(nonceBytes)
  84. body := fmt.Sprintf(`{"nonce":%q}`, nonce)
  85. req, err := http.NewRequest("POST", strings.TrimRight(serverURL, "/")+"/api/agents/pair/hello", strings.NewReader(body))
  86. if err != nil {
  87. return "", err
  88. }
  89. req.Header.Set("Content-Type", "application/json")
  90. hc := &http.Client{
  91. Transport: t,
  92. Timeout: 15 * time.Second,
  93. // A redirect would move the request to another connection, whose
  94. // chain is not the one recorded.
  95. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
  96. }
  97. res, err := hc.Do(req)
  98. if err != nil {
  99. return "", fmt.Errorf("pair hello: %w", err)
  100. }
  101. defer res.Body.Close()
  102. if res.StatusCode != http.StatusOK {
  103. b, _ := io.ReadAll(io.LimitReader(res.Body, 512))
  104. return "", fmt.Errorf("pair hello: HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(b)))
  105. }
  106. var hello struct {
  107. ServerFP string `json:"server_fp"`
  108. MAC string `json:"mac"`
  109. }
  110. if err := json.NewDecoder(io.LimitReader(res.Body, 4096)).Decode(&hello); err != nil {
  111. return "", fmt.Errorf("pair hello: %w", err)
  112. }
  113. fp := tlspin.Normalize(hello.ServerFP)
  114. want := pairproof.MAC(pairingToken, nonce, fp)
  115. if !hmac.Equal([]byte(strings.ToLower(hello.MAC)), []byte(want)) {
  116. return "", errors.New("pair hello: the server could not prove it holds the pairing token; " +
  117. "this is not the server the token came from, or the token is wrong")
  118. }
  119. mu.Lock()
  120. chain := seen
  121. mu.Unlock()
  122. // The proven key must be the one this connection authenticated with: the
  123. // leaf's own key, or a CA key that signed the leaf for this host. Merely
  124. // appearing in the chain is not enough - a relay can attach the real
  125. // server's certificate to its own.
  126. u, err := url.Parse(serverURL)
  127. if err != nil {
  128. return "", err
  129. }
  130. if err := tlspin.Verify(chain, u.Hostname(), []string{fp}, time.Now()); err != nil {
  131. return "", fmt.Errorf("pair hello: the proven key is not the one this connection authenticated with; "+
  132. "something between this device and the server is intercepting the connection (%v)", err)
  133. }
  134. return fp, nil
  135. }