authority.go 15 KB

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