jwk.go 8.9 KB

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