4
0

api.go 11 KB

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