tls.go 11 KB

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