jwt.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package serviceaccount
  14. import (
  15. "context"
  16. "crypto/ecdsa"
  17. "crypto/elliptic"
  18. "crypto/rsa"
  19. "encoding/base64"
  20. "encoding/json"
  21. "fmt"
  22. "strings"
  23. jose "gopkg.in/square/go-jose.v2"
  24. "gopkg.in/square/go-jose.v2/jwt"
  25. "k8s.io/api/core/v1"
  26. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  27. "k8s.io/apiserver/pkg/authentication/authenticator"
  28. )
  29. // ServiceAccountTokenGetter defines functions to retrieve a named service account and secret
  30. type ServiceAccountTokenGetter interface {
  31. GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error)
  32. GetPod(namespace, name string) (*v1.Pod, error)
  33. GetSecret(namespace, name string) (*v1.Secret, error)
  34. }
  35. type TokenGenerator interface {
  36. // GenerateToken generates a token which will identify the given
  37. // ServiceAccount. privateClaims is an interface that will be
  38. // serialized into the JWT payload JSON encoding at the root level of
  39. // the payload object. Public claims take precedent over private
  40. // claims i.e. if both claims and privateClaims have an "exp" field,
  41. // the value in claims will be used.
  42. GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error)
  43. }
  44. // JWTTokenGenerator returns a TokenGenerator that generates signed JWT tokens, using the given privateKey.
  45. // privateKey is a PEM-encoded byte array of a private RSA key.
  46. // JWTTokenAuthenticator()
  47. func JWTTokenGenerator(iss string, privateKey interface{}) (TokenGenerator, error) {
  48. var alg jose.SignatureAlgorithm
  49. switch pk := privateKey.(type) {
  50. case *rsa.PrivateKey:
  51. alg = jose.RS256
  52. case *ecdsa.PrivateKey:
  53. switch pk.Curve {
  54. case elliptic.P256():
  55. alg = jose.ES256
  56. case elliptic.P384():
  57. alg = jose.ES384
  58. case elliptic.P521():
  59. alg = jose.ES512
  60. default:
  61. return nil, fmt.Errorf("unknown private key curve, must be 256, 384, or 521")
  62. }
  63. case jose.OpaqueSigner:
  64. alg = jose.SignatureAlgorithm(pk.Public().Algorithm)
  65. default:
  66. return nil, fmt.Errorf("unknown private key type %T, must be *rsa.PrivateKey, *ecdsa.PrivateKey, or jose.OpaqueSigner", privateKey)
  67. }
  68. signer, err := jose.NewSigner(
  69. jose.SigningKey{
  70. Algorithm: alg,
  71. Key: privateKey,
  72. },
  73. nil,
  74. )
  75. if err != nil {
  76. return nil, err
  77. }
  78. return &jwtTokenGenerator{
  79. iss: iss,
  80. signer: signer,
  81. }, nil
  82. }
  83. type jwtTokenGenerator struct {
  84. iss string
  85. signer jose.Signer
  86. }
  87. func (j *jwtTokenGenerator) GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error) {
  88. // claims are applied in reverse precedence
  89. return jwt.Signed(j.signer).
  90. Claims(privateClaims).
  91. Claims(claims).
  92. Claims(&jwt.Claims{
  93. Issuer: j.iss,
  94. }).
  95. CompactSerialize()
  96. }
  97. // JWTTokenAuthenticator authenticates tokens as JWT tokens produced by JWTTokenGenerator
  98. // Token signatures are verified using each of the given public keys until one works (allowing key rotation)
  99. // If lookup is true, the service account and secret referenced as claims inside the token are retrieved and verified with the provided ServiceAccountTokenGetter
  100. func JWTTokenAuthenticator(iss string, keys []interface{}, implicitAuds authenticator.Audiences, validator Validator) authenticator.Token {
  101. return &jwtTokenAuthenticator{
  102. iss: iss,
  103. keys: keys,
  104. implicitAuds: implicitAuds,
  105. validator: validator,
  106. }
  107. }
  108. type jwtTokenAuthenticator struct {
  109. iss string
  110. keys []interface{}
  111. validator Validator
  112. implicitAuds authenticator.Audiences
  113. }
  114. // Validator is called by the JWT token authenticator to apply domain specific
  115. // validation to a token and extract user information.
  116. type Validator interface {
  117. // Validate validates a token and returns user information or an error.
  118. // Validator can assume that the issuer and signature of a token are already
  119. // verified when this function is called.
  120. Validate(tokenData string, public *jwt.Claims, private interface{}) (*ServiceAccountInfo, error)
  121. // NewPrivateClaims returns a struct that the authenticator should
  122. // deserialize the JWT payload into. The authenticator may then pass this
  123. // struct back to the Validator as the 'private' argument to a Validate()
  124. // call. This struct should contain fields for any private claims that the
  125. // Validator requires to validate the JWT.
  126. NewPrivateClaims() interface{}
  127. }
  128. func (j *jwtTokenAuthenticator) AuthenticateToken(ctx context.Context, tokenData string) (*authenticator.Response, bool, error) {
  129. if !j.hasCorrectIssuer(tokenData) {
  130. return nil, false, nil
  131. }
  132. tok, err := jwt.ParseSigned(tokenData)
  133. if err != nil {
  134. return nil, false, nil
  135. }
  136. public := &jwt.Claims{}
  137. private := j.validator.NewPrivateClaims()
  138. var (
  139. found bool
  140. errlist []error
  141. )
  142. for _, key := range j.keys {
  143. if err := tok.Claims(key, public, private); err != nil {
  144. errlist = append(errlist, err)
  145. continue
  146. }
  147. found = true
  148. break
  149. }
  150. if !found {
  151. return nil, false, utilerrors.NewAggregate(errlist)
  152. }
  153. tokenAudiences := authenticator.Audiences(public.Audience)
  154. if len(tokenAudiences) == 0 {
  155. // only apiserver audiences are allowed for legacy tokens
  156. tokenAudiences = j.implicitAuds
  157. }
  158. requestedAudiences, ok := authenticator.AudiencesFrom(ctx)
  159. if !ok {
  160. // default to apiserver audiences
  161. requestedAudiences = j.implicitAuds
  162. }
  163. auds := authenticator.Audiences(tokenAudiences).Intersect(requestedAudiences)
  164. if len(auds) == 0 && len(j.implicitAuds) != 0 {
  165. return nil, false, fmt.Errorf("token audiences %q is invalid for the target audiences %q", tokenAudiences, requestedAudiences)
  166. }
  167. // If we get here, we have a token with a recognized signature and
  168. // issuer string.
  169. sa, err := j.validator.Validate(tokenData, public, private)
  170. if err != nil {
  171. return nil, false, err
  172. }
  173. return &authenticator.Response{
  174. User: sa.UserInfo(),
  175. Audiences: auds,
  176. }, true, nil
  177. }
  178. // hasCorrectIssuer returns true if tokenData is a valid JWT in compact
  179. // serialization format and the "iss" claim matches the iss field of this token
  180. // authenticator, and otherwise returns false.
  181. //
  182. // Note: go-jose currently does not allow access to unverified JWS payloads.
  183. // See https://github.com/square/go-jose/issues/169
  184. func (j *jwtTokenAuthenticator) hasCorrectIssuer(tokenData string) bool {
  185. parts := strings.Split(tokenData, ".")
  186. if len(parts) != 3 {
  187. return false
  188. }
  189. payload, err := base64.RawURLEncoding.DecodeString(parts[1])
  190. if err != nil {
  191. return false
  192. }
  193. claims := struct {
  194. // WARNING: this JWT is not verified. Do not trust these claims.
  195. Issuer string `json:"iss"`
  196. }{}
  197. if err := json.Unmarshal(payload, &claims); err != nil {
  198. return false
  199. }
  200. if claims.Issuer != j.iss {
  201. return false
  202. }
  203. return true
  204. }