middleware.go 11 KB

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