jwk.go 8.7 KB

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