scep.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/rsa"
  6. "crypto/subtle"
  7. "crypto/x509"
  8. "encoding/pem"
  9. "fmt"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/linkedca"
  13. "go.step.sm/crypto/kms"
  14. kmsapi "go.step.sm/crypto/kms/apiv1"
  15. "go.step.sm/crypto/x509util"
  16. "github.com/smallstep/certificates/internal/httptransport"
  17. "github.com/smallstep/certificates/webhook"
  18. )
  19. // SCEP is the SCEP provisioner type, an entity that can authorize the
  20. // SCEP provisioning flow
  21. type SCEP struct {
  22. *base
  23. ID string `json:"-"`
  24. Type string `json:"type"`
  25. Name string `json:"name"`
  26. ForceCN bool `json:"forceCN,omitempty"`
  27. ChallengePassword string `json:"challenge,omitempty"`
  28. Capabilities []string `json:"capabilities,omitempty"`
  29. // IncludeRoot makes the provisioner return the CA root in addition to the
  30. // intermediate in the GetCACerts response
  31. IncludeRoot bool `json:"includeRoot,omitempty"`
  32. // ExcludeIntermediate makes the provisioner skip the intermediate CA in the
  33. // GetCACerts response
  34. ExcludeIntermediate bool `json:"excludeIntermediate,omitempty"`
  35. // MinimumPublicKeyLength is the minimum length for public keys in CSRs
  36. MinimumPublicKeyLength int `json:"minimumPublicKeyLength,omitempty"`
  37. // TODO(hs): also support a separate signer configuration?
  38. DecrypterCertificate []byte `json:"decrypterCertificate,omitempty"`
  39. DecrypterKeyPEM []byte `json:"decrypterKeyPEM,omitempty"`
  40. DecrypterKeyURI string `json:"decrypterKey,omitempty"`
  41. DecrypterKeyPassword string `json:"decrypterKeyPassword,omitempty"`
  42. // Numerical identifier for the ContentEncryptionAlgorithm as defined in github.com/mozilla-services/pkcs7
  43. // at https://github.com/mozilla-services/pkcs7/blob/33d05740a3526e382af6395d3513e73d4e66d1cb/encrypt.go#L63
  44. // Defaults to 0, being DES-CBC
  45. EncryptionAlgorithmIdentifier int `json:"encryptionAlgorithmIdentifier,omitempty"`
  46. Options *Options `json:"options,omitempty"`
  47. Claims *Claims `json:"claims,omitempty"`
  48. ctl *Controller
  49. encryptionAlgorithm int
  50. challengeValidationController *challengeValidationController
  51. notificationController *notificationController
  52. keyManager SCEPKeyManager
  53. decrypter crypto.Decrypter
  54. decrypterCertificate *x509.Certificate
  55. signer crypto.Signer
  56. signerCertificate *x509.Certificate
  57. }
  58. // GetID returns the provisioner unique identifier.
  59. func (s *SCEP) GetID() string {
  60. if s.ID != "" {
  61. return s.ID
  62. }
  63. return s.GetIDForToken()
  64. }
  65. // GetIDForToken returns an identifier that will be used to load the provisioner
  66. // from a token.
  67. func (s *SCEP) GetIDForToken() string {
  68. return "scep/" + s.Name
  69. }
  70. // GetName returns the name of the provisioner.
  71. func (s *SCEP) GetName() string {
  72. return s.Name
  73. }
  74. // GetType returns the type of provisioner.
  75. func (s *SCEP) GetType() Type {
  76. return TypeSCEP
  77. }
  78. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  79. func (s *SCEP) GetEncryptedKey() (string, string, bool) {
  80. return "", "", false
  81. }
  82. // GetTokenID returns the identifier of the token. This provisioner will always
  83. // return [ErrTokenFlowNotSupported].
  84. func (s *SCEP) GetTokenID(string) (string, error) {
  85. return "", ErrTokenFlowNotSupported
  86. }
  87. // GetOptions returns the configured provisioner options.
  88. func (s *SCEP) GetOptions() *Options {
  89. return s.Options
  90. }
  91. // DefaultTLSCertDuration returns the default TLS cert duration enforced by
  92. // the provisioner.
  93. func (s *SCEP) DefaultTLSCertDuration() time.Duration {
  94. return s.ctl.Claimer.DefaultTLSCertDuration()
  95. }
  96. type challengeValidationController struct {
  97. client HTTPClient
  98. wrapTransport httptransport.Wrapper
  99. webhooks []*Webhook
  100. }
  101. // newChallengeValidationController creates a new challengeValidationController
  102. // that performs challenge validation through webhooks.
  103. func newChallengeValidationController(client HTTPClient, tw httptransport.Wrapper, webhooks []*Webhook) *challengeValidationController {
  104. scepHooks := []*Webhook{}
  105. for _, wh := range webhooks {
  106. if wh.Kind != linkedca.Webhook_SCEPCHALLENGE.String() {
  107. continue
  108. }
  109. if !isCertTypeOK(wh) {
  110. continue
  111. }
  112. scepHooks = append(scepHooks, wh)
  113. }
  114. return &challengeValidationController{
  115. client: client,
  116. wrapTransport: tw,
  117. webhooks: scepHooks,
  118. }
  119. }
  120. var (
  121. ErrSCEPChallengeInvalid = errors.New("webhook server did not allow request")
  122. ErrSCEPNotificationFailed = errors.New("scep notification failed")
  123. )
  124. // Validate executes zero or more configured webhooks to
  125. // validate the SCEP challenge. If at least one of them indicates
  126. // the challenge value is accepted, validation succeeds. In
  127. // that case, the other webhooks will be skipped. If none of
  128. // the webhooks indicates the value of the challenge was accepted,
  129. // an error is returned.
  130. func (c *challengeValidationController) Validate(ctx context.Context, csr *x509.CertificateRequest, provisionerName, challenge, transactionID string) ([]SignCSROption, error) {
  131. var opts []SignCSROption
  132. for _, wh := range c.webhooks {
  133. req, err := webhook.NewRequestBody(webhook.WithX509CertificateRequest(csr))
  134. if err != nil {
  135. return nil, fmt.Errorf("failed creating new webhook request: %w", err)
  136. }
  137. req.ProvisionerName = provisionerName
  138. req.SCEPChallenge = challenge
  139. req.SCEPTransactionID = transactionID
  140. resp, err := wh.DoWithContext(ctx, c.client, c.wrapTransport, req, nil) // TODO(hs): support templated URL? Requires some refactoring
  141. if err != nil {
  142. return nil, fmt.Errorf("failed executing webhook request: %w", err)
  143. }
  144. if resp.Allow {
  145. opts = append(opts, TemplateDataModifierFunc(func(data x509util.TemplateData) {
  146. data.SetWebhook(wh.Name, resp.Data)
  147. }))
  148. }
  149. }
  150. if len(opts) == 0 {
  151. return nil, ErrSCEPChallengeInvalid
  152. }
  153. return opts, nil
  154. }
  155. type notificationController struct {
  156. client HTTPClient
  157. wrapTransport httptransport.Wrapper
  158. webhooks []*Webhook
  159. }
  160. // newNotificationController creates a new notificationController
  161. // that performs SCEP notifications through webhooks.
  162. func newNotificationController(client HTTPClient, tw httptransport.Wrapper, webhooks []*Webhook) *notificationController {
  163. scepHooks := []*Webhook{}
  164. for _, wh := range webhooks {
  165. if wh.Kind != linkedca.Webhook_NOTIFYING.String() {
  166. continue
  167. }
  168. if !isCertTypeOK(wh) {
  169. continue
  170. }
  171. scepHooks = append(scepHooks, wh)
  172. }
  173. return &notificationController{
  174. client: client,
  175. wrapTransport: tw,
  176. webhooks: scepHooks,
  177. }
  178. }
  179. func (c *notificationController) Success(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
  180. for _, wh := range c.webhooks {
  181. req, err := webhook.NewRequestBody(webhook.WithX509CertificateRequest(csr), webhook.WithX509Certificate(nil, cert)) // TODO(hs): pass in the x509util.Certifiate too?
  182. if err != nil {
  183. return fmt.Errorf("failed creating new webhook request: %w", err)
  184. }
  185. req.X509Certificate.Raw = cert.Raw // adding the full certificate DER bytes
  186. req.SCEPTransactionID = transactionID
  187. if _, err = wh.DoWithContext(ctx, c.client, c.wrapTransport, req, nil); err != nil {
  188. return fmt.Errorf("failed executing webhook request: %w: %w", ErrSCEPNotificationFailed, err)
  189. }
  190. }
  191. return nil
  192. }
  193. func (c *notificationController) Failure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
  194. for _, wh := range c.webhooks {
  195. req, err := webhook.NewRequestBody(webhook.WithX509CertificateRequest(csr))
  196. if err != nil {
  197. return fmt.Errorf("failed creating new webhook request: %w", err)
  198. }
  199. req.SCEPTransactionID = transactionID
  200. req.SCEPErrorCode = errorCode
  201. req.SCEPErrorDescription = errorDescription
  202. if _, err = wh.DoWithContext(ctx, c.client, c.wrapTransport, req, nil); err != nil {
  203. return fmt.Errorf("failed executing webhook request: %w: %w", ErrSCEPNotificationFailed, err)
  204. }
  205. }
  206. return nil
  207. }
  208. // isCertTypeOK returns whether or not the webhook can be used
  209. // with the SCEP challenge validation webhook controller.
  210. func isCertTypeOK(wh *Webhook) bool {
  211. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  212. return true
  213. }
  214. return linkedca.Webhook_X509.String() == wh.CertType
  215. }
  216. // Init initializes and validates the fields of a SCEP type.
  217. func (s *SCEP) Init(config Config) (err error) {
  218. switch {
  219. case s.Type == "":
  220. return errors.New("provisioner type cannot be empty")
  221. case s.Name == "":
  222. return errors.New("provisioner name cannot be empty")
  223. }
  224. // Default to 2048 bits minimum public key length (for CSRs) if not set
  225. if s.MinimumPublicKeyLength == 0 {
  226. s.MinimumPublicKeyLength = 2048
  227. }
  228. if s.MinimumPublicKeyLength%8 != 0 {
  229. return errors.Errorf("%d bits is not exactly divisible by 8", s.MinimumPublicKeyLength)
  230. }
  231. // Set the encryption algorithm to use
  232. s.encryptionAlgorithm = s.EncryptionAlgorithmIdentifier // TODO(hs): we might want to upgrade the default security to AES-CBC?
  233. if s.encryptionAlgorithm < 0 || s.encryptionAlgorithm > 4 {
  234. return errors.New("only encryption algorithm identifiers from 0 to 4 are valid")
  235. }
  236. // Prepare the SCEP challenge validator
  237. s.challengeValidationController = newChallengeValidationController(
  238. config.WebhookClient,
  239. config.WrapTransport,
  240. s.GetOptions().GetWebhooks(),
  241. )
  242. // Prepare the SCEP notification controller
  243. s.notificationController = newNotificationController(
  244. config.WebhookClient,
  245. config.WrapTransport,
  246. s.GetOptions().GetWebhooks(),
  247. )
  248. // parse the decrypter key PEM contents if available
  249. if len(s.DecrypterKeyPEM) > 0 {
  250. // try reading the PEM for validation
  251. block, rest := pem.Decode(s.DecrypterKeyPEM)
  252. if len(rest) > 0 {
  253. return errors.New("failed parsing decrypter key: trailing data")
  254. }
  255. if block == nil {
  256. return errors.New("failed parsing decrypter key: no PEM block found")
  257. }
  258. opts := kms.Options{
  259. Type: kmsapi.SoftKMS,
  260. }
  261. km, err := kms.New(context.Background(), opts)
  262. if err != nil {
  263. return fmt.Errorf("failed initializing kms: %w", err)
  264. }
  265. scepKeyManager, ok := km.(SCEPKeyManager)
  266. if !ok {
  267. return fmt.Errorf("%q is not a kmsapi.Decrypter", opts.Type)
  268. }
  269. s.keyManager = scepKeyManager
  270. if s.decrypter, err = s.keyManager.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  271. DecryptionKeyPEM: s.DecrypterKeyPEM,
  272. Password: []byte(s.DecrypterKeyPassword),
  273. PasswordPrompter: kmsapi.NonInteractivePasswordPrompter,
  274. }); err != nil {
  275. return fmt.Errorf("failed creating decrypter: %w", err)
  276. }
  277. if s.signer, err = s.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  278. SigningKeyPEM: s.DecrypterKeyPEM, // TODO(hs): support distinct signer key in the future?
  279. Password: []byte(s.DecrypterKeyPassword),
  280. PasswordPrompter: kmsapi.NonInteractivePasswordPrompter,
  281. }); err != nil {
  282. return fmt.Errorf("failed creating signer: %w", err)
  283. }
  284. }
  285. if s.DecrypterKeyURI != "" {
  286. kmsType, err := kmsapi.TypeOf(s.DecrypterKeyURI)
  287. if err != nil {
  288. return fmt.Errorf("failed parsing decrypter key: %w", err)
  289. }
  290. if config.SCEPKeyManager != nil {
  291. s.keyManager = config.SCEPKeyManager
  292. } else {
  293. if kmsType == kmsapi.DefaultKMS {
  294. kmsType = kmsapi.SoftKMS
  295. }
  296. opts := kms.Options{
  297. Type: kmsType,
  298. URI: s.DecrypterKeyURI,
  299. }
  300. km, err := kms.New(context.Background(), opts)
  301. if err != nil {
  302. return fmt.Errorf("failed initializing kms: %w", err)
  303. }
  304. scepKeyManager, ok := km.(SCEPKeyManager)
  305. if !ok {
  306. return fmt.Errorf("%q is not a kmsapi.Decrypter", opts.Type)
  307. }
  308. s.keyManager = scepKeyManager
  309. }
  310. // Create decrypter and signer with the same key:
  311. // TODO(hs): support distinct signer key in the future?
  312. if s.decrypter, err = s.keyManager.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  313. DecryptionKey: s.DecrypterKeyURI,
  314. Password: []byte(s.DecrypterKeyPassword),
  315. PasswordPrompter: kmsapi.NonInteractivePasswordPrompter,
  316. }); err != nil {
  317. return fmt.Errorf("failed creating decrypter: %w", err)
  318. }
  319. if s.signer, err = s.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  320. SigningKey: s.DecrypterKeyURI,
  321. Password: []byte(s.DecrypterKeyPassword),
  322. PasswordPrompter: kmsapi.NonInteractivePasswordPrompter,
  323. }); err != nil {
  324. return fmt.Errorf("failed creating signer: %w", err)
  325. }
  326. }
  327. // parse the decrypter certificate contents if available
  328. if len(s.DecrypterCertificate) > 0 {
  329. block, rest := pem.Decode(s.DecrypterCertificate)
  330. if len(rest) > 0 {
  331. return errors.New("failed parsing decrypter certificate: trailing data")
  332. }
  333. if block == nil {
  334. return errors.New("failed parsing decrypter certificate: no PEM block found")
  335. }
  336. if s.decrypterCertificate, err = x509.ParseCertificate(block.Bytes); err != nil {
  337. return fmt.Errorf("failed parsing decrypter certificate: %w", err)
  338. }
  339. // the decrypter certificate is also the signer certificate
  340. s.signerCertificate = s.decrypterCertificate
  341. }
  342. // TODO(hs): alternatively, check if the KMS keyManager is a CertificateManager
  343. // and load the certificate corresponding to the decryption key?
  344. // Final validation for the decrypter.
  345. if s.decrypter != nil {
  346. decrypterPublicKey, ok := s.decrypter.Public().(*rsa.PublicKey)
  347. if !ok {
  348. return fmt.Errorf("only RSA keys are supported")
  349. }
  350. if s.decrypterCertificate == nil {
  351. return fmt.Errorf("provisioner %q does not have a decrypter certificate set", s.Name)
  352. }
  353. if !decrypterPublicKey.Equal(s.decrypterCertificate.PublicKey) {
  354. return errors.New("mismatch between decrypter certificate and decrypter public keys")
  355. }
  356. }
  357. // TODO: add other, SCEP specific, options?
  358. s.ctl, err = NewController(s, s.Claims, config, s.Options)
  359. return
  360. }
  361. // AuthorizeSign does not do any verification, because all verification is handled
  362. // in the SCEP protocol. This method returns a list of modifiers / constraints
  363. // on the resulting certificate.
  364. func (s *SCEP) AuthorizeSign(context.Context, string) ([]SignOption, error) {
  365. return []SignOption{
  366. s,
  367. // modifiers / withOptions
  368. newProvisionerExtensionOption(TypeSCEP, s.Name, "").WithControllerOptions(s.ctl),
  369. newForceCNOption(s.ForceCN),
  370. profileDefaultDuration(s.ctl.Claimer.DefaultTLSCertDuration()),
  371. // validators
  372. newPublicKeyMinimumLengthValidator(s.MinimumPublicKeyLength),
  373. newValidityValidator(s.ctl.Claimer.MinTLSCertDuration(), s.ctl.Claimer.MaxTLSCertDuration()),
  374. newX509NamePolicyValidator(s.ctl.getPolicy().getX509()),
  375. s.ctl.newWebhookController(nil, linkedca.Webhook_X509),
  376. }, nil
  377. }
  378. // GetCapabilities returns the CA capabilities
  379. func (s *SCEP) GetCapabilities() []string {
  380. return s.Capabilities
  381. }
  382. // ShouldIncludeRootInChain indicates if the CA should
  383. // return its intermediate, which is currently used for
  384. // both signing and decryption, as well as the root in
  385. // its chain.
  386. func (s *SCEP) ShouldIncludeRootInChain() bool {
  387. return s.IncludeRoot
  388. }
  389. // ShouldIncludeIntermediateInChain indicates if the
  390. // CA should include the intermediate CA certificate in the
  391. // GetCACerts response. This is true by default, but can be
  392. // overridden through configuration in case SCEP clients
  393. // don't pick the right recipient.
  394. func (s *SCEP) ShouldIncludeIntermediateInChain() bool {
  395. return !s.ExcludeIntermediate
  396. }
  397. // GetContentEncryptionAlgorithm returns the numeric identifier
  398. // for the pkcs7 package encryption algorithm to use.
  399. func (s *SCEP) GetContentEncryptionAlgorithm() int {
  400. return s.encryptionAlgorithm
  401. }
  402. // ValidateChallenge validates the provided challenge. It starts by
  403. // selecting the validation method to use, then performs validation
  404. // according to that method.
  405. func (s *SCEP) ValidateChallenge(ctx context.Context, csr *x509.CertificateRequest, challenge, transactionID string) ([]SignCSROption, error) {
  406. if s.challengeValidationController == nil {
  407. return nil, fmt.Errorf("provisioner %q wasn't initialized", s.Name)
  408. }
  409. switch s.selectValidationMethod() {
  410. case validationMethodWebhook:
  411. return s.challengeValidationController.Validate(ctx, csr, s.Name, challenge, transactionID)
  412. default:
  413. if subtle.ConstantTimeCompare([]byte(s.ChallengePassword), []byte(challenge)) == 0 {
  414. return nil, errors.New("invalid challenge password provided")
  415. }
  416. return []SignCSROption{}, nil
  417. }
  418. }
  419. func (s *SCEP) NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
  420. if s.notificationController == nil {
  421. return fmt.Errorf("provisioner %q wasn't initialized", s.Name)
  422. }
  423. return s.notificationController.Success(ctx, csr, cert, transactionID)
  424. }
  425. func (s *SCEP) NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
  426. if s.notificationController == nil {
  427. return fmt.Errorf("provisioner %q wasn't initialized", s.Name)
  428. }
  429. return s.notificationController.Failure(ctx, csr, transactionID, errorCode, errorDescription)
  430. }
  431. type validationMethod string
  432. const (
  433. validationMethodNone validationMethod = "none"
  434. validationMethodStatic validationMethod = "static"
  435. validationMethodWebhook validationMethod = "webhook"
  436. )
  437. // selectValidationMethod returns the method to validate SCEP
  438. // challenges. If a webhook is configured with kind `SCEPCHALLENGE`,
  439. // the webhook method will be used. If a challenge password is set,
  440. // the static method is used. It will default to the `none` method.
  441. func (s *SCEP) selectValidationMethod() validationMethod {
  442. if len(s.challengeValidationController.webhooks) > 0 {
  443. return validationMethodWebhook
  444. }
  445. if s.ChallengePassword != "" {
  446. return validationMethodStatic
  447. }
  448. return validationMethodNone
  449. }
  450. // GetDecrypter returns the provisioner specific decrypter,
  451. // used to decrypt SCEP request messages sent by a SCEP client.
  452. // The decrypter consists of a crypto.Decrypter (a private key)
  453. // and a certificate for the public key corresponding to the
  454. // private key.
  455. func (s *SCEP) GetDecrypter() (*x509.Certificate, crypto.Decrypter) {
  456. return s.decrypterCertificate, s.decrypter
  457. }
  458. // GetSigner returns the provisioner specific signer, used to
  459. // sign SCEP response messages for the client. The signer consists
  460. // of a crypto.Signer and a certificate for the public key
  461. // corresponding to the private key.
  462. func (s *SCEP) GetSigner() (*x509.Certificate, crypto.Signer) {
  463. return s.signerCertificate, s.signer
  464. }