4
0

api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. "github.com/smallstep/pkcs7"
  15. smallscep "github.com/smallstep/scep"
  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, r, 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, r, fmt.Errorf("scep get request failed: %w", err))
  101. return
  102. }
  103. writeResponse(w, r, 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, r, 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, r, fmt.Errorf("scep post request failed: %w", err))
  121. return
  122. }
  123. writeResponse(w, r, res)
  124. }
  125. func decodeRequest(r *http.Request) (request, error) {
  126. defer r.Body.Close()
  127. method := r.Method
  128. query, err := url.ParseQuery(r.URL.RawQuery)
  129. if err != nil {
  130. return request{}, fmt.Errorf("failed parsing URL query: %w", err)
  131. }
  132. operation := query.Get("operation")
  133. if operation == "" {
  134. return request{}, errors.New("no operation provided")
  135. }
  136. switch method {
  137. case http.MethodGet:
  138. switch operation {
  139. case opnGetCACert, opnGetCACaps:
  140. return request{
  141. Operation: operation,
  142. Message: []byte{},
  143. }, nil
  144. case opnPKIOperation:
  145. message := query.Get("message")
  146. decodedMessage, err := decodeMessage(message, r)
  147. if err != nil {
  148. return request{}, fmt.Errorf("failed decoding message: %w", 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{}, fmt.Errorf("failed reading request body: %w", 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. func decodeMessage(message string, r *http.Request) ([]byte, error) {
  171. if message == "" {
  172. return nil, errors.New("message must not be empty")
  173. }
  174. // decode the message, which should be base64 standard encoded. Any characters that
  175. // were escaped in the original query, were unescaped as part of url.ParseQuery, so
  176. // that doesn't need to be performed here. Return early if successful.
  177. decodedMessage, err := base64.StdEncoding.DecodeString(message)
  178. if err == nil {
  179. return decodedMessage, nil
  180. }
  181. // only interested in corrupt input errors below this. This type of error is the
  182. // most likely to return, but better safe than sorry.
  183. if _, ok := errors.AsType[base64.CorruptInputError](err); !ok {
  184. return nil, fmt.Errorf("failed base64 decoding message: %w", err)
  185. }
  186. // the below code is a workaround for macOS when it sends a GET PKIOperation, which seems to result
  187. // in a query with the '+' and '/' not being percent encoded; only the padding ('=') is encoded.
  188. // When that is unescaped in the code before this, this results in invalid base64. The workaround
  189. // is to obtain the original query, extract the message, apply transformation(s) to make it valid
  190. // base64 and try decoding it again. If it succeeds, the happy path can be followed with the patched
  191. // message. Otherwise we still return an error.
  192. rawQuery, err := parseRawQuery(r.URL.RawQuery)
  193. if err != nil {
  194. return nil, fmt.Errorf("failed to parse raw query: %w", err)
  195. }
  196. rawMessage := rawQuery.Get("message")
  197. if rawMessage == "" {
  198. return nil, errors.New("no message in raw query")
  199. }
  200. rawMessage = strings.ReplaceAll(rawMessage, "%3D", "=") // apparently the padding arrives encoded; the others (+, /) not?
  201. decodedMessage, err = base64.StdEncoding.DecodeString(rawMessage)
  202. if err != nil {
  203. return nil, fmt.Errorf("failed base64 decoding raw message: %w", err)
  204. }
  205. return decodedMessage, nil
  206. }
  207. // parseRawQuery parses a URL query into url.Values. It skips
  208. // unescaping keys and values. This code is based on url.ParseQuery.
  209. func parseRawQuery(query string) (url.Values, error) {
  210. m := make(url.Values)
  211. err := parseRawQueryWithoutUnescaping(m, query)
  212. return m, err
  213. }
  214. // parseRawQueryWithoutUnescaping parses the raw query into url.Values, skipping
  215. // unescaping of the parts. This code is based on url.parseQuery.
  216. func parseRawQueryWithoutUnescaping(m url.Values, query string) (err error) {
  217. for query != "" {
  218. var key string
  219. key, query, _ = strings.Cut(query, "&")
  220. if strings.Contains(key, ";") {
  221. return errors.New("invalid semicolon separator in query")
  222. }
  223. if key == "" {
  224. continue
  225. }
  226. key, value, _ := strings.Cut(key, "=")
  227. m[key] = append(m[key], value)
  228. }
  229. return err
  230. }
  231. // lookupProvisioner loads the provisioner associated with the request.
  232. // Responds 404 if the provisioner does not exist.
  233. func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {
  234. return func(w http.ResponseWriter, r *http.Request) {
  235. name := chi.URLParam(r, "provisionerName")
  236. provisionerName, err := url.PathUnescape(name)
  237. if err != nil {
  238. fail(w, r, fmt.Errorf("error url unescaping provisioner name '%s'", name))
  239. return
  240. }
  241. ctx := r.Context()
  242. auth := authority.MustFromContext(ctx)
  243. p, err := auth.LoadProvisionerByName(provisionerName)
  244. if err != nil {
  245. fail(w, r, err)
  246. return
  247. }
  248. prov, ok := p.(*provisioner.SCEP)
  249. if !ok {
  250. fail(w, r, errors.New("provisioner must be of type SCEP"))
  251. return
  252. }
  253. ctx = scep.NewProvisionerContext(ctx, scep.Provisioner(prov))
  254. next(w, r.WithContext(ctx))
  255. }
  256. }
  257. // GetCACert returns the CA certificates in a SCEP response
  258. func GetCACert(ctx context.Context) (Response, error) {
  259. auth := scep.MustFromContext(ctx)
  260. certs, err := auth.GetCACertificates(ctx)
  261. if err != nil {
  262. return Response{}, err
  263. }
  264. if len(certs) == 0 {
  265. return Response{}, errors.New("missing CA cert")
  266. }
  267. res := Response{
  268. Operation: opnGetCACert,
  269. CACertNum: len(certs),
  270. }
  271. if len(certs) == 1 {
  272. res.Data = certs[0].Raw
  273. } else {
  274. // create degenerate pkcs7 certificate structure, according to
  275. // https://tools.ietf.org/html/rfc8894#section-4.2.1.2, because
  276. // not signed or encrypted data has to be returned.
  277. data, err := smallscep.DegenerateCertificates(certs)
  278. if err != nil {
  279. return Response{}, err
  280. }
  281. res.Data = data
  282. }
  283. return res, nil
  284. }
  285. // GetCACaps returns the CA capabilities in a SCEP response
  286. func GetCACaps(ctx context.Context) (Response, error) {
  287. auth := scep.MustFromContext(ctx)
  288. caps := auth.GetCACaps(ctx)
  289. res := Response{
  290. Operation: opnGetCACaps,
  291. Data: formatCapabilities(caps),
  292. }
  293. return res, nil
  294. }
  295. // PKIOperation performs PKI operations and returns a SCEP response
  296. func PKIOperation(ctx context.Context, req request) (Response, error) {
  297. // parse the message using smallscep implementation
  298. microMsg, err := smallscep.ParsePKIMessage(req.Message)
  299. if err != nil {
  300. // return the error, because we can't use the msg for creating a CertRep
  301. return Response{}, fmt.Errorf("failed parsing SCEP request: %w", err)
  302. }
  303. // this is essentially doing the same as smallscep.ParsePKIMessage, but
  304. // gives us access to the p7 itself in scep.PKIMessage. Essentially a small
  305. // wrapper for the smallscep implementation.
  306. p7, err := pkcs7.Parse(microMsg.Raw)
  307. if err != nil {
  308. return Response{}, err
  309. }
  310. // copy over properties to our internal PKIMessage
  311. msg := &scep.PKIMessage{
  312. TransactionID: microMsg.TransactionID,
  313. MessageType: microMsg.MessageType,
  314. SenderNonce: microMsg.SenderNonce,
  315. Raw: microMsg.Raw,
  316. P7: p7,
  317. }
  318. auth := scep.MustFromContext(ctx)
  319. if err := auth.DecryptPKIEnvelope(ctx, msg); err != nil {
  320. return Response{}, err
  321. }
  322. // NOTE: at this point we have sufficient information for returning nicely signed CertReps
  323. csr := msg.CSRReqMessage.CSR
  324. transactionID := string(msg.TransactionID)
  325. challengePassword := msg.CSRReqMessage.ChallengePassword
  326. // NOTE: we're blocking the RenewalReq if the challenge does not match, because otherwise we don't have any authentication.
  327. // The macOS SCEP client performs renewals using PKCSreq. The CertNanny SCEP client will use PKCSreq with challenge too, it seems,
  328. // even if using the renewal flow as described in the README.md. MicroMDM SCEP client also only does PKCSreq by default, unless
  329. // a certificate exists; then it will use RenewalReq. Adding the challenge check here may be a small breaking change for clients.
  330. // We'll have to see how it works out.
  331. var signCSROpts []provisioner.SignCSROption
  332. if msg.MessageType == smallscep.PKCSReq || msg.MessageType == smallscep.RenewalReq {
  333. challengeOptions, err := auth.ValidateChallenge(ctx, csr, challengePassword, transactionID)
  334. if err != nil {
  335. if errors.Is(err, provisioner.ErrSCEPChallengeInvalid) {
  336. return createFailureResponse(ctx, csr, msg, smallscep.BadRequest, err.Error(), err)
  337. }
  338. // Keep the client-facing infoText fixed, but pass the real error
  339. // as failError so writeResponse logs the actual cause.
  340. return createFailureResponse(ctx, csr, msg, smallscep.BadRequest, "failed validating challenge password", err)
  341. }
  342. signCSROpts = append(signCSROpts, challengeOptions...)
  343. } else {
  344. scepErr := fmt.Errorf("unexpected message type: (%s)", string(msg.MessageType))
  345. return createFailureResponse(ctx, csr, msg, smallscep.BadRequest, scepErr.Error(), scepErr)
  346. }
  347. // TODO: authorize renewal: we can authorize renewals with the challenge password (if reusable secrets are used).
  348. // Renewals OPTIONALLY include the challenge if the existing cert is used as authentication, but client SHOULD omit the challenge.
  349. // This means that for renewal requests we should check the certificate provided to be signed before by the CA. We could
  350. // enforce use of the challenge if we want too. That way we could be more flexible in terms of authentication scheme (i.e. reusing
  351. // tokens from other provisioners, calling a webhook, storing multiple secrets, allowing them to be multi-use, etc).
  352. // Authentication by the (self-signed) certificate with an optional challenge is required; supporting renewals incl. verification
  353. // of the client cert is not.
  354. certRep, err := auth.SignCSR(ctx, csr, msg, signCSROpts...)
  355. if err != nil {
  356. if notifyErr := auth.NotifyFailure(ctx, csr, transactionID, 0, err.Error()); notifyErr != nil {
  357. // TODO(hs): ignore this error case? It's not critical if the notification fails; but logging it might be good
  358. _ = notifyErr
  359. }
  360. return createFailureResponse(ctx, csr, msg, smallscep.BadRequest, "internal server error; please see the certificate authority logs for more info", fmt.Errorf("error when signing new certificate: %w", err))
  361. }
  362. if notifyErr := auth.NotifySuccess(ctx, csr, certRep.Certificate, transactionID); notifyErr != nil {
  363. // TODO(hs): ignore this error case? It's not critical if the notification fails; but logging it might be good
  364. _ = notifyErr
  365. }
  366. res := Response{
  367. Operation: opnPKIOperation,
  368. Data: certRep.Raw,
  369. Certificate: certRep.Certificate,
  370. }
  371. return res, nil
  372. }
  373. func formatCapabilities(caps []string) []byte {
  374. return []byte(strings.Join(caps, "\r\n"))
  375. }
  376. // writeResponse writes a SCEP response back to the SCEP client.
  377. func writeResponse(w http.ResponseWriter, r *http.Request, res Response) {
  378. if res.Error != nil {
  379. log.Error(w, r, res.Error)
  380. }
  381. if res.Certificate != nil {
  382. api.LogCertificate(w, res.Certificate)
  383. }
  384. w.Header().Set("Content-Type", contentHeader(res))
  385. _, _ = w.Write(res.Data)
  386. }
  387. func fail(w http.ResponseWriter, r *http.Request, err error) {
  388. log.Error(w, r, err)
  389. http.Error(w, err.Error(), http.StatusInternalServerError)
  390. }
  391. func createFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *scep.PKIMessage, info smallscep.FailInfo, infoText string, failError error) (Response, error) {
  392. auth := scep.MustFromContext(ctx)
  393. certRepMsg, err := auth.CreateFailureResponse(ctx, csr, msg, scep.FailInfoName(info), infoText)
  394. if err != nil {
  395. return Response{}, err
  396. }
  397. return Response{
  398. Operation: opnPKIOperation,
  399. Data: certRepMsg.Raw,
  400. Error: failError,
  401. }, nil
  402. }
  403. func contentHeader(r Response) string {
  404. switch r.Operation {
  405. default:
  406. return "text/plain"
  407. case opnGetCACert:
  408. if r.CACertNum > 1 {
  409. return "application/x-x509-ca-ra-cert"
  410. }
  411. return "application/x-x509-ca-cert"
  412. case opnPKIOperation:
  413. return "application/x-pki-message"
  414. }
  415. }