handler.go 11 KB

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