middleware.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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/pkg/errors"
  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(), acme.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.Auth.NewNonce()
  58. if err != nil {
  59. api.WriteError(w, err)
  60. return
  61. }
  62. w.Header().Set("Replay-Nonce", nonce)
  63. w.Header().Set("Cache-Control", "no-store")
  64. logNonce(w, 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.Auth.GetLink(r.Context(),
  73. acme.DirectoryLink, 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.Auth.GetLink(r.Context(), acme.CertificateLink, 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.MalformedErr(errors.Errorf(
  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.ServerInternalErr(errors.Wrap(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.MalformedErr(errors.Wrap(err, "failed to parse JWS from request body")))
  111. return
  112. }
  113. ctx := context.WithValue(r.Context(), acme.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. jws, err := acme.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.MalformedErr(errors.Errorf("request body does not contain a signature")))
  141. return
  142. }
  143. if len(jws.Signatures) > 1 {
  144. api.WriteError(w, acme.MalformedErr(errors.Errorf("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.MalformedErr(errors.Errorf("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.MalformedErr(errors.Errorf("rsa "+
  165. "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.MalformedErr(errors.Errorf("jws key type and algorithm do not match")))
  171. return
  172. }
  173. }
  174. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  175. // we good
  176. default:
  177. api.WriteError(w, acme.MalformedErr(errors.Errorf("unsuitable algorithm: %s", hdr.Algorithm)))
  178. return
  179. }
  180. // Check the validity/freshness of the Nonce.
  181. if err := h.Auth.UseNonce(hdr.Nonce); err != nil {
  182. api.WriteError(w, err)
  183. return
  184. }
  185. // Check that the JWS url matches the requested url.
  186. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  187. if !ok {
  188. api.WriteError(w, acme.MalformedErr(errors.Errorf("jws missing url protected header")))
  189. return
  190. }
  191. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  192. if jwsURL != reqURL.String() {
  193. api.WriteError(w, acme.MalformedErr(errors.Errorf("url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL)))
  194. return
  195. }
  196. if hdr.JSONWebKey != nil && len(hdr.KeyID) > 0 {
  197. api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk and kid are mutually exclusive")))
  198. return
  199. }
  200. if hdr.JSONWebKey == nil && len(hdr.KeyID) == 0 {
  201. api.WriteError(w, acme.MalformedErr(errors.Errorf("either jwk or kid must be defined in jws protected header")))
  202. return
  203. }
  204. next(w, r)
  205. }
  206. }
  207. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  208. // in the context. Make sure to parse and validate the JWS before running this
  209. // middleware.
  210. func (h *Handler) extractJWK(next nextHTTP) nextHTTP {
  211. return func(w http.ResponseWriter, r *http.Request) {
  212. ctx := r.Context()
  213. jws, err := acme.JwsFromContext(r.Context())
  214. if err != nil {
  215. api.WriteError(w, err)
  216. return
  217. }
  218. jwk := jws.Signatures[0].Protected.JSONWebKey
  219. if jwk == nil {
  220. api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk expected in protected header")))
  221. return
  222. }
  223. if !jwk.Valid() {
  224. api.WriteError(w, acme.MalformedErr(errors.Errorf("invalid jwk in protected header")))
  225. return
  226. }
  227. ctx = context.WithValue(ctx, acme.JwkContextKey, jwk)
  228. acc, err := h.Auth.GetAccountByKey(ctx, jwk)
  229. switch {
  230. case nosql.IsErrNotFound(err):
  231. // For NewAccount requests ...
  232. break
  233. case err != nil:
  234. api.WriteError(w, err)
  235. return
  236. default:
  237. if !acc.IsValid() {
  238. api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
  239. return
  240. }
  241. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  242. }
  243. next(w, r.WithContext(ctx))
  244. }
  245. }
  246. // lookupProvisioner loads the provisioner associated with the request.
  247. // Responsds 404 if the provisioner does not exist.
  248. func (h *Handler) lookupProvisioner(next nextHTTP) nextHTTP {
  249. return func(w http.ResponseWriter, r *http.Request) {
  250. ctx := r.Context()
  251. name := chi.URLParam(r, "provisionerID")
  252. provID, err := url.PathUnescape(name)
  253. if err != nil {
  254. api.WriteError(w, acme.ServerInternalErr(errors.Wrapf(err, "error url unescaping provisioner id '%s'", name)))
  255. return
  256. }
  257. p, err := h.Auth.LoadProvisionerByID("acme/" + provID)
  258. if err != nil {
  259. api.WriteError(w, err)
  260. return
  261. }
  262. acmeProv, ok := p.(*provisioner.ACME)
  263. if !ok {
  264. api.WriteError(w, acme.AccountDoesNotExistErr(errors.New("provisioner must be of type ACME")))
  265. return
  266. }
  267. ctx = context.WithValue(ctx, acme.ProvisionerContextKey, acme.Provisioner(acmeProv))
  268. next(w, r.WithContext(ctx))
  269. }
  270. }
  271. // lookupJWK loads the JWK associated with the acme account referenced by the
  272. // kid parameter of the signed payload.
  273. // Make sure to parse and validate the JWS before running this middleware.
  274. func (h *Handler) lookupJWK(next nextHTTP) nextHTTP {
  275. return func(w http.ResponseWriter, r *http.Request) {
  276. ctx := r.Context()
  277. jws, err := acme.JwsFromContext(ctx)
  278. if err != nil {
  279. api.WriteError(w, err)
  280. return
  281. }
  282. kidPrefix := h.Auth.GetLink(ctx, acme.AccountLink, true, "")
  283. kid := jws.Signatures[0].Protected.KeyID
  284. if !strings.HasPrefix(kid, kidPrefix) {
  285. api.WriteError(w, acme.MalformedErr(errors.Errorf("kid does not have "+
  286. "required prefix; expected %s, but got %s", kidPrefix, kid)))
  287. return
  288. }
  289. accID := strings.TrimPrefix(kid, kidPrefix)
  290. acc, err := h.Auth.GetAccount(r.Context(), accID)
  291. switch {
  292. case nosql.IsErrNotFound(err):
  293. api.WriteError(w, acme.AccountDoesNotExistErr(nil))
  294. return
  295. case err != nil:
  296. api.WriteError(w, err)
  297. return
  298. default:
  299. if !acc.IsValid() {
  300. api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
  301. return
  302. }
  303. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  304. ctx = context.WithValue(ctx, acme.JwkContextKey, acc.Key)
  305. next(w, r.WithContext(ctx))
  306. return
  307. }
  308. }
  309. }
  310. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  311. // Make sure to parse and validate the JWS before running this middleware.
  312. func (h *Handler) verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  313. return func(w http.ResponseWriter, r *http.Request) {
  314. jws, err := acme.JwsFromContext(r.Context())
  315. if err != nil {
  316. api.WriteError(w, err)
  317. return
  318. }
  319. jwk, err := acme.JwkFromContext(r.Context())
  320. if err != nil {
  321. api.WriteError(w, err)
  322. return
  323. }
  324. if len(jwk.Algorithm) != 0 && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  325. api.WriteError(w, acme.MalformedErr(errors.New("verifier and signature algorithm do not match")))
  326. return
  327. }
  328. payload, err := jws.Verify(jwk)
  329. if err != nil {
  330. api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "error verifying jws")))
  331. return
  332. }
  333. ctx := context.WithValue(r.Context(), acme.PayloadContextKey, &payloadInfo{
  334. value: payload,
  335. isPostAsGet: string(payload) == "",
  336. isEmptyJSON: string(payload) == "{}",
  337. })
  338. next(w, r.WithContext(ctx))
  339. }
  340. }
  341. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  342. func (h *Handler) isPostAsGet(next nextHTTP) nextHTTP {
  343. return func(w http.ResponseWriter, r *http.Request) {
  344. payload, err := payloadFromContext(r.Context())
  345. if err != nil {
  346. api.WriteError(w, err)
  347. return
  348. }
  349. if !payload.isPostAsGet {
  350. api.WriteError(w, acme.MalformedErr(errors.Errorf("expected POST-as-GET")))
  351. return
  352. }
  353. next(w, r)
  354. }
  355. }