handler.go 10 KB

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