jwk.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "time"
  6. "github.com/pkg/errors"
  7. "github.com/smallstep/cli/crypto/x509util"
  8. "github.com/smallstep/cli/jose"
  9. )
  10. // jwtPayload extends jwt.Claims with step attributes.
  11. type jwtPayload struct {
  12. jose.Claims
  13. SANs []string `json:"sans,omitempty"`
  14. Step *stepPayload `json:"step,omitempty"`
  15. }
  16. type stepPayload struct {
  17. SSH *SSHOptions `json:"ssh,omitempty"`
  18. }
  19. // JWK is the default provisioner, an entity that can sign tokens necessary for
  20. // signature requests.
  21. type JWK struct {
  22. Type string `json:"type"`
  23. Name string `json:"name"`
  24. Key *jose.JSONWebKey `json:"key"`
  25. EncryptedKey string `json:"encryptedKey,omitempty"`
  26. Claims *Claims `json:"claims,omitempty"`
  27. claimer *Claimer
  28. audiences Audiences
  29. }
  30. // GetID returns the provisioner unique identifier. The name and credential id
  31. // should uniquely identify any JWK provisioner.
  32. func (p *JWK) GetID() string {
  33. return p.Name + ":" + p.Key.KeyID
  34. }
  35. // GetTokenID returns the identifier of the token.
  36. func (p *JWK) GetTokenID(ott string) (string, error) {
  37. // Validate payload
  38. token, err := jose.ParseSigned(ott)
  39. if err != nil {
  40. return "", errors.Wrap(err, "error parsing token")
  41. }
  42. // Get claims w/out verification. We need to look up the provisioner
  43. // key in order to verify the claims and we need the issuer from the claims
  44. // before we can look up the provisioner.
  45. var claims jose.Claims
  46. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  47. return "", errors.Wrap(err, "error verifying claims")
  48. }
  49. return claims.ID, nil
  50. }
  51. // GetName returns the name of the provisioner.
  52. func (p *JWK) GetName() string {
  53. return p.Name
  54. }
  55. // GetType returns the type of provisioner.
  56. func (p *JWK) GetType() Type {
  57. return TypeJWK
  58. }
  59. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  60. func (p *JWK) GetEncryptedKey() (string, string, bool) {
  61. return p.Key.KeyID, p.EncryptedKey, len(p.EncryptedKey) > 0
  62. }
  63. // Init initializes and validates the fields of a JWK type.
  64. func (p *JWK) Init(config Config) (err error) {
  65. switch {
  66. case p.Type == "":
  67. return errors.New("provisioner type cannot be empty")
  68. case p.Name == "":
  69. return errors.New("provisioner name cannot be empty")
  70. case p.Key == nil:
  71. return errors.New("provisioner key cannot be empty")
  72. }
  73. // Update claims with global ones
  74. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  75. return err
  76. }
  77. p.audiences = config.Audiences
  78. return err
  79. }
  80. // authorizeToken performs common jwt authorization actions and returns the
  81. // claims for case specific downstream parsing.
  82. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  83. func (p *JWK) authorizeToken(token string, audiences []string) (*jwtPayload, error) {
  84. jwt, err := jose.ParseSigned(token)
  85. if err != nil {
  86. return nil, errors.Wrapf(err, "error parsing token")
  87. }
  88. var claims jwtPayload
  89. if err = jwt.Claims(p.Key, &claims); err != nil {
  90. return nil, errors.Wrap(err, "error parsing claims")
  91. }
  92. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  93. // more than a few minutes.
  94. if err = claims.ValidateWithLeeway(jose.Expected{
  95. Issuer: p.Name,
  96. Time: time.Now().UTC(),
  97. }, time.Minute); err != nil {
  98. return nil, errors.Wrapf(err, "invalid token")
  99. }
  100. // validate audiences with the defaults
  101. if !matchesAudience(claims.Audience, audiences) {
  102. return nil, errors.New("invalid token: invalid audience claim (aud)")
  103. }
  104. if claims.Subject == "" {
  105. return nil, errors.New("token subject cannot be empty")
  106. }
  107. return &claims, nil
  108. }
  109. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  110. // revoke the certificate with serial number in the `sub` property.
  111. func (p *JWK) AuthorizeRevoke(token string) error {
  112. _, err := p.authorizeToken(token, p.audiences.Revoke)
  113. return err
  114. }
  115. // AuthorizeSign validates the given token.
  116. func (p *JWK) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  117. claims, err := p.authorizeToken(token, p.audiences.Sign)
  118. if err != nil {
  119. return nil, err
  120. }
  121. // Check for SSH sign-ing request.
  122. if MethodFromContext(ctx) == SignSSHMethod {
  123. if !p.claimer.IsSSHCAEnabled() {
  124. return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
  125. }
  126. return p.authorizeSSHSign(claims)
  127. }
  128. // NOTE: This is for backwards compatibility with older versions of cli
  129. // and certificates. Older versions added the token subject as the only SAN
  130. // in a CSR by default.
  131. if len(claims.SANs) == 0 {
  132. claims.SANs = []string{claims.Subject}
  133. }
  134. dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
  135. return []SignOption{
  136. // modifiers / withOptions
  137. newProvisionerExtensionOption(TypeJWK, p.Name, p.Key.KeyID),
  138. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  139. // validators
  140. commonNameValidator(claims.Subject),
  141. defaultPublicKeyValidator{},
  142. dnsNamesValidator(dnsNames),
  143. emailAddressesValidator(emails),
  144. ipAddressesValidator(ips),
  145. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  146. }, nil
  147. }
  148. // AuthorizeRenewal returns an error if the renewal is disabled.
  149. func (p *JWK) AuthorizeRenewal(cert *x509.Certificate) error {
  150. if p.claimer.IsDisableRenewal() {
  151. return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
  152. }
  153. return nil
  154. }
  155. // authorizeSSHSign returns the list of SignOption for a SignSSH request.
  156. func (p *JWK) authorizeSSHSign(claims *jwtPayload) ([]SignOption, error) {
  157. t := now()
  158. if claims.Step == nil || claims.Step.SSH == nil {
  159. return nil, errors.New("authorization token must be an SSH provisioning token")
  160. }
  161. opts := claims.Step.SSH
  162. signOptions := []SignOption{
  163. // validates user's SSHOptions with the ones in the token
  164. sshCertificateOptionsValidator(*opts),
  165. // set the key id to the token subject
  166. sshCertificateKeyIDModifier(claims.Subject),
  167. }
  168. // Add modifiers from custom claims
  169. if opts.CertType != "" {
  170. signOptions = append(signOptions, sshCertificateCertTypeModifier(opts.CertType))
  171. }
  172. if len(opts.Principals) > 0 {
  173. signOptions = append(signOptions, sshCertificatePrincipalsModifier(opts.Principals))
  174. }
  175. if !opts.ValidAfter.IsZero() {
  176. signOptions = append(signOptions, sshCertificateValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  177. }
  178. if !opts.ValidBefore.IsZero() {
  179. signOptions = append(signOptions, sshCertificateValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  180. }
  181. // Default to a user certificate with no principals if not set
  182. signOptions = append(signOptions, sshCertificateDefaultsModifier{CertType: SSHUserCert})
  183. return append(signOptions,
  184. // Set the default extensions.
  185. &sshDefaultExtensionModifier{},
  186. // Set the validity bounds if not set.
  187. sshDefaultValidityModifier(p.claimer),
  188. // Validate public key
  189. &sshDefaultPublicKeyValidator{},
  190. // Validate the validity period.
  191. &sshCertificateValidityValidator{p.claimer},
  192. // Require and validate all the default fields in the SSH certificate.
  193. &sshCertificateDefaultValidator{},
  194. ), nil
  195. }