middleware.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package api
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "go.step.sm/crypto/jose"
  11. "go.step.sm/crypto/keyutil"
  12. "github.com/smallstep/certificates/acme"
  13. "github.com/smallstep/certificates/api/render"
  14. "github.com/smallstep/certificates/authority/provisioner"
  15. "github.com/smallstep/certificates/logging"
  16. "github.com/smallstep/nosql"
  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. // addNonce is a middleware that adds a nonce to the response header.
  28. func addNonce(next nextHTTP) nextHTTP {
  29. return func(w http.ResponseWriter, r *http.Request) {
  30. db := acme.MustDatabaseFromContext(r.Context())
  31. nonce, err := db.CreateNonce(r.Context())
  32. if err != nil {
  33. render.Error(w, err)
  34. return
  35. }
  36. w.Header().Set("Replay-Nonce", string(nonce))
  37. w.Header().Set("Cache-Control", "no-store")
  38. logNonce(w, string(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 addDirLink(next nextHTTP) nextHTTP {
  45. return func(w http.ResponseWriter, r *http.Request) {
  46. ctx := r.Context()
  47. linker := acme.MustLinkerFromContext(ctx)
  48. w.Header().Add("Link", link(linker.GetLink(ctx, acme.DirectoryLinkType), "index"))
  49. next(w, r)
  50. }
  51. }
  52. // verifyContentType is a middleware that verifies that content type is
  53. // application/jose+json.
  54. func verifyContentType(next nextHTTP) nextHTTP {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. p, err := provisionerFromContext(r.Context())
  57. if err != nil {
  58. render.Error(w, err)
  59. return
  60. }
  61. u := &url.URL{
  62. Path: acme.GetUnescapedPathSuffix(acme.CertificateLinkType, p.GetName(), ""),
  63. }
  64. var expected []string
  65. if strings.Contains(r.URL.String(), u.EscapedPath()) {
  66. // GET /certificate requests allow a greater range of content types.
  67. expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
  68. } else {
  69. // By default every request should have content-type applictaion/jose+json.
  70. expected = []string{"application/jose+json"}
  71. }
  72. ct := r.Header.Get("Content-Type")
  73. for _, e := range expected {
  74. if ct == e {
  75. next(w, r)
  76. return
  77. }
  78. }
  79. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  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 parseJWS(next nextHTTP) nextHTTP {
  85. return func(w http.ResponseWriter, r *http.Request) {
  86. body, err := io.ReadAll(r.Body)
  87. if err != nil {
  88. render.Error(w, acme.WrapErrorISE(err, "failed to read request body"))
  89. return
  90. }
  91. jws, err := jose.ParseJWS(string(body))
  92. if err != nil {
  93. render.Error(w, acme.WrapError(acme.ErrorMalformedType, 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 validateJWS(next nextHTTP) nextHTTP {
  116. return func(w http.ResponseWriter, r *http.Request) {
  117. ctx := r.Context()
  118. db := acme.MustDatabaseFromContext(ctx)
  119. jws, err := jwsFromContext(ctx)
  120. if err != nil {
  121. render.Error(w, err)
  122. return
  123. }
  124. if len(jws.Signatures) == 0 {
  125. render.Error(w, acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"))
  126. return
  127. }
  128. if len(jws.Signatures) > 1 {
  129. render.Error(w, acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"))
  130. return
  131. }
  132. sig := jws.Signatures[0]
  133. uh := sig.Unprotected
  134. if len(uh.KeyID) > 0 ||
  135. uh.JSONWebKey != nil ||
  136. len(uh.Algorithm) > 0 ||
  137. len(uh.Nonce) > 0 ||
  138. len(uh.ExtraHeaders) > 0 {
  139. render.Error(w, acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"))
  140. return
  141. }
  142. hdr := sig.Protected
  143. switch hdr.Algorithm {
  144. case jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512:
  145. if hdr.JSONWebKey != nil {
  146. switch k := hdr.JSONWebKey.Key.(type) {
  147. case *rsa.PublicKey:
  148. if k.Size() < keyutil.MinRSAKeyBytes {
  149. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  150. "rsa keys must be at least %d bits (%d bytes) in size",
  151. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes))
  152. return
  153. }
  154. default:
  155. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  156. "jws key type and algorithm do not match"))
  157. return
  158. }
  159. }
  160. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  161. // we good
  162. default:
  163. render.Error(w, acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", hdr.Algorithm))
  164. return
  165. }
  166. // Check the validity/freshness of the Nonce.
  167. if err := db.DeleteNonce(ctx, acme.Nonce(hdr.Nonce)); err != nil {
  168. render.Error(w, err)
  169. return
  170. }
  171. // Check that the JWS url matches the requested url.
  172. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  173. if !ok {
  174. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"))
  175. return
  176. }
  177. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  178. if jwsURL != reqURL.String() {
  179. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  180. "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. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"))
  185. return
  186. }
  187. if hdr.JSONWebKey == nil && hdr.KeyID == "" {
  188. render.Error(w, acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"))
  189. return
  190. }
  191. next(w, r)
  192. }
  193. }
  194. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  195. // in the context. Make sure to parse and validate the JWS before running this
  196. // middleware.
  197. func extractJWK(next nextHTTP) nextHTTP {
  198. return func(w http.ResponseWriter, r *http.Request) {
  199. ctx := r.Context()
  200. db := acme.MustDatabaseFromContext(ctx)
  201. jws, err := jwsFromContext(ctx)
  202. if err != nil {
  203. render.Error(w, err)
  204. return
  205. }
  206. jwk := jws.Signatures[0].Protected.JSONWebKey
  207. if jwk == nil {
  208. render.Error(w, acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"))
  209. return
  210. }
  211. if !jwk.Valid() {
  212. render.Error(w, acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"))
  213. return
  214. }
  215. // Overwrite KeyID with the JWK thumbprint.
  216. jwk.KeyID, err = acme.KeyToID(jwk)
  217. if err != nil {
  218. render.Error(w, acme.WrapErrorISE(err, "error getting KeyID from JWK"))
  219. return
  220. }
  221. // Store the JWK in the context.
  222. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  223. // Get Account OR continue to generate a new one OR continue Revoke with certificate private key
  224. acc, err := db.GetAccountByKeyID(ctx, jwk.KeyID)
  225. switch {
  226. case errors.Is(err, acme.ErrNotFound):
  227. // For NewAccount and Revoke requests ...
  228. break
  229. case err != nil:
  230. render.Error(w, err)
  231. return
  232. default:
  233. if !acc.IsValid() {
  234. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  235. return
  236. }
  237. ctx = context.WithValue(ctx, accContextKey, acc)
  238. }
  239. next(w, r.WithContext(ctx))
  240. }
  241. }
  242. // checkPrerequisites checks if all prerequisites for serving ACME
  243. // are met by the CA configuration.
  244. func checkPrerequisites(next nextHTTP) nextHTTP {
  245. return func(w http.ResponseWriter, r *http.Request) {
  246. ctx := r.Context()
  247. // If the function is not set assume that all prerequisites are met.
  248. checkFunc, ok := acme.PrerequisitesCheckerFromContext(ctx)
  249. if ok {
  250. ok, err := checkFunc(ctx)
  251. if err != nil {
  252. render.Error(w, acme.WrapErrorISE(err, "error checking acme provisioner prerequisites"))
  253. return
  254. }
  255. if !ok {
  256. render.Error(w, acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"))
  257. return
  258. }
  259. }
  260. next(w, r)
  261. }
  262. }
  263. // lookupJWK loads the JWK associated with the acme account referenced by the
  264. // kid parameter of the signed payload.
  265. // Make sure to parse and validate the JWS before running this middleware.
  266. func lookupJWK(next nextHTTP) nextHTTP {
  267. return func(w http.ResponseWriter, r *http.Request) {
  268. ctx := r.Context()
  269. db := acme.MustDatabaseFromContext(ctx)
  270. linker := acme.MustLinkerFromContext(ctx)
  271. jws, err := jwsFromContext(ctx)
  272. if err != nil {
  273. render.Error(w, err)
  274. return
  275. }
  276. kidPrefix := linker.GetLink(ctx, acme.AccountLinkType, "")
  277. kid := jws.Signatures[0].Protected.KeyID
  278. if !strings.HasPrefix(kid, kidPrefix) {
  279. render.Error(w, acme.NewError(acme.ErrorMalformedType,
  280. "kid does not have required prefix; expected %s, but got %s",
  281. kidPrefix, kid))
  282. return
  283. }
  284. accID := strings.TrimPrefix(kid, kidPrefix)
  285. acc, err := db.GetAccount(ctx, accID)
  286. switch {
  287. case nosql.IsErrNotFound(err):
  288. render.Error(w, acme.NewError(acme.ErrorAccountDoesNotExistType, "account with ID '%s' not found", accID))
  289. return
  290. case err != nil:
  291. render.Error(w, err)
  292. return
  293. default:
  294. if !acc.IsValid() {
  295. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  296. return
  297. }
  298. ctx = context.WithValue(ctx, accContextKey, acc)
  299. ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
  300. next(w, r.WithContext(ctx))
  301. return
  302. }
  303. }
  304. }
  305. // extractOrLookupJWK forwards handling to either extractJWK or
  306. // lookupJWK based on the presence of a JWK or a KID, respectively.
  307. func extractOrLookupJWK(next nextHTTP) nextHTTP {
  308. return func(w http.ResponseWriter, r *http.Request) {
  309. ctx := r.Context()
  310. jws, err := jwsFromContext(ctx)
  311. if err != nil {
  312. render.Error(w, err)
  313. return
  314. }
  315. // at this point the JWS has already been verified (if correctly configured in middleware),
  316. // and it can be used to check if a JWK exists. This flow is used when the ACME client
  317. // signed the payload with a certificate private key.
  318. if canExtractJWKFrom(jws) {
  319. extractJWK(next)(w, r)
  320. return
  321. }
  322. // default to looking up the JWK based on KeyID. This flow is used when the ACME client
  323. // signed the payload with an account private key.
  324. lookupJWK(next)(w, r)
  325. }
  326. }
  327. // canExtractJWKFrom checks if the JWS has a JWK that can be extracted
  328. func canExtractJWKFrom(jws *jose.JSONWebSignature) bool {
  329. if jws == nil {
  330. return false
  331. }
  332. if len(jws.Signatures) == 0 {
  333. return false
  334. }
  335. return jws.Signatures[0].Protected.JSONWebKey != nil
  336. }
  337. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  338. // Make sure to parse and validate the JWS before running this middleware.
  339. func verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  340. return func(w http.ResponseWriter, r *http.Request) {
  341. ctx := r.Context()
  342. jws, err := jwsFromContext(ctx)
  343. if err != nil {
  344. render.Error(w, err)
  345. return
  346. }
  347. jwk, err := jwkFromContext(ctx)
  348. if err != nil {
  349. render.Error(w, err)
  350. return
  351. }
  352. if jwk.Algorithm != "" && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  353. render.Error(w, acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"))
  354. return
  355. }
  356. payload, err := jws.Verify(jwk)
  357. if err != nil {
  358. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws"))
  359. return
  360. }
  361. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{
  362. value: payload,
  363. isPostAsGet: len(payload) == 0,
  364. isEmptyJSON: string(payload) == "{}",
  365. })
  366. next(w, r.WithContext(ctx))
  367. }
  368. }
  369. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  370. func isPostAsGet(next nextHTTP) nextHTTP {
  371. return func(w http.ResponseWriter, r *http.Request) {
  372. payload, err := payloadFromContext(r.Context())
  373. if err != nil {
  374. render.Error(w, err)
  375. return
  376. }
  377. if !payload.isPostAsGet {
  378. render.Error(w, acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"))
  379. return
  380. }
  381. next(w, r)
  382. }
  383. }
  384. // ContextKey is the key type for storing and searching for ACME request
  385. // essentials in the context of a request.
  386. type ContextKey string
  387. const (
  388. // accContextKey account key
  389. accContextKey = ContextKey("acc")
  390. // jwsContextKey jws key
  391. jwsContextKey = ContextKey("jws")
  392. // jwkContextKey jwk key
  393. jwkContextKey = ContextKey("jwk")
  394. // payloadContextKey payload key
  395. payloadContextKey = ContextKey("payload")
  396. )
  397. // accountFromContext searches the context for an ACME account. Returns the
  398. // account or an error.
  399. func accountFromContext(ctx context.Context) (*acme.Account, error) {
  400. val, ok := ctx.Value(accContextKey).(*acme.Account)
  401. if !ok || val == nil {
  402. return nil, acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context")
  403. }
  404. return val, nil
  405. }
  406. // jwkFromContext searches the context for a JWK. Returns the JWK or an error.
  407. func jwkFromContext(ctx context.Context) (*jose.JSONWebKey, error) {
  408. val, ok := ctx.Value(jwkContextKey).(*jose.JSONWebKey)
  409. if !ok || val == nil {
  410. return nil, acme.NewErrorISE("jwk expected in request context")
  411. }
  412. return val, nil
  413. }
  414. // jwsFromContext searches the context for a JWS. Returns the JWS or an error.
  415. func jwsFromContext(ctx context.Context) (*jose.JSONWebSignature, error) {
  416. val, ok := ctx.Value(jwsContextKey).(*jose.JSONWebSignature)
  417. if !ok || val == nil {
  418. return nil, acme.NewErrorISE("jws expected in request context")
  419. }
  420. return val, nil
  421. }
  422. // provisionerFromContext searches the context for a provisioner. Returns the
  423. // provisioner or an error.
  424. func provisionerFromContext(ctx context.Context) (acme.Provisioner, error) {
  425. p, ok := acme.ProvisionerFromContext(ctx)
  426. if !ok || p == nil {
  427. return nil, acme.NewErrorISE("provisioner expected in request context")
  428. }
  429. return p, nil
  430. }
  431. // acmeProvisionerFromContext searches the context for an ACME provisioner. Returns
  432. // pointer to an ACME provisioner or an error.
  433. func acmeProvisionerFromContext(ctx context.Context) (*provisioner.ACME, error) {
  434. p, err := provisionerFromContext(ctx)
  435. if err != nil {
  436. return nil, err
  437. }
  438. ap, ok := p.(*provisioner.ACME)
  439. if !ok {
  440. return nil, acme.NewErrorISE("provisioner in context is not an ACME provisioner")
  441. }
  442. return ap, nil
  443. }
  444. // payloadFromContext searches the context for a payload. Returns the payload
  445. // or an error.
  446. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  447. val, ok := ctx.Value(payloadContextKey).(*payloadInfo)
  448. if !ok || val == nil {
  449. return nil, acme.NewErrorISE("payload expected in request context")
  450. }
  451. return val, nil
  452. }