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