handler.go 12 KB

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