signer.go 14 KB

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