handler.go 11 KB

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