handler.go 11 KB

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