tls.go 12 KB

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