authority.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package scep
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "sync"
  9. "github.com/smallstep/pkcs7"
  10. smallscep "github.com/smallstep/scep"
  11. smallscepx509util "github.com/smallstep/scep/x509util"
  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. signAuth SignAuthority
  18. roots []*x509.Certificate
  19. intermediates []*x509.Certificate
  20. defaultSigner crypto.Signer
  21. signerCertificate *x509.Certificate
  22. defaultDecrypter crypto.Decrypter
  23. decrypterCertificate *x509.Certificate
  24. scepProvisionerNames []string
  25. provisionersMutex sync.RWMutex
  26. encryptionAlgorithmMutex sync.Mutex
  27. }
  28. type authorityKey struct{}
  29. // NewContext adds the given authority to the context.
  30. func NewContext(ctx context.Context, a *Authority) context.Context {
  31. return context.WithValue(ctx, authorityKey{}, a)
  32. }
  33. // FromContext returns the current authority from the given context.
  34. func FromContext(ctx context.Context) (a *Authority, ok bool) {
  35. a, ok = ctx.Value(authorityKey{}).(*Authority)
  36. return
  37. }
  38. // MustFromContext returns the current authority from the given context. It will
  39. // panic if the authority is not in the context.
  40. func MustFromContext(ctx context.Context) *Authority {
  41. if a, ok := FromContext(ctx); !ok {
  42. panic("scep authority is not in the context")
  43. } else {
  44. return a
  45. }
  46. }
  47. // SignAuthority is the interface for a signing authority
  48. type SignAuthority interface {
  49. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  50. LoadProvisionerByName(string) (provisioner.Interface, error)
  51. }
  52. // New returns a new Authority that implements the SCEP interface.
  53. func New(signAuth SignAuthority, opts Options) (*Authority, error) {
  54. if err := opts.Validate(); err != nil {
  55. return nil, err
  56. }
  57. return &Authority{
  58. signAuth: signAuth, // TODO: provide signAuth through context instead?
  59. roots: opts.Roots,
  60. intermediates: opts.Intermediates,
  61. defaultSigner: opts.Signer,
  62. signerCertificate: opts.SignerCert,
  63. defaultDecrypter: opts.Decrypter,
  64. decrypterCertificate: opts.SignerCert, // the intermediate signer cert is also the decrypter cert (if RSA)
  65. scepProvisionerNames: opts.SCEPProvisionerNames,
  66. }, nil
  67. }
  68. // Validate validates if the SCEP Authority has a valid configuration.
  69. // The validation includes a check if a decrypter is available, either
  70. // an authority wide decrypter, or a provisioner specific decrypter.
  71. func (a *Authority) Validate() error {
  72. if a == nil {
  73. return nil
  74. }
  75. a.provisionersMutex.RLock()
  76. defer a.provisionersMutex.RUnlock()
  77. noDefaultDecrypterAvailable := a.defaultDecrypter == nil
  78. for _, name := range a.scepProvisionerNames {
  79. p, err := a.LoadProvisionerByName(name)
  80. if err != nil {
  81. return fmt.Errorf("failed loading provisioner %q: %w", name, err)
  82. }
  83. if scepProv, ok := p.(*provisioner.SCEP); ok {
  84. cert, decrypter := scepProv.GetDecrypter()
  85. // TODO(hs): return sentinel/typed error, to be able to ignore/log these cases during init?
  86. if cert == nil && noDefaultDecrypterAvailable {
  87. return fmt.Errorf("SCEP provisioner %q does not have a decrypter certificate", name)
  88. }
  89. if decrypter == nil && noDefaultDecrypterAvailable {
  90. return fmt.Errorf("SCEP provisioner %q does not have decrypter", name)
  91. }
  92. }
  93. }
  94. return nil
  95. }
  96. // UpdateProvisioners updates the SCEP Authority with the new, and hopefully
  97. // current SCEP provisioners configured. This allows the Authority to be
  98. // validated with the latest data.
  99. func (a *Authority) UpdateProvisioners(scepProvisionerNames []string) {
  100. if a == nil {
  101. return
  102. }
  103. a.provisionersMutex.Lock()
  104. defer a.provisionersMutex.Unlock()
  105. a.scepProvisionerNames = scepProvisionerNames
  106. }
  107. var (
  108. // TODO: check the default capabilities; https://tools.ietf.org/html/rfc8894#section-3.5.2
  109. defaultCapabilities = []string{
  110. "Renewal", // NOTE: removing this will result in macOS SCEP client stating the server doesn't support renewal, but it uses PKCSreq to do so.
  111. "SHA-1",
  112. "SHA-256",
  113. "AES",
  114. "DES3",
  115. "SCEPStandard",
  116. "POSTPKIOperation",
  117. }
  118. )
  119. // LoadProvisionerByName calls out to the SignAuthority interface to load a
  120. // provisioner by name.
  121. func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  122. return a.signAuth.LoadProvisionerByName(name)
  123. }
  124. // GetCACertificates returns the certificate (chain) for the CA.
  125. //
  126. // This methods returns the "SCEP Server (RA)" certificate, the issuing CA up to and excl. the root.
  127. // Some clients do need the root certificate however; also see: https://github.com/openxpki/openxpki/issues/73
  128. //
  129. // In case a provisioner specific decrypter is available, this is used as the "SCEP Server (RA)" certificate
  130. // instead of the CA intermediate directly. This uses a distinct instance of a KMS for doing the SCEP key
  131. // operations, so that RSA can be used for just SCEP.
  132. //
  133. // Using an RA does not seem to exist in https://tools.ietf.org/html/rfc8894, but is mentioned in
  134. // https://tools.ietf.org/id/draft-nourse-scep-21.html.
  135. func (a *Authority) GetCACertificates(ctx context.Context) (certs []*x509.Certificate, err error) {
  136. p := provisionerFromContext(ctx)
  137. // if a provisioner specific RSA decrypter is available, it is returned as
  138. // the first certificate.
  139. if decrypterCertificate, _ := p.GetDecrypter(); decrypterCertificate != nil {
  140. certs = append(certs, decrypterCertificate)
  141. }
  142. // the CA intermediate is added to the chain by default. It's possible to
  143. // exclude it from being added through configuration. This can be useful in
  144. // environments where the SCEP client doesn't select the right RSA decrypter
  145. // certificate, resulting in the wrong recipient in the PKCS7 message.
  146. if p.ShouldIncludeIntermediateInChain() || len(certs) == 0 {
  147. // TODO(hs): ensure logic is in place that checks the signer is the first
  148. // intermediate and that there are no double certificates.
  149. certs = append(certs, a.intermediates...)
  150. }
  151. // the CA roots are added for completeness when configured to do so. Clients
  152. // are responsible to select the right cert(s) to store and use.
  153. if p.ShouldIncludeRootInChain() {
  154. certs = append(certs, a.roots...)
  155. }
  156. return certs, nil
  157. }
  158. // DecryptPKIEnvelope decrypts an enveloped message
  159. func (a *Authority) DecryptPKIEnvelope(ctx context.Context, msg *PKIMessage) error {
  160. p7c, err := pkcs7.Parse(msg.P7.Content)
  161. if err != nil {
  162. return fmt.Errorf("error parsing pkcs7 content: %w", err)
  163. }
  164. cert, decrypter, err := a.selectDecrypter(ctx)
  165. if err != nil {
  166. return fmt.Errorf("failed selecting decrypter: %w", err)
  167. }
  168. envelope, err := p7c.Decrypt(cert, decrypter)
  169. if err != nil {
  170. return fmt.Errorf("error decrypting encrypted pkcs7 content: %w", err)
  171. }
  172. msg.pkiEnvelope = envelope
  173. switch msg.MessageType {
  174. case smallscep.CertRep:
  175. certs, err := smallscep.CACerts(msg.pkiEnvelope)
  176. if err != nil {
  177. return fmt.Errorf("error extracting CA certs from pkcs7 degenerate data: %w", err)
  178. }
  179. msg.CertRepMessage.Certificate = certs[0]
  180. return nil
  181. case smallscep.PKCSReq, smallscep.UpdateReq, smallscep.RenewalReq:
  182. csr, err := x509.ParseCertificateRequest(msg.pkiEnvelope)
  183. if err != nil {
  184. return fmt.Errorf("parse CSR from pkiEnvelope: %w", err)
  185. }
  186. if err := csr.CheckSignature(); err != nil {
  187. return fmt.Errorf("invalid CSR signature; %w", err)
  188. }
  189. // extract the challenge password
  190. cp, err := smallscepx509util.ParseChallengePassword(msg.pkiEnvelope)
  191. if err != nil {
  192. return fmt.Errorf("parse challenge password in pkiEnvelope: %w", err)
  193. }
  194. msg.CSRReqMessage = &smallscep.CSRReqMessage{
  195. RawDecrypted: msg.pkiEnvelope,
  196. CSR: csr,
  197. ChallengePassword: cp,
  198. }
  199. return nil
  200. case smallscep.GetCRL, smallscep.GetCert, smallscep.CertPoll:
  201. return errors.New("not implemented")
  202. }
  203. return nil
  204. }
  205. // SignCSR creates an x509.Certificate based on a CSR template and Cert Authority credentials
  206. // returns a new PKIMessage with CertRep data
  207. func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage) (*PKIMessage, error) {
  208. // TODO: intermediate storage of the request? In SCEP it's possible to request a csr/certificate
  209. // to be signed, which can be performed asynchronously / out-of-band. In that case a client can
  210. // poll for the status. It seems to be similar as what can happen in ACME, so might want to model
  211. // the implementation after the one in the ACME authority. Requires storage, etc.
  212. p := provisionerFromContext(ctx)
  213. // check if CSRReqMessage has already been decrypted
  214. if msg.CSRReqMessage.CSR == nil {
  215. if err := a.DecryptPKIEnvelope(ctx, msg); err != nil {
  216. return nil, err
  217. }
  218. csr = msg.CSRReqMessage.CSR
  219. }
  220. // Template data
  221. sans := []string{}
  222. sans = append(sans, csr.DNSNames...)
  223. sans = append(sans, csr.EmailAddresses...)
  224. for _, v := range csr.IPAddresses {
  225. sans = append(sans, v.String())
  226. }
  227. for _, v := range csr.URIs {
  228. sans = append(sans, v.String())
  229. }
  230. if len(sans) == 0 {
  231. sans = append(sans, csr.Subject.CommonName)
  232. }
  233. data := x509util.CreateTemplateData(csr.Subject.CommonName, sans)
  234. data.SetCertificateRequest(csr)
  235. data.SetSubject(x509util.Subject{
  236. Country: csr.Subject.Country,
  237. Organization: csr.Subject.Organization,
  238. OrganizationalUnit: csr.Subject.OrganizationalUnit,
  239. Locality: csr.Subject.Locality,
  240. Province: csr.Subject.Province,
  241. StreetAddress: csr.Subject.StreetAddress,
  242. PostalCode: csr.Subject.PostalCode,
  243. SerialNumber: csr.Subject.SerialNumber,
  244. CommonName: csr.Subject.CommonName,
  245. })
  246. // Get authorizations from the SCEP provisioner.
  247. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  248. signOps, err := p.AuthorizeSign(ctx, "")
  249. if err != nil {
  250. return nil, fmt.Errorf("error retrieving authorization options from SCEP provisioner: %w", err)
  251. }
  252. // Unlike most of the provisioners, scep's AuthorizeSign method doesn't
  253. // define the templates, and the template data used in WebHooks is not
  254. // available.
  255. for _, signOp := range signOps {
  256. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  257. wc.TemplateData = data
  258. }
  259. }
  260. opts := provisioner.SignOptions{}
  261. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  262. if err != nil {
  263. return nil, fmt.Errorf("error creating template options from SCEP provisioner: %w", err)
  264. }
  265. signOps = append(signOps, templateOptions)
  266. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  267. if err != nil {
  268. return nil, fmt.Errorf("error generating certificate for order: %w", err)
  269. }
  270. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  271. cert := certChain[0]
  272. // and create a degenerate cert structure
  273. deg, err := smallscep.DegenerateCertificates([]*x509.Certificate{cert})
  274. if err != nil {
  275. return nil, fmt.Errorf("failed generating degenerate certificate: %w", err)
  276. }
  277. e7, err := a.encrypt(deg, msg.P7.Certificates, p.GetContentEncryptionAlgorithm())
  278. if err != nil {
  279. return nil, fmt.Errorf("failed encrypting degenerate certificate: %w", err)
  280. }
  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: smallscep.SUCCESS,
  291. },
  292. {
  293. Type: oidSCEPmessageType,
  294. Value: smallscep.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. signerCert, signer, err := a.selectSigner(ctx)
  315. if err != nil {
  316. return nil, fmt.Errorf("failed selecting signer: %w", err)
  317. }
  318. // sign the attributes
  319. if err := signedData.AddSigner(signerCert, signer, config); err != nil {
  320. return nil, err
  321. }
  322. certRepBytes, err := signedData.Finish()
  323. if err != nil {
  324. return nil, err
  325. }
  326. cr := &CertRepMessage{
  327. PKIStatus: smallscep.SUCCESS,
  328. RecipientNonce: smallscep.RecipientNonce(msg.SenderNonce),
  329. Certificate: cert,
  330. degenerate: deg,
  331. }
  332. // create a CertRep message from the original
  333. crepMsg := &PKIMessage{
  334. Raw: certRepBytes,
  335. TransactionID: msg.TransactionID,
  336. MessageType: smallscep.CertRep,
  337. CertRepMessage: cr,
  338. }
  339. return crepMsg, nil
  340. }
  341. func (a *Authority) encrypt(content []byte, recipients []*x509.Certificate, algorithm int) ([]byte, error) {
  342. // apparently the pkcs7 library uses a global default setting for the content encryption
  343. // algorithm to use when en- or decrypting data. We need to restore the current setting after
  344. // the cryptographic operation, so that other usages of the library are not influenced by
  345. // this call to Encrypt(). We are not required to use the same algorithm the SCEP client uses.
  346. a.encryptionAlgorithmMutex.Lock()
  347. defer a.encryptionAlgorithmMutex.Unlock()
  348. encryptionAlgorithmToRestore := pkcs7.ContentEncryptionAlgorithm
  349. defer func() {
  350. pkcs7.ContentEncryptionAlgorithm = encryptionAlgorithmToRestore
  351. }()
  352. pkcs7.ContentEncryptionAlgorithm = algorithm
  353. e7, err := pkcs7.Encrypt(content, recipients)
  354. if err != nil {
  355. return nil, err
  356. }
  357. return e7, nil
  358. }
  359. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  360. func (a *Authority) CreateFailureResponse(ctx context.Context, _ *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  361. config := pkcs7.SignerInfoConfig{
  362. ExtraSignedAttributes: []pkcs7.Attribute{
  363. {
  364. Type: oidSCEPtransactionID,
  365. Value: msg.TransactionID,
  366. },
  367. {
  368. Type: oidSCEPpkiStatus,
  369. Value: smallscep.FAILURE,
  370. },
  371. {
  372. Type: oidSCEPfailInfo,
  373. Value: info,
  374. },
  375. {
  376. Type: oidSCEPfailInfoText,
  377. Value: infoText,
  378. },
  379. {
  380. Type: oidSCEPmessageType,
  381. Value: smallscep.CertRep,
  382. },
  383. {
  384. Type: oidSCEPsenderNonce,
  385. Value: msg.SenderNonce,
  386. },
  387. {
  388. Type: oidSCEPrecipientNonce,
  389. Value: msg.SenderNonce,
  390. },
  391. },
  392. }
  393. signedData, err := pkcs7.NewSignedData(nil)
  394. if err != nil {
  395. return nil, err
  396. }
  397. signerCert, signer, err := a.selectSigner(ctx)
  398. if err != nil {
  399. return nil, fmt.Errorf("failed selecting signer: %w", err)
  400. }
  401. // sign the attributes
  402. if err := signedData.AddSigner(signerCert, signer, config); err != nil {
  403. return nil, err
  404. }
  405. certRepBytes, err := signedData.Finish()
  406. if err != nil {
  407. return nil, err
  408. }
  409. cr := &CertRepMessage{
  410. PKIStatus: smallscep.FAILURE,
  411. FailInfo: smallscep.FailInfo(info),
  412. RecipientNonce: smallscep.RecipientNonce(msg.SenderNonce),
  413. }
  414. // create a CertRep message from the original
  415. crepMsg := &PKIMessage{
  416. Raw: certRepBytes,
  417. TransactionID: msg.TransactionID,
  418. MessageType: smallscep.CertRep,
  419. CertRepMessage: cr,
  420. }
  421. return crepMsg, nil
  422. }
  423. // GetCACaps returns the CA capabilities
  424. func (a *Authority) GetCACaps(ctx context.Context) []string {
  425. p := provisionerFromContext(ctx)
  426. caps := p.GetCapabilities()
  427. if len(caps) == 0 {
  428. return defaultCapabilities
  429. }
  430. // TODO: validate the caps? Ensure they are the right format according to RFC?
  431. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  432. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  433. // For example for renewals, which we could disable in the provisioner, should then also
  434. // not be reported in cacaps operation.
  435. return caps
  436. }
  437. func (a *Authority) ValidateChallenge(ctx context.Context, csr *x509.CertificateRequest, challenge, transactionID string) error {
  438. p := provisionerFromContext(ctx)
  439. return p.ValidateChallenge(ctx, csr, challenge, transactionID)
  440. }
  441. func (a *Authority) NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
  442. p := provisionerFromContext(ctx)
  443. return p.NotifySuccess(ctx, csr, cert, transactionID)
  444. }
  445. func (a *Authority) NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
  446. p := provisionerFromContext(ctx)
  447. return p.NotifyFailure(ctx, csr, transactionID, errorCode, errorDescription)
  448. }
  449. func (a *Authority) selectDecrypter(ctx context.Context) (cert *x509.Certificate, decrypter crypto.Decrypter, err error) {
  450. p := provisionerFromContext(ctx)
  451. cert, decrypter = p.GetDecrypter()
  452. switch {
  453. case cert != nil && decrypter != nil:
  454. return
  455. case cert == nil && decrypter != nil:
  456. return nil, nil, fmt.Errorf("provisioner %q does not have a decrypter certificate available", p.GetName())
  457. case cert != nil && decrypter == nil:
  458. return nil, nil, fmt.Errorf("provisioner %q does not have a decrypter available", p.GetName())
  459. }
  460. cert, decrypter = a.decrypterCertificate, a.defaultDecrypter
  461. switch {
  462. case cert == nil && decrypter != nil:
  463. return nil, nil, fmt.Errorf("provisioner %q does not have a default decrypter certificate available", p.GetName())
  464. case cert != nil && decrypter == nil:
  465. return nil, nil, fmt.Errorf("provisioner %q does not have a default decrypter available", p.GetName())
  466. }
  467. return
  468. }
  469. func (a *Authority) selectSigner(ctx context.Context) (cert *x509.Certificate, signer crypto.Signer, err error) {
  470. p := provisionerFromContext(ctx)
  471. cert, signer = p.GetSigner()
  472. switch {
  473. case cert != nil && signer != nil:
  474. return
  475. case cert == nil && signer != nil:
  476. return nil, nil, fmt.Errorf("provisioner %q does not have a signer certificate available", p.GetName())
  477. case cert != nil && signer == nil:
  478. return nil, nil, fmt.Errorf("provisioner %q does not have a signer available", p.GetName())
  479. }
  480. cert, signer = a.signerCertificate, a.defaultSigner
  481. switch {
  482. case cert == nil && signer != nil:
  483. return nil, nil, fmt.Errorf("provisioner %q does not have a default signer certificate available", p.GetName())
  484. case cert != nil && signer == nil:
  485. return nil, nil, fmt.Errorf("provisioner %q does not have a default signer available", p.GetName())
  486. }
  487. return
  488. }