revoke.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "go.step.sm/crypto/jose"
  12. "golang.org/x/crypto/ocsp"
  13. "github.com/smallstep/certificates/acme"
  14. "github.com/smallstep/certificates/api/render"
  15. "github.com/smallstep/certificates/authority"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. "github.com/smallstep/certificates/logging"
  18. )
  19. type revokePayload struct {
  20. Certificate string `json:"certificate"`
  21. ReasonCode *int `json:"reason,omitempty"`
  22. }
  23. // RevokeCert attempts to revoke a certificate.
  24. func RevokeCert(w http.ResponseWriter, r *http.Request) {
  25. ctx := r.Context()
  26. db := acme.MustDatabaseFromContext(ctx)
  27. linker := acme.MustLinkerFromContext(ctx)
  28. jws, err := jwsFromContext(ctx)
  29. if err != nil {
  30. render.Error(w, err)
  31. return
  32. }
  33. prov, err := provisionerFromContext(ctx)
  34. if err != nil {
  35. render.Error(w, err)
  36. return
  37. }
  38. payload, err := payloadFromContext(ctx)
  39. if err != nil {
  40. render.Error(w, err)
  41. return
  42. }
  43. var p revokePayload
  44. err = json.Unmarshal(payload.value, &p)
  45. if err != nil {
  46. render.Error(w, acme.WrapErrorISE(err, "error unmarshaling payload"))
  47. return
  48. }
  49. certBytes, err := base64.RawURLEncoding.DecodeString(p.Certificate)
  50. if err != nil {
  51. // in this case the most likely cause is a client that didn't properly encode the certificate
  52. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err, "error base64url decoding payload certificate property"))
  53. return
  54. }
  55. certToBeRevoked, err := x509.ParseCertificate(certBytes)
  56. if err != nil {
  57. // in this case a client may have encoded something different than a certificate
  58. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err, "error parsing certificate"))
  59. return
  60. }
  61. serial := certToBeRevoked.SerialNumber.String()
  62. dbCert, err := db.GetCertificateBySerial(ctx, serial)
  63. if err != nil {
  64. render.Error(w, acme.WrapErrorISE(err, "error retrieving certificate by serial"))
  65. return
  66. }
  67. if !bytes.Equal(dbCert.Leaf.Raw, certToBeRevoked.Raw) {
  68. // this should never happen
  69. render.Error(w, acme.NewErrorISE("certificate raw bytes are not equal"))
  70. return
  71. }
  72. if shouldCheckAccountFrom(jws) {
  73. account, err := accountFromContext(ctx)
  74. if err != nil {
  75. render.Error(w, err)
  76. return
  77. }
  78. acmeErr := isAccountAuthorized(ctx, dbCert, certToBeRevoked, account)
  79. if acmeErr != nil {
  80. render.Error(w, acmeErr)
  81. return
  82. }
  83. } else {
  84. // if account doesn't need to be checked, the JWS should be verified to be signed by the
  85. // private key that belongs to the public key in the certificate to be revoked.
  86. _, err := jws.Verify(certToBeRevoked.PublicKey)
  87. if err != nil {
  88. // TODO(hs): possible to determine an error vs. unauthorized and thus provide an ISE vs. Unauthorized?
  89. render.Error(w, wrapUnauthorizedError(certToBeRevoked, nil, "verification of jws using certificate public key failed", err))
  90. return
  91. }
  92. }
  93. ca := mustAuthority(ctx)
  94. hasBeenRevokedBefore, err := ca.IsRevoked(serial)
  95. if err != nil {
  96. render.Error(w, acme.WrapErrorISE(err, "error retrieving revocation status of certificate"))
  97. return
  98. }
  99. if hasBeenRevokedBefore {
  100. render.Error(w, acme.NewError(acme.ErrorAlreadyRevokedType, "certificate was already revoked"))
  101. return
  102. }
  103. reasonCode := p.ReasonCode
  104. acmeErr := validateReasonCode(reasonCode)
  105. if acmeErr != nil {
  106. render.Error(w, acmeErr)
  107. return
  108. }
  109. // Authorize revocation by ACME provisioner
  110. ctx = provisioner.NewContextWithMethod(ctx, provisioner.RevokeMethod)
  111. err = prov.AuthorizeRevoke(ctx, "")
  112. if err != nil {
  113. render.Error(w, acme.WrapErrorISE(err, "error authorizing revocation on provisioner"))
  114. return
  115. }
  116. options := revokeOptions(serial, certToBeRevoked, reasonCode)
  117. err = ca.Revoke(ctx, options)
  118. if err != nil {
  119. render.Error(w, wrapRevokeErr(err))
  120. return
  121. }
  122. logRevoke(w, options)
  123. w.Header().Add("Link", link(linker.GetLink(ctx, acme.DirectoryLinkType), "index"))
  124. w.Write(nil)
  125. }
  126. // isAccountAuthorized checks if an ACME account that was retrieved earlier is authorized
  127. // to revoke the certificate. An Account must always be valid in order to revoke a certificate.
  128. // In case the certificate retrieved from the database belongs to the Account, the Account is
  129. // authorized. If the certificate retrieved from the database doesn't belong to the Account,
  130. // the identifiers in the certificate are extracted and compared against the (valid) Authorizations
  131. // that are stored for the ACME Account. If these sets match, the Account is considered authorized
  132. // to revoke the certificate. If this check fails, the client will receive an unauthorized error.
  133. func isAccountAuthorized(_ context.Context, dbCert *acme.Certificate, certToBeRevoked *x509.Certificate, account *acme.Account) *acme.Error {
  134. if !account.IsValid() {
  135. return wrapUnauthorizedError(certToBeRevoked, nil, fmt.Sprintf("account '%s' has status '%s'", account.ID, account.Status), nil)
  136. }
  137. certificateBelongsToAccount := dbCert.AccountID == account.ID
  138. if certificateBelongsToAccount {
  139. return nil // return early
  140. }
  141. // TODO(hs): according to RFC8555: 7.6, a server MUST consider the following accounts authorized
  142. // to revoke a certificate:
  143. //
  144. // o the account that issued the certificate.
  145. // o an account that holds authorizations for all of the identifiers in the certificate.
  146. //
  147. // We currently only support the first case. The second might result in step going OOM when
  148. // large numbers of Authorizations are involved when the current nosql interface is in use.
  149. // We want to protect users from this failure scenario, so that's why it hasn't been added yet.
  150. // This issue is tracked in https://github.com/smallstep/certificates/issues/767
  151. // not authorized; fail closed.
  152. return wrapUnauthorizedError(certToBeRevoked, nil, fmt.Sprintf("account '%s' is not authorized", account.ID), nil)
  153. }
  154. // wrapRevokeErr is a best effort implementation to transform an error during
  155. // revocation into an ACME error, so that clients can understand the error.
  156. func wrapRevokeErr(err error) *acme.Error {
  157. t := err.Error()
  158. if strings.Contains(t, "is already revoked") {
  159. return acme.NewError(acme.ErrorAlreadyRevokedType, t)
  160. }
  161. return acme.WrapErrorISE(err, "error when revoking certificate")
  162. }
  163. // unauthorizedError returns an ACME error indicating the request was
  164. // not authorized to revoke the certificate.
  165. func wrapUnauthorizedError(cert *x509.Certificate, unauthorizedIdentifiers []acme.Identifier, msg string, err error) *acme.Error {
  166. var acmeErr *acme.Error
  167. if err == nil {
  168. acmeErr = acme.NewError(acme.ErrorUnauthorizedType, msg)
  169. } else {
  170. acmeErr = acme.WrapError(acme.ErrorUnauthorizedType, err, msg)
  171. }
  172. acmeErr.Status = http.StatusForbidden // RFC8555 7.6 shows example with 403
  173. switch {
  174. case len(unauthorizedIdentifiers) > 0:
  175. identifier := unauthorizedIdentifiers[0] // picking the first; compound may be an option too?
  176. acmeErr.Detail = fmt.Sprintf("No authorization provided for name %s", identifier.Value)
  177. case cert.Subject.String() != "":
  178. acmeErr.Detail = fmt.Sprintf("No authorization provided for name %s", cert.Subject.CommonName)
  179. default:
  180. acmeErr.Detail = "No authorization provided"
  181. }
  182. return acmeErr
  183. }
  184. // logRevoke logs successful revocation of certificate
  185. func logRevoke(w http.ResponseWriter, ri *authority.RevokeOptions) {
  186. if rl, ok := w.(logging.ResponseLogger); ok {
  187. rl.WithFields(map[string]interface{}{
  188. "serial": ri.Serial,
  189. "reasonCode": ri.ReasonCode,
  190. "reason": ri.Reason,
  191. "passiveOnly": ri.PassiveOnly,
  192. "ACME": ri.ACME,
  193. })
  194. }
  195. }
  196. // validateReasonCode validates the revocation reason
  197. func validateReasonCode(reasonCode *int) *acme.Error {
  198. if reasonCode != nil && ((*reasonCode < ocsp.Unspecified || *reasonCode > ocsp.AACompromise) || *reasonCode == 7) {
  199. return acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds")
  200. }
  201. // NOTE: it's possible to add additional requirements to the reason code:
  202. // The server MAY disallow a subset of reasonCodes from being
  203. // used by the user. If a request contains a disallowed reasonCode,
  204. // then the server MUST reject it with the error type
  205. // "urn:ietf:params:acme:error:badRevocationReason"
  206. // No additional checks have been implemented so far.
  207. return nil
  208. }
  209. // revokeOptions determines the RevokeOptions for the Authority to use in revocation
  210. func revokeOptions(serial string, certToBeRevoked *x509.Certificate, reasonCode *int) *authority.RevokeOptions {
  211. opts := &authority.RevokeOptions{
  212. Serial: serial,
  213. ACME: true,
  214. Crt: certToBeRevoked,
  215. }
  216. if reasonCode != nil { // NOTE: when implementing CRL and/or OCSP, and reason code is missing, CRL entry extension should be omitted
  217. opts.Reason = reason(*reasonCode)
  218. opts.ReasonCode = *reasonCode
  219. }
  220. return opts
  221. }
  222. // reason transforms an integer reason code to a
  223. // textual description of the revocation reason.
  224. func reason(reasonCode int) string {
  225. switch reasonCode {
  226. case ocsp.Unspecified:
  227. return "unspecified reason"
  228. case ocsp.KeyCompromise:
  229. return "key compromised"
  230. case ocsp.CACompromise:
  231. return "ca compromised"
  232. case ocsp.AffiliationChanged:
  233. return "affiliation changed"
  234. case ocsp.Superseded:
  235. return "superseded"
  236. case ocsp.CessationOfOperation:
  237. return "cessation of operation"
  238. case ocsp.CertificateHold:
  239. return "certificate hold"
  240. case ocsp.RemoveFromCRL:
  241. return "remove from crl"
  242. case ocsp.PrivilegeWithdrawn:
  243. return "privilege withdrawn"
  244. case ocsp.AACompromise:
  245. return "aa compromised"
  246. default:
  247. return "unspecified reason"
  248. }
  249. }
  250. // shouldCheckAccountFrom indicates whether an account should be
  251. // retrieved from the context, so that it can be used for
  252. // additional checks. This should only be done when no JWK
  253. // can be extracted from the request, as that would indicate
  254. // that the revocation request was signed with a certificate
  255. // key pair (and not an account key pair). Looking up such
  256. // a JWK would result in no Account being found.
  257. func shouldCheckAccountFrom(jws *jose.JSONWebSignature) bool {
  258. return !canExtractJWKFrom(jws)
  259. }