middleware.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. package api
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "strings"
  11. "go.step.sm/crypto/jose"
  12. "go.step.sm/crypto/keyutil"
  13. "github.com/smallstep/certificates/acme"
  14. "github.com/smallstep/certificates/api/render"
  15. "github.com/smallstep/certificates/authority/provisioner"
  16. "github.com/smallstep/certificates/logging"
  17. )
  18. type nextHTTP = func(http.ResponseWriter, *http.Request)
  19. func logNonce(w http.ResponseWriter, nonce string) {
  20. if rl, ok := w.(logging.ResponseLogger); ok {
  21. m := map[string]interface{}{
  22. "nonce": nonce,
  23. }
  24. rl.WithFields(m)
  25. }
  26. }
  27. // addNonce is a middleware that adds a nonce to the response header.
  28. func addNonce(next nextHTTP) nextHTTP {
  29. return func(w http.ResponseWriter, r *http.Request) {
  30. db := acme.MustDatabaseFromContext(r.Context())
  31. nonce, err := db.CreateNonce(r.Context())
  32. if err != nil {
  33. render.Error(w, err)
  34. return
  35. }
  36. w.Header().Set("Replay-Nonce", string(nonce))
  37. w.Header().Set("Cache-Control", "no-store")
  38. logNonce(w, string(nonce))
  39. next(w, r)
  40. }
  41. }
  42. // addDirLink is a middleware that adds a 'Link' response reader with the
  43. // directory index url.
  44. func addDirLink(next nextHTTP) nextHTTP {
  45. return func(w http.ResponseWriter, r *http.Request) {
  46. ctx := r.Context()
  47. linker := acme.MustLinkerFromContext(ctx)
  48. w.Header().Add("Link", link(linker.GetLink(ctx, acme.DirectoryLinkType), "index"))
  49. next(w, r)
  50. }
  51. }
  52. // verifyContentType is a middleware that verifies that content type is
  53. // application/jose+json.
  54. func verifyContentType(next nextHTTP) nextHTTP {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. p, err := provisionerFromContext(r.Context())
  57. if err != nil {
  58. render.Error(w, err)
  59. return
  60. }
  61. u := &url.URL{
  62. Path: acme.GetUnescapedPathSuffix(acme.CertificateLinkType, p.GetName(), ""),
  63. }
  64. var expected []string
  65. if strings.Contains(r.URL.String(), u.EscapedPath()) {
  66. // GET /certificate requests allow a greater range of content types.
  67. expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
  68. } else {
  69. // By default every request should have content-type applictaion/jose+json.
  70. expected = []string{"application/jose+json"}
  71. }
  72. ct := r.Header.Get("Content-Type")
  73. for _, e := range expected {
  74. if ct == e {
  75. next(w, r)
  76. return
  77. }
  78. }
  79. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  80. "expected content-type to be in %s, but got %s", expected, ct))
  81. }
  82. }
  83. // parseJWS is a middleware that parses a request body into a JSONWebSignature struct.
  84. func parseJWS(next nextHTTP) nextHTTP {
  85. return func(w http.ResponseWriter, r *http.Request) {
  86. body, err := io.ReadAll(r.Body)
  87. if err != nil {
  88. render.Error(w, acme.WrapErrorISE(err, "failed to read request body"))
  89. return
  90. }
  91. jws, err := jose.ParseJWS(string(body))
  92. if err != nil {
  93. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err, "failed to parse JWS from request body"))
  94. return
  95. }
  96. ctx := context.WithValue(r.Context(), jwsContextKey, jws)
  97. next(w, r.WithContext(ctx))
  98. }
  99. }
  100. // validateJWS checks the request body for to verify that it meets ACME
  101. // requirements for a JWS.
  102. //
  103. // The JWS MUST NOT have multiple signatures
  104. // The JWS Unencoded Payload Option [RFC7797] MUST NOT be used
  105. // The JWS Unprotected Header [RFC7515] MUST NOT be used
  106. // The JWS Payload MUST NOT be detached
  107. // The JWS Protected Header MUST include the following fields:
  108. // - “alg” (Algorithm).
  109. // This field MUST NOT contain “none” or a Message Authentication Code
  110. // (MAC) algorithm (e.g. one in which the algorithm registry description
  111. // mentions MAC/HMAC).
  112. // - “nonce” (defined in Section 6.5)
  113. // - “url” (defined in Section 6.4)
  114. // - Either “jwk” (JSON Web Key) or “kid” (Key ID) as specified below<Paste>
  115. func validateJWS(next nextHTTP) nextHTTP {
  116. return func(w http.ResponseWriter, r *http.Request) {
  117. ctx := r.Context()
  118. db := acme.MustDatabaseFromContext(ctx)
  119. jws, err := jwsFromContext(ctx)
  120. if err != nil {
  121. render.Error(w, err)
  122. return
  123. }
  124. if len(jws.Signatures) == 0 {
  125. render.Error(w, acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"))
  126. return
  127. }
  128. if len(jws.Signatures) > 1 {
  129. render.Error(w, acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"))
  130. return
  131. }
  132. sig := jws.Signatures[0]
  133. uh := sig.Unprotected
  134. if len(uh.KeyID) > 0 ||
  135. uh.JSONWebKey != nil ||
  136. len(uh.Algorithm) > 0 ||
  137. len(uh.Nonce) > 0 ||
  138. len(uh.ExtraHeaders) > 0 {
  139. render.Error(w, acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"))
  140. return
  141. }
  142. hdr := sig.Protected
  143. switch hdr.Algorithm {
  144. case jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512:
  145. if hdr.JSONWebKey != nil {
  146. switch k := hdr.JSONWebKey.Key.(type) {
  147. case *rsa.PublicKey:
  148. if k.Size() < keyutil.MinRSAKeyBytes {
  149. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  150. "rsa keys must be at least %d bits (%d bytes) in size",
  151. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes))
  152. return
  153. }
  154. default:
  155. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  156. "jws key type and algorithm do not match"))
  157. return
  158. }
  159. }
  160. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  161. // we good
  162. default:
  163. render.Error(w, acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", hdr.Algorithm))
  164. return
  165. }
  166. // Check the validity/freshness of the Nonce.
  167. if err := db.DeleteNonce(ctx, acme.Nonce(hdr.Nonce)); err != nil {
  168. render.Error(w, err)
  169. return
  170. }
  171. // Check that the JWS url matches the requested url.
  172. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  173. if !ok {
  174. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"))
  175. return
  176. }
  177. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  178. if jwsURL != reqURL.String() {
  179. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  180. "url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL))
  181. return
  182. }
  183. if hdr.JSONWebKey != nil && len(hdr.KeyID) > 0 {
  184. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"))
  185. return
  186. }
  187. if hdr.JSONWebKey == nil && hdr.KeyID == "" {
  188. render.Error(w, acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"))
  189. return
  190. }
  191. next(w, r)
  192. }
  193. }
  194. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  195. // in the context. Make sure to parse and validate the JWS before running this
  196. // middleware.
  197. func extractJWK(next nextHTTP) nextHTTP {
  198. return func(w http.ResponseWriter, r *http.Request) {
  199. ctx := r.Context()
  200. db := acme.MustDatabaseFromContext(ctx)
  201. jws, err := jwsFromContext(ctx)
  202. if err != nil {
  203. render.Error(w, err)
  204. return
  205. }
  206. jwk := jws.Signatures[0].Protected.JSONWebKey
  207. if jwk == nil {
  208. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"))
  209. return
  210. }
  211. if !jwk.Valid() {
  212. render.Error(w, acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"))
  213. return
  214. }
  215. // Overwrite KeyID with the JWK thumbprint.
  216. jwk.KeyID, err = acme.KeyToID(jwk)
  217. if err != nil {
  218. render.Error(w, acme.WrapErrorISE(err, "error getting KeyID from JWK"))
  219. return
  220. }
  221. // Store the JWK in the context.
  222. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  223. // Get Account OR continue to generate a new one OR continue Revoke with certificate private key
  224. acc, err := db.GetAccountByKeyID(ctx, jwk.KeyID)
  225. switch {
  226. case errors.Is(err, acme.ErrNotFound):
  227. // For NewAccount and Revoke requests ...
  228. break
  229. case err != nil:
  230. render.Error(w, err)
  231. return
  232. default:
  233. if !acc.IsValid() {
  234. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  235. return
  236. }
  237. ctx = context.WithValue(ctx, accContextKey, acc)
  238. }
  239. next(w, r.WithContext(ctx))
  240. }
  241. }
  242. // checkPrerequisites checks if all prerequisites for serving ACME
  243. // are met by the CA configuration.
  244. func checkPrerequisites(next nextHTTP) nextHTTP {
  245. return func(w http.ResponseWriter, r *http.Request) {
  246. ctx := r.Context()
  247. // If the function is not set assume that all prerequisites are met.
  248. checkFunc, ok := acme.PrerequisitesCheckerFromContext(ctx)
  249. if ok {
  250. ok, err := checkFunc(ctx)
  251. if err != nil {
  252. render.Error(w, acme.WrapErrorISE(err, "error checking acme provisioner prerequisites"))
  253. return
  254. }
  255. if !ok {
  256. render.Error(w, acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"))
  257. return
  258. }
  259. }
  260. next(w, r)
  261. }
  262. }
  263. // lookupJWK loads the JWK associated with the acme account referenced by the
  264. // kid parameter of the signed payload.
  265. // Make sure to parse and validate the JWS before running this middleware.
  266. func lookupJWK(next nextHTTP) nextHTTP {
  267. return func(w http.ResponseWriter, r *http.Request) {
  268. ctx := r.Context()
  269. db := acme.MustDatabaseFromContext(ctx)
  270. jws, err := jwsFromContext(ctx)
  271. if err != nil {
  272. render.Error(w, err)
  273. return
  274. }
  275. kid := jws.Signatures[0].Protected.KeyID
  276. if kid == "" {
  277. render.Error(w, acme.NewError(acme.ErrorMalformedType, "signature missing 'kid'"))
  278. return
  279. }
  280. accID := path.Base(kid)
  281. acc, err := db.GetAccount(ctx, accID)
  282. switch {
  283. case acme.IsErrNotFound(err):
  284. render.Error(w, acme.NewError(acme.ErrorAccountDoesNotExistType, "account with ID '%s' not found", accID))
  285. return
  286. case err != nil:
  287. render.Error(w, err)
  288. return
  289. default:
  290. if !acc.IsValid() {
  291. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  292. return
  293. }
  294. if storedLocation := acc.GetLocation(); storedLocation != "" {
  295. if kid != storedLocation {
  296. // ACME accounts should have a stored location equivalent to the
  297. // kid in the ACME request.
  298. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  299. "kid does not match stored account location; expected %s, but got %s",
  300. storedLocation, kid))
  301. return
  302. }
  303. // Verify that the provisioner with which the account was created
  304. // matches the provisioner in the request URL.
  305. reqProv := acme.MustProvisionerFromContext(ctx)
  306. reqProvName := reqProv.GetName()
  307. accProvName := acc.ProvisionerName
  308. if reqProvName != accProvName {
  309. // Provisioner in the URL must match the provisioner with
  310. // which the account was created.
  311. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  312. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  313. accProvName, reqProvName))
  314. return
  315. }
  316. } else {
  317. // This code will only execute for old ACME accounts that do
  318. // not have a cached location. The following validation was
  319. // the original implementation of the `kid` check which has
  320. // since been deprecated. However, the code will remain to
  321. // ensure consistent behavior for old ACME accounts.
  322. linker := acme.MustLinkerFromContext(ctx)
  323. kidPrefix := linker.GetLink(ctx, acme.AccountLinkType, "")
  324. if !strings.HasPrefix(kid, kidPrefix) {
  325. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  326. "kid does not have required prefix; expected %s, but got %s",
  327. kidPrefix, kid))
  328. return
  329. }
  330. }
  331. ctx = context.WithValue(ctx, accContextKey, acc)
  332. ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
  333. next(w, r.WithContext(ctx))
  334. return
  335. }
  336. }
  337. }
  338. // extractOrLookupJWK forwards handling to either extractJWK or
  339. // lookupJWK based on the presence of a JWK or a KID, respectively.
  340. func extractOrLookupJWK(next nextHTTP) nextHTTP {
  341. return func(w http.ResponseWriter, r *http.Request) {
  342. ctx := r.Context()
  343. jws, err := jwsFromContext(ctx)
  344. if err != nil {
  345. render.Error(w, err)
  346. return
  347. }
  348. // at this point the JWS has already been verified (if correctly configured in middleware),
  349. // and it can be used to check if a JWK exists. This flow is used when the ACME client
  350. // signed the payload with a certificate private key.
  351. if canExtractJWKFrom(jws) {
  352. extractJWK(next)(w, r)
  353. return
  354. }
  355. // default to looking up the JWK based on KeyID. This flow is used when the ACME client
  356. // signed the payload with an account private key.
  357. lookupJWK(next)(w, r)
  358. }
  359. }
  360. // canExtractJWKFrom checks if the JWS has a JWK that can be extracted
  361. func canExtractJWKFrom(jws *jose.JSONWebSignature) bool {
  362. if jws == nil {
  363. return false
  364. }
  365. if len(jws.Signatures) == 0 {
  366. return false
  367. }
  368. return jws.Signatures[0].Protected.JSONWebKey != nil
  369. }
  370. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  371. // Make sure to parse and validate the JWS before running this middleware.
  372. func verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  373. return func(w http.ResponseWriter, r *http.Request) {
  374. ctx := r.Context()
  375. jws, err := jwsFromContext(ctx)
  376. if err != nil {
  377. render.Error(w, err)
  378. return
  379. }
  380. jwk, err := jwkFromContext(ctx)
  381. if err != nil {
  382. render.Error(w, err)
  383. return
  384. }
  385. if jwk.Algorithm != "" && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  386. render.Error(w, acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"))
  387. return
  388. }
  389. payload, err := jws.Verify(jwk)
  390. if err != nil {
  391. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws"))
  392. return
  393. }
  394. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{
  395. value: payload,
  396. isPostAsGet: len(payload) == 0,
  397. isEmptyJSON: string(payload) == "{}",
  398. })
  399. next(w, r.WithContext(ctx))
  400. }
  401. }
  402. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  403. func isPostAsGet(next nextHTTP) nextHTTP {
  404. return func(w http.ResponseWriter, r *http.Request) {
  405. payload, err := payloadFromContext(r.Context())
  406. if err != nil {
  407. render.Error(w, err)
  408. return
  409. }
  410. if !payload.isPostAsGet {
  411. render.Error(w, acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"))
  412. return
  413. }
  414. next(w, r)
  415. }
  416. }
  417. // ContextKey is the key type for storing and searching for ACME request
  418. // essentials in the context of a request.
  419. type ContextKey string
  420. const (
  421. // accContextKey account key
  422. accContextKey = ContextKey("acc")
  423. // jwsContextKey jws key
  424. jwsContextKey = ContextKey("jws")
  425. // jwkContextKey jwk key
  426. jwkContextKey = ContextKey("jwk")
  427. // payloadContextKey payload key
  428. payloadContextKey = ContextKey("payload")
  429. )
  430. // accountFromContext searches the context for an ACME account. Returns the
  431. // account or an error.
  432. func accountFromContext(ctx context.Context) (*acme.Account, error) {
  433. val, ok := ctx.Value(accContextKey).(*acme.Account)
  434. if !ok || val == nil {
  435. return nil, acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context")
  436. }
  437. return val, nil
  438. }
  439. // jwkFromContext searches the context for a JWK. Returns the JWK or an error.
  440. func jwkFromContext(ctx context.Context) (*jose.JSONWebKey, error) {
  441. val, ok := ctx.Value(jwkContextKey).(*jose.JSONWebKey)
  442. if !ok || val == nil {
  443. return nil, acme.NewErrorISE("jwk expected in request context")
  444. }
  445. return val, nil
  446. }
  447. // jwsFromContext searches the context for a JWS. Returns the JWS or an error.
  448. func jwsFromContext(ctx context.Context) (*jose.JSONWebSignature, error) {
  449. val, ok := ctx.Value(jwsContextKey).(*jose.JSONWebSignature)
  450. if !ok || val == nil {
  451. return nil, acme.NewErrorISE("jws expected in request context")
  452. }
  453. return val, nil
  454. }
  455. // provisionerFromContext searches the context for a provisioner. Returns the
  456. // provisioner or an error.
  457. func provisionerFromContext(ctx context.Context) (acme.Provisioner, error) {
  458. p, ok := acme.ProvisionerFromContext(ctx)
  459. if !ok || p == nil {
  460. return nil, acme.NewErrorISE("provisioner expected in request context")
  461. }
  462. return p, nil
  463. }
  464. // acmeProvisionerFromContext searches the context for an ACME provisioner. Returns
  465. // pointer to an ACME provisioner or an error.
  466. func acmeProvisionerFromContext(ctx context.Context) (*provisioner.ACME, error) {
  467. p, err := provisionerFromContext(ctx)
  468. if err != nil {
  469. return nil, err
  470. }
  471. ap, ok := p.(*provisioner.ACME)
  472. if !ok {
  473. return nil, acme.NewErrorISE("provisioner in context is not an ACME provisioner")
  474. }
  475. return ap, nil
  476. }
  477. // payloadFromContext searches the context for a payload. Returns the payload
  478. // or an error.
  479. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  480. val, ok := ctx.Value(payloadContextKey).(*payloadInfo)
  481. if !ok || val == nil {
  482. return nil, acme.NewErrorISE("payload expected in request context")
  483. }
  484. return val, nil
  485. }