middleware.go 15 KB

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