tls.go 13 KB

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