4
0

jwk.go 9.7 KB

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