handler.go 12 KB

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