4
0

authority.go 18 KB

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