jwk.go 8.7 KB

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