handler.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package api
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "time"
  9. "github.com/go-chi/chi"
  10. "github.com/smallstep/certificates/acme"
  11. "github.com/smallstep/certificates/api"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. )
  14. func link(url, typ string) string {
  15. return fmt.Sprintf("<%s>;rel=\"%s\"", url, typ)
  16. }
  17. // Clock that returns time in UTC rounded to seconds.
  18. type Clock int
  19. // Now returns the UTC time rounded to seconds.
  20. func (c *Clock) Now() time.Time {
  21. return time.Now().UTC().Round(time.Second)
  22. }
  23. var clock = new(Clock)
  24. type payloadInfo struct {
  25. value []byte
  26. isPostAsGet bool
  27. isEmptyJSON bool
  28. }
  29. // Handler is the ACME API request handler.
  30. type Handler struct {
  31. db acme.DB
  32. backdate provisioner.Duration
  33. ca acme.CertificateAuthority
  34. linker Linker
  35. }
  36. // HandlerOptions required to create a new ACME API request handler.
  37. type HandlerOptions struct {
  38. Backdate provisioner.Duration
  39. // DB storage backend that impements the acme.DB interface.
  40. DB acme.DB
  41. // DNS the host used to generate accurate ACME links. By default the authority
  42. // will use the Host from the request, so this value will only be used if
  43. // request.Host is empty.
  44. DNS string
  45. // Prefix is a URL path prefix under which the ACME api is served. This
  46. // prefix is required to generate accurate ACME links.
  47. // E.g. https://ca.smallstep.com/acme/my-acme-provisioner/new-account --
  48. // "acme" is the prefix from which the ACME api is accessed.
  49. Prefix string
  50. CA acme.CertificateAuthority
  51. }
  52. // NewHandler returns a new ACME API handler.
  53. func NewHandler(ops HandlerOptions) api.RouterHandler {
  54. return &Handler{
  55. ca: ops.CA,
  56. db: ops.DB,
  57. backdate: ops.Backdate,
  58. linker: NewLinker(ops.DNS, ops.Prefix),
  59. }
  60. }
  61. // Route traffic and implement the Router interface.
  62. func (h *Handler) Route(r api.Router) {
  63. getLink := h.linker.GetLinkExplicit
  64. // Standard ACME API
  65. r.MethodFunc("GET", getLink(NewNonceLinkType, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  66. r.MethodFunc("HEAD", getLink(NewNonceLinkType, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  67. r.MethodFunc("GET", getLink(DirectoryLinkType, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  68. r.MethodFunc("HEAD", getLink(DirectoryLinkType, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  69. extractPayloadByJWK := func(next nextHTTP) nextHTTP {
  70. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.extractJWK(h.verifyAndExtractJWSPayload(next)))))))))
  71. }
  72. extractPayloadByKid := func(next nextHTTP) nextHTTP {
  73. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.lookupJWK(h.verifyAndExtractJWSPayload(next)))))))))
  74. }
  75. r.MethodFunc("POST", getLink(NewAccountLinkType, "{provisionerID}", false, nil), extractPayloadByJWK(h.NewAccount))
  76. r.MethodFunc("POST", getLink(AccountLinkType, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.GetUpdateAccount))
  77. r.MethodFunc("POST", getLink(KeyChangeLinkType, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.NotImplemented))
  78. r.MethodFunc("POST", getLink(NewOrderLinkType, "{provisionerID}", false, nil), extractPayloadByKid(h.NewOrder))
  79. r.MethodFunc("POST", getLink(OrderLinkType, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrder)))
  80. r.MethodFunc("POST", getLink(OrdersByAccountLinkType, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrdersByAccountID)))
  81. r.MethodFunc("POST", getLink(FinalizeLinkType, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.FinalizeOrder))
  82. r.MethodFunc("POST", getLink(AuthzLinkType, "{provisionerID}", false, nil, "{authzID}"), extractPayloadByKid(h.isPostAsGet(h.GetAuthorization)))
  83. r.MethodFunc("POST", getLink(ChallengeLinkType, "{provisionerID}", false, nil, "{authzID}", "{chID}"), extractPayloadByKid(h.GetChallenge))
  84. r.MethodFunc("POST", getLink(CertificateLinkType, "{provisionerID}", false, nil, "{certID}"), extractPayloadByKid(h.isPostAsGet(h.GetCertificate)))
  85. }
  86. // GetNonce just sets the right header since a Nonce is added to each response
  87. // by middleware by default.
  88. func (h *Handler) GetNonce(w http.ResponseWriter, r *http.Request) {
  89. if r.Method == "HEAD" {
  90. w.WriteHeader(http.StatusOK)
  91. } else {
  92. w.WriteHeader(http.StatusNoContent)
  93. }
  94. }
  95. // Directory represents an ACME directory for configuring clients.
  96. type Directory struct {
  97. NewNonce string `json:"newNonce,omitempty"`
  98. NewAccount string `json:"newAccount,omitempty"`
  99. NewOrder string `json:"newOrder,omitempty"`
  100. NewAuthz string `json:"newAuthz,omitempty"`
  101. RevokeCert string `json:"revokeCert,omitempty"`
  102. KeyChange string `json:"keyChange,omitempty"`
  103. }
  104. // ToLog enables response logging for the Directory type.
  105. func (d *Directory) ToLog() (interface{}, error) {
  106. b, err := json.Marshal(d)
  107. if err != nil {
  108. return nil, acme.WrapErrorISE(err, "error marshaling directory for logging")
  109. }
  110. return string(b), nil
  111. }
  112. type directory struct {
  113. prefix, dns string
  114. }
  115. // GetDirectory is the ACME resource for returning a directory configuration
  116. // for client configuration.
  117. func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
  118. ctx := r.Context()
  119. api.JSON(w, &Directory{
  120. NewNonce: h.linker.GetLink(ctx, NewNonceLinkType, true),
  121. NewAccount: h.linker.GetLink(ctx, NewAccountLinkType, true),
  122. NewOrder: h.linker.GetLink(ctx, NewOrderLinkType, true),
  123. RevokeCert: h.linker.GetLink(ctx, RevokeCertLinkType, true),
  124. KeyChange: h.linker.GetLink(ctx, KeyChangeLinkType, true),
  125. })
  126. }
  127. // NotImplemented returns a 501 and is generally a placeholder for functionality which
  128. // MAY be added at some point in the future but is not in any way a guarantee of such.
  129. func (h *Handler) NotImplemented(w http.ResponseWriter, r *http.Request) {
  130. api.WriteError(w, acme.NewError(acme.ErrorNotImplementedType, "this API is not implemented"))
  131. }
  132. // GetAuthorization ACME api for retrieving an Authz.
  133. func (h *Handler) GetAuthorization(w http.ResponseWriter, r *http.Request) {
  134. ctx := r.Context()
  135. acc, err := accountFromContext(ctx)
  136. if err != nil {
  137. api.WriteError(w, err)
  138. return
  139. }
  140. az, err := h.db.GetAuthorization(ctx, chi.URLParam(r, "authzID"))
  141. if err != nil {
  142. api.WriteError(w, acme.WrapErrorISE(err, "error retrieving authorization"))
  143. return
  144. }
  145. if acc.ID != az.AccountID {
  146. api.WriteError(w, acme.NewError(acme.ErrorUnauthorizedType,
  147. "account '%s' does not own authorization '%s'", acc.ID, az.ID))
  148. return
  149. }
  150. if err = az.UpdateStatus(ctx, h.db); err != nil {
  151. api.WriteError(w, acme.WrapErrorISE(err, "error updating authorization status"))
  152. }
  153. h.linker.LinkAuthorization(ctx, az)
  154. w.Header().Set("Location", h.linker.GetLink(ctx, AuthzLinkType, true, az.ID))
  155. api.JSON(w, az)
  156. }
  157. // GetChallenge ACME api for retrieving a Challenge.
  158. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  159. ctx := r.Context()
  160. acc, err := accountFromContext(ctx)
  161. if err != nil {
  162. api.WriteError(w, err)
  163. return
  164. }
  165. // Just verify that the payload was set, since we're not strictly adhering
  166. // to ACME V2 spec for reasons specified below.
  167. _, err = payloadFromContext(ctx)
  168. if err != nil {
  169. api.WriteError(w, err)
  170. return
  171. }
  172. // NOTE: We should be checking ^^^ that the request is either a POST-as-GET, or
  173. // that the payload is an empty JSON block ({}). However, older ACME clients
  174. // still send a vestigial body (rather than an empty JSON block) and
  175. // strict enforcement would render these clients broken. For the time being
  176. // we'll just ignore the body.
  177. ch, err := h.db.GetChallenge(ctx, chi.URLParam(r, "chID"), chi.URLParam(r, "authzID"))
  178. if err != nil {
  179. api.WriteError(w, acme.WrapErrorISE(err, "error retrieving challenge"))
  180. return
  181. }
  182. if acc.ID != ch.AccountID {
  183. api.WriteError(w, acme.NewError(acme.ErrorUnauthorizedType,
  184. "account '%s' does not own challenge '%s'", acc.ID, ch.ID))
  185. return
  186. }
  187. client := http.Client{
  188. Timeout: time.Duration(30 * time.Second),
  189. }
  190. dialer := &net.Dialer{
  191. Timeout: 30 * time.Second,
  192. }
  193. jwk, err := jwkFromContext(ctx)
  194. if err != nil {
  195. api.WriteError(w, err)
  196. return
  197. }
  198. if err = ch.Validate(ctx, h.db, jwk, acme.ValidateOptions{
  199. HTTPGet: client.Get,
  200. LookupTxt: net.LookupTXT,
  201. TLSDial: func(network, addr string, config *tls.Config) (*tls.Conn, error) {
  202. return tls.DialWithDialer(dialer, network, addr, config)
  203. },
  204. }); err != nil {
  205. api.WriteError(w, acme.WrapErrorISE(err, "error validating challenge"))
  206. return
  207. }
  208. h.linker.LinkChallenge(ctx, ch)
  209. w.Header().Add("Link", link(h.linker.GetLink(ctx, AuthzLinkType, true, ch.AuthzID), "up"))
  210. w.Header().Set("Location", h.linker.GetLink(ctx, ChallengeLinkType, true, ch.AuthzID, ch.ID))
  211. api.JSON(w, ch)
  212. }
  213. // GetCertificate ACME api for retrieving a Certificate.
  214. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  215. ctx := r.Context()
  216. acc, err := accountFromContext(ctx)
  217. if err != nil {
  218. api.WriteError(w, err)
  219. return
  220. }
  221. certID := chi.URLParam(r, "certID")
  222. cert, err := h.db.GetCertificate(ctx, certID)
  223. if err != nil {
  224. api.WriteError(w, acme.WrapErrorISE(err, "error retrieving certificate"))
  225. return
  226. }
  227. if cert.AccountID != acc.ID {
  228. api.WriteError(w, acme.NewError(acme.ErrorUnauthorizedType,
  229. "account '%s' does not own certificate '%s'", acc.ID, certID))
  230. return
  231. }
  232. certBytes, err := cert.ToACME()
  233. if err != nil {
  234. api.WriteError(w, acme.WrapErrorISE(err, "error converting cert to ACME representation"))
  235. return
  236. }
  237. api.LogCertificate(w, cert.Leaf)
  238. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  239. w.Write(certBytes)
  240. }