jwk.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. templateOptions,
  148. // modifiers / withOptions
  149. newProvisionerExtensionOption(TypeJWK, p.Name, p.Key.KeyID),
  150. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  151. // validators
  152. commonNameValidator(claims.Subject),
  153. defaultPublicKeyValidator{},
  154. defaultSANsValidator(claims.SANs),
  155. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  156. }, nil
  157. }
  158. // AuthorizeRenew returns an error if the renewal is disabled.
  159. // NOTE: This method does not actually validate the certificate or check it's
  160. // revocation status. Just confirms that the provisioner that created the
  161. // certificate was configured to allow renewals.
  162. func (p *JWK) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  163. return p.ctl.AuthorizeRenew(ctx, cert)
  164. }
  165. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  166. func (p *JWK) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  167. if !p.ctl.Claimer.IsSSHCAEnabled() {
  168. return nil, errs.Unauthorized("jwk.AuthorizeSSHSign; sshCA is disabled for jwk provisioner '%s'", p.GetName())
  169. }
  170. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  171. if err != nil {
  172. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSSHSign")
  173. }
  174. if claims.Step == nil || claims.Step.SSH == nil {
  175. return nil, errs.Unauthorized("jwk.AuthorizeSSHSign; jwk token must be an SSH provisioning token")
  176. }
  177. opts := claims.Step.SSH
  178. signOptions := []SignOption{
  179. // validates user's SignSSHOptions with the ones in the token
  180. sshCertOptionsValidator(*opts),
  181. // validate users's KeyID is the token subject.
  182. sshCertOptionsValidator(SignSSHOptions{KeyID: claims.Subject}),
  183. }
  184. // Default template attributes.
  185. certType := sshutil.UserCert
  186. keyID := claims.Subject
  187. principals := []string{claims.Subject}
  188. // Use options in the token.
  189. if opts.CertType != "" {
  190. if certType, err = sshutil.CertTypeFromString(opts.CertType); err != nil {
  191. return nil, errs.BadRequestErr(err, err.Error())
  192. }
  193. }
  194. if opts.KeyID != "" {
  195. keyID = opts.KeyID
  196. }
  197. if len(opts.Principals) > 0 {
  198. principals = opts.Principals
  199. }
  200. // Certificate templates.
  201. data := sshutil.CreateTemplateData(certType, keyID, principals)
  202. if v, err := unsafeParseSigned(token); err == nil {
  203. data.SetToken(v)
  204. }
  205. templateOptions, err := TemplateSSHOptions(p.Options, data)
  206. if err != nil {
  207. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSign")
  208. }
  209. signOptions = append(signOptions, templateOptions)
  210. // Add modifiers from custom claims
  211. t := now()
  212. if !opts.ValidAfter.IsZero() {
  213. signOptions = append(signOptions, sshCertValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  214. }
  215. if !opts.ValidBefore.IsZero() {
  216. signOptions = append(signOptions, sshCertValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  217. }
  218. return append(signOptions,
  219. // Set the validity bounds if not set.
  220. &sshDefaultDuration{p.ctl.Claimer},
  221. // Validate public key
  222. &sshDefaultPublicKeyValidator{},
  223. // Validate the validity period.
  224. &sshCertValidityValidator{p.ctl.Claimer},
  225. // Require and validate all the default fields in the SSH certificate.
  226. &sshCertDefaultValidator{},
  227. ), nil
  228. }
  229. // AuthorizeSSHRevoke returns nil if the token is valid, false otherwise.
  230. func (p *JWK) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  231. _, err := p.authorizeToken(token, p.ctl.Audiences.SSHRevoke)
  232. return errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSSHRevoke")
  233. }