authority.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. Sign(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) (*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. // Get authorizations from the SCEP provisioner.
  250. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  251. signOps, err := p.AuthorizeSign(ctx, "")
  252. if err != nil {
  253. return nil, fmt.Errorf("error retrieving authorization options from SCEP provisioner: %w", err)
  254. }
  255. // Unlike most of the provisioners, scep's AuthorizeSign method doesn't
  256. // define the templates, and the template data used in WebHooks is not
  257. // available.
  258. for _, signOp := range signOps {
  259. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  260. wc.TemplateData = data
  261. }
  262. }
  263. opts := provisioner.SignOptions{}
  264. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  265. if err != nil {
  266. return nil, fmt.Errorf("error creating template options from SCEP provisioner: %w", err)
  267. }
  268. signOps = append(signOps, templateOptions)
  269. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  270. if err != nil {
  271. return nil, fmt.Errorf("error generating certificate for order: %w", err)
  272. }
  273. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  274. cert := certChain[0]
  275. // and create a degenerate cert structure
  276. deg, err := smallscep.DegenerateCertificates([]*x509.Certificate{cert})
  277. if err != nil {
  278. return nil, fmt.Errorf("failed generating degenerate certificate: %w", err)
  279. }
  280. e7, err := a.encrypt(deg, msg.P7.Certificates, p.GetContentEncryptionAlgorithm())
  281. if err != nil {
  282. return nil, fmt.Errorf("failed encrypting degenerate certificate: %w", err)
  283. }
  284. // PKIMessageAttributes to be signed
  285. config := pkcs7.SignerInfoConfig{
  286. ExtraSignedAttributes: []pkcs7.Attribute{
  287. {
  288. Type: oidSCEPtransactionID,
  289. Value: msg.TransactionID,
  290. },
  291. {
  292. Type: oidSCEPpkiStatus,
  293. Value: smallscep.SUCCESS,
  294. },
  295. {
  296. Type: oidSCEPmessageType,
  297. Value: smallscep.CertRep,
  298. },
  299. {
  300. Type: oidSCEPrecipientNonce,
  301. Value: msg.SenderNonce,
  302. },
  303. {
  304. Type: oidSCEPsenderNonce,
  305. Value: msg.SenderNonce,
  306. },
  307. },
  308. }
  309. signedData, err := pkcs7.NewSignedData(e7)
  310. if err != nil {
  311. return nil, err
  312. }
  313. // add the certificate into the signed data type
  314. // this cert must be added before the signedData because the recipient will expect it
  315. // as the first certificate in the array
  316. signedData.AddCertificate(cert)
  317. signerCert, signer, err := a.selectSigner(ctx)
  318. if err != nil {
  319. return nil, fmt.Errorf("failed selecting signer: %w", err)
  320. }
  321. // sign the attributes
  322. if err := signedData.AddSigner(signerCert, signer, config); err != nil {
  323. return nil, err
  324. }
  325. certRepBytes, err := signedData.Finish()
  326. if err != nil {
  327. return nil, err
  328. }
  329. cr := &CertRepMessage{
  330. PKIStatus: smallscep.SUCCESS,
  331. RecipientNonce: smallscep.RecipientNonce(msg.SenderNonce),
  332. Certificate: cert,
  333. degenerate: deg,
  334. }
  335. // create a CertRep message from the original
  336. crepMsg := &PKIMessage{
  337. Raw: certRepBytes,
  338. TransactionID: msg.TransactionID,
  339. MessageType: smallscep.CertRep,
  340. CertRepMessage: cr,
  341. }
  342. return crepMsg, nil
  343. }
  344. func (a *Authority) encrypt(content []byte, recipients []*x509.Certificate, algorithm int) ([]byte, error) {
  345. // apparently the pkcs7 library uses a global default setting for the content encryption
  346. // algorithm to use when en- or decrypting data. We need to restore the current setting after
  347. // the cryptographic operation, so that other usages of the library are not influenced by
  348. // this call to Encrypt(). We are not required to use the same algorithm the SCEP client uses.
  349. a.encryptionAlgorithmMutex.Lock()
  350. defer a.encryptionAlgorithmMutex.Unlock()
  351. encryptionAlgorithmToRestore := pkcs7.ContentEncryptionAlgorithm
  352. defer func() {
  353. pkcs7.ContentEncryptionAlgorithm = encryptionAlgorithmToRestore
  354. }()
  355. pkcs7.ContentEncryptionAlgorithm = algorithm
  356. e7, err := pkcs7.Encrypt(content, recipients)
  357. if err != nil {
  358. return nil, err
  359. }
  360. return e7, nil
  361. }
  362. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  363. func (a *Authority) CreateFailureResponse(ctx context.Context, _ *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  364. config := pkcs7.SignerInfoConfig{
  365. ExtraSignedAttributes: []pkcs7.Attribute{
  366. {
  367. Type: oidSCEPtransactionID,
  368. Value: msg.TransactionID,
  369. },
  370. {
  371. Type: oidSCEPpkiStatus,
  372. Value: smallscep.FAILURE,
  373. },
  374. {
  375. Type: oidSCEPfailInfo,
  376. Value: info,
  377. },
  378. {
  379. Type: oidSCEPfailInfoText,
  380. Value: infoText,
  381. },
  382. {
  383. Type: oidSCEPmessageType,
  384. Value: smallscep.CertRep,
  385. },
  386. {
  387. Type: oidSCEPsenderNonce,
  388. Value: msg.SenderNonce,
  389. },
  390. {
  391. Type: oidSCEPrecipientNonce,
  392. Value: msg.SenderNonce,
  393. },
  394. },
  395. }
  396. signedData, err := pkcs7.NewSignedData(nil)
  397. if err != nil {
  398. return nil, err
  399. }
  400. signerCert, signer, err := a.selectSigner(ctx)
  401. if err != nil {
  402. return nil, fmt.Errorf("failed selecting signer: %w", err)
  403. }
  404. // sign the attributes
  405. if err := signedData.AddSigner(signerCert, signer, config); err != nil {
  406. return nil, err
  407. }
  408. certRepBytes, err := signedData.Finish()
  409. if err != nil {
  410. return nil, err
  411. }
  412. cr := &CertRepMessage{
  413. PKIStatus: smallscep.FAILURE,
  414. FailInfo: smallscep.FailInfo(info),
  415. RecipientNonce: smallscep.RecipientNonce(msg.SenderNonce),
  416. }
  417. // create a CertRep message from the original
  418. crepMsg := &PKIMessage{
  419. Raw: certRepBytes,
  420. TransactionID: msg.TransactionID,
  421. MessageType: smallscep.CertRep,
  422. CertRepMessage: cr,
  423. }
  424. return crepMsg, nil
  425. }
  426. // GetCACaps returns the CA capabilities
  427. func (a *Authority) GetCACaps(ctx context.Context) []string {
  428. p := provisionerFromContext(ctx)
  429. caps := p.GetCapabilities()
  430. if len(caps) == 0 {
  431. return defaultCapabilities
  432. }
  433. // TODO: validate the caps? Ensure they are the right format according to RFC?
  434. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  435. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  436. // For example for renewals, which we could disable in the provisioner, should then also
  437. // not be reported in cacaps operation.
  438. return caps
  439. }
  440. func (a *Authority) ValidateChallenge(ctx context.Context, csr *x509.CertificateRequest, challenge, transactionID string) error {
  441. p := provisionerFromContext(ctx)
  442. return p.ValidateChallenge(ctx, csr, challenge, transactionID)
  443. }
  444. func (a *Authority) NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
  445. p := provisionerFromContext(ctx)
  446. return p.NotifySuccess(ctx, csr, cert, transactionID)
  447. }
  448. func (a *Authority) NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
  449. p := provisionerFromContext(ctx)
  450. return p.NotifyFailure(ctx, csr, transactionID, errorCode, errorDescription)
  451. }
  452. func (a *Authority) selectDecrypter(ctx context.Context) (cert *x509.Certificate, decrypter crypto.Decrypter, err error) {
  453. p := provisionerFromContext(ctx)
  454. cert, decrypter = p.GetDecrypter()
  455. switch {
  456. case cert != nil && decrypter != nil:
  457. return
  458. case cert == nil && decrypter != nil:
  459. return nil, nil, fmt.Errorf("provisioner %q does not have a decrypter certificate available", p.GetName())
  460. case cert != nil && decrypter == nil:
  461. return nil, nil, fmt.Errorf("provisioner %q does not have a decrypter available", p.GetName())
  462. }
  463. cert, decrypter = a.decrypterCertificate, a.defaultDecrypter
  464. switch {
  465. case cert == nil && decrypter != nil:
  466. return nil, nil, fmt.Errorf("provisioner %q does not have a default decrypter certificate available", p.GetName())
  467. case cert != nil && decrypter == nil:
  468. return nil, nil, fmt.Errorf("provisioner %q does not have a default decrypter available", p.GetName())
  469. }
  470. return
  471. }
  472. func (a *Authority) selectSigner(ctx context.Context) (cert *x509.Certificate, signer crypto.Signer, err error) {
  473. p := provisionerFromContext(ctx)
  474. cert, signer = p.GetSigner()
  475. switch {
  476. case cert != nil && signer != nil:
  477. return
  478. case cert == nil && signer != nil:
  479. return nil, nil, fmt.Errorf("provisioner %q does not have a signer certificate available", p.GetName())
  480. case cert != nil && signer == nil:
  481. return nil, nil, fmt.Errorf("provisioner %q does not have a signer available", p.GetName())
  482. }
  483. cert, signer = a.signerCertificate, a.defaultSigner
  484. switch {
  485. case cert == nil && signer != nil:
  486. return nil, nil, fmt.Errorf("provisioner %q does not have a default signer certificate available", p.GetName())
  487. case cert != nil && signer == nil:
  488. return nil, nil, fmt.Errorf("provisioner %q does not have a default signer available", p.GetName())
  489. }
  490. return
  491. }