api.go 8.7 KB

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