api.go 13 KB

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