tls.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/certificates/authority/provisioner"
  15. "github.com/smallstep/certificates/db"
  16. "github.com/smallstep/certificates/errs"
  17. "github.com/smallstep/cli/crypto/pemutil"
  18. "github.com/smallstep/cli/crypto/tlsutil"
  19. "github.com/smallstep/cli/crypto/x509util"
  20. "github.com/smallstep/cli/jose"
  21. )
  22. // GetTLSOptions returns the tls options configured.
  23. func (a *Authority) GetTLSOptions() *tlsutil.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 *x509util.ASN1DN) x509util.WithOption {
  29. return func(p x509util.Profile) error {
  30. if def == nil {
  31. return errors.New("default ASN1DN template cannot be nil")
  32. }
  33. crt := p.Subject()
  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.Options, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  57. var (
  58. opts = []interface{}{errs.WithKeyVal("csr", csr), errs.WithKeyVal("signOptions", signOpts)}
  59. mods = []x509util.WithOption{withDefaultASN1DN(a.config.AuthorityConfig.Template)}
  60. certValidators = []provisioner.CertificateValidator{}
  61. forcedModifiers = []provisioner.CertificateEnforcer{provisioner.ExtraExtsEnforcer{}}
  62. )
  63. // Set backdate with the configured value
  64. signOpts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  65. for _, op := range extraOpts {
  66. switch k := op.(type) {
  67. case provisioner.CertificateValidator:
  68. certValidators = append(certValidators, k)
  69. case provisioner.CertificateRequestValidator:
  70. if err := k.Valid(csr); err != nil {
  71. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  72. }
  73. case provisioner.ProfileModifier:
  74. mods = append(mods, k.Option(signOpts))
  75. case provisioner.CertificateEnforcer:
  76. forcedModifiers = append(forcedModifiers, k)
  77. default:
  78. return nil, errs.InternalServer("authority.Sign; invalid extra option type %T", append([]interface{}{k}, opts...)...)
  79. }
  80. }
  81. if err := csr.CheckSignature(); err != nil {
  82. return nil, errs.Wrap(http.StatusBadRequest, err, "authority.Sign; invalid certificate request", opts...)
  83. }
  84. leaf, err := x509util.NewLeafProfileWithCSR(csr, a.x509Issuer, a.x509Signer, mods...)
  85. if err != nil {
  86. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign", opts...)
  87. }
  88. // Certificate validation
  89. for _, v := range certValidators {
  90. if err := v.Valid(leaf.Subject(), signOpts); err != nil {
  91. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  92. }
  93. }
  94. // Certificate modifiers after validation
  95. for _, m := range forcedModifiers {
  96. if err := m.Enforce(leaf.Subject()); err != nil {
  97. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.Sign", opts...)
  98. }
  99. }
  100. crtBytes, err := leaf.CreateCertificate()
  101. if err != nil {
  102. return nil, errs.Wrap(http.StatusInternalServerError, err,
  103. "authority.Sign; error creating new leaf certificate", opts...)
  104. }
  105. serverCert, err := x509.ParseCertificate(crtBytes)
  106. if err != nil {
  107. return nil, errs.Wrap(http.StatusInternalServerError, err,
  108. "authority.Sign; error parsing new leaf certificate", opts...)
  109. }
  110. if err = a.db.StoreCertificate(serverCert); err != nil {
  111. if err != db.ErrNotImplemented {
  112. return nil, errs.Wrap(http.StatusInternalServerError, err,
  113. "authority.Sign; error storing certificate in db", opts...)
  114. }
  115. }
  116. return []*x509.Certificate{serverCert, a.x509Issuer}, nil
  117. }
  118. // Renew creates a new Certificate identical to the old certificate, except
  119. // with a validity window that begins 'now'.
  120. func (a *Authority) Renew(oldCert *x509.Certificate) ([]*x509.Certificate, error) {
  121. return a.Rekey(oldCert, nil)
  122. }
  123. // Rekey is used for rekeying and renewing based on the public key.
  124. // If the public key is 'nil' then it's assumed that the cert should be renewed
  125. // using the existing public key. If the public key is not 'nil' then it's
  126. // assumed that the cert should be rekeyed.
  127. // For both Rekey and Renew all other attributes of the new certificate should
  128. // match the old certificate. The exceptions are 'AuthorityKeyId' (which may
  129. // have changed), 'SubjectKeyId' (different in case of rekey), and
  130. // 'NotBefore/NotAfter' (the validity duration of the new certificate should be
  131. // equal to the old one, but starting 'now').
  132. func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  133. isRekey := (pk != nil)
  134. opts := []interface{}{errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String())}
  135. // Check step provisioner extensions
  136. if err := a.authorizeRenew(oldCert); err != nil {
  137. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  138. }
  139. // Durations
  140. backdate := a.config.AuthorityConfig.Backdate.Duration
  141. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  142. now := time.Now().UTC()
  143. newCert := &x509.Certificate{
  144. Issuer: a.x509Issuer.Subject,
  145. Subject: oldCert.Subject,
  146. NotBefore: now.Add(-1 * backdate),
  147. NotAfter: now.Add(duration - backdate),
  148. KeyUsage: oldCert.KeyUsage,
  149. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  150. ExtKeyUsage: oldCert.ExtKeyUsage,
  151. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  152. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  153. IsCA: oldCert.IsCA,
  154. MaxPathLen: oldCert.MaxPathLen,
  155. MaxPathLenZero: oldCert.MaxPathLenZero,
  156. OCSPServer: oldCert.OCSPServer,
  157. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  158. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  159. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  160. DNSNames: oldCert.DNSNames,
  161. EmailAddresses: oldCert.EmailAddresses,
  162. IPAddresses: oldCert.IPAddresses,
  163. URIs: oldCert.URIs,
  164. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  165. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  166. PermittedIPRanges: oldCert.PermittedIPRanges,
  167. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  168. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  169. PermittedURIDomains: oldCert.PermittedURIDomains,
  170. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  171. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  172. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  173. }
  174. if isRekey {
  175. newCert.PublicKey = pk
  176. } else {
  177. newCert.PublicKey = oldCert.PublicKey
  178. }
  179. // Copy all extensions except:
  180. // 1. Authority Key Identifier - This one might be different if we rotate the intermediate certificate
  181. // and it will cause a TLS bad certificate error.
  182. // 2. Subject Key Identifier, if rekey - For rekey, SubjectKeyIdentifier extension will be calculated
  183. // for the new public key by NewLeafProfilewithTemplate()
  184. for _, ext := range oldCert.Extensions {
  185. if ext.Id.Equal(oidAuthorityKeyIdentifier) {
  186. continue
  187. }
  188. if ext.Id.Equal(oidSubjectKeyIdentifier) && isRekey {
  189. newCert.SubjectKeyId = nil
  190. continue
  191. }
  192. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  193. }
  194. leaf, err := x509util.NewLeafProfileWithTemplate(newCert, a.x509Issuer, a.x509Signer)
  195. if err != nil {
  196. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  197. }
  198. crtBytes, err := leaf.CreateCertificate()
  199. if err != nil {
  200. return nil, errs.Wrap(http.StatusInternalServerError, err,
  201. "authority.Rekey; error renewing certificate from existing server certificate", opts...)
  202. }
  203. serverCert, err := x509.ParseCertificate(crtBytes)
  204. if err != nil {
  205. return nil, errs.Wrap(http.StatusInternalServerError, err,
  206. "authority.Rekey; error parsing new server certificate", opts...)
  207. }
  208. if err = a.db.StoreCertificate(serverCert); err != nil {
  209. if err != db.ErrNotImplemented {
  210. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey; error storing certificate in db", opts...)
  211. }
  212. }
  213. return []*x509.Certificate{serverCert, a.x509Issuer}, nil
  214. }
  215. // RevokeOptions are the options for the Revoke API.
  216. type RevokeOptions struct {
  217. Serial string
  218. Reason string
  219. ReasonCode int
  220. PassiveOnly bool
  221. MTLS bool
  222. Crt *x509.Certificate
  223. OTT string
  224. }
  225. // Revoke revokes a certificate.
  226. //
  227. // NOTE: Only supports passive revocation - prevent existing certificates from
  228. // being renewed.
  229. //
  230. // TODO: Add OCSP and CRL support.
  231. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  232. opts := []interface{}{
  233. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  234. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  235. errs.WithKeyVal("reason", revokeOpts.Reason),
  236. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  237. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  238. errs.WithKeyVal("context", string(provisioner.MethodFromContext(ctx))),
  239. }
  240. if revokeOpts.MTLS {
  241. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  242. } else {
  243. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  244. }
  245. rci := &db.RevokedCertificateInfo{
  246. Serial: revokeOpts.Serial,
  247. ReasonCode: revokeOpts.ReasonCode,
  248. Reason: revokeOpts.Reason,
  249. MTLS: revokeOpts.MTLS,
  250. RevokedAt: time.Now().UTC(),
  251. }
  252. var (
  253. p provisioner.Interface
  254. err error
  255. )
  256. // If not mTLS then get the TokenID of the token.
  257. if !revokeOpts.MTLS {
  258. token, err := jose.ParseSigned(revokeOpts.OTT)
  259. if err != nil {
  260. return errs.Wrap(http.StatusUnauthorized, err,
  261. "authority.Revoke; error parsing token", opts...)
  262. }
  263. // Get claims w/out verification.
  264. var claims Claims
  265. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  266. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  267. }
  268. // This method will also validate the audiences for JWK provisioners.
  269. var ok bool
  270. p, ok = a.provisioners.LoadByToken(token, &claims.Claims)
  271. if !ok {
  272. return errs.InternalServer("authority.Revoke; provisioner not found", opts...)
  273. }
  274. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  275. if err != nil {
  276. return errs.Wrap(http.StatusInternalServerError, err,
  277. "authority.Revoke; could not get ID for token")
  278. }
  279. opts = append(opts, errs.WithKeyVal("tokenID", rci.TokenID))
  280. } else {
  281. // Load the Certificate provisioner if one exists.
  282. p, err = a.LoadProvisionerByCertificate(revokeOpts.Crt)
  283. if err != nil {
  284. return errs.Wrap(http.StatusUnauthorized, err,
  285. "authority.Revoke: unable to load certificate provisioner", opts...)
  286. }
  287. }
  288. rci.ProvisionerID = p.GetID()
  289. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  290. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  291. err = a.db.RevokeSSH(rci)
  292. } else { // default to revoke x509
  293. err = a.db.Revoke(rci)
  294. }
  295. switch err {
  296. case nil:
  297. return nil
  298. case db.ErrNotImplemented:
  299. return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...)
  300. case db.ErrAlreadyExists:
  301. return errs.BadRequest("authority.Revoke; certificate with serial "+
  302. "number %s has already been revoked", append([]interface{}{rci.Serial}, opts...)...)
  303. default:
  304. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  305. }
  306. }
  307. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  308. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  309. profile, err := x509util.NewLeafProfile("Step Online CA", a.x509Issuer, a.x509Signer,
  310. x509util.WithHosts(strings.Join(a.config.DNSNames, ",")))
  311. if err != nil {
  312. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  313. }
  314. crtBytes, err := profile.CreateCertificate()
  315. if err != nil {
  316. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  317. }
  318. keyPEM, err := pemutil.Serialize(profile.SubjectPrivateKey())
  319. if err != nil {
  320. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  321. }
  322. crtPEM := pem.EncodeToMemory(&pem.Block{
  323. Type: "CERTIFICATE",
  324. Bytes: crtBytes,
  325. })
  326. // Load the x509 key pair (combining server and intermediate blocks)
  327. // to a tls.Certificate.
  328. intermediatePEM, err := pemutil.Serialize(a.x509Issuer)
  329. if err != nil {
  330. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  331. }
  332. tlsCrt, err := tls.X509KeyPair(append(crtPEM,
  333. pem.EncodeToMemory(intermediatePEM)...),
  334. pem.EncodeToMemory(keyPEM))
  335. if err != nil {
  336. return nil, errs.Wrap(http.StatusInternalServerError, err,
  337. "authority.GetTLSCertificate; error creating tls certificate")
  338. }
  339. // Get the 'leaf' certificate and set the attribute accordingly.
  340. leaf, err := x509.ParseCertificate(tlsCrt.Certificate[0])
  341. if err != nil {
  342. return nil, errs.Wrap(http.StatusInternalServerError, err,
  343. "authority.GetTLSCertificate; error parsing tls certificate")
  344. }
  345. tlsCrt.Leaf = leaf
  346. return &tlsCrt, nil
  347. }