scep.go 18 KB

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