handler.go 12 KB

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