middleware.go 15 KB

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