4
0

api.go 14 KB

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