tls.go 18 KB

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