jwk.go 7.7 KB

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