api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Package api implements a SCEP HTTP server.
  2. package api
  3. import (
  4. "context"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "github.com/go-chi/chi"
  14. microscep "github.com/micromdm/scep/v2/scep"
  15. "go.mozilla.org/pkcs7"
  16. "github.com/smallstep/certificates/api"
  17. "github.com/smallstep/certificates/api/log"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. "github.com/smallstep/certificates/scep"
  20. )
  21. const (
  22. opnGetCACert = "GetCACert"
  23. opnGetCACaps = "GetCACaps"
  24. opnPKIOperation = "PKIOperation"
  25. // TODO: add other (more optional) operations and handling
  26. )
  27. const maxPayloadSize = 2 << 20
  28. // request is a SCEP server request.
  29. type request struct {
  30. Operation string
  31. Message []byte
  32. }
  33. // Response is a SCEP server Response.
  34. type Response struct {
  35. Operation string
  36. CACertNum int
  37. Data []byte
  38. Certificate *x509.Certificate
  39. Error error
  40. }
  41. // handler is the SCEP request handler.
  42. type handler struct {
  43. auth *scep.Authority
  44. }
  45. // Route traffic and implement the Router interface.
  46. //
  47. // Deprecated: use scep.Route(r api.Router)
  48. func (h *handler) Route(r api.Router) {
  49. route(r, func(next http.HandlerFunc) http.HandlerFunc {
  50. return func(w http.ResponseWriter, r *http.Request) {
  51. ctx := scep.NewContext(r.Context(), h.auth)
  52. next(w, r.WithContext(ctx))
  53. }
  54. })
  55. }
  56. // New returns a new SCEP API router.
  57. //
  58. // Deprecated: use scep.Route(r api.Router)
  59. func New(auth *scep.Authority) api.RouterHandler {
  60. return &handler{auth: auth}
  61. }
  62. // Route traffic and implement the Router interface.
  63. func Route(r api.Router) {
  64. route(r, nil)
  65. }
  66. func route(r api.Router, middleware func(next http.HandlerFunc) http.HandlerFunc) {
  67. getHandler := lookupProvisioner(Get)
  68. postHandler := lookupProvisioner(Post)
  69. // For backward compatibility.
  70. if middleware != nil {
  71. getHandler = middleware(getHandler)
  72. postHandler = middleware(postHandler)
  73. }
  74. r.MethodFunc(http.MethodGet, "/{provisionerName}/*", getHandler)
  75. r.MethodFunc(http.MethodGet, "/{provisionerName}", getHandler)
  76. r.MethodFunc(http.MethodPost, "/{provisionerName}/*", postHandler)
  77. r.MethodFunc(http.MethodPost, "/{provisionerName}", postHandler)
  78. }
  79. // Get handles all SCEP GET requests
  80. func Get(w http.ResponseWriter, r *http.Request) {
  81. req, err := decodeRequest(r)
  82. if err != nil {
  83. fail(w, fmt.Errorf("invalid scep get request: %w", err))
  84. return
  85. }
  86. ctx := r.Context()
  87. var res Response
  88. switch req.Operation {
  89. case opnGetCACert:
  90. res, err = GetCACert(ctx)
  91. case opnGetCACaps:
  92. res, err = GetCACaps(ctx)
  93. case opnPKIOperation:
  94. res, err = PKIOperation(ctx, req)
  95. default:
  96. err = fmt.Errorf("unknown operation: %s", req.Operation)
  97. }
  98. if err != nil {
  99. fail(w, fmt.Errorf("scep get request failed: %w", err))
  100. return
  101. }
  102. writeResponse(w, res)
  103. }
  104. // Post handles all SCEP POST requests
  105. func Post(w http.ResponseWriter, r *http.Request) {
  106. req, err := decodeRequest(r)
  107. if err != nil {
  108. fail(w, fmt.Errorf("invalid scep post request: %w", err))
  109. return
  110. }
  111. var res Response
  112. switch req.Operation {
  113. case opnPKIOperation:
  114. res, err = PKIOperation(r.Context(), req)
  115. default:
  116. err = fmt.Errorf("unknown operation: %s", req.Operation)
  117. }
  118. if err != nil {
  119. fail(w, fmt.Errorf("scep post request failed: %w", err))
  120. return
  121. }
  122. writeResponse(w, res)
  123. }
  124. func decodeRequest(r *http.Request) (request, error) {
  125. defer r.Body.Close()
  126. method := r.Method
  127. query := r.URL.Query()
  128. var operation string
  129. if _, ok := query["operation"]; ok {
  130. operation = query.Get("operation")
  131. }
  132. switch method {
  133. case http.MethodGet:
  134. switch operation {
  135. case opnGetCACert, opnGetCACaps:
  136. return request{
  137. Operation: operation,
  138. Message: []byte{},
  139. }, nil
  140. case opnPKIOperation:
  141. var message string
  142. if _, ok := query["message"]; ok {
  143. message = query.Get("message")
  144. }
  145. // TODO: verify this; right type of encoding? Needs additional transformations?
  146. decodedMessage, err := base64.StdEncoding.DecodeString(message)
  147. if err != nil {
  148. return request{}, err
  149. }
  150. return request{
  151. Operation: operation,
  152. Message: decodedMessage,
  153. }, nil
  154. default:
  155. return request{}, fmt.Errorf("unsupported operation: %s", operation)
  156. }
  157. case http.MethodPost:
  158. body, err := io.ReadAll(io.LimitReader(r.Body, maxPayloadSize))
  159. if err != nil {
  160. return request{}, err
  161. }
  162. return request{
  163. Operation: operation,
  164. Message: body,
  165. }, nil
  166. default:
  167. return request{}, fmt.Errorf("unsupported method: %s", method)
  168. }
  169. }
  170. // lookupProvisioner loads the provisioner associated with the request.
  171. // Responds 404 if the provisioner does not exist.
  172. func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {
  173. return func(w http.ResponseWriter, r *http.Request) {
  174. name := chi.URLParam(r, "provisionerName")
  175. provisionerName, err := url.PathUnescape(name)
  176. if err != nil {
  177. fail(w, fmt.Errorf("error url unescaping provisioner name '%s'", name))
  178. return
  179. }
  180. ctx := r.Context()
  181. auth := scep.MustFromContext(ctx)
  182. p, err := auth.LoadProvisionerByName(provisionerName)
  183. if err != nil {
  184. fail(w, err)
  185. return
  186. }
  187. prov, ok := p.(*provisioner.SCEP)
  188. if !ok {
  189. fail(w, errors.New("provisioner must be of type SCEP"))
  190. return
  191. }
  192. ctx = context.WithValue(ctx, scep.ProvisionerContextKey, scep.Provisioner(prov))
  193. next(w, r.WithContext(ctx))
  194. }
  195. }
  196. // GetCACert returns the CA certificates in a SCEP response
  197. func GetCACert(ctx context.Context) (Response, error) {
  198. auth := scep.MustFromContext(ctx)
  199. certs, err := auth.GetCACertificates(ctx)
  200. if err != nil {
  201. return Response{}, err
  202. }
  203. if len(certs) == 0 {
  204. return Response{}, errors.New("missing CA cert")
  205. }
  206. res := Response{
  207. Operation: opnGetCACert,
  208. CACertNum: len(certs),
  209. }
  210. if len(certs) == 1 {
  211. res.Data = certs[0].Raw
  212. } else {
  213. // create degenerate pkcs7 certificate structure, according to
  214. // https://tools.ietf.org/html/rfc8894#section-4.2.1.2, because
  215. // not signed or encrypted data has to be returned.
  216. data, err := microscep.DegenerateCertificates(certs)
  217. if err != nil {
  218. return Response{}, err
  219. }
  220. res.Data = data
  221. }
  222. return res, nil
  223. }
  224. // GetCACaps returns the CA capabilities in a SCEP response
  225. func GetCACaps(ctx context.Context) (Response, error) {
  226. auth := scep.MustFromContext(ctx)
  227. caps := auth.GetCACaps(ctx)
  228. res := Response{
  229. Operation: opnGetCACaps,
  230. Data: formatCapabilities(caps),
  231. }
  232. return res, nil
  233. }
  234. // PKIOperation performs PKI operations and returns a SCEP response
  235. func PKIOperation(ctx context.Context, req request) (Response, error) {
  236. // parse the message using microscep implementation
  237. microMsg, err := microscep.ParsePKIMessage(req.Message)
  238. if err != nil {
  239. // return the error, because we can't use the msg for creating a CertRep
  240. return Response{}, err
  241. }
  242. // this is essentially doing the same as microscep.ParsePKIMessage, but
  243. // gives us access to the p7 itself in scep.PKIMessage. Essentially a small
  244. // wrapper for the microscep implementation.
  245. p7, err := pkcs7.Parse(microMsg.Raw)
  246. if err != nil {
  247. return Response{}, err
  248. }
  249. // copy over properties to our internal PKIMessage
  250. msg := &scep.PKIMessage{
  251. TransactionID: microMsg.TransactionID,
  252. MessageType: microMsg.MessageType,
  253. SenderNonce: microMsg.SenderNonce,
  254. Raw: microMsg.Raw,
  255. P7: p7,
  256. }
  257. auth := scep.MustFromContext(ctx)
  258. if err := auth.DecryptPKIEnvelope(ctx, msg); err != nil {
  259. return Response{}, err
  260. }
  261. // NOTE: at this point we have sufficient information for returning nicely signed CertReps
  262. csr := msg.CSRReqMessage.CSR
  263. transactionID := string(msg.TransactionID)
  264. challengePassword := msg.CSRReqMessage.ChallengePassword
  265. // NOTE: we're blocking the RenewalReq if the challenge does not match, because otherwise we don't have any authentication.
  266. // The macOS SCEP client performs renewals using PKCSreq. The CertNanny SCEP client will use PKCSreq with challenge too, it seems,
  267. // even if using the renewal flow as described in the README.md. MicroMDM SCEP client also only does PKCSreq by default, unless
  268. // a certificate exists; then it will use RenewalReq. Adding the challenge check here may be a small breaking change for clients.
  269. // We'll have to see how it works out.
  270. if msg.MessageType == microscep.PKCSReq || msg.MessageType == microscep.RenewalReq {
  271. if err := auth.ValidateChallenge(ctx, challengePassword, transactionID); err != nil {
  272. if errors.Is(err, provisioner.ErrSCEPChallengeInvalid) {
  273. return createFailureResponse(ctx, csr, msg, microscep.BadRequest, err)
  274. }
  275. return createFailureResponse(ctx, csr, msg, microscep.BadRequest, errors.New("failed validating challenge password"))
  276. }
  277. }
  278. // TODO: authorize renewal: we can authorize renewals with the challenge password (if reusable secrets are used).
  279. // Renewals OPTIONALLY include the challenge if the existing cert is used as authentication, but client SHOULD omit the challenge.
  280. // This means that for renewal requests we should check the certificate provided to be signed before by the CA. We could
  281. // enforce use of the challenge if we want too. That way we could be more flexible in terms of authentication scheme (i.e. reusing
  282. // tokens from other provisioners, calling a webhook, storing multiple secrets, allowing them to be multi-use, etc).
  283. // Authentication by the (self-signed) certificate with an optional challenge is required; supporting renewals incl. verification
  284. // of the client cert is not.
  285. certRep, err := auth.SignCSR(ctx, csr, msg)
  286. if err != nil {
  287. return createFailureResponse(ctx, csr, msg, microscep.BadRequest, fmt.Errorf("error when signing new certificate: %w", err))
  288. }
  289. res := Response{
  290. Operation: opnPKIOperation,
  291. Data: certRep.Raw,
  292. Certificate: certRep.Certificate,
  293. }
  294. return res, nil
  295. }
  296. func formatCapabilities(caps []string) []byte {
  297. return []byte(strings.Join(caps, "\r\n"))
  298. }
  299. // writeResponse writes a SCEP response back to the SCEP client.
  300. func writeResponse(w http.ResponseWriter, res Response) {
  301. if res.Error != nil {
  302. log.Error(w, res.Error)
  303. }
  304. if res.Certificate != nil {
  305. api.LogCertificate(w, res.Certificate)
  306. }
  307. w.Header().Set("Content-Type", contentHeader(res))
  308. _, _ = w.Write(res.Data)
  309. }
  310. func fail(w http.ResponseWriter, err error) {
  311. log.Error(w, err)
  312. http.Error(w, err.Error(), http.StatusInternalServerError)
  313. }
  314. func createFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *scep.PKIMessage, info microscep.FailInfo, failError error) (Response, error) {
  315. auth := scep.MustFromContext(ctx)
  316. certRepMsg, err := auth.CreateFailureResponse(ctx, csr, msg, scep.FailInfoName(info), failError.Error())
  317. if err != nil {
  318. return Response{}, err
  319. }
  320. return Response{
  321. Operation: opnPKIOperation,
  322. Data: certRepMsg.Raw,
  323. Error: failError,
  324. }, nil
  325. }
  326. func contentHeader(r Response) string {
  327. switch r.Operation {
  328. default:
  329. return "text/plain"
  330. case opnGetCACert:
  331. if r.CACertNum > 1 {
  332. return "application/x-x509-ca-ra-cert"
  333. }
  334. return "application/x-x509-ca-cert"
  335. case opnPKIOperation:
  336. return "application/x-pki-message"
  337. }
  338. }