signer.go 12 KB

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