middleware.go 15 KB

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