signer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // Package signer implements certificate signature functionality for CFSSL.
  2. package signer
  3. import (
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rsa"
  8. "crypto/sha1"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "encoding/asn1"
  12. "errors"
  13. "math/big"
  14. "net/http"
  15. "strings"
  16. "time"
  17. "github.com/cloudflare/cfssl/certdb"
  18. "github.com/cloudflare/cfssl/config"
  19. "github.com/cloudflare/cfssl/csr"
  20. cferr "github.com/cloudflare/cfssl/errors"
  21. "github.com/cloudflare/cfssl/info"
  22. )
  23. // Subject contains the information that should be used to override the
  24. // subject information when signing a certificate.
  25. type Subject struct {
  26. CN string
  27. Names []csr.Name `json:"names"`
  28. SerialNumber string
  29. }
  30. // Extension represents a raw extension to be included in the certificate. The
  31. // "value" field must be hex encoded.
  32. type Extension struct {
  33. ID config.OID `json:"id"`
  34. Critical bool `json:"critical"`
  35. Value string `json:"value"`
  36. }
  37. // SignRequest stores a signature request, which contains the hostname,
  38. // the CSR, optional subject information, and the signature profile.
  39. //
  40. // Extensions provided in the signRequest are copied into the certificate, as
  41. // long as they are in the ExtensionWhitelist for the signer's policy.
  42. // Extensions requested in the CSR are ignored, except for those processed by
  43. // ParseCertificateRequest (mainly subjectAltName).
  44. type SignRequest struct {
  45. Hosts []string `json:"hosts"`
  46. Request string `json:"certificate_request"`
  47. Subject *Subject `json:"subject,omitempty"`
  48. Profile string `json:"profile"`
  49. CRLOverride string `json:"crl_override"`
  50. Label string `json:"label"`
  51. Serial *big.Int `json:"serial,omitempty"`
  52. Extensions []Extension `json:"extensions,omitempty"`
  53. // If provided, NotBefore will be used without modification (except
  54. // for canonicalization) as the value of the notBefore field of the
  55. // certificate. In particular no backdating adjustment will be made
  56. // when NotBefore is provided.
  57. NotBefore time.Time
  58. // If provided, NotAfter will be used without modification (except
  59. // for canonicalization) as the value of the notAfter field of the
  60. // certificate.
  61. NotAfter time.Time
  62. // If ReturnPrecert is true a certificate with the CT poison extension
  63. // will be returned from the Signer instead of attempting to retrieve
  64. // SCTs and populate the tbsCert with them itself. This precert can then
  65. // be passed to SignFromPrecert with the SCTs in order to create a
  66. // valid certificate.
  67. ReturnPrecert bool
  68. }
  69. // appendIf appends to a if s is not an empty string.
  70. func appendIf(s string, a *[]string) {
  71. if s != "" {
  72. *a = append(*a, s)
  73. }
  74. }
  75. // Name returns the PKIX name for the subject.
  76. func (s *Subject) Name() pkix.Name {
  77. var name pkix.Name
  78. name.CommonName = s.CN
  79. for _, n := range s.Names {
  80. appendIf(n.C, &name.Country)
  81. appendIf(n.ST, &name.Province)
  82. appendIf(n.L, &name.Locality)
  83. appendIf(n.O, &name.Organization)
  84. appendIf(n.OU, &name.OrganizationalUnit)
  85. }
  86. name.SerialNumber = s.SerialNumber
  87. return name
  88. }
  89. // SplitHosts takes a comma-spearated list of hosts and returns a slice
  90. // with the hosts split
  91. func SplitHosts(hostList string) []string {
  92. if hostList == "" {
  93. return nil
  94. }
  95. return strings.Split(hostList, ",")
  96. }
  97. // A Signer contains a CA's certificate and private key for signing
  98. // certificates, a Signing policy to refer to and a SignatureAlgorithm.
  99. type Signer interface {
  100. Info(info.Req) (*info.Resp, error)
  101. Policy() *config.Signing
  102. SetDBAccessor(certdb.Accessor)
  103. GetDBAccessor() certdb.Accessor
  104. SetPolicy(*config.Signing)
  105. SigAlgo() x509.SignatureAlgorithm
  106. Sign(req SignRequest) (cert []byte, err error)
  107. SetReqModifier(func(*http.Request, []byte))
  108. }
  109. // Profile gets the specific profile from the signer
  110. func Profile(s Signer, profile string) (*config.SigningProfile, error) {
  111. var p *config.SigningProfile
  112. policy := s.Policy()
  113. if policy != nil && policy.Profiles != nil && profile != "" {
  114. p = policy.Profiles[profile]
  115. }
  116. if p == nil && policy != nil {
  117. p = policy.Default
  118. }
  119. if p == nil {
  120. return nil, cferr.Wrap(cferr.APIClientError, cferr.ClientHTTPError, errors.New("profile must not be nil"))
  121. }
  122. return p, nil
  123. }
  124. // DefaultSigAlgo returns an appropriate X.509 signature algorithm given
  125. // the CA's private key.
  126. func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm {
  127. pub := priv.Public()
  128. switch pub := pub.(type) {
  129. case *rsa.PublicKey:
  130. keySize := pub.N.BitLen()
  131. switch {
  132. case keySize >= 4096:
  133. return x509.SHA512WithRSA
  134. case keySize >= 3072:
  135. return x509.SHA384WithRSA
  136. case keySize >= 2048:
  137. return x509.SHA256WithRSA
  138. default:
  139. return x509.SHA1WithRSA
  140. }
  141. case *ecdsa.PublicKey:
  142. switch pub.Curve {
  143. case elliptic.P256():
  144. return x509.ECDSAWithSHA256
  145. case elliptic.P384():
  146. return x509.ECDSAWithSHA384
  147. case elliptic.P521():
  148. return x509.ECDSAWithSHA512
  149. default:
  150. return x509.ECDSAWithSHA1
  151. }
  152. default:
  153. return x509.UnknownSignatureAlgorithm
  154. }
  155. }
  156. // ParseCertificateRequest takes an incoming certificate request and
  157. // builds a certificate template from it.
  158. func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) {
  159. csrv, err := x509.ParseCertificateRequest(csrBytes)
  160. if err != nil {
  161. err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
  162. return
  163. }
  164. err = csrv.CheckSignature()
  165. if err != nil {
  166. err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err)
  167. return
  168. }
  169. template = &x509.Certificate{
  170. Subject: csrv.Subject,
  171. PublicKeyAlgorithm: csrv.PublicKeyAlgorithm,
  172. PublicKey: csrv.PublicKey,
  173. SignatureAlgorithm: s.SigAlgo(),
  174. DNSNames: csrv.DNSNames,
  175. IPAddresses: csrv.IPAddresses,
  176. EmailAddresses: csrv.EmailAddresses,
  177. }
  178. for _, val := range csrv.Extensions {
  179. // Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9)
  180. // extension and append to template if necessary
  181. if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
  182. var constraints csr.BasicConstraints
  183. var rest []byte
  184. if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil {
  185. return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
  186. } else if len(rest) != 0 {
  187. return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints"))
  188. }
  189. template.BasicConstraintsValid = true
  190. template.IsCA = constraints.IsCA
  191. template.MaxPathLen = constraints.MaxPathLen
  192. template.MaxPathLenZero = template.MaxPathLen == 0
  193. }
  194. }
  195. return
  196. }
  197. type subjectPublicKeyInfo struct {
  198. Algorithm pkix.AlgorithmIdentifier
  199. SubjectPublicKey asn1.BitString
  200. }
  201. // ComputeSKI derives an SKI from the certificate's public key in a
  202. // standard manner. This is done by computing the SHA-1 digest of the
  203. // SubjectPublicKeyInfo component of the certificate.
  204. func ComputeSKI(template *x509.Certificate) ([]byte, error) {
  205. pub := template.PublicKey
  206. encodedPub, err := x509.MarshalPKIXPublicKey(pub)
  207. if err != nil {
  208. return nil, err
  209. }
  210. var subPKI subjectPublicKeyInfo
  211. _, err = asn1.Unmarshal(encodedPub, &subPKI)
  212. if err != nil {
  213. return nil, err
  214. }
  215. pubHash := sha1.Sum(subPKI.SubjectPublicKey.Bytes)
  216. return pubHash[:], nil
  217. }
  218. // FillTemplate is a utility function that tries to load as much of
  219. // the certificate template as possible from the profiles and current
  220. // template. It fills in the key uses, expiration, revocation URLs
  221. // and SKI.
  222. func FillTemplate(template *x509.Certificate, defaultProfile, profile *config.SigningProfile, notBefore time.Time, notAfter time.Time) error {
  223. ski, err := ComputeSKI(template)
  224. if err != nil {
  225. return err
  226. }
  227. var (
  228. eku []x509.ExtKeyUsage
  229. ku x509.KeyUsage
  230. backdate time.Duration
  231. expiry time.Duration
  232. crlURL, ocspURL string
  233. issuerURL = profile.IssuerURL
  234. )
  235. // The third value returned from Usages is a list of unknown key usages.
  236. // This should be used when validating the profile at load, and isn't used
  237. // here.
  238. ku, eku, _ = profile.Usages()
  239. if profile.IssuerURL == nil {
  240. issuerURL = defaultProfile.IssuerURL
  241. }
  242. if ku == 0 && len(eku) == 0 {
  243. return cferr.New(cferr.PolicyError, cferr.NoKeyUsages)
  244. }
  245. if expiry = profile.Expiry; expiry == 0 {
  246. expiry = defaultProfile.Expiry
  247. }
  248. if crlURL = profile.CRL; crlURL == "" {
  249. crlURL = defaultProfile.CRL
  250. }
  251. if ocspURL = profile.OCSP; ocspURL == "" {
  252. ocspURL = defaultProfile.OCSP
  253. }
  254. if notBefore.IsZero() {
  255. if !profile.NotBefore.IsZero() {
  256. notBefore = profile.NotBefore
  257. } else {
  258. if backdate = profile.Backdate; backdate == 0 {
  259. backdate = -5 * time.Minute
  260. } else {
  261. backdate = -1 * profile.Backdate
  262. }
  263. notBefore = time.Now().Round(time.Minute).Add(backdate)
  264. }
  265. }
  266. notBefore = notBefore.UTC()
  267. if notAfter.IsZero() {
  268. if !profile.NotAfter.IsZero() {
  269. notAfter = profile.NotAfter
  270. } else {
  271. notAfter = notBefore.Add(expiry)
  272. }
  273. }
  274. notAfter = notAfter.UTC()
  275. template.NotBefore = notBefore
  276. template.NotAfter = notAfter
  277. template.KeyUsage = ku
  278. template.ExtKeyUsage = eku
  279. template.BasicConstraintsValid = true
  280. template.IsCA = profile.CAConstraint.IsCA
  281. if template.IsCA {
  282. template.MaxPathLen = profile.CAConstraint.MaxPathLen
  283. if template.MaxPathLen == 0 {
  284. template.MaxPathLenZero = profile.CAConstraint.MaxPathLenZero
  285. }
  286. template.DNSNames = nil
  287. template.EmailAddresses = nil
  288. }
  289. template.SubjectKeyId = ski
  290. if ocspURL != "" {
  291. template.OCSPServer = []string{ocspURL}
  292. }
  293. if crlURL != "" {
  294. template.CRLDistributionPoints = []string{crlURL}
  295. }
  296. if len(issuerURL) != 0 {
  297. template.IssuingCertificateURL = issuerURL
  298. }
  299. if len(profile.Policies) != 0 {
  300. err = addPolicies(template, profile.Policies)
  301. if err != nil {
  302. return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err)
  303. }
  304. }
  305. if profile.OCSPNoCheck {
  306. ocspNoCheckExtension := pkix.Extension{
  307. Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1, 5},
  308. Critical: false,
  309. Value: []byte{0x05, 0x00},
  310. }
  311. template.ExtraExtensions = append(template.ExtraExtensions, ocspNoCheckExtension)
  312. }
  313. return nil
  314. }
  315. type policyInformation struct {
  316. PolicyIdentifier asn1.ObjectIdentifier
  317. Qualifiers []interface{} `asn1:"tag:optional,omitempty"`
  318. }
  319. type cpsPolicyQualifier struct {
  320. PolicyQualifierID asn1.ObjectIdentifier
  321. Qualifier string `asn1:"tag:optional,ia5"`
  322. }
  323. type userNotice struct {
  324. ExplicitText string `asn1:"tag:optional,utf8"`
  325. }
  326. type userNoticePolicyQualifier struct {
  327. PolicyQualifierID asn1.ObjectIdentifier
  328. Qualifier userNotice
  329. }
  330. var (
  331. // Per https://tools.ietf.org/html/rfc3280.html#page-106, this represents:
  332. // iso(1) identified-organization(3) dod(6) internet(1) security(5)
  333. // mechanisms(5) pkix(7) id-qt(2) id-qt-cps(1)
  334. iDQTCertificationPracticeStatement = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 1}
  335. // iso(1) identified-organization(3) dod(6) internet(1) security(5)
  336. // mechanisms(5) pkix(7) id-qt(2) id-qt-unotice(2)
  337. iDQTUserNotice = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2}
  338. // CTPoisonOID is the object ID of the critical poison extension for precertificates
  339. // https://tools.ietf.org/html/rfc6962#page-9
  340. CTPoisonOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
  341. // SCTListOID is the object ID for the Signed Certificate Timestamp certificate extension
  342. // https://tools.ietf.org/html/rfc6962#page-14
  343. SCTListOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
  344. )
  345. // addPolicies adds Certificate Policies and optional Policy Qualifiers to a
  346. // certificate, based on the input config. Go's x509 library allows setting
  347. // Certificate Policies easily, but does not support nested Policy Qualifiers
  348. // under those policies. So we need to construct the ASN.1 structure ourselves.
  349. func addPolicies(template *x509.Certificate, policies []config.CertificatePolicy) error {
  350. asn1PolicyList := []policyInformation{}
  351. for _, policy := range policies {
  352. pi := policyInformation{
  353. // The PolicyIdentifier is an OID assigned to a given issuer.
  354. PolicyIdentifier: asn1.ObjectIdentifier(policy.ID),
  355. }
  356. for _, qualifier := range policy.Qualifiers {
  357. switch qualifier.Type {
  358. case "id-qt-unotice":
  359. pi.Qualifiers = append(pi.Qualifiers,
  360. userNoticePolicyQualifier{
  361. PolicyQualifierID: iDQTUserNotice,
  362. Qualifier: userNotice{
  363. ExplicitText: qualifier.Value,
  364. },
  365. })
  366. case "id-qt-cps":
  367. pi.Qualifiers = append(pi.Qualifiers,
  368. cpsPolicyQualifier{
  369. PolicyQualifierID: iDQTCertificationPracticeStatement,
  370. Qualifier: qualifier.Value,
  371. })
  372. default:
  373. return errors.New("Invalid qualifier type in Policies " + qualifier.Type)
  374. }
  375. }
  376. asn1PolicyList = append(asn1PolicyList, pi)
  377. }
  378. asn1Bytes, err := asn1.Marshal(asn1PolicyList)
  379. if err != nil {
  380. return err
  381. }
  382. template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{
  383. Id: asn1.ObjectIdentifier{2, 5, 29, 32},
  384. Critical: false,
  385. Value: asn1Bytes,
  386. })
  387. return nil
  388. }