tls.go 18 KB

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