scep.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "fmt"
  6. "net/http"
  7. "time"
  8. "github.com/pkg/errors"
  9. "go.step.sm/linkedca"
  10. "github.com/smallstep/certificates/webhook"
  11. )
  12. // SCEP is the SCEP provisioner type, an entity that can authorize the
  13. // SCEP provisioning flow
  14. type SCEP struct {
  15. *base
  16. ID string `json:"-"`
  17. Type string `json:"type"`
  18. Name string `json:"name"`
  19. ForceCN bool `json:"forceCN,omitempty"`
  20. ChallengePassword string `json:"challenge,omitempty"`
  21. Capabilities []string `json:"capabilities,omitempty"`
  22. // IncludeRoot makes the provisioner return the CA root in addition to the
  23. // intermediate in the GetCACerts response
  24. IncludeRoot bool `json:"includeRoot,omitempty"`
  25. // MinimumPublicKeyLength is the minimum length for public keys in CSRs
  26. MinimumPublicKeyLength int `json:"minimumPublicKeyLength,omitempty"`
  27. // Numerical identifier for the ContentEncryptionAlgorithm as defined in github.com/mozilla-services/pkcs7
  28. // at https://github.com/mozilla-services/pkcs7/blob/33d05740a3526e382af6395d3513e73d4e66d1cb/encrypt.go#L63
  29. // Defaults to 0, being DES-CBC
  30. EncryptionAlgorithmIdentifier int `json:"encryptionAlgorithmIdentifier,omitempty"`
  31. Options *Options `json:"options,omitempty"`
  32. Claims *Claims `json:"claims,omitempty"`
  33. ctl *Controller
  34. encryptionAlgorithm int
  35. challengeValidationController *challengeValidationController
  36. }
  37. // GetID returns the provisioner unique identifier.
  38. func (s *SCEP) GetID() string {
  39. if s.ID != "" {
  40. return s.ID
  41. }
  42. return s.GetIDForToken()
  43. }
  44. // GetIDForToken returns an identifier that will be used to load the provisioner
  45. // from a token.
  46. func (s *SCEP) GetIDForToken() string {
  47. return "scep/" + s.Name
  48. }
  49. // GetName returns the name of the provisioner.
  50. func (s *SCEP) GetName() string {
  51. return s.Name
  52. }
  53. // GetType returns the type of provisioner.
  54. func (s *SCEP) GetType() Type {
  55. return TypeSCEP
  56. }
  57. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  58. func (s *SCEP) GetEncryptedKey() (string, string, bool) {
  59. return "", "", false
  60. }
  61. // GetTokenID returns the identifier of the token.
  62. func (s *SCEP) GetTokenID(string) (string, error) {
  63. return "", errors.New("scep provisioner does not implement GetTokenID")
  64. }
  65. // GetOptions returns the configured provisioner options.
  66. func (s *SCEP) GetOptions() *Options {
  67. return s.Options
  68. }
  69. // DefaultTLSCertDuration returns the default TLS cert duration enforced by
  70. // the provisioner.
  71. func (s *SCEP) DefaultTLSCertDuration() time.Duration {
  72. return s.ctl.Claimer.DefaultTLSCertDuration()
  73. }
  74. type challengeValidationController struct {
  75. client *http.Client
  76. webhooks []*Webhook
  77. }
  78. // newChallengeValidationController creates a new challengeValidationController
  79. // that performs challenge validation through webhooks.
  80. func newChallengeValidationController(client *http.Client, webhooks []*Webhook) *challengeValidationController {
  81. scepHooks := []*Webhook{}
  82. for _, wh := range webhooks {
  83. if wh.Kind != linkedca.Webhook_SCEPCHALLENGE.String() {
  84. continue
  85. }
  86. if !isCertTypeOK(wh) {
  87. continue
  88. }
  89. scepHooks = append(scepHooks, wh)
  90. }
  91. return &challengeValidationController{
  92. client: client,
  93. webhooks: scepHooks,
  94. }
  95. }
  96. var (
  97. ErrSCEPChallengeInvalid = errors.New("webhook server did not allow request")
  98. )
  99. // Validate executes zero or more configured webhooks to
  100. // validate the SCEP challenge. If at least one of them indicates
  101. // the challenge value is accepted, validation succeeds. In
  102. // that case, the other webhooks will be skipped. If none of
  103. // the webhooks indicates the value of the challenge was accepted,
  104. // an error is returned.
  105. func (c *challengeValidationController) Validate(ctx context.Context, challenge, transactionID string) error {
  106. for _, wh := range c.webhooks {
  107. req := &webhook.RequestBody{
  108. SCEPChallenge: challenge,
  109. SCEPTransactionID: transactionID,
  110. }
  111. resp, err := wh.DoWithContext(ctx, c.client, req, nil) // TODO(hs): support templated URL? Requires some refactoring
  112. if err != nil {
  113. return fmt.Errorf("failed executing webhook request: %w", err)
  114. }
  115. if resp.Allow {
  116. return nil // return early when response is positive
  117. }
  118. }
  119. return ErrSCEPChallengeInvalid
  120. }
  121. // isCertTypeOK returns whether or not the webhook can be used
  122. // with the SCEP challenge validation webhook controller.
  123. func isCertTypeOK(wh *Webhook) bool {
  124. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  125. return true
  126. }
  127. return linkedca.Webhook_X509.String() == wh.CertType
  128. }
  129. // Init initializes and validates the fields of a SCEP type.
  130. func (s *SCEP) Init(config Config) (err error) {
  131. switch {
  132. case s.Type == "":
  133. return errors.New("provisioner type cannot be empty")
  134. case s.Name == "":
  135. return errors.New("provisioner name cannot be empty")
  136. }
  137. // Default to 2048 bits minimum public key length (for CSRs) if not set
  138. if s.MinimumPublicKeyLength == 0 {
  139. s.MinimumPublicKeyLength = 2048
  140. }
  141. if s.MinimumPublicKeyLength%8 != 0 {
  142. return errors.Errorf("%d bits is not exactly divisible by 8", s.MinimumPublicKeyLength)
  143. }
  144. s.encryptionAlgorithm = s.EncryptionAlgorithmIdentifier // TODO(hs): we might want to upgrade the default security to AES-CBC?
  145. if s.encryptionAlgorithm < 0 || s.encryptionAlgorithm > 4 {
  146. return errors.New("only encryption algorithm identifiers from 0 to 4 are valid")
  147. }
  148. s.challengeValidationController = newChallengeValidationController(
  149. config.WebhookClient,
  150. s.GetOptions().GetWebhooks(),
  151. )
  152. // TODO: add other, SCEP specific, options?
  153. s.ctl, err = NewController(s, s.Claims, config, s.Options)
  154. return
  155. }
  156. // AuthorizeSign does not do any verification, because all verification is handled
  157. // in the SCEP protocol. This method returns a list of modifiers / constraints
  158. // on the resulting certificate.
  159. func (s *SCEP) AuthorizeSign(context.Context, string) ([]SignOption, error) {
  160. return []SignOption{
  161. s,
  162. // modifiers / withOptions
  163. newProvisionerExtensionOption(TypeSCEP, s.Name, ""),
  164. newForceCNOption(s.ForceCN),
  165. profileDefaultDuration(s.ctl.Claimer.DefaultTLSCertDuration()),
  166. // validators
  167. newPublicKeyMinimumLengthValidator(s.MinimumPublicKeyLength),
  168. newValidityValidator(s.ctl.Claimer.MinTLSCertDuration(), s.ctl.Claimer.MaxTLSCertDuration()),
  169. newX509NamePolicyValidator(s.ctl.getPolicy().getX509()),
  170. s.ctl.newWebhookController(nil, linkedca.Webhook_X509),
  171. }, nil
  172. }
  173. // GetCapabilities returns the CA capabilities
  174. func (s *SCEP) GetCapabilities() []string {
  175. return s.Capabilities
  176. }
  177. // ShouldIncludeRootInChain indicates if the CA should
  178. // return its intermediate, which is currently used for
  179. // both signing and decryption, as well as the root in
  180. // its chain.
  181. func (s *SCEP) ShouldIncludeRootInChain() bool {
  182. return s.IncludeRoot
  183. }
  184. // GetContentEncryptionAlgorithm returns the numeric identifier
  185. // for the pkcs7 package encryption algorithm to use.
  186. func (s *SCEP) GetContentEncryptionAlgorithm() int {
  187. return s.encryptionAlgorithm
  188. }
  189. // ValidateChallenge validates the provided challenge. It starts by
  190. // selecting the validation method to use, then performs validation
  191. // according to that method.
  192. func (s *SCEP) ValidateChallenge(ctx context.Context, challenge, transactionID string) error {
  193. if s.challengeValidationController == nil {
  194. return fmt.Errorf("provisioner %q wasn't initialized", s.Name)
  195. }
  196. switch s.selectValidationMethod() {
  197. case validationMethodWebhook:
  198. return s.challengeValidationController.Validate(ctx, challenge, transactionID)
  199. default:
  200. if subtle.ConstantTimeCompare([]byte(s.ChallengePassword), []byte(challenge)) == 0 {
  201. return errors.New("invalid challenge password provided")
  202. }
  203. return nil
  204. }
  205. }
  206. type validationMethod string
  207. const (
  208. validationMethodNone validationMethod = "none"
  209. validationMethodStatic validationMethod = "static"
  210. validationMethodWebhook validationMethod = "webhook"
  211. )
  212. // selectValidationMethod returns the method to validate SCEP
  213. // challenges. If a webhook is configured with kind `SCEPCHALLENGE`,
  214. // the webhook method will be used. If a challenge password is set,
  215. // the static method is used. It will default to the `none` method.
  216. func (s *SCEP) selectValidationMethod() validationMethod {
  217. if len(s.challengeValidationController.webhooks) > 0 {
  218. return validationMethodWebhook
  219. }
  220. if s.ChallengePassword != "" {
  221. return validationMethodStatic
  222. }
  223. return validationMethodNone
  224. }