tls.go 16 KB

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