jwt.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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"
  17. "crypto/ecdsa"
  18. "crypto/elliptic"
  19. "crypto/rsa"
  20. "crypto/x509"
  21. "encoding/base64"
  22. "encoding/json"
  23. "fmt"
  24. "strings"
  25. jose "gopkg.in/square/go-jose.v2"
  26. "gopkg.in/square/go-jose.v2/jwt"
  27. v1 "k8s.io/api/core/v1"
  28. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  29. "k8s.io/apiserver/pkg/authentication/authenticator"
  30. )
  31. // ServiceAccountTokenGetter defines functions to retrieve a named service account and secret
  32. type ServiceAccountTokenGetter interface {
  33. GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error)
  34. GetPod(namespace, name string) (*v1.Pod, error)
  35. GetSecret(namespace, name string) (*v1.Secret, error)
  36. }
  37. type TokenGenerator interface {
  38. // GenerateToken generates a token which will identify the given
  39. // ServiceAccount. privateClaims is an interface that will be
  40. // serialized into the JWT payload JSON encoding at the root level of
  41. // the payload object. Public claims take precedent over private
  42. // claims i.e. if both claims and privateClaims have an "exp" field,
  43. // the value in claims will be used.
  44. GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error)
  45. }
  46. // JWTTokenGenerator returns a TokenGenerator that generates signed JWT tokens, using the given privateKey.
  47. // privateKey is a PEM-encoded byte array of a private RSA key.
  48. func JWTTokenGenerator(iss string, privateKey interface{}) (TokenGenerator, error) {
  49. var signer jose.Signer
  50. var err error
  51. switch pk := privateKey.(type) {
  52. case *rsa.PrivateKey:
  53. signer, err = signerFromRSAPrivateKey(pk)
  54. if err != nil {
  55. return nil, fmt.Errorf("could not generate signer for RSA keypair: %v", err)
  56. }
  57. case *ecdsa.PrivateKey:
  58. signer, err = signerFromECDSAPrivateKey(pk)
  59. if err != nil {
  60. return nil, fmt.Errorf("could not generate signer for ECDSA keypair: %v", err)
  61. }
  62. case jose.OpaqueSigner:
  63. signer, err = signerFromOpaqueSigner(pk)
  64. if err != nil {
  65. return nil, fmt.Errorf("could not generate signer for OpaqueSigner: %v", err)
  66. }
  67. default:
  68. return nil, fmt.Errorf("unknown private key type %T, must be *rsa.PrivateKey, *ecdsa.PrivateKey, or jose.OpaqueSigner", privateKey)
  69. }
  70. return &jwtTokenGenerator{
  71. iss: iss,
  72. signer: signer,
  73. }, nil
  74. }
  75. // keyIDFromPublicKey derives a key ID non-reversibly from a public key.
  76. //
  77. // The Key ID is field on a given on JWTs and JWKs that help relying parties
  78. // pick the correct key for verification when the identity party advertises
  79. // multiple keys.
  80. //
  81. // Making the derivation non-reversible makes it impossible for someone to
  82. // accidentally obtain the real key from the key ID and use it for token
  83. // validation.
  84. func keyIDFromPublicKey(publicKey interface{}) (string, error) {
  85. publicKeyDERBytes, err := x509.MarshalPKIXPublicKey(publicKey)
  86. if err != nil {
  87. return "", fmt.Errorf("failed to serialize public key to DER format: %v", err)
  88. }
  89. hasher := crypto.SHA256.New()
  90. hasher.Write(publicKeyDERBytes)
  91. publicKeyDERHash := hasher.Sum(nil)
  92. keyID := base64.RawURLEncoding.EncodeToString(publicKeyDERHash)
  93. return keyID, nil
  94. }
  95. func signerFromRSAPrivateKey(keyPair *rsa.PrivateKey) (jose.Signer, error) {
  96. keyID, err := keyIDFromPublicKey(&keyPair.PublicKey)
  97. if err != nil {
  98. return nil, fmt.Errorf("failed to derive keyID: %v", err)
  99. }
  100. // IMPORTANT: If this function is updated to support additional key sizes,
  101. // algorithmForPublicKey in serviceaccount/openidmetadata.go must also be
  102. // updated to support the same key sizes. Today we only support RS256.
  103. // Wrap the RSA keypair in a JOSE JWK with the designated key ID.
  104. privateJWK := &jose.JSONWebKey{
  105. Algorithm: string(jose.RS256),
  106. Key: keyPair,
  107. KeyID: keyID,
  108. Use: "sig",
  109. }
  110. signer, err := jose.NewSigner(
  111. jose.SigningKey{
  112. Algorithm: jose.RS256,
  113. Key: privateJWK,
  114. },
  115. nil,
  116. )
  117. if err != nil {
  118. return nil, fmt.Errorf("failed to create signer: %v", err)
  119. }
  120. return signer, nil
  121. }
  122. func signerFromECDSAPrivateKey(keyPair *ecdsa.PrivateKey) (jose.Signer, error) {
  123. var alg jose.SignatureAlgorithm
  124. switch keyPair.Curve {
  125. case elliptic.P256():
  126. alg = jose.ES256
  127. case elliptic.P384():
  128. alg = jose.ES384
  129. case elliptic.P521():
  130. alg = jose.ES512
  131. default:
  132. return nil, fmt.Errorf("unknown private key curve, must be 256, 384, or 521")
  133. }
  134. keyID, err := keyIDFromPublicKey(&keyPair.PublicKey)
  135. if err != nil {
  136. return nil, fmt.Errorf("failed to derive keyID: %v", err)
  137. }
  138. // Wrap the ECDSA keypair in a JOSE JWK with the designated key ID.
  139. privateJWK := &jose.JSONWebKey{
  140. Algorithm: string(alg),
  141. Key: keyPair,
  142. KeyID: keyID,
  143. Use: "sig",
  144. }
  145. signer, err := jose.NewSigner(
  146. jose.SigningKey{
  147. Algorithm: alg,
  148. Key: privateJWK,
  149. },
  150. nil,
  151. )
  152. if err != nil {
  153. return nil, fmt.Errorf("failed to create signer: %v", err)
  154. }
  155. return signer, nil
  156. }
  157. func signerFromOpaqueSigner(opaqueSigner jose.OpaqueSigner) (jose.Signer, error) {
  158. alg := jose.SignatureAlgorithm(opaqueSigner.Public().Algorithm)
  159. signer, err := jose.NewSigner(
  160. jose.SigningKey{
  161. Algorithm: alg,
  162. Key: &jose.JSONWebKey{
  163. Algorithm: string(alg),
  164. Key: opaqueSigner,
  165. KeyID: opaqueSigner.Public().KeyID,
  166. Use: "sig",
  167. },
  168. },
  169. nil,
  170. )
  171. if err != nil {
  172. return nil, fmt.Errorf("failed to create signer: %v", err)
  173. }
  174. return signer, nil
  175. }
  176. type jwtTokenGenerator struct {
  177. iss string
  178. signer jose.Signer
  179. }
  180. func (j *jwtTokenGenerator) GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error) {
  181. // claims are applied in reverse precedence
  182. return jwt.Signed(j.signer).
  183. Claims(privateClaims).
  184. Claims(claims).
  185. Claims(&jwt.Claims{
  186. Issuer: j.iss,
  187. }).
  188. CompactSerialize()
  189. }
  190. // JWTTokenAuthenticator authenticates tokens as JWT tokens produced by JWTTokenGenerator
  191. // Token signatures are verified using each of the given public keys until one works (allowing key rotation)
  192. // If lookup is true, the service account and secret referenced as claims inside the token are retrieved and verified with the provided ServiceAccountTokenGetter
  193. func JWTTokenAuthenticator(iss string, keys []interface{}, implicitAuds authenticator.Audiences, validator Validator) authenticator.Token {
  194. return &jwtTokenAuthenticator{
  195. iss: iss,
  196. keys: keys,
  197. implicitAuds: implicitAuds,
  198. validator: validator,
  199. }
  200. }
  201. type jwtTokenAuthenticator struct {
  202. iss string
  203. keys []interface{}
  204. validator Validator
  205. implicitAuds authenticator.Audiences
  206. }
  207. // Validator is called by the JWT token authenticator to apply domain specific
  208. // validation to a token and extract user information.
  209. type Validator interface {
  210. // Validate validates a token and returns user information or an error.
  211. // Validator can assume that the issuer and signature of a token are already
  212. // verified when this function is called.
  213. Validate(tokenData string, public *jwt.Claims, private interface{}) (*ServiceAccountInfo, error)
  214. // NewPrivateClaims returns a struct that the authenticator should
  215. // deserialize the JWT payload into. The authenticator may then pass this
  216. // struct back to the Validator as the 'private' argument to a Validate()
  217. // call. This struct should contain fields for any private claims that the
  218. // Validator requires to validate the JWT.
  219. NewPrivateClaims() interface{}
  220. }
  221. func (j *jwtTokenAuthenticator) AuthenticateToken(ctx context.Context, tokenData string) (*authenticator.Response, bool, error) {
  222. if !j.hasCorrectIssuer(tokenData) {
  223. return nil, false, nil
  224. }
  225. tok, err := jwt.ParseSigned(tokenData)
  226. if err != nil {
  227. return nil, false, nil
  228. }
  229. public := &jwt.Claims{}
  230. private := j.validator.NewPrivateClaims()
  231. // TODO: Pick the key that has the same key ID as `tok`, if one exists.
  232. var (
  233. found bool
  234. errlist []error
  235. )
  236. for _, key := range j.keys {
  237. if err := tok.Claims(key, public, private); err != nil {
  238. errlist = append(errlist, err)
  239. continue
  240. }
  241. found = true
  242. break
  243. }
  244. if !found {
  245. return nil, false, utilerrors.NewAggregate(errlist)
  246. }
  247. tokenAudiences := authenticator.Audiences(public.Audience)
  248. if len(tokenAudiences) == 0 {
  249. // only apiserver audiences are allowed for legacy tokens
  250. tokenAudiences = j.implicitAuds
  251. }
  252. requestedAudiences, ok := authenticator.AudiencesFrom(ctx)
  253. if !ok {
  254. // default to apiserver audiences
  255. requestedAudiences = j.implicitAuds
  256. }
  257. auds := authenticator.Audiences(tokenAudiences).Intersect(requestedAudiences)
  258. if len(auds) == 0 && len(j.implicitAuds) != 0 {
  259. return nil, false, fmt.Errorf("token audiences %q is invalid for the target audiences %q", tokenAudiences, requestedAudiences)
  260. }
  261. // If we get here, we have a token with a recognized signature and
  262. // issuer string.
  263. sa, err := j.validator.Validate(tokenData, public, private)
  264. if err != nil {
  265. return nil, false, err
  266. }
  267. return &authenticator.Response{
  268. User: sa.UserInfo(),
  269. Audiences: auds,
  270. }, true, nil
  271. }
  272. // hasCorrectIssuer returns true if tokenData is a valid JWT in compact
  273. // serialization format and the "iss" claim matches the iss field of this token
  274. // authenticator, and otherwise returns false.
  275. //
  276. // Note: go-jose currently does not allow access to unverified JWS payloads.
  277. // See https://github.com/square/go-jose/issues/169
  278. func (j *jwtTokenAuthenticator) hasCorrectIssuer(tokenData string) bool {
  279. parts := strings.Split(tokenData, ".")
  280. if len(parts) != 3 {
  281. return false
  282. }
  283. payload, err := base64.RawURLEncoding.DecodeString(parts[1])
  284. if err != nil {
  285. return false
  286. }
  287. claims := struct {
  288. // WARNING: this JWT is not verified. Do not trust these claims.
  289. Issuer string `json:"iss"`
  290. }{}
  291. if err := json.Unmarshal(payload, &claims); err != nil {
  292. return false
  293. }
  294. if claims.Issuer != j.iss {
  295. return false
  296. }
  297. return true
  298. }