scep.go 18 KB

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