api.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Package api implements an EST HTTP server.
  2. package api
  3. import (
  4. "context"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "github.com/go-chi/chi/v5"
  15. "github.com/smallstep/certificates/api"
  16. "github.com/smallstep/certificates/api/log"
  17. "github.com/smallstep/certificates/authority"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. provest "github.com/smallstep/certificates/authority/provisioner/est"
  20. "github.com/smallstep/certificates/est"
  21. )
  22. const (
  23. maxPayloadSize = 2 << 20
  24. )
  25. // BearerToken extracts a bearer token from an [*http.Request].
  26. func BearerToken(r *http.Request) (string, bool) {
  27. auth := r.Header.Get("Authorization")
  28. const prefix = "Bearer "
  29. // Case insensitive prefix match. See Issue 22736.
  30. if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
  31. return "", false
  32. }
  33. return auth[len(prefix):], true
  34. }
  35. // Route configures the EST routes under the provided [api.Router].
  36. func Route(r api.Router) {
  37. r.MethodFunc(http.MethodGet, "/cacerts", getCACerts)
  38. r.MethodFunc(http.MethodGet, "/csrattrs", getCSRAttrs)
  39. r.MethodFunc(http.MethodPost, "/simpleenroll", enroll)
  40. r.MethodFunc(http.MethodPost, "/simplereenroll", enroll)
  41. }
  42. func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {
  43. return func(w http.ResponseWriter, r *http.Request) {
  44. name := chi.URLParam(r, "label")
  45. if name == "" {
  46. failWithStatus(w, r, http.StatusBadRequest, errors.New("missing provisioner name"))
  47. return
  48. }
  49. provisionerName, err := url.PathUnescape(name)
  50. if err != nil {
  51. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("error url unescaping provisioner name '%s'", name))
  52. return
  53. }
  54. ctx := r.Context()
  55. auth := authority.MustFromContext(ctx)
  56. p, err := auth.LoadProvisionerByName(provisionerName)
  57. if err != nil {
  58. failWithStatus(w, r, http.StatusNotFound, err)
  59. return
  60. }
  61. prov, ok := p.(*provisioner.EST)
  62. if !ok {
  63. failWithStatus(w, r, http.StatusBadRequest, errors.New("provisioner must be of type EST"))
  64. return
  65. }
  66. ctx = est.NewProvisionerContext(ctx, est.Provisioner(prov))
  67. next(w, r.WithContext(ctx))
  68. }
  69. }
  70. func getCACerts(w http.ResponseWriter, r *http.Request) {
  71. lookupProvisioner(getCACertsHandler)(w, r)
  72. }
  73. func getCACertsHandler(w http.ResponseWriter, r *http.Request) {
  74. ctx := r.Context()
  75. auth := est.MustFromContext(ctx)
  76. certs, err := auth.GetCACertificates(ctx)
  77. if err != nil {
  78. fail(w, r, fmt.Errorf("failed to get CA certificates: %w", err))
  79. return
  80. }
  81. data, err := auth.BuildResponse(ctx, certs)
  82. if err != nil {
  83. fail(w, r, fmt.Errorf("failed to encode CA certificates: %w", err))
  84. return
  85. }
  86. writeResponse(w, data, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
  87. }
  88. func getCSRAttrs(w http.ResponseWriter, r *http.Request) {
  89. lookupProvisioner(getCSRAttrsHandler)(w, r)
  90. }
  91. func getCSRAttrsHandler(w http.ResponseWriter, r *http.Request) {
  92. ctx := r.Context()
  93. prov := est.ProvisionerFromContext(ctx)
  94. attrs, err := prov.GetCSRAttributes(ctx)
  95. if err != nil {
  96. fail(w, r, fmt.Errorf("failed to get CSR attributes: %w", err))
  97. return
  98. }
  99. if attrs == nil {
  100. attrs = []byte{}
  101. }
  102. // Minimal implementation: allow provisioner to return nil/empty for "no attributes".
  103. writeResponse(w, attrs, "application/csrattrs", http.StatusOK)
  104. }
  105. func enroll(w http.ResponseWriter, r *http.Request) {
  106. lookupProvisioner(enrollHandler)(w, r)
  107. }
  108. func enrollHandler(w http.ResponseWriter, r *http.Request) {
  109. ctx := r.Context()
  110. ctx, err := authContextFromRequest(ctx, r)
  111. if err != nil {
  112. failWithStatus(w, r, http.StatusUnauthorized, err)
  113. return
  114. }
  115. body, err := io.ReadAll(io.LimitReader(r.Body, maxPayloadSize))
  116. if err != nil {
  117. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed reading request body: %w", err))
  118. return
  119. }
  120. if err := requireContentType(r, "application/pkcs10"); err != nil {
  121. failWithStatus(w, r, http.StatusUnsupportedMediaType, err)
  122. return
  123. }
  124. der, err := decodeBase64Payload(body)
  125. if err != nil {
  126. failWithStatus(w, r, http.StatusBadRequest, err)
  127. return
  128. }
  129. csr, err := parseCSR(der)
  130. if err != nil {
  131. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed parsing CSR: %w", err))
  132. return
  133. }
  134. if err := csr.CheckSignature(); err != nil {
  135. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("invalid CSR signature: %w", err))
  136. return
  137. }
  138. opts, err := authorizeEnrollRequest(ctx, csr)
  139. if err != nil {
  140. failWithStatus(w, r, http.StatusUnauthorized, err)
  141. return
  142. }
  143. r = r.WithContext(ctx)
  144. auth := est.MustFromContext(ctx)
  145. cert, err := auth.SignCSR(ctx, csr, opts...)
  146. if err != nil {
  147. failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed issuing certificate: %w", err))
  148. return
  149. }
  150. response, err := auth.BuildResponse(ctx, []*x509.Certificate{cert})
  151. if err != nil {
  152. failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed encoding issued certificate: %w", err))
  153. return
  154. }
  155. writeResponse(w, response, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
  156. }
  157. var errMissingAuth = errors.New("missing authentication material")
  158. // authContextFromRequest extracts auth material from the request into the context.
  159. func authContextFromRequest(ctx context.Context, r *http.Request) (context.Context, error) {
  160. if r.TLS == nil {
  161. return ctx, errors.New("missing TLS connection")
  162. }
  163. prov := est.ProvisionerFromContext(ctx)
  164. cfg := prov.GetClientCertificateConfig()
  165. if cfg.Enable {
  166. if cfg.ForwardedTLSClientCertHeader != "" {
  167. // When a forwarded header is configured, only use it — never
  168. // fall back to r.TLS.PeerCertificates, which would be the
  169. // proxy's own certificate, not the actual client's.
  170. if forwardedtlsClientCert := r.Header.Get(cfg.ForwardedTLSClientCertHeader); forwardedtlsClientCert != "" {
  171. certDER, err := base64.StdEncoding.DecodeString(forwardedtlsClientCert)
  172. if err != nil {
  173. return ctx, fmt.Errorf("failed to decode client certificate from forwarded header: %w", err)
  174. }
  175. certs, err := x509.ParseCertificates(certDER)
  176. if err != nil {
  177. return ctx, fmt.Errorf("failed to parse client certificate from forwarded header: %w", err)
  178. }
  179. if len(certs) == 0 {
  180. return ctx, errors.New("no certificates found in forwarded header")
  181. }
  182. ctx = est.NewClientCertificateContext(ctx, certs[0])
  183. ctx = est.NewClientCertificateChainContext(ctx, certs)
  184. }
  185. } else if len(r.TLS.PeerCertificates) > 0 {
  186. ctx = est.NewClientCertificateContext(ctx, r.TLS.PeerCertificates[0])
  187. ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
  188. }
  189. }
  190. if authHeader := r.Header.Get("Authorization"); authHeader != "" {
  191. ctx = est.NewAuthenticationHeaderContext(ctx, authHeader)
  192. if token, ok := BearerToken(r); ok {
  193. ctx = est.NewBearerTokenContext(ctx, token)
  194. } else if username, password, ok := r.BasicAuth(); ok {
  195. ctx = est.NewBasicAuthContext(ctx, est.BasicAuth{
  196. Username: username,
  197. Password: password,
  198. })
  199. }
  200. }
  201. if _, ok := est.ClientCertificateFromContext(ctx); !ok {
  202. if _, ok := est.AuthenticationHeaderFromContext(ctx); !ok {
  203. return ctx, errMissingAuth
  204. }
  205. }
  206. return ctx, nil
  207. }
  208. // authorizeEnrollRequest validates the request against provisioner-configured auth methods.
  209. func authorizeEnrollRequest(ctx context.Context, csr *x509.CertificateRequest) ([]provisioner.SignCSROption, error) {
  210. prov := est.ProvisionerFromContext(ctx)
  211. ca := authority.MustFromContext(ctx)
  212. req := provest.AuthRequest{
  213. CSR: csr,
  214. CARoots: ca.GetRootCertificates(),
  215. CAIntermediates: ca.GetIntermediateCertificates(),
  216. }
  217. if cert, ok := est.ClientCertificateFromContext(ctx); ok {
  218. req.ClientCertificate = cert
  219. req.ClientCertificateChain, _ = est.ClientCertificateChainFromContext(ctx)
  220. }
  221. if authHeader, ok := est.AuthenticationHeaderFromContext(ctx); ok {
  222. req.AuthenticationHeader = authHeader
  223. if auth, ok := est.BasicAuthFromContext(ctx); ok {
  224. req.BasicAuthUsername = auth.Username
  225. req.BasicAuthPassword = auth.Password
  226. }
  227. if token, ok := est.BearerTokenFromContext(ctx); ok {
  228. req.BearerToken = token
  229. }
  230. }
  231. opts, err := prov.AuthorizeRequest(ctx, req)
  232. if err != nil {
  233. return nil, err
  234. }
  235. return opts, nil
  236. }
  237. func parseCSR(body []byte) (*x509.CertificateRequest, error) {
  238. if len(body) == 0 {
  239. return nil, errors.New("empty body")
  240. }
  241. return x509.ParseCertificateRequest(body)
  242. }
  243. func decodeBase64Payload(body []byte) ([]byte, error) {
  244. if len(body) == 0 {
  245. return nil, errors.New("empty body")
  246. }
  247. trimmed := strings.Map(func(r rune) rune {
  248. switch r {
  249. case ' ', '\n', '\r', '\t':
  250. return -1
  251. default:
  252. return r
  253. }
  254. }, string(body))
  255. if trimmed == "" {
  256. return nil, errors.New("empty base64 payload")
  257. }
  258. decoded := make([]byte, base64.StdEncoding.DecodedLen(len(trimmed)))
  259. n, err := base64.StdEncoding.Decode(decoded, []byte(trimmed))
  260. if err != nil {
  261. return nil, fmt.Errorf("invalid base64 payload: %w", err)
  262. }
  263. return decoded[:n], nil
  264. }
  265. func requireContentType(r *http.Request, want string) error {
  266. ct := r.Header.Get("Content-Type")
  267. if ct == "" {
  268. return errors.New("missing Content-Type header")
  269. }
  270. mt, _, err := mime.ParseMediaType(ct)
  271. if err != nil {
  272. return fmt.Errorf("invalid Content-Type header: %w", err)
  273. }
  274. if mt != want {
  275. return fmt.Errorf("unsupported Content-Type %q", mt)
  276. }
  277. return nil
  278. }
  279. func writeResponse(w http.ResponseWriter, data []byte, contentType string, status int) {
  280. w.Header().Set("Content-Type", contentType)
  281. w.Header().Set("Content-Transfer-Encoding", "base64")
  282. w.WriteHeader(status)
  283. encoder := base64.NewEncoder(base64.StdEncoding, w)
  284. _, _ = encoder.Write(data)
  285. _ = encoder.Close()
  286. }
  287. func fail(w http.ResponseWriter, r *http.Request, err error) {
  288. log.Error(w, r, err)
  289. http.Error(w, err.Error(), http.StatusInternalServerError)
  290. }
  291. func failWithStatus(w http.ResponseWriter, r *http.Request, status int, err error) {
  292. log.Error(w, r, err)
  293. http.Error(w, err.Error(), status)
  294. }