tlspin.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // Package tlspin — validación TLS del agente por pinning SPKI (Fase 9 R2).
  2. //
  3. // Sustituye a NETPULSE_INSECURE_TLS: en vez de saltar la verificación del
  4. // certificado, el agente pinea el hash SHA-256 del SubjectPublicKeyInfo del
  5. // servidor. Fail-closed: HTTPS sin fingerprint → error (nunca degrada a
  6. // insecure).
  7. package tlspin
  8. import (
  9. "crypto/sha256"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/hex"
  13. "errors"
  14. "fmt"
  15. "net/http"
  16. "net/url"
  17. "slices"
  18. "strings"
  19. "time"
  20. )
  21. // Normalize limpia un fingerprint: quita prefijo "sha256/", dos-puntos y
  22. // espacios, y lo pasa a minúsculas. Formato esperado: 64 hex chars.
  23. func Normalize(s string) string {
  24. // Lower-cased first, so "SHA256/" is stripped as well as "sha256/".
  25. s = strings.ToLower(strings.TrimSpace(s))
  26. return strings.NewReplacer("sha256/", "", ":", "", " ", "").Replace(s)
  27. }
  28. // BuildTransport crea un *http.Transport con la validación TLS adecuada:
  29. // - HTTP: transporte por defecto (sin TLS).
  30. // - HTTPS con fp: TLS con pinning SPKI (VerifyConnection).
  31. // - HTTPS sin fp: error (fail-closed).
  32. //
  33. // FORK: fps may hold several comma-separated pins, and a pin may name either
  34. // the server's own key (as before) or a CA in the chain the server presents;
  35. // see Verify. More than one pin is what lets the server move to a new CA
  36. // without a window in which its agents cannot reach it.
  37. func BuildTransport(serverURL, fps string) (*http.Transport, error) {
  38. t := http.DefaultTransport.(*http.Transport).Clone()
  39. if !strings.HasPrefix(serverURL, "https://") {
  40. return t, nil // HTTP plano: sin TLS
  41. }
  42. pins, err := ParsePins(fps)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if len(pins) == 0 {
  47. host := serverURL
  48. if u, err := url.Parse(serverURL); err == nil && u.Host != "" {
  49. host = u.Host
  50. }
  51. return nil, fmt.Errorf("HTTPS requires NETPULSE_SERVER_FP (SPKI pinning, without InsecureSkipVerify); get it with install-agent.sh (it derives it from the certificate automatically) or with: openssl s_client -connect %s </dev/null 2>/dev/null | openssl x509 -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum", host)
  52. }
  53. u, err := url.Parse(serverURL)
  54. if err != nil {
  55. return nil, fmt.Errorf("server URL: %w", err)
  56. }
  57. host := u.Hostname()
  58. if host == "" {
  59. // Without a host there is nothing to check the certificate's names
  60. // against, and a CA pin would accept any name the CA signed.
  61. return nil, fmt.Errorf("server URL %q has no host", serverURL)
  62. }
  63. t.TLSClientConfig = &tls.Config{
  64. // InsecureSkipVerify salta la verificación normal de CA; la decisión
  65. // final la toma VerifyConnection contra el SPKI pineado.
  66. InsecureSkipVerify: true, //nolint:gosec // pinning deliberado por SPKI
  67. // VerifyConnection rather than VerifyPeerCertificate: it also runs on
  68. // resumed sessions, so a session cache added later cannot let a
  69. // connection skip the pin.
  70. VerifyConnection: func(cs tls.ConnectionState) error {
  71. return Verify(cs.PeerCertificates, host, pins, time.Now())
  72. },
  73. MinVersion: tls.VersionTLS12,
  74. }
  75. return t, nil
  76. }
  77. // ParsePins splits a comma-separated list of fingerprints, normalizing each.
  78. // A pin that is not a SHA-256 in hex is an error rather than a pin that can
  79. // never match: a typo in the env file should say so, not look like an
  80. // impostor server.
  81. func ParsePins(fps string) ([]string, error) {
  82. var pins []string
  83. for _, p := range strings.Split(Normalize(fps), ",") {
  84. if p == "" {
  85. continue
  86. }
  87. if b, err := hex.DecodeString(p); err != nil || len(b) != sha256.Size {
  88. return nil, fmt.Errorf("NETPULSE_SERVER_FP: %q is not a SHA-256 fingerprint (64 hex characters)", p)
  89. }
  90. pins = append(pins, p)
  91. }
  92. return pins, nil
  93. }
  94. // Verify decides whether the chain a server presented matches one of pins.
  95. //
  96. // A pin on the leaf's own key accepts the connection outright - the original
  97. // behaviour, which checks neither name nor dates: the key is the identity.
  98. //
  99. // A pin on a CA accepts it only if the pinned key signed a leaf that is valid
  100. // now, for server authentication, for host. Pinning a CA hands it the power
  101. // to vouch for other keys, so those checks are what keeps "signed by our CA"
  102. // from meaning "any certificate our CA ever signed, for any name, at any
  103. // time".
  104. //
  105. // What is enforced is the leaf's signature by the pinned key. The CA
  106. // certificate itself, as the server sends it, is not signed by anything this
  107. // check trusts - anyone can present a copy of its key with other fields - so
  108. // its own dates and name constraints cannot be relied on here, and its CA
  109. // flags are only checked to catch a pin pointing at the wrong certificate.
  110. // The server must send the CA certificate in its chain: a hash cannot stand
  111. // in for it.
  112. func Verify(chain []*x509.Certificate, host string, pins []string, now time.Time) error {
  113. if len(chain) == 0 {
  114. return fmt.Errorf("no peer certificates")
  115. }
  116. leaf := chain[0]
  117. // The handshake has already proved the peer holds the leaf's private key,
  118. // so a pinned key presented as the leaf is that key's holder - even when
  119. // it is a CA's key, which only its owner can present this way.
  120. if slices.Contains(pins, spki(leaf)) {
  121. return nil
  122. }
  123. var lastErr error
  124. for i, c := range chain[1:] {
  125. if !slices.Contains(pins, spki(c)) {
  126. continue
  127. }
  128. // A CA without a key usage extension (OpenSSL's default for one) may
  129. // sign; one that has the extension must include certificate signing.
  130. if !c.IsCA || !c.BasicConstraintsValid || (c.KeyUsage != 0 && c.KeyUsage&x509.KeyUsageCertSign == 0) {
  131. lastErr = fmt.Errorf("the pinned key belongs to a certificate that is not a CA")
  132. continue
  133. }
  134. roots := x509.NewCertPool()
  135. roots.AddCert(c)
  136. inter := x509.NewCertPool()
  137. for j, o := range chain[1:] {
  138. if j != i {
  139. inter.AddCert(o)
  140. }
  141. }
  142. _, err := leaf.Verify(x509.VerifyOptions{
  143. DNSName: host,
  144. Roots: roots,
  145. Intermediates: inter,
  146. CurrentTime: now,
  147. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  148. })
  149. if err == nil {
  150. return nil
  151. }
  152. // Another pinned certificate further up the chain may still vouch
  153. // for the leaf, as during a move to a new CA.
  154. lastErr = explain(err, host)
  155. }
  156. if lastErr != nil {
  157. return lastErr
  158. }
  159. return fmt.Errorf("SPKI mismatch: the server's key %s matches no pinned key", spki(leaf))
  160. }
  161. // explain turns a chain verification error into one that says what to check.
  162. func explain(err error, host string) error {
  163. var hostErr x509.HostnameError
  164. var invalid x509.CertificateInvalidError
  165. switch {
  166. case err == nil:
  167. return nil
  168. case errors.As(err, &hostErr):
  169. return fmt.Errorf("the server's certificate does not name %s: %w", host, err)
  170. case errors.As(err, &invalid) && invalid.Reason == x509.Expired:
  171. return fmt.Errorf("the server's certificate is expired or not yet valid - "+
  172. "if this device's clock is not set yet (no NTP), this clears once it is: %w", err)
  173. default:
  174. return fmt.Errorf("the server's certificate was not issued by the pinned CA: %w", err)
  175. }
  176. }
  177. func spki(c *x509.Certificate) string {
  178. sum := sha256.Sum256(c.RawSubjectPublicKeyInfo)
  179. return hex.EncodeToString(sum[:])
  180. }
  181. // VerifySPKI comprueba que el SPKI hash del leaf cert coincida con el
  182. // fingerprint esperado (SHA-256 hex del DER del SubjectPublicKeyInfo).
  183. func VerifySPKI(rawCerts [][]byte, wantHex string) error {
  184. if len(rawCerts) == 0 {
  185. return fmt.Errorf("no peer certificates")
  186. }
  187. leaf, err := x509.ParseCertificate(rawCerts[0])
  188. if err != nil {
  189. return fmt.Errorf("parsear leaf: %w", err)
  190. }
  191. sum := sha256.Sum256(leaf.RawSubjectPublicKeyInfo)
  192. got := hex.EncodeToString(sum[:])
  193. if got != wantHex {
  194. return fmt.Errorf("SPKI mismatch: got %s, want %s", got, wantHex)
  195. }
  196. return nil
  197. }