signer.go 12 KB

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