handler.go 10 KB

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