api.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. "github.com/smallstep/certificates/est"
  20. )
  21. const (
  22. maxPayloadSize = 2 << 20
  23. )
  24. // Route configures the EST routes under the provided router.
  25. func Route(r api.Router) {
  26. r.MethodFunc(http.MethodGet, "/{provisionerName}/cacerts", getCACerts)
  27. r.MethodFunc(http.MethodGet, "/{provisionerName}/csrattrs", getCSRAttrs)
  28. r.MethodFunc(http.MethodPost, "/{provisionerName}/simpleenroll", enroll)
  29. r.MethodFunc(http.MethodPost, "/{provisionerName}/simplereenroll", enroll)
  30. }
  31. func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {
  32. return func(w http.ResponseWriter, r *http.Request) {
  33. name := chi.URLParam(r, "provisionerName")
  34. if name == "" || name == "/" {
  35. name = r.URL.Query().Get("provisioner")
  36. }
  37. if name == "" {
  38. fail(w, r, errors.New("missing provisioner name"))
  39. return
  40. }
  41. provisionerName, err := url.PathUnescape(name)
  42. if err != nil {
  43. fail(w, r, fmt.Errorf("error url unescaping provisioner name '%s'", name))
  44. return
  45. }
  46. ctx := r.Context()
  47. auth := authority.MustFromContext(ctx)
  48. p, err := auth.LoadProvisionerByName(provisionerName)
  49. if err != nil {
  50. fail(w, r, err)
  51. return
  52. }
  53. prov, ok := p.(*provisioner.EST)
  54. if !ok {
  55. fail(w, r, errors.New("provisioner must be of type EST"))
  56. return
  57. }
  58. ctx = est.NewProvisionerContext(ctx, est.Provisioner(prov))
  59. next(w, r.WithContext(ctx))
  60. }
  61. }
  62. func getCACerts(w http.ResponseWriter, r *http.Request) {
  63. lookupProvisioner(getCACertsHandler)(w, r)
  64. }
  65. func getCACertsHandler(w http.ResponseWriter, r *http.Request) {
  66. ctx := r.Context()
  67. auth := est.MustFromContext(ctx)
  68. certs, err := auth.GetCACertificates(ctx)
  69. if err != nil {
  70. fail(w, r, fmt.Errorf("failed to get CA certificates: %w", err))
  71. return
  72. }
  73. data, err := auth.BuildResponse(ctx, certs)
  74. if err != nil {
  75. fail(w, r, fmt.Errorf("failed to encode CA certificates: %w", err))
  76. return
  77. }
  78. writeResponse(w, r, data, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
  79. }
  80. func getCSRAttrs(w http.ResponseWriter, r *http.Request) {
  81. lookupProvisioner(getCSRAttrsHandler)(w, r)
  82. }
  83. func getCSRAttrsHandler(w http.ResponseWriter, r *http.Request) {
  84. ctx := r.Context()
  85. prov := est.ProvisionerFromContext(ctx)
  86. attrs, err := prov.GetCSRAttributes(ctx)
  87. if err != nil {
  88. fail(w, r, fmt.Errorf("failed to get CSR attributes: %w", err))
  89. return
  90. }
  91. if attrs == nil {
  92. attrs = []byte{}
  93. }
  94. // Minimal implementation: allow provisioner to return nil/empty for "no attributes".
  95. writeResponse(w, r, attrs, "application/csrattrs", http.StatusOK)
  96. }
  97. func enroll(w http.ResponseWriter, r *http.Request) {
  98. lookupProvisioner(enrollHandler)(w, r)
  99. }
  100. func enrollHandler(w http.ResponseWriter, r *http.Request) {
  101. ctx := r.Context()
  102. ctx, err := authContextFromRequest(ctx, r)
  103. if err != nil {
  104. if errors.Is(err, errMissingClientCertificateOrBasicAuth) {
  105. w.Header().Set("WWW-Authenticate", `Basic realm="EST"`)
  106. }
  107. failWithStatus(w, r, http.StatusUnauthorized, err)
  108. return
  109. }
  110. body, err := io.ReadAll(io.LimitReader(r.Body, maxPayloadSize))
  111. if err != nil {
  112. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed reading request body: %w", err))
  113. return
  114. }
  115. if err := requireContentType(r, "application/pkcs10"); err != nil {
  116. failWithStatus(w, r, http.StatusUnsupportedMediaType, err)
  117. return
  118. }
  119. der, err := decodeBase64Payload(body)
  120. if err != nil {
  121. failWithStatus(w, r, http.StatusBadRequest, err)
  122. return
  123. }
  124. csr, err := parseCSR(der)
  125. if err != nil {
  126. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed parsing CSR: %w", err))
  127. return
  128. }
  129. if err := csr.CheckSignature(); err != nil {
  130. failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("invalid CSR signature: %w", err))
  131. return
  132. }
  133. opts, err := authorizeEnrollRequest(ctx, csr)
  134. if err != nil {
  135. failWithStatus(w, r, http.StatusUnauthorized, err)
  136. return
  137. }
  138. r = r.WithContext(ctx)
  139. auth := est.MustFromContext(ctx)
  140. issued, err := auth.SignCSR(ctx, csr, opts...)
  141. if err != nil {
  142. failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed issuing certificate: %w", err))
  143. return
  144. }
  145. signed, err := auth.BuildResponse(ctx, []*x509.Certificate{issued})
  146. if err != nil {
  147. failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed encoding issued certificate: %w", err))
  148. return
  149. }
  150. writeResponse(w, r, signed, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
  151. }
  152. var errMissingClientCertificateOrBasicAuth = errors.New("missing client certificate or basic auth")
  153. // authContextFromRequest extracts auth material from the request into the context.
  154. func authContextFromRequest(ctx context.Context, r *http.Request) (context.Context, error) {
  155. if r.TLS == nil {
  156. return ctx, errors.New("missing TLS connection")
  157. }
  158. if len(r.TLS.PeerCertificates) > 0 {
  159. ctx = est.NewClientCertificateContext(ctx, r.TLS.PeerCertificates[0])
  160. ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
  161. }
  162. if username, password, ok := r.BasicAuth(); ok {
  163. ctx = est.NewBasicAuthContext(ctx, est.BasicAuth{
  164. Username: username,
  165. Password: password,
  166. })
  167. }
  168. if _, ok := est.ClientCertificateFromContext(ctx); !ok {
  169. if _, ok := est.BasicAuthFromContext(ctx); !ok {
  170. return ctx, errMissingClientCertificateOrBasicAuth
  171. }
  172. }
  173. return ctx, nil
  174. }
  175. // authorizeEnrollRequest validates the request against provisioner-configured auth methods.
  176. func authorizeEnrollRequest(ctx context.Context, csr *x509.CertificateRequest) ([]provisioner.SignCSROption, error) {
  177. prov := est.ProvisionerFromContext(ctx)
  178. ca := authority.MustFromContext(ctx)
  179. req := provisioner.ESTAuthRequest{
  180. CSR: csr,
  181. CARoots: ca.GetRootCertificates(),
  182. CAIntermediates: ca.GetIntermediateCertificates(),
  183. }
  184. if cert, ok := est.ClientCertificateFromContext(ctx); ok {
  185. req.ClientCertificate = cert
  186. req.ClientCertificateChain, _ = est.ClientCertificateChainFromContext(ctx)
  187. }
  188. if auth, ok := est.BasicAuthFromContext(ctx); ok {
  189. req.BasicAuthUsername = auth.Username
  190. req.BasicAuthPassword = auth.Password
  191. }
  192. opts, err := prov.AuthorizeRequest(ctx, req)
  193. if err != nil {
  194. return nil, err
  195. }
  196. return opts, nil
  197. }
  198. func parseCSR(body []byte) (*x509.CertificateRequest, error) {
  199. if len(body) == 0 {
  200. return nil, errors.New("empty body")
  201. }
  202. return x509.ParseCertificateRequest(body)
  203. }
  204. func decodeBase64Payload(body []byte) ([]byte, error) {
  205. if len(body) == 0 {
  206. return nil, errors.New("empty body")
  207. }
  208. trimmed := strings.Map(func(r rune) rune {
  209. switch r {
  210. case ' ', '\n', '\r', '\t':
  211. return -1
  212. default:
  213. return r
  214. }
  215. }, string(body))
  216. if trimmed == "" {
  217. return nil, errors.New("empty base64 payload")
  218. }
  219. decoded := make([]byte, base64.StdEncoding.DecodedLen(len(trimmed)))
  220. n, err := base64.StdEncoding.Decode(decoded, []byte(trimmed))
  221. if err != nil {
  222. return nil, fmt.Errorf("invalid base64 payload: %w", err)
  223. }
  224. return decoded[:n], nil
  225. }
  226. func requireContentType(r *http.Request, want string) error {
  227. ct := r.Header.Get("Content-Type")
  228. if ct == "" {
  229. return errors.New("missing Content-Type header")
  230. }
  231. mt, _, err := mime.ParseMediaType(ct)
  232. if err != nil {
  233. return fmt.Errorf("invalid Content-Type header: %w", err)
  234. }
  235. if mt != want {
  236. return fmt.Errorf("unsupported Content-Type %q", mt)
  237. }
  238. return nil
  239. }
  240. func writeResponse(w http.ResponseWriter, r *http.Request, data []byte, contentType string, status int) {
  241. w.Header().Set("Content-Type", contentType)
  242. w.Header().Set("Content-Transfer-Encoding", "base64")
  243. w.WriteHeader(status)
  244. encoder := base64.NewEncoder(base64.StdEncoding, w)
  245. _, _ = encoder.Write(data)
  246. _ = encoder.Close()
  247. }
  248. func fail(w http.ResponseWriter, r *http.Request, err error) {
  249. log.Error(w, r, err)
  250. http.Error(w, err.Error(), http.StatusInternalServerError)
  251. }
  252. func failWithStatus(w http.ResponseWriter, r *http.Request, status int, err error) {
  253. log.Error(w, r, err)
  254. http.Error(w, err.Error(), status)
  255. }