signer.go 14 KB

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