auth.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/ed25519"
  10. "crypto/elliptic"
  11. "crypto/rsa"
  12. "errors"
  13. "fmt"
  14. "hash"
  15. "io"
  16. circlPki "github.com/cloudflare/circl/pki"
  17. circlSign "github.com/cloudflare/circl/sign"
  18. )
  19. // verifyHandshakeSignature verifies a signature against pre-hashed
  20. // (if required) handshake contents.
  21. func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error {
  22. switch sigType {
  23. case signatureECDSA:
  24. pubKey, ok := pubkey.(*ecdsa.PublicKey)
  25. if !ok {
  26. return fmt.Errorf("expected an ECDSA public key, got %T", pubkey)
  27. }
  28. if !ecdsa.VerifyASN1(pubKey, signed, sig) {
  29. return errors.New("ECDSA verification failure")
  30. }
  31. case signatureEd25519:
  32. pubKey, ok := pubkey.(ed25519.PublicKey)
  33. if !ok {
  34. return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey)
  35. }
  36. if !ed25519.Verify(pubKey, signed, sig) {
  37. return errors.New("Ed25519 verification failure")
  38. }
  39. case signaturePKCS1v15:
  40. pubKey, ok := pubkey.(*rsa.PublicKey)
  41. if !ok {
  42. return fmt.Errorf("expected an RSA public key, got %T", pubkey)
  43. }
  44. if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil {
  45. return err
  46. }
  47. case signatureRSAPSS:
  48. pubKey, ok := pubkey.(*rsa.PublicKey)
  49. if !ok {
  50. return fmt.Errorf("expected an RSA public key, got %T", pubkey)
  51. }
  52. signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
  53. if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil {
  54. return err
  55. }
  56. default:
  57. // [UTLS SECTION BEGINS]
  58. // Ported from cloudflare/go
  59. scheme := circlSchemeBySigType(sigType)
  60. if scheme == nil {
  61. return errors.New("internal error: unknown signature type")
  62. }
  63. pubKey, ok := pubkey.(circlSign.PublicKey)
  64. if !ok {
  65. return fmt.Errorf("expected a %s public key, got %T", scheme.Name(), pubkey)
  66. }
  67. if !scheme.Verify(pubKey, signed, sig, nil) {
  68. return fmt.Errorf("%s verification failure", scheme.Name())
  69. }
  70. // [UTLS SECTION ENDS]
  71. }
  72. return nil
  73. }
  74. const (
  75. serverSignatureContext = "TLS 1.3, server CertificateVerify\x00"
  76. clientSignatureContext = "TLS 1.3, client CertificateVerify\x00"
  77. )
  78. var signaturePadding = []byte{
  79. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  80. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  81. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  82. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  83. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  84. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  85. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  86. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  87. }
  88. // signedMessage returns the pre-hashed (if necessary) message to be signed by
  89. // certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3.
  90. func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte {
  91. if sigHash == directSigning {
  92. b := &bytes.Buffer{}
  93. b.Write(signaturePadding)
  94. io.WriteString(b, context)
  95. b.Write(transcript.Sum(nil))
  96. return b.Bytes()
  97. }
  98. h := sigHash.New()
  99. h.Write(signaturePadding)
  100. io.WriteString(h, context)
  101. h.Write(transcript.Sum(nil))
  102. return h.Sum(nil)
  103. }
  104. // typeAndHashFromSignatureScheme returns the corresponding signature type and
  105. // crypto.Hash for a given TLS SignatureScheme.
  106. func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error) {
  107. switch signatureAlgorithm {
  108. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  109. sigType = signaturePKCS1v15
  110. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  111. sigType = signatureRSAPSS
  112. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  113. sigType = signatureECDSA
  114. case Ed25519:
  115. sigType = signatureEd25519
  116. default:
  117. // [UTLS SECTION BEGINS]
  118. // Ported from cloudflare/go
  119. scheme := circlPki.SchemeByTLSID(uint(signatureAlgorithm))
  120. if scheme == nil {
  121. return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
  122. }
  123. sigType = sigTypeByCirclScheme(scheme)
  124. if sigType == 0 {
  125. return 0, 0, fmt.Errorf("circl scheme %s not supported",
  126. scheme.Name())
  127. }
  128. // [UTLS SECTION ENDS]
  129. }
  130. switch signatureAlgorithm {
  131. case PKCS1WithSHA1, ECDSAWithSHA1:
  132. hash = crypto.SHA1
  133. case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256:
  134. hash = crypto.SHA256
  135. case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384:
  136. hash = crypto.SHA384
  137. case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512:
  138. hash = crypto.SHA512
  139. case Ed25519:
  140. hash = directSigning
  141. default:
  142. // [UTLS SECTION BEGINS]
  143. // Ported from cloudflare/go
  144. scheme := circlPki.SchemeByTLSID(uint(signatureAlgorithm))
  145. if scheme == nil {
  146. return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
  147. }
  148. hash = directSigning
  149. // [UTLS SECTION ENDS]
  150. }
  151. return sigType, hash, nil
  152. }
  153. // legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for
  154. // a given public key used with TLS 1.0 and 1.1, before the introduction of
  155. // signature algorithm negotiation.
  156. func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) {
  157. switch pub.(type) {
  158. case *rsa.PublicKey:
  159. return signaturePKCS1v15, crypto.MD5SHA1, nil
  160. case *ecdsa.PublicKey:
  161. return signatureECDSA, crypto.SHA1, nil
  162. case ed25519.PublicKey:
  163. // RFC 8422 specifies support for Ed25519 in TLS 1.0 and 1.1,
  164. // but it requires holding on to a handshake transcript to do a
  165. // full signature, and not even OpenSSL bothers with the
  166. // complexity, so we can't even test it properly.
  167. return 0, 0, fmt.Errorf("tls: Ed25519 public keys are not supported before TLS 1.2")
  168. // [UTLS SECTION BEGINS]
  169. // Ported from cloudflare/go
  170. case circlSign.PublicKey:
  171. return 0, 0, fmt.Errorf("tls: circl public keys are not supported before TLS 1.2")
  172. // [UTLS SECTION ENDS]
  173. default:
  174. return 0, 0, fmt.Errorf("tls: unsupported public key: %T", pub)
  175. }
  176. }
  177. var rsaSignatureSchemes = []struct {
  178. scheme SignatureScheme
  179. minModulusBytes int
  180. maxVersion uint16
  181. }{
  182. // RSA-PSS is used with PSSSaltLengthEqualsHash, and requires
  183. // emLen >= hLen + sLen + 2
  184. {PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13},
  185. {PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13},
  186. {PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13},
  187. // PKCS #1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires
  188. // emLen >= len(prefix) + hLen + 11
  189. // TLS 1.3 dropped support for PKCS #1 v1.5 in favor of RSA-PSS.
  190. {PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12},
  191. {PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12},
  192. {PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12},
  193. {PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12},
  194. }
  195. // signatureSchemesForCertificate returns the list of supported SignatureSchemes
  196. // for a given certificate, based on the public key and the protocol version,
  197. // and optionally filtered by its explicit SupportedSignatureAlgorithms.
  198. //
  199. // This function must be kept in sync with supportedSignatureAlgorithms.
  200. // FIPS filtering is applied in the caller, selectSignatureScheme.
  201. func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
  202. priv, ok := cert.PrivateKey.(crypto.Signer)
  203. if !ok {
  204. return nil
  205. }
  206. var sigAlgs []SignatureScheme
  207. switch pub := priv.Public().(type) {
  208. case *ecdsa.PublicKey:
  209. if version != VersionTLS13 {
  210. // In TLS 1.2 and earlier, ECDSA algorithms are not
  211. // constrained to a single curve.
  212. sigAlgs = []SignatureScheme{
  213. ECDSAWithP256AndSHA256,
  214. ECDSAWithP384AndSHA384,
  215. ECDSAWithP521AndSHA512,
  216. ECDSAWithSHA1,
  217. }
  218. break
  219. }
  220. switch pub.Curve {
  221. case elliptic.P256():
  222. sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
  223. case elliptic.P384():
  224. sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
  225. case elliptic.P521():
  226. sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
  227. default:
  228. return nil
  229. }
  230. case *rsa.PublicKey:
  231. size := pub.Size()
  232. sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
  233. for _, candidate := range rsaSignatureSchemes {
  234. if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
  235. sigAlgs = append(sigAlgs, candidate.scheme)
  236. }
  237. }
  238. case ed25519.PublicKey:
  239. sigAlgs = []SignatureScheme{Ed25519}
  240. // [UTLS SECTION BEGINS]
  241. // Ported from cloudflare/go
  242. case circlSign.PublicKey:
  243. scheme := pub.Scheme()
  244. tlsScheme, ok := scheme.(circlPki.TLSScheme)
  245. if !ok {
  246. return nil
  247. }
  248. sigAlgs = []SignatureScheme{SignatureScheme(tlsScheme.TLSIdentifier())}
  249. // [UTLS SECTION ENDS]
  250. default:
  251. return nil
  252. }
  253. if cert.SupportedSignatureAlgorithms != nil {
  254. var filteredSigAlgs []SignatureScheme
  255. for _, sigAlg := range sigAlgs {
  256. if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) {
  257. filteredSigAlgs = append(filteredSigAlgs, sigAlg)
  258. }
  259. }
  260. return filteredSigAlgs
  261. }
  262. return sigAlgs
  263. }
  264. // selectSignatureScheme picks a SignatureScheme from the peer's preference list
  265. // that works with the selected certificate. It's only called for protocol
  266. // versions that support signature algorithms, so TLS 1.2 and 1.3.
  267. func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
  268. supportedAlgs := signatureSchemesForCertificate(vers, c)
  269. if len(supportedAlgs) == 0 {
  270. return 0, unsupportedCertificateError(c)
  271. }
  272. if len(peerAlgs) == 0 && vers == VersionTLS12 {
  273. // For TLS 1.2, if the client didn't send signature_algorithms then we
  274. // can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
  275. peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1}
  276. }
  277. // Pick signature scheme in the peer's preference order, as our
  278. // preference order is not configurable.
  279. for _, preferredAlg := range peerAlgs {
  280. if needFIPS() && !isSupportedSignatureAlgorithm(preferredAlg, fipsSupportedSignatureAlgorithms) {
  281. continue
  282. }
  283. if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
  284. return preferredAlg, nil
  285. }
  286. }
  287. return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms")
  288. }
  289. // unsupportedCertificateError returns a helpful error for certificates with
  290. // an unsupported private key.
  291. func unsupportedCertificateError(cert *Certificate) error {
  292. switch cert.PrivateKey.(type) {
  293. case rsa.PrivateKey, ecdsa.PrivateKey:
  294. return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T",
  295. cert.PrivateKey, cert.PrivateKey)
  296. case *ed25519.PrivateKey:
  297. return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey")
  298. }
  299. signer, ok := cert.PrivateKey.(crypto.Signer)
  300. if !ok {
  301. return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer",
  302. cert.PrivateKey)
  303. }
  304. switch pub := signer.Public().(type) {
  305. case *ecdsa.PublicKey:
  306. switch pub.Curve {
  307. case elliptic.P256():
  308. case elliptic.P384():
  309. case elliptic.P521():
  310. default:
  311. return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
  312. }
  313. case *rsa.PublicKey:
  314. return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
  315. case ed25519.PublicKey:
  316. default:
  317. return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
  318. }
  319. if cert.SupportedSignatureAlgorithms != nil {
  320. return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
  321. }
  322. return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
  323. }