api.go 10 KB

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