middleware.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/cli/crypto/keys"
  16. "github.com/smallstep/cli/jose"
  17. "github.com/smallstep/nosql"
  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. // addNonce is a middleware that adds a nonce to the response header.
  29. func (h *Handler) addNonce(next nextHTTP) nextHTTP {
  30. return func(w http.ResponseWriter, r *http.Request) {
  31. nonce, err := h.Auth.NewNonce()
  32. if err != nil {
  33. api.WriteError(w, err)
  34. return
  35. }
  36. w.Header().Set("Replay-Nonce", nonce)
  37. w.Header().Set("Cache-Control", "no-store")
  38. logNonce(w, 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 (h *Handler) addDirLink(next nextHTTP) nextHTTP {
  45. return func(w http.ResponseWriter, r *http.Request) {
  46. prov, err := provisionerFromContext(r)
  47. if err != nil {
  48. api.WriteError(w, err)
  49. return
  50. }
  51. w.Header().Add("Link", link(h.Auth.GetLink(acme.DirectoryLink, acme.URLSafeProvisionerName(prov), true), "index"))
  52. next(w, r)
  53. }
  54. }
  55. // verifyContentType is a middleware that verifies that content type is
  56. // application/jose+json.
  57. func (h *Handler) verifyContentType(next nextHTTP) nextHTTP {
  58. return func(w http.ResponseWriter, r *http.Request) {
  59. prov, err := provisionerFromContext(r)
  60. if err != nil {
  61. api.WriteError(w, err)
  62. return
  63. }
  64. ct := r.Header.Get("Content-Type")
  65. var expected []string
  66. if strings.Contains(r.URL.Path, h.Auth.GetLink(acme.CertificateLink, acme.URLSafeProvisionerName(prov), false, "")) {
  67. // GET /certificate requests allow a greater range of content types.
  68. expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
  69. } else {
  70. // By default every request should have content-type applictaion/jose+json.
  71. expected = []string{"application/jose+json"}
  72. }
  73. for _, e := range expected {
  74. if ct == e {
  75. next(w, r)
  76. return
  77. }
  78. }
  79. api.WriteError(w, acme.MalformedErr(errors.Errorf(
  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 (h *Handler) parseJWS(next nextHTTP) nextHTTP {
  85. return func(w http.ResponseWriter, r *http.Request) {
  86. body, err := ioutil.ReadAll(r.Body)
  87. if err != nil {
  88. api.WriteError(w, acme.ServerInternalErr(errors.Wrap(err, "failed to read request body")))
  89. return
  90. }
  91. jws, err := jose.ParseJWS(string(body))
  92. if err != nil {
  93. api.WriteError(w, acme.MalformedErr(errors.Wrap(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 (h *Handler) validateJWS(next nextHTTP) nextHTTP {
  116. return func(w http.ResponseWriter, r *http.Request) {
  117. jws, err := jwsFromContext(r)
  118. if err != nil {
  119. api.WriteError(w, err)
  120. return
  121. }
  122. if len(jws.Signatures) == 0 {
  123. api.WriteError(w, acme.MalformedErr(errors.Errorf("request body does not contain a signature")))
  124. return
  125. }
  126. if len(jws.Signatures) > 1 {
  127. api.WriteError(w, acme.MalformedErr(errors.Errorf("request body contains more than one signature")))
  128. return
  129. }
  130. sig := jws.Signatures[0]
  131. uh := sig.Unprotected
  132. if len(uh.KeyID) > 0 ||
  133. uh.JSONWebKey != nil ||
  134. len(uh.Algorithm) > 0 ||
  135. len(uh.Nonce) > 0 ||
  136. len(uh.ExtraHeaders) > 0 {
  137. api.WriteError(w, acme.MalformedErr(errors.Errorf("unprotected header must not be used")))
  138. return
  139. }
  140. hdr := sig.Protected
  141. switch hdr.Algorithm {
  142. case jose.RS256, jose.RS384, jose.RS512:
  143. if hdr.JSONWebKey != nil {
  144. switch k := hdr.JSONWebKey.Key.(type) {
  145. case *rsa.PublicKey:
  146. if k.Size() < keys.MinRSAKeyBytes {
  147. api.WriteError(w, acme.MalformedErr(errors.Errorf("rsa "+
  148. "keys must be at least %d bits (%d bytes) in size",
  149. 8*keys.MinRSAKeyBytes, keys.MinRSAKeyBytes)))
  150. return
  151. }
  152. default:
  153. api.WriteError(w, acme.MalformedErr(errors.Errorf("jws key type and algorithm do not match")))
  154. return
  155. }
  156. }
  157. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  158. // we good
  159. default:
  160. api.WriteError(w, acme.MalformedErr(errors.Errorf("unsuitable algorithm: %s", hdr.Algorithm)))
  161. return
  162. }
  163. // Check the validity/freshness of the Nonce.
  164. if err := h.Auth.UseNonce(hdr.Nonce); err != nil {
  165. api.WriteError(w, err)
  166. return
  167. }
  168. // Check that the JWS url matches the requested url.
  169. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  170. if !ok {
  171. api.WriteError(w, acme.MalformedErr(errors.Errorf("jws missing url protected header")))
  172. return
  173. }
  174. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  175. if jwsURL != reqURL.String() {
  176. api.WriteError(w, acme.MalformedErr(errors.Errorf("url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL)))
  177. return
  178. }
  179. if hdr.JSONWebKey != nil && len(hdr.KeyID) > 0 {
  180. api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk and kid are mutually exclusive")))
  181. return
  182. }
  183. if hdr.JSONWebKey == nil && len(hdr.KeyID) == 0 {
  184. api.WriteError(w, acme.MalformedErr(errors.Errorf("either jwk or kid must be defined in jws protected header")))
  185. return
  186. }
  187. next(w, r)
  188. }
  189. }
  190. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  191. // in the context. Make sure to parse and validate the JWS before running this
  192. // middleware.
  193. func (h *Handler) extractJWK(next nextHTTP) nextHTTP {
  194. return func(w http.ResponseWriter, r *http.Request) {
  195. ctx := r.Context()
  196. prov, err := provisionerFromContext(r)
  197. if err != nil {
  198. api.WriteError(w, err)
  199. return
  200. }
  201. jws, err := jwsFromContext(r)
  202. if err != nil {
  203. api.WriteError(w, err)
  204. return
  205. }
  206. jwk := jws.Signatures[0].Protected.JSONWebKey
  207. if jwk == nil {
  208. api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk expected in protected header")))
  209. return
  210. }
  211. if !jwk.Valid() {
  212. api.WriteError(w, acme.MalformedErr(errors.Errorf("invalid jwk in protected header")))
  213. return
  214. }
  215. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  216. acc, err := h.Auth.GetAccountByKey(prov, jwk)
  217. switch {
  218. case nosql.IsErrNotFound(err):
  219. // For NewAccount requests ...
  220. break
  221. case err != nil:
  222. api.WriteError(w, err)
  223. return
  224. default:
  225. if !acc.IsValid() {
  226. api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
  227. return
  228. }
  229. ctx = context.WithValue(ctx, accContextKey, acc)
  230. }
  231. next(w, r.WithContext(ctx))
  232. }
  233. }
  234. // lookupProvisioner loads the provisioner associated with the request.
  235. // Responsds 404 if the provisioner does not exist.
  236. func (h *Handler) lookupProvisioner(next nextHTTP) nextHTTP {
  237. return func(w http.ResponseWriter, r *http.Request) {
  238. ctx := r.Context()
  239. name := chi.URLParam(r, "provisionerID")
  240. provID, err := url.PathUnescape(name)
  241. if err != nil {
  242. api.WriteError(w, acme.ServerInternalErr(errors.Wrapf(err, "error url unescaping provisioner id '%s'", name)))
  243. return
  244. }
  245. p, err := h.Auth.LoadProvisionerByID("acme/" + provID)
  246. if err != nil {
  247. api.WriteError(w, err)
  248. return
  249. }
  250. if p.GetType() != provisioner.TypeACME {
  251. api.WriteError(w, acme.AccountDoesNotExistErr(errors.New("provisioner must be of type ACME")))
  252. return
  253. }
  254. ctx = context.WithValue(ctx, provisionerContextKey, p)
  255. next(w, r.WithContext(ctx))
  256. }
  257. }
  258. // lookupJWK loads the JWK associated with the acme account referenced by the
  259. // kid parameter of the signed payload.
  260. // Make sure to parse and validate the JWS before running this middleware.
  261. func (h *Handler) lookupJWK(next nextHTTP) nextHTTP {
  262. return func(w http.ResponseWriter, r *http.Request) {
  263. ctx := r.Context()
  264. prov, err := provisionerFromContext(r)
  265. if err != nil {
  266. api.WriteError(w, err)
  267. return
  268. }
  269. jws, err := jwsFromContext(r)
  270. if err != nil {
  271. api.WriteError(w, err)
  272. return
  273. }
  274. kidPrefix := h.Auth.GetLink(acme.AccountLink, acme.URLSafeProvisionerName(prov), true, "")
  275. kid := jws.Signatures[0].Protected.KeyID
  276. if !strings.HasPrefix(kid, kidPrefix) {
  277. api.WriteError(w, acme.MalformedErr(errors.Errorf("kid does not have "+
  278. "required prefix; expected %s, but got %s", kidPrefix, kid)))
  279. return
  280. }
  281. accID := strings.TrimPrefix(kid, kidPrefix)
  282. acc, err := h.Auth.GetAccount(prov, accID)
  283. switch {
  284. case nosql.IsErrNotFound(err):
  285. api.WriteError(w, acme.AccountDoesNotExistErr(nil))
  286. return
  287. case err != nil:
  288. api.WriteError(w, err)
  289. return
  290. default:
  291. if !acc.IsValid() {
  292. api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
  293. return
  294. }
  295. ctx = context.WithValue(ctx, accContextKey, acc)
  296. ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
  297. next(w, r.WithContext(ctx))
  298. return
  299. }
  300. }
  301. }
  302. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  303. // Make sure to parse and validate the JWS before running this middleware.
  304. func (h *Handler) verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  305. return func(w http.ResponseWriter, r *http.Request) {
  306. jws, err := jwsFromContext(r)
  307. if err != nil {
  308. api.WriteError(w, err)
  309. return
  310. }
  311. jwk, err := jwkFromContext(r)
  312. if err != nil {
  313. api.WriteError(w, err)
  314. return
  315. }
  316. if len(jwk.Algorithm) != 0 && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  317. api.WriteError(w, acme.MalformedErr(errors.New("verifier and signature algorithm do not match")))
  318. return
  319. }
  320. payload, err := jws.Verify(jwk)
  321. if err != nil {
  322. api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "error verifying jws")))
  323. return
  324. }
  325. ctx := context.WithValue(r.Context(), payloadContextKey, &payloadInfo{
  326. value: payload,
  327. isPostAsGet: string(payload) == "",
  328. isEmptyJSON: string(payload) == "{}",
  329. })
  330. next(w, r.WithContext(ctx))
  331. }
  332. }
  333. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  334. func (h *Handler) isPostAsGet(next nextHTTP) nextHTTP {
  335. return func(w http.ResponseWriter, r *http.Request) {
  336. payload, err := payloadFromContext(r)
  337. if err != nil {
  338. api.WriteError(w, err)
  339. return
  340. }
  341. if !payload.isPostAsGet {
  342. api.WriteError(w, acme.MalformedErr(errors.Errorf("expected POST-as-GET")))
  343. return
  344. }
  345. next(w, r)
  346. }
  347. }