handler.go 12 KB

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