handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package api
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "encoding/pem"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "github.com/go-chi/chi"
  11. "github.com/smallstep/certificates/acme"
  12. "github.com/smallstep/certificates/api"
  13. "github.com/smallstep/certificates/api/render"
  14. "github.com/smallstep/certificates/authority"
  15. "github.com/smallstep/certificates/authority/provisioner"
  16. "github.com/smallstep/certificates/utils/debug/q"
  17. )
  18. func link(url, typ string) string {
  19. return fmt.Sprintf("<%s>;rel=%q", url, typ)
  20. }
  21. // Clock that returns time in UTC rounded to seconds.
  22. type Clock struct{}
  23. // Now returns the UTC time rounded to seconds.
  24. func (c *Clock) Now() time.Time {
  25. return time.Now().UTC().Truncate(time.Second)
  26. }
  27. var clock Clock
  28. type payloadInfo struct {
  29. value []byte
  30. isPostAsGet bool
  31. isEmptyJSON bool
  32. }
  33. // HandlerOptions required to create a new ACME API request handler.
  34. type HandlerOptions struct {
  35. // DB storage backend that implements the acme.DB interface.
  36. //
  37. // Deprecated: use acme.NewContex(context.Context, acme.DB)
  38. DB acme.DB
  39. // CA is the certificate authority interface.
  40. //
  41. // Deprecated: use authority.NewContext(context.Context, *authority.Authority)
  42. CA acme.CertificateAuthority
  43. // Backdate is the duration that the CA will subtract from the current time
  44. // to set the NotBefore in the certificate.
  45. Backdate provisioner.Duration
  46. // DNS the host used to generate accurate ACME links. By default the authority
  47. // will use the Host from the request, so this value will only be used if
  48. // request.Host is empty.
  49. DNS string
  50. // Prefix is a URL path prefix under which the ACME api is served. This
  51. // prefix is required to generate accurate ACME links.
  52. // E.g. https://ca.smallstep.com/acme/my-acme-provisioner/new-account --
  53. // "acme" is the prefix from which the ACME api is accessed.
  54. Prefix string
  55. // PrerequisitesChecker checks if all prerequisites for serving ACME are
  56. // met by the CA configuration.
  57. PrerequisitesChecker func(ctx context.Context) (bool, error)
  58. }
  59. var mustAuthority = func(ctx context.Context) acme.CertificateAuthority {
  60. return authority.MustFromContext(ctx)
  61. }
  62. // handler is the ACME API request handler.
  63. type handler struct {
  64. opts *HandlerOptions
  65. }
  66. // Route traffic and implement the Router interface. For backward compatibility
  67. // this route adds will add a new middleware that will set the ACME components
  68. // on the context.
  69. //
  70. // Note: this method is deprecated in step-ca, other applications can still use
  71. // this to support ACME, but the recommendation is to use use
  72. // api.Route(api.Router) and acme.NewContext() instead.
  73. func (h *handler) Route(r api.Router) {
  74. client := acme.NewClient()
  75. linker := acme.NewLinker(h.opts.DNS, h.opts.Prefix)
  76. route(r, func(next nextHTTP) nextHTTP {
  77. return func(w http.ResponseWriter, r *http.Request) {
  78. ctx := r.Context()
  79. if ca, ok := h.opts.CA.(*authority.Authority); ok && ca != nil {
  80. ctx = authority.NewContext(ctx, ca)
  81. }
  82. ctx = acme.NewContext(ctx, h.opts.DB, client, linker, h.opts.PrerequisitesChecker)
  83. next(w, r.WithContext(ctx))
  84. }
  85. })
  86. }
  87. // NewHandler returns a new ACME API handler.
  88. //
  89. // Note: this method is deprecated in step-ca, other applications can still use
  90. // this to support ACME, but the recommendation is to use use
  91. // api.Route(api.Router) and acme.NewContext() instead.
  92. func NewHandler(opts HandlerOptions) api.RouterHandler {
  93. return &handler{
  94. opts: &opts,
  95. }
  96. }
  97. // Route traffic and implement the Router interface. This method requires that
  98. // all the acme components, authority, db, client, linker, and prerequisite
  99. // checker to be present in the context.
  100. func Route(r api.Router) {
  101. route(r, nil)
  102. }
  103. func route(r api.Router, middleware func(next nextHTTP) nextHTTP) {
  104. commonMiddleware := func(next nextHTTP) nextHTTP {
  105. handler := func(w http.ResponseWriter, r *http.Request) {
  106. // Linker middleware gets the provisioner and current url from the
  107. // request and sets them in the context.
  108. linker := acme.MustLinkerFromContext(r.Context())
  109. linker.Middleware(http.HandlerFunc(checkPrerequisites(next))).ServeHTTP(w, r)
  110. }
  111. if middleware != nil {
  112. handler = middleware(handler)
  113. }
  114. return handler
  115. }
  116. validatingMiddleware := func(next nextHTTP) nextHTTP {
  117. return commonMiddleware(addNonce(addDirLink(verifyContentType(parseJWS(validateJWS(next))))))
  118. }
  119. extractPayloadByJWK := func(next nextHTTP) nextHTTP {
  120. return validatingMiddleware(extractJWK(verifyAndExtractJWSPayload(next)))
  121. }
  122. extractPayloadByKid := func(next nextHTTP) nextHTTP {
  123. return validatingMiddleware(lookupJWK(verifyAndExtractJWSPayload(next)))
  124. }
  125. extractPayloadByKidOrJWK := func(next nextHTTP) nextHTTP {
  126. return validatingMiddleware(extractOrLookupJWK(verifyAndExtractJWSPayload(next)))
  127. }
  128. getPath := acme.GetUnescapedPathSuffix
  129. // Standard ACME API
  130. r.MethodFunc("GET", getPath(acme.NewNonceLinkType, "{provisionerID}"),
  131. commonMiddleware(addNonce(addDirLink(GetNonce))))
  132. r.MethodFunc("HEAD", getPath(acme.NewNonceLinkType, "{provisionerID}"),
  133. commonMiddleware(addNonce(addDirLink(GetNonce))))
  134. r.MethodFunc("GET", getPath(acme.DirectoryLinkType, "{provisionerID}"),
  135. commonMiddleware(GetDirectory))
  136. r.MethodFunc("HEAD", getPath(acme.DirectoryLinkType, "{provisionerID}"),
  137. commonMiddleware(GetDirectory))
  138. r.MethodFunc("POST", getPath(acme.NewAccountLinkType, "{provisionerID}"),
  139. extractPayloadByJWK(NewAccount))
  140. r.MethodFunc("POST", getPath(acme.AccountLinkType, "{provisionerID}", "{accID}"),
  141. extractPayloadByKid(GetOrUpdateAccount))
  142. r.MethodFunc("POST", getPath(acme.KeyChangeLinkType, "{provisionerID}", "{accID}"),
  143. extractPayloadByKid(NotImplemented))
  144. r.MethodFunc("POST", getPath(acme.NewOrderLinkType, "{provisionerID}"),
  145. extractPayloadByKid(NewOrder))
  146. r.MethodFunc("POST", getPath(acme.OrderLinkType, "{provisionerID}", "{ordID}"),
  147. extractPayloadByKid(isPostAsGet(GetOrder)))
  148. r.MethodFunc("POST", getPath(acme.OrdersByAccountLinkType, "{provisionerID}", "{accID}"),
  149. extractPayloadByKid(isPostAsGet(GetOrdersByAccountID)))
  150. r.MethodFunc("POST", getPath(acme.FinalizeLinkType, "{provisionerID}", "{ordID}"),
  151. extractPayloadByKid(FinalizeOrder))
  152. r.MethodFunc("POST", getPath(acme.AuthzLinkType, "{provisionerID}", "{authzID}"),
  153. extractPayloadByKid(isPostAsGet(GetAuthorization)))
  154. r.MethodFunc("POST", getPath(acme.ChallengeLinkType, "{provisionerID}", "{authzID}", "{chID}"),
  155. extractPayloadByKid(GetChallenge))
  156. r.MethodFunc("POST", getPath(acme.CertificateLinkType, "{provisionerID}", "{certID}"),
  157. extractPayloadByKid(isPostAsGet(GetCertificate)))
  158. r.MethodFunc("POST", getPath(acme.RevokeCertLinkType, "{provisionerID}"),
  159. extractPayloadByKidOrJWK(RevokeCert))
  160. }
  161. // GetNonce just sets the right header since a Nonce is added to each response
  162. // by middleware by default.
  163. func GetNonce(w http.ResponseWriter, r *http.Request) {
  164. if r.Method == "HEAD" {
  165. w.WriteHeader(http.StatusOK)
  166. } else {
  167. w.WriteHeader(http.StatusNoContent)
  168. }
  169. }
  170. type Meta struct {
  171. TermsOfService string `json:"termsOfService,omitempty"`
  172. Website string `json:"website,omitempty"`
  173. CaaIdentities []string `json:"caaIdentities,omitempty"`
  174. ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"`
  175. }
  176. // Directory represents an ACME directory for configuring clients.
  177. type Directory struct {
  178. NewNonce string `json:"newNonce"`
  179. NewAccount string `json:"newAccount"`
  180. NewOrder string `json:"newOrder"`
  181. RevokeCert string `json:"revokeCert"`
  182. KeyChange string `json:"keyChange"`
  183. Meta *Meta `json:"meta,omitempty"`
  184. }
  185. // ToLog enables response logging for the Directory type.
  186. func (d *Directory) ToLog() (interface{}, error) {
  187. b, err := json.Marshal(d)
  188. if err != nil {
  189. return nil, acme.WrapErrorISE(err, "error marshaling directory for logging")
  190. }
  191. return string(b), nil
  192. }
  193. // GetDirectory is the ACME resource for returning a directory configuration
  194. // for client configuration.
  195. func GetDirectory(w http.ResponseWriter, r *http.Request) {
  196. ctx := r.Context()
  197. acmeProv, err := acmeProvisionerFromContext(ctx)
  198. if err != nil {
  199. render.Error(w, err)
  200. return
  201. }
  202. linker := acme.MustLinkerFromContext(ctx)
  203. render.JSON(w, &Directory{
  204. NewNonce: linker.GetLink(ctx, acme.NewNonceLinkType),
  205. NewAccount: linker.GetLink(ctx, acme.NewAccountLinkType),
  206. NewOrder: linker.GetLink(ctx, acme.NewOrderLinkType),
  207. RevokeCert: linker.GetLink(ctx, acme.RevokeCertLinkType),
  208. KeyChange: linker.GetLink(ctx, acme.KeyChangeLinkType),
  209. Meta: createMetaObject(acmeProv),
  210. })
  211. }
  212. // createMetaObject creates a Meta object if the ACME provisioner
  213. // has one or more properties that are written in the ACME directory output.
  214. // It returns nil if none of the properties are set.
  215. func createMetaObject(p *provisioner.ACME) *Meta {
  216. if shouldAddMetaObject(p) {
  217. return &Meta{
  218. TermsOfService: p.TermsOfService,
  219. Website: p.Website,
  220. CaaIdentities: p.CaaIdentities,
  221. ExternalAccountRequired: p.RequireEAB,
  222. }
  223. }
  224. return nil
  225. }
  226. // shouldAddMetaObject returns whether or not the ACME provisioner
  227. // has properties configured that must be added to the ACME directory object.
  228. func shouldAddMetaObject(p *provisioner.ACME) bool {
  229. switch {
  230. case p.TermsOfService != "":
  231. return true
  232. case p.Website != "":
  233. return true
  234. case len(p.CaaIdentities) > 0:
  235. return true
  236. case p.RequireEAB:
  237. return true
  238. default:
  239. return false
  240. }
  241. }
  242. // NotImplemented returns a 501 and is generally a placeholder for functionality which
  243. // MAY be added at some point in the future but is not in any way a guarantee of such.
  244. func NotImplemented(w http.ResponseWriter, r *http.Request) {
  245. render.Error(w, acme.NewError(acme.ErrorNotImplementedType, "this API is not implemented"))
  246. }
  247. // GetAuthorization ACME api for retrieving an Authz.
  248. func GetAuthorization(w http.ResponseWriter, r *http.Request) {
  249. ctx := r.Context()
  250. db := acme.MustDatabaseFromContext(ctx)
  251. linker := acme.MustLinkerFromContext(ctx)
  252. acc, err := accountFromContext(ctx)
  253. if err != nil {
  254. render.Error(w, err)
  255. return
  256. }
  257. az, err := db.GetAuthorization(ctx, chi.URLParam(r, "authzID"))
  258. if err != nil {
  259. render.Error(w, acme.WrapErrorISE(err, "error retrieving authorization"))
  260. return
  261. }
  262. if acc.ID != az.AccountID {
  263. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  264. "account '%s' does not own authorization '%s'", acc.ID, az.ID))
  265. return
  266. }
  267. if err = az.UpdateStatus(ctx, db); err != nil {
  268. render.Error(w, acme.WrapErrorISE(err, "error updating authorization status"))
  269. return
  270. }
  271. linker.LinkAuthorization(ctx, az)
  272. w.Header().Set("Location", linker.GetLink(ctx, acme.AuthzLinkType, az.ID))
  273. render.JSON(w, az)
  274. }
  275. // GetChallenge ACME api for retrieving a Challenge.
  276. func GetChallenge(w http.ResponseWriter, r *http.Request) {
  277. ctx := r.Context()
  278. db := acme.MustDatabaseFromContext(ctx)
  279. linker := acme.MustLinkerFromContext(ctx)
  280. acc, err := accountFromContext(ctx)
  281. if err != nil {
  282. render.Error(w, err)
  283. return
  284. }
  285. payload, err := payloadFromContext(ctx)
  286. if err != nil {
  287. render.Error(w, err)
  288. return
  289. }
  290. // NOTE: We should be checking that the request is either a POST-as-GET, or
  291. // that for all challenges except for device-attest-01, the payload is an
  292. // empty JSON block ({}). However, older ACME clients still send a vestigial
  293. // body (rather than an empty JSON block) and strict enforcement would
  294. // render these clients broken.
  295. azID := chi.URLParam(r, "authzID")
  296. ch, err := db.GetChallenge(ctx, chi.URLParam(r, "chID"), azID)
  297. if err != nil {
  298. render.Error(w, acme.WrapErrorISE(err, "error retrieving challenge"))
  299. return
  300. }
  301. ch.AuthorizationID = azID
  302. if acc.ID != ch.AccountID {
  303. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  304. "account '%s' does not own challenge '%s'", acc.ID, ch.ID))
  305. return
  306. }
  307. jwk, err := jwkFromContext(ctx)
  308. if err != nil {
  309. render.Error(w, err)
  310. return
  311. }
  312. if err = ch.Validate(ctx, db, jwk, payload.value); err != nil {
  313. render.Error(w, acme.WrapErrorISE(err, "error validating challenge"))
  314. return
  315. }
  316. q.Q(ch)
  317. linker.LinkChallenge(ctx, ch, azID)
  318. w.Header().Add("Link", link(linker.GetLink(ctx, acme.AuthzLinkType, azID), "up"))
  319. w.Header().Set("Location", linker.GetLink(ctx, acme.ChallengeLinkType, azID, ch.ID))
  320. render.JSON(w, ch)
  321. }
  322. // GetCertificate ACME api for retrieving a Certificate.
  323. func GetCertificate(w http.ResponseWriter, r *http.Request) {
  324. ctx := r.Context()
  325. db := acme.MustDatabaseFromContext(ctx)
  326. acc, err := accountFromContext(ctx)
  327. if err != nil {
  328. render.Error(w, err)
  329. return
  330. }
  331. certID := chi.URLParam(r, "certID")
  332. cert, err := db.GetCertificate(ctx, certID)
  333. if err != nil {
  334. render.Error(w, acme.WrapErrorISE(err, "error retrieving certificate"))
  335. return
  336. }
  337. if cert.AccountID != acc.ID {
  338. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  339. "account '%s' does not own certificate '%s'", acc.ID, certID))
  340. return
  341. }
  342. var certBytes []byte
  343. for _, c := range append([]*x509.Certificate{cert.Leaf}, cert.Intermediates...) {
  344. certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
  345. Type: "CERTIFICATE",
  346. Bytes: c.Raw,
  347. })...)
  348. }
  349. api.LogCertificate(w, cert.Leaf)
  350. w.Header().Set("Content-Type", "application/pem-certificate-chain")
  351. w.Write(certBytes)
  352. }