4
0

jwk.go 10 KB

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