jwk.go 8.2 KB

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