handler.go 9.8 KB

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