authority.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package scep
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. microx509util "github.com/micromdm/scep/v2/cryptoutil/x509util"
  10. microscep "github.com/micromdm/scep/v2/scep"
  11. "go.mozilla.org/pkcs7"
  12. "go.step.sm/crypto/x509util"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. )
  15. // Authority is the layer that handles all SCEP interactions.
  16. type Authority struct {
  17. prefix string
  18. dns string
  19. intermediateCertificate *x509.Certificate
  20. caCerts []*x509.Certificate // TODO(hs): change to use these instead of root and intermediate
  21. service *Service
  22. signAuth SignAuthority
  23. }
  24. // AuthorityOptions required to create a new SCEP Authority.
  25. type AuthorityOptions struct {
  26. // Service provides the certificate chain, the signer and the decrypter to the Authority
  27. Service *Service
  28. // DNS is the host used to generate accurate SCEP links. By default the authority
  29. // will use the Host from the request, so this value will only be used if
  30. // request.Host is empty.
  31. DNS string
  32. // Prefix is a URL path prefix under which the SCEP api is served. This
  33. // prefix is required to generate accurate SCEP links.
  34. Prefix string
  35. }
  36. // SignAuthority is the interface for a signing authority
  37. type SignAuthority interface {
  38. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  39. LoadProvisionerByName(string) (provisioner.Interface, error)
  40. }
  41. // New returns a new Authority that implements the SCEP interface.
  42. func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) {
  43. authority := &Authority{
  44. prefix: ops.Prefix,
  45. dns: ops.DNS,
  46. signAuth: signAuth,
  47. }
  48. // TODO: this is not really nice to do; the Service should be removed
  49. // in its entirety to make this more interoperable with the rest of
  50. // step-ca, I think.
  51. if ops.Service != nil {
  52. authority.caCerts = ops.Service.certificateChain
  53. // TODO(hs): look into refactoring SCEP into using just caCerts everywhere, if it makes sense for more elaborate SCEP configuration. Keeping it like this for clarity (for now).
  54. authority.intermediateCertificate = ops.Service.certificateChain[0]
  55. authority.service = ops.Service
  56. }
  57. return authority, nil
  58. }
  59. var (
  60. // TODO: check the default capabilities; https://tools.ietf.org/html/rfc8894#section-3.5.2
  61. defaultCapabilities = []string{
  62. "Renewal", // NOTE: removing this will result in macOS SCEP client stating the server doesn't support renewal, but it uses PKCSreq to do so.
  63. "SHA-1",
  64. "SHA-256",
  65. "AES",
  66. "DES3",
  67. "SCEPStandard",
  68. "POSTPKIOperation",
  69. }
  70. )
  71. // LoadProvisionerByName calls out to the SignAuthority interface to load a
  72. // provisioner by name.
  73. func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  74. return a.signAuth.LoadProvisionerByName(name)
  75. }
  76. // GetLinkExplicit returns the requested link from the directory.
  77. func (a *Authority) GetLinkExplicit(provName string, abs bool, baseURL *url.URL, inputs ...string) string {
  78. return a.getLinkExplicit(provName, abs, baseURL, inputs...)
  79. }
  80. // getLinkExplicit returns an absolute or partial path to the given resource and a base
  81. // URL dynamically obtained from the request for which the link is being calculated.
  82. func (a *Authority) getLinkExplicit(provisionerName string, abs bool, baseURL *url.URL, inputs ...string) string {
  83. link := "/" + provisionerName
  84. if abs {
  85. // Copy the baseURL value from the pointer. https://github.com/golang/go/issues/38351
  86. u := url.URL{}
  87. if baseURL != nil {
  88. u = *baseURL
  89. }
  90. // If no Scheme is set, then default to http (in case of SCEP)
  91. if u.Scheme == "" {
  92. u.Scheme = "http"
  93. }
  94. // If no Host is set, then use the default (first DNS attr in the ca.json).
  95. if u.Host == "" {
  96. u.Host = a.dns
  97. }
  98. u.Path = a.prefix + link
  99. return u.String()
  100. }
  101. return link
  102. }
  103. // GetCACertificates returns the certificate (chain) for the CA
  104. func (a *Authority) GetCACertificates(ctx context.Context) ([]*x509.Certificate, error) {
  105. // TODO: this should return: the "SCEP Server (RA)" certificate, the issuing CA up to and excl. the root
  106. // Some clients do need the root certificate however; also see: https://github.com/openxpki/openxpki/issues/73
  107. //
  108. // This means we might need to think about if we should use the current intermediate CA
  109. // certificate as the "SCEP Server (RA)" certificate. It might be better to have a distinct
  110. // RA certificate, with a corresponding rsa.PrivateKey, just for SCEP usage, which is signed by
  111. // the intermediate CA. Will need to look how we can provide this nicely within step-ca.
  112. //
  113. // This might also mean that we might want to use a distinct instance of KMS for doing the key operations,
  114. // so that we can use RSA just for SCEP.
  115. //
  116. // Using an RA does not seem to exist in https://tools.ietf.org/html/rfc8894, but is mentioned in
  117. // https://tools.ietf.org/id/draft-nourse-scep-21.html. Will continue using the CA directly for now.
  118. //
  119. // The certificate to use should probably depend on the (configured) provisioner and may
  120. // use a distinct certificate, apart from the intermediate.
  121. p, err := provisionerFromContext(ctx)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if len(a.caCerts) == 0 {
  126. return nil, errors.New("no intermediate certificate available in SCEP authority")
  127. }
  128. certs := []*x509.Certificate{}
  129. certs = append(certs, a.caCerts[0])
  130. // NOTE: we're adding the CA roots here, but they are (highly likely) different than what the RFC means.
  131. // Clients are responsible to select the right cert(s) to use, though.
  132. if p.ShouldIncludeRootInChain() && len(a.caCerts) > 1 {
  133. certs = append(certs, a.caCerts[1])
  134. }
  135. return certs, nil
  136. }
  137. // DecryptPKIEnvelope decrypts an enveloped message
  138. func (a *Authority) DecryptPKIEnvelope(ctx context.Context, msg *PKIMessage) error {
  139. p7c, err := pkcs7.Parse(msg.P7.Content)
  140. if err != nil {
  141. return fmt.Errorf("error parsing pkcs7 content: %w", err)
  142. }
  143. envelope, err := p7c.Decrypt(a.intermediateCertificate, a.service.decrypter)
  144. if err != nil {
  145. return fmt.Errorf("error decrypting encrypted pkcs7 content: %w", err)
  146. }
  147. msg.pkiEnvelope = envelope
  148. switch msg.MessageType {
  149. case microscep.CertRep:
  150. certs, err := microscep.CACerts(msg.pkiEnvelope)
  151. if err != nil {
  152. return fmt.Errorf("error extracting CA certs from pkcs7 degenerate data: %w", err)
  153. }
  154. msg.CertRepMessage.Certificate = certs[0]
  155. return nil
  156. case microscep.PKCSReq, microscep.UpdateReq, microscep.RenewalReq:
  157. csr, err := x509.ParseCertificateRequest(msg.pkiEnvelope)
  158. if err != nil {
  159. return fmt.Errorf("parse CSR from pkiEnvelope: %w", err)
  160. }
  161. // check for challengePassword
  162. cp, err := microx509util.ParseChallengePassword(msg.pkiEnvelope)
  163. if err != nil {
  164. return fmt.Errorf("parse challenge password in pkiEnvelope: %w", err)
  165. }
  166. msg.CSRReqMessage = &microscep.CSRReqMessage{
  167. RawDecrypted: msg.pkiEnvelope,
  168. CSR: csr,
  169. ChallengePassword: cp,
  170. }
  171. return nil
  172. case microscep.GetCRL, microscep.GetCert, microscep.CertPoll:
  173. return errors.New("not implemented")
  174. }
  175. return nil
  176. }
  177. // SignCSR creates an x509.Certificate based on a CSR template and Cert Authority credentials
  178. // returns a new PKIMessage with CertRep data
  179. func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage) (*PKIMessage, error) {
  180. // TODO: intermediate storage of the request? In SCEP it's possible to request a csr/certificate
  181. // to be signed, which can be performed asynchronously / out-of-band. In that case a client can
  182. // poll for the status. It seems to be similar as what can happen in ACME, so might want to model
  183. // the implementation after the one in the ACME authority. Requires storage, etc.
  184. p, err := provisionerFromContext(ctx)
  185. if err != nil {
  186. return nil, err
  187. }
  188. // check if CSRReqMessage has already been decrypted
  189. if msg.CSRReqMessage.CSR == nil {
  190. if err := a.DecryptPKIEnvelope(ctx, msg); err != nil {
  191. return nil, err
  192. }
  193. csr = msg.CSRReqMessage.CSR
  194. }
  195. // Template data
  196. sans := []string{}
  197. sans = append(sans, csr.DNSNames...)
  198. sans = append(sans, csr.EmailAddresses...)
  199. for _, v := range csr.IPAddresses {
  200. sans = append(sans, v.String())
  201. }
  202. for _, v := range csr.URIs {
  203. sans = append(sans, v.String())
  204. }
  205. if len(sans) == 0 {
  206. sans = append(sans, csr.Subject.CommonName)
  207. }
  208. data := x509util.CreateTemplateData(csr.Subject.CommonName, sans)
  209. data.SetCertificateRequest(csr)
  210. data.SetSubject(x509util.Subject{
  211. Country: csr.Subject.Country,
  212. Organization: csr.Subject.Organization,
  213. OrganizationalUnit: csr.Subject.OrganizationalUnit,
  214. Locality: csr.Subject.Locality,
  215. Province: csr.Subject.Province,
  216. StreetAddress: csr.Subject.StreetAddress,
  217. PostalCode: csr.Subject.PostalCode,
  218. SerialNumber: csr.Subject.SerialNumber,
  219. CommonName: csr.Subject.CommonName,
  220. })
  221. // Get authorizations from the SCEP provisioner.
  222. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  223. signOps, err := p.AuthorizeSign(ctx, "")
  224. if err != nil {
  225. return nil, fmt.Errorf("error retrieving authorization options from SCEP provisioner: %w", err)
  226. }
  227. opts := provisioner.SignOptions{}
  228. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  229. if err != nil {
  230. return nil, fmt.Errorf("error creating template options from SCEP provisioner: %w", err)
  231. }
  232. signOps = append(signOps, templateOptions)
  233. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  234. if err != nil {
  235. return nil, fmt.Errorf("error generating certificate for order: %w", err)
  236. }
  237. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  238. cert := certChain[0]
  239. // and create a degenerate cert structure
  240. deg, err := microscep.DegenerateCertificates([]*x509.Certificate{cert})
  241. if err != nil {
  242. return nil, err
  243. }
  244. // apparently the pkcs7 library uses a global default setting for the content encryption
  245. // algorithm to use when en- or decrypting data. We need to restore the current setting after
  246. // the cryptographic operation, so that other usages of the library are not influenced by
  247. // this call to Encrypt(). We are not required to use the same algorithm the SCEP client uses.
  248. encryptionAlgorithmToRestore := pkcs7.ContentEncryptionAlgorithm
  249. pkcs7.ContentEncryptionAlgorithm = p.GetContentEncryptionAlgorithm()
  250. e7, err := pkcs7.Encrypt(deg, msg.P7.Certificates)
  251. if err != nil {
  252. return nil, err
  253. }
  254. pkcs7.ContentEncryptionAlgorithm = encryptionAlgorithmToRestore
  255. // PKIMessageAttributes to be signed
  256. config := pkcs7.SignerInfoConfig{
  257. ExtraSignedAttributes: []pkcs7.Attribute{
  258. {
  259. Type: oidSCEPtransactionID,
  260. Value: msg.TransactionID,
  261. },
  262. {
  263. Type: oidSCEPpkiStatus,
  264. Value: microscep.SUCCESS,
  265. },
  266. {
  267. Type: oidSCEPmessageType,
  268. Value: microscep.CertRep,
  269. },
  270. {
  271. Type: oidSCEPrecipientNonce,
  272. Value: msg.SenderNonce,
  273. },
  274. {
  275. Type: oidSCEPsenderNonce,
  276. Value: msg.SenderNonce,
  277. },
  278. },
  279. }
  280. signedData, err := pkcs7.NewSignedData(e7)
  281. if err != nil {
  282. return nil, err
  283. }
  284. // add the certificate into the signed data type
  285. // this cert must be added before the signedData because the recipient will expect it
  286. // as the first certificate in the array
  287. signedData.AddCertificate(cert)
  288. authCert := a.intermediateCertificate
  289. // sign the attributes
  290. if err := signedData.AddSigner(authCert, a.service.signer, config); err != nil {
  291. return nil, err
  292. }
  293. certRepBytes, err := signedData.Finish()
  294. if err != nil {
  295. return nil, err
  296. }
  297. cr := &CertRepMessage{
  298. PKIStatus: microscep.SUCCESS,
  299. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  300. Certificate: cert,
  301. degenerate: deg,
  302. }
  303. // create a CertRep message from the original
  304. crepMsg := &PKIMessage{
  305. Raw: certRepBytes,
  306. TransactionID: msg.TransactionID,
  307. MessageType: microscep.CertRep,
  308. CertRepMessage: cr,
  309. }
  310. return crepMsg, nil
  311. }
  312. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  313. func (a *Authority) CreateFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  314. config := pkcs7.SignerInfoConfig{
  315. ExtraSignedAttributes: []pkcs7.Attribute{
  316. {
  317. Type: oidSCEPtransactionID,
  318. Value: msg.TransactionID,
  319. },
  320. {
  321. Type: oidSCEPpkiStatus,
  322. Value: microscep.FAILURE,
  323. },
  324. {
  325. Type: oidSCEPfailInfo,
  326. Value: info,
  327. },
  328. {
  329. Type: oidSCEPfailInfoText,
  330. Value: infoText,
  331. },
  332. {
  333. Type: oidSCEPmessageType,
  334. Value: microscep.CertRep,
  335. },
  336. {
  337. Type: oidSCEPsenderNonce,
  338. Value: msg.SenderNonce,
  339. },
  340. {
  341. Type: oidSCEPrecipientNonce,
  342. Value: msg.SenderNonce,
  343. },
  344. },
  345. }
  346. signedData, err := pkcs7.NewSignedData(nil)
  347. if err != nil {
  348. return nil, err
  349. }
  350. // sign the attributes
  351. if err := signedData.AddSigner(a.intermediateCertificate, a.service.signer, config); err != nil {
  352. return nil, err
  353. }
  354. certRepBytes, err := signedData.Finish()
  355. if err != nil {
  356. return nil, err
  357. }
  358. cr := &CertRepMessage{
  359. PKIStatus: microscep.FAILURE,
  360. FailInfo: microscep.FailInfo(info),
  361. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  362. }
  363. // create a CertRep message from the original
  364. crepMsg := &PKIMessage{
  365. Raw: certRepBytes,
  366. TransactionID: msg.TransactionID,
  367. MessageType: microscep.CertRep,
  368. CertRepMessage: cr,
  369. }
  370. return crepMsg, nil
  371. }
  372. // MatchChallengePassword verifies a SCEP challenge password
  373. func (a *Authority) MatchChallengePassword(ctx context.Context, password string) (bool, error) {
  374. p, err := provisionerFromContext(ctx)
  375. if err != nil {
  376. return false, err
  377. }
  378. if subtle.ConstantTimeCompare([]byte(p.GetChallengePassword()), []byte(password)) == 1 {
  379. return true, nil
  380. }
  381. // TODO: support dynamic challenges, i.e. a list of challenges instead of one?
  382. // That's probably a bit harder to configure, though; likely requires some data store
  383. // that can be interacted with more easily, via some internal API, for example.
  384. return false, nil
  385. }
  386. // GetCACaps returns the CA capabilities
  387. func (a *Authority) GetCACaps(ctx context.Context) []string {
  388. p, err := provisionerFromContext(ctx)
  389. if err != nil {
  390. return defaultCapabilities
  391. }
  392. caps := p.GetCapabilities()
  393. if len(caps) == 0 {
  394. return defaultCapabilities
  395. }
  396. // TODO: validate the caps? Ensure they are the right format according to RFC?
  397. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  398. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  399. // For example for renewals, which we could disable in the provisioner, should then also
  400. // not be reported in cacaps operation.
  401. return caps
  402. }