revoke.go 9.8 KB

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