tls.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/base64"
  9. "encoding/pem"
  10. "net/http"
  11. "time"
  12. "github.com/pkg/errors"
  13. "github.com/smallstep/certificates/authority/config"
  14. "github.com/smallstep/certificates/authority/provisioner"
  15. casapi "github.com/smallstep/certificates/cas/apiv1"
  16. "github.com/smallstep/certificates/db"
  17. "github.com/smallstep/certificates/errs"
  18. "go.step.sm/crypto/jose"
  19. "go.step.sm/crypto/keyutil"
  20. "go.step.sm/crypto/pemutil"
  21. "go.step.sm/crypto/x509util"
  22. )
  23. // GetTLSOptions returns the tls options configured.
  24. func (a *Authority) GetTLSOptions() *config.TLSOptions {
  25. return a.config.TLS
  26. }
  27. var oidAuthorityKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 35}
  28. var oidSubjectKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 14}
  29. func withDefaultASN1DN(def *config.ASN1DN) provisioner.CertificateModifierFunc {
  30. return func(crt *x509.Certificate, opts provisioner.SignOptions) error {
  31. if def == nil {
  32. return errors.New("default ASN1DN template cannot be nil")
  33. }
  34. if len(crt.Subject.Country) == 0 && def.Country != "" {
  35. crt.Subject.Country = append(crt.Subject.Country, def.Country)
  36. }
  37. if len(crt.Subject.Organization) == 0 && def.Organization != "" {
  38. crt.Subject.Organization = append(crt.Subject.Organization, def.Organization)
  39. }
  40. if len(crt.Subject.OrganizationalUnit) == 0 && def.OrganizationalUnit != "" {
  41. crt.Subject.OrganizationalUnit = append(crt.Subject.OrganizationalUnit, def.OrganizationalUnit)
  42. }
  43. if len(crt.Subject.Locality) == 0 && def.Locality != "" {
  44. crt.Subject.Locality = append(crt.Subject.Locality, def.Locality)
  45. }
  46. if len(crt.Subject.Province) == 0 && def.Province != "" {
  47. crt.Subject.Province = append(crt.Subject.Province, def.Province)
  48. }
  49. if len(crt.Subject.StreetAddress) == 0 && def.StreetAddress != "" {
  50. crt.Subject.StreetAddress = append(crt.Subject.StreetAddress, def.StreetAddress)
  51. }
  52. return nil
  53. }
  54. }
  55. // Sign creates a signed certificate from a certificate signing request.
  56. func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  57. var (
  58. certOptions []x509util.Option
  59. certValidators []provisioner.CertificateValidator
  60. certModifiers []provisioner.CertificateModifier
  61. certEnforcers []provisioner.CertificateEnforcer
  62. )
  63. opts := []interface{}{errs.WithKeyVal("csr", csr), errs.WithKeyVal("signOptions", signOpts)}
  64. if err := csr.CheckSignature(); err != nil {
  65. return nil, errs.Wrap(http.StatusBadRequest, err, "authority.Sign; invalid certificate request", opts...)
  66. }
  67. // Set backdate with the configured value
  68. signOpts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  69. for _, op := range extraOpts {
  70. switch k := op.(type) {
  71. // Adds new options to NewCertificate
  72. case provisioner.CertificateOptions:
  73. certOptions = append(certOptions, k.Options(signOpts)...)
  74. // Validate the given certificate request.
  75. case provisioner.CertificateRequestValidator:
  76. if err := k.Valid(csr); err != nil {
  77. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  78. }
  79. // Validates the unsigned certificate template.
  80. case provisioner.CertificateValidator:
  81. certValidators = append(certValidators, k)
  82. // Modifies a certificate before validating it.
  83. case provisioner.CertificateModifier:
  84. certModifiers = append(certModifiers, k)
  85. // Modifies a certificate after validating it.
  86. case provisioner.CertificateEnforcer:
  87. certEnforcers = append(certEnforcers, k)
  88. default:
  89. return nil, errs.InternalServer("authority.Sign; invalid extra option type %T", append([]interface{}{k}, opts...)...)
  90. }
  91. }
  92. cert, err := x509util.NewCertificate(csr, certOptions...)
  93. if err != nil {
  94. if _, ok := err.(*x509util.TemplateError); ok {
  95. return nil, errs.NewErr(http.StatusBadRequest, err,
  96. errs.WithMessage(err.Error()),
  97. errs.WithKeyVal("csr", csr),
  98. errs.WithKeyVal("signOptions", signOpts),
  99. )
  100. }
  101. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign", opts...)
  102. }
  103. // Certificate modifiers before validation
  104. leaf := cert.GetCertificate()
  105. // Set default subject
  106. if err := withDefaultASN1DN(a.config.AuthorityConfig.Template).Modify(leaf, signOpts); err != nil {
  107. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  108. }
  109. for _, m := range certModifiers {
  110. if err := m.Modify(leaf, signOpts); err != nil {
  111. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  112. }
  113. }
  114. // Certificate validation.
  115. for _, v := range certValidators {
  116. if err := v.Valid(leaf, signOpts); err != nil {
  117. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  118. }
  119. }
  120. // Certificate modifiers after validation
  121. for _, m := range certEnforcers {
  122. if err := m.Enforce(leaf); err != nil {
  123. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  124. }
  125. }
  126. lifetime := leaf.NotAfter.Sub(leaf.NotBefore.Add(signOpts.Backdate))
  127. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  128. Template: leaf,
  129. CSR: csr,
  130. Lifetime: lifetime,
  131. Backdate: signOpts.Backdate,
  132. })
  133. if err != nil {
  134. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error creating certificate", opts...)
  135. }
  136. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  137. if err = a.storeCertificate(fullchain); err != nil {
  138. if err != db.ErrNotImplemented {
  139. return nil, errs.Wrap(http.StatusInternalServerError, err,
  140. "authority.Sign; error storing certificate in db", opts...)
  141. }
  142. }
  143. return fullchain, nil
  144. }
  145. // Renew creates a new Certificate identical to the old certificate, except
  146. // with a validity window that begins 'now'.
  147. func (a *Authority) Renew(oldCert *x509.Certificate) ([]*x509.Certificate, error) {
  148. return a.Rekey(oldCert, nil)
  149. }
  150. // Rekey is used for rekeying and renewing based on the public key.
  151. // If the public key is 'nil' then it's assumed that the cert should be renewed
  152. // using the existing public key. If the public key is not 'nil' then it's
  153. // assumed that the cert should be rekeyed.
  154. // For both Rekey and Renew all other attributes of the new certificate should
  155. // match the old certificate. The exceptions are 'AuthorityKeyId' (which may
  156. // have changed), 'SubjectKeyId' (different in case of rekey), and
  157. // 'NotBefore/NotAfter' (the validity duration of the new certificate should be
  158. // equal to the old one, but starting 'now').
  159. func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  160. isRekey := (pk != nil)
  161. opts := []interface{}{errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String())}
  162. // Check step provisioner extensions
  163. if err := a.authorizeRenew(oldCert); err != nil {
  164. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  165. }
  166. // Durations
  167. backdate := a.config.AuthorityConfig.Backdate.Duration
  168. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  169. lifetime := duration - backdate
  170. // Create new certificate from previous values.
  171. // Issuer, NotBefore, NotAfter and SubjectKeyId will be set by the CAS.
  172. newCert := &x509.Certificate{
  173. Subject: oldCert.Subject,
  174. KeyUsage: oldCert.KeyUsage,
  175. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  176. ExtKeyUsage: oldCert.ExtKeyUsage,
  177. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  178. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  179. IsCA: oldCert.IsCA,
  180. MaxPathLen: oldCert.MaxPathLen,
  181. MaxPathLenZero: oldCert.MaxPathLenZero,
  182. OCSPServer: oldCert.OCSPServer,
  183. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  184. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  185. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  186. DNSNames: oldCert.DNSNames,
  187. EmailAddresses: oldCert.EmailAddresses,
  188. IPAddresses: oldCert.IPAddresses,
  189. URIs: oldCert.URIs,
  190. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  191. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  192. PermittedIPRanges: oldCert.PermittedIPRanges,
  193. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  194. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  195. PermittedURIDomains: oldCert.PermittedURIDomains,
  196. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  197. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  198. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  199. }
  200. if isRekey {
  201. newCert.PublicKey = pk
  202. } else {
  203. newCert.PublicKey = oldCert.PublicKey
  204. }
  205. // Copy all extensions except:
  206. //
  207. // 1. Authority Key Identifier - This one might be different if we rotate
  208. // the intermediate certificate and it will cause a TLS bad certificate
  209. // error.
  210. //
  211. // 2. Subject Key Identifier, if rekey - For rekey, SubjectKeyIdentifier
  212. // extension will be calculated for the new public key by
  213. // x509util.CreateCertificate()
  214. for _, ext := range oldCert.Extensions {
  215. if ext.Id.Equal(oidAuthorityKeyIdentifier) {
  216. continue
  217. }
  218. if ext.Id.Equal(oidSubjectKeyIdentifier) && isRekey {
  219. newCert.SubjectKeyId = nil
  220. continue
  221. }
  222. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  223. }
  224. resp, err := a.x509CAService.RenewCertificate(&casapi.RenewCertificateRequest{
  225. Template: newCert,
  226. Lifetime: lifetime,
  227. Backdate: backdate,
  228. })
  229. if err != nil {
  230. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  231. }
  232. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  233. if err = a.storeRenewedCertificate(oldCert, fullchain); err != nil {
  234. if err != db.ErrNotImplemented {
  235. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey; error storing certificate in db", opts...)
  236. }
  237. }
  238. return fullchain, nil
  239. }
  240. // storeCertificate allows to use an extension of the db.AuthDB interface that
  241. // can log the full chain of certificates.
  242. //
  243. // TODO: at some point we should replace the db.AuthDB interface to implement
  244. // `StoreCertificate(...*x509.Certificate) error` instead of just
  245. // `StoreCertificate(*x509.Certificate) error`.
  246. func (a *Authority) storeCertificate(fullchain []*x509.Certificate) error {
  247. if s, ok := a.db.(interface {
  248. StoreCertificateChain(...*x509.Certificate) error
  249. }); ok {
  250. return s.StoreCertificateChain(fullchain...)
  251. }
  252. return a.db.StoreCertificate(fullchain[0])
  253. }
  254. // storeRenewedCertificate allows to use an extension of the db.AuthDB interface
  255. // that can log if a certificate has been renewed or rekeyed.
  256. //
  257. // TODO: at some point we should implement this in the standard implementation.
  258. func (a *Authority) storeRenewedCertificate(oldCert *x509.Certificate, fullchain []*x509.Certificate) error {
  259. if s, ok := a.db.(interface {
  260. StoreRenewedCertificate(*x509.Certificate, ...*x509.Certificate) error
  261. }); ok {
  262. return s.StoreRenewedCertificate(oldCert, fullchain...)
  263. }
  264. return a.db.StoreCertificate(fullchain[0])
  265. }
  266. // RevokeOptions are the options for the Revoke API.
  267. type RevokeOptions struct {
  268. Serial string
  269. Reason string
  270. ReasonCode int
  271. PassiveOnly bool
  272. MTLS bool
  273. Crt *x509.Certificate
  274. OTT string
  275. }
  276. // Revoke revokes a certificate.
  277. //
  278. // NOTE: Only supports passive revocation - prevent existing certificates from
  279. // being renewed.
  280. //
  281. // TODO: Add OCSP and CRL support.
  282. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  283. opts := []interface{}{
  284. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  285. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  286. errs.WithKeyVal("reason", revokeOpts.Reason),
  287. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  288. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  289. errs.WithKeyVal("context", provisioner.MethodFromContext(ctx).String()),
  290. }
  291. if revokeOpts.MTLS {
  292. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  293. } else {
  294. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  295. }
  296. rci := &db.RevokedCertificateInfo{
  297. Serial: revokeOpts.Serial,
  298. ReasonCode: revokeOpts.ReasonCode,
  299. Reason: revokeOpts.Reason,
  300. MTLS: revokeOpts.MTLS,
  301. RevokedAt: time.Now().UTC(),
  302. }
  303. var (
  304. p provisioner.Interface
  305. err error
  306. )
  307. // If not mTLS then get the TokenID of the token.
  308. if !revokeOpts.MTLS {
  309. token, err := jose.ParseSigned(revokeOpts.OTT)
  310. if err != nil {
  311. return errs.Wrap(http.StatusUnauthorized, err,
  312. "authority.Revoke; error parsing token", opts...)
  313. }
  314. // Get claims w/out verification.
  315. var claims Claims
  316. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  317. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  318. }
  319. // This method will also validate the audiences for JWK provisioners.
  320. p, err = a.LoadProvisionerByToken(token, &claims.Claims)
  321. if err != nil {
  322. return err
  323. }
  324. rci.ProvisionerID = p.GetID()
  325. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  326. if err != nil && !errors.Is(err, provisioner.ErrAllowTokenReuse) {
  327. return errs.Wrap(http.StatusInternalServerError, err,
  328. "authority.Revoke; could not get ID for token")
  329. }
  330. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  331. opts = append(opts, errs.WithKeyVal("tokenID", rci.TokenID))
  332. } else {
  333. // Load the Certificate provisioner if one exists.
  334. if p, err = a.LoadProvisionerByCertificate(revokeOpts.Crt); err == nil {
  335. rci.ProvisionerID = p.GetID()
  336. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  337. }
  338. }
  339. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  340. err = a.db.RevokeSSH(rci)
  341. } else {
  342. // Revoke an X.509 certificate using CAS. If the certificate is not
  343. // provided we will try to read it from the db. If the read fails we
  344. // won't throw an error as it will be responsibility of the CAS
  345. // implementation to require a certificate.
  346. var revokedCert *x509.Certificate
  347. if revokeOpts.Crt != nil {
  348. revokedCert = revokeOpts.Crt
  349. } else if rci.Serial != "" {
  350. revokedCert, _ = a.db.GetCertificate(rci.Serial)
  351. }
  352. // CAS operation, note that SoftCAS (default) is a noop.
  353. // The revoke happens when this is stored in the db.
  354. _, err = a.x509CAService.RevokeCertificate(&casapi.RevokeCertificateRequest{
  355. Certificate: revokedCert,
  356. SerialNumber: rci.Serial,
  357. Reason: rci.Reason,
  358. ReasonCode: rci.ReasonCode,
  359. PassiveOnly: revokeOpts.PassiveOnly,
  360. })
  361. if err != nil {
  362. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  363. }
  364. // Save as revoked in the Db.
  365. err = a.db.Revoke(rci)
  366. }
  367. switch err {
  368. case nil:
  369. return nil
  370. case db.ErrNotImplemented:
  371. return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...)
  372. case db.ErrAlreadyExists:
  373. return errs.BadRequest("authority.Revoke; certificate with serial "+
  374. "number %s has already been revoked", append([]interface{}{rci.Serial}, opts...)...)
  375. default:
  376. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  377. }
  378. }
  379. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  380. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  381. fatal := func(err error) (*tls.Certificate, error) {
  382. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  383. }
  384. // Generate default key.
  385. priv, err := keyutil.GenerateDefaultKey()
  386. if err != nil {
  387. return fatal(err)
  388. }
  389. signer, ok := priv.(crypto.Signer)
  390. if !ok {
  391. return fatal(errors.New("private key is not a crypto.Signer"))
  392. }
  393. // Create initial certificate request.
  394. cr, err := x509util.CreateCertificateRequest("Step Online CA", a.config.DNSNames, signer)
  395. if err != nil {
  396. return fatal(err)
  397. }
  398. // Generate certificate template directly from the certificate request.
  399. template, err := x509util.NewCertificate(cr)
  400. if err != nil {
  401. return fatal(err)
  402. }
  403. // Get x509 certificate template, set validity and sign it.
  404. now := time.Now()
  405. certTpl := template.GetCertificate()
  406. certTpl.NotBefore = now.Add(-1 * time.Minute)
  407. certTpl.NotAfter = now.Add(24 * time.Hour)
  408. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  409. Template: certTpl,
  410. CSR: cr,
  411. Lifetime: 24 * time.Hour,
  412. Backdate: 1 * time.Minute,
  413. })
  414. if err != nil {
  415. return fatal(err)
  416. }
  417. // Generate PEM blocks to create tls.Certificate
  418. pemBlocks := pem.EncodeToMemory(&pem.Block{
  419. Type: "CERTIFICATE",
  420. Bytes: resp.Certificate.Raw,
  421. })
  422. for _, crt := range resp.CertificateChain {
  423. pemBlocks = append(pemBlocks, pem.EncodeToMemory(&pem.Block{
  424. Type: "CERTIFICATE",
  425. Bytes: crt.Raw,
  426. })...)
  427. }
  428. keyPEM, err := pemutil.Serialize(priv)
  429. if err != nil {
  430. return fatal(err)
  431. }
  432. tlsCrt, err := tls.X509KeyPair(pemBlocks, pem.EncodeToMemory(keyPEM))
  433. if err != nil {
  434. return fatal(err)
  435. }
  436. // Set leaf certificate
  437. tlsCrt.Leaf = resp.Certificate
  438. return &tlsCrt, nil
  439. }