jwt.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. // Wrap the RSA keypair in a JOSE JWK with the designated key ID.
  101. privateJWK := &jose.JSONWebKey{
  102. Algorithm: string(jose.RS256),
  103. Key: keyPair,
  104. KeyID: keyID,
  105. Use: "sig",
  106. }
  107. signer, err := jose.NewSigner(
  108. jose.SigningKey{
  109. Algorithm: jose.RS256,
  110. Key: privateJWK,
  111. },
  112. nil,
  113. )
  114. if err != nil {
  115. return nil, fmt.Errorf("failed to create signer: %v", err)
  116. }
  117. return signer, nil
  118. }
  119. func signerFromECDSAPrivateKey(keyPair *ecdsa.PrivateKey) (jose.Signer, error) {
  120. var alg jose.SignatureAlgorithm
  121. switch keyPair.Curve {
  122. case elliptic.P256():
  123. alg = jose.ES256
  124. case elliptic.P384():
  125. alg = jose.ES384
  126. case elliptic.P521():
  127. alg = jose.ES512
  128. default:
  129. return nil, fmt.Errorf("unknown private key curve, must be 256, 384, or 521")
  130. }
  131. keyID, err := keyIDFromPublicKey(&keyPair.PublicKey)
  132. if err != nil {
  133. return nil, fmt.Errorf("failed to derive keyID: %v", err)
  134. }
  135. // Wrap the ECDSA keypair in a JOSE JWK with the designated key ID.
  136. privateJWK := &jose.JSONWebKey{
  137. Algorithm: string(alg),
  138. Key: keyPair,
  139. KeyID: keyID,
  140. Use: "sig",
  141. }
  142. signer, err := jose.NewSigner(
  143. jose.SigningKey{
  144. Algorithm: alg,
  145. Key: privateJWK,
  146. },
  147. nil,
  148. )
  149. if err != nil {
  150. return nil, fmt.Errorf("failed to create signer: %v", err)
  151. }
  152. return signer, nil
  153. }
  154. func signerFromOpaqueSigner(opaqueSigner jose.OpaqueSigner) (jose.Signer, error) {
  155. alg := jose.SignatureAlgorithm(opaqueSigner.Public().Algorithm)
  156. signer, err := jose.NewSigner(
  157. jose.SigningKey{
  158. Algorithm: alg,
  159. Key: &jose.JSONWebKey{
  160. Algorithm: string(alg),
  161. Key: opaqueSigner,
  162. KeyID: opaqueSigner.Public().KeyID,
  163. Use: "sig",
  164. },
  165. },
  166. nil,
  167. )
  168. if err != nil {
  169. return nil, fmt.Errorf("failed to create signer: %v", err)
  170. }
  171. return signer, nil
  172. }
  173. type jwtTokenGenerator struct {
  174. iss string
  175. signer jose.Signer
  176. }
  177. func (j *jwtTokenGenerator) GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error) {
  178. // claims are applied in reverse precedence
  179. return jwt.Signed(j.signer).
  180. Claims(privateClaims).
  181. Claims(claims).
  182. Claims(&jwt.Claims{
  183. Issuer: j.iss,
  184. }).
  185. CompactSerialize()
  186. }
  187. // JWTTokenAuthenticator authenticates tokens as JWT tokens produced by JWTTokenGenerator
  188. // Token signatures are verified using each of the given public keys until one works (allowing key rotation)
  189. // If lookup is true, the service account and secret referenced as claims inside the token are retrieved and verified with the provided ServiceAccountTokenGetter
  190. func JWTTokenAuthenticator(iss string, keys []interface{}, implicitAuds authenticator.Audiences, validator Validator) authenticator.Token {
  191. return &jwtTokenAuthenticator{
  192. iss: iss,
  193. keys: keys,
  194. implicitAuds: implicitAuds,
  195. validator: validator,
  196. }
  197. }
  198. type jwtTokenAuthenticator struct {
  199. iss string
  200. keys []interface{}
  201. validator Validator
  202. implicitAuds authenticator.Audiences
  203. }
  204. // Validator is called by the JWT token authenticator to apply domain specific
  205. // validation to a token and extract user information.
  206. type Validator interface {
  207. // Validate validates a token and returns user information or an error.
  208. // Validator can assume that the issuer and signature of a token are already
  209. // verified when this function is called.
  210. Validate(tokenData string, public *jwt.Claims, private interface{}) (*ServiceAccountInfo, error)
  211. // NewPrivateClaims returns a struct that the authenticator should
  212. // deserialize the JWT payload into. The authenticator may then pass this
  213. // struct back to the Validator as the 'private' argument to a Validate()
  214. // call. This struct should contain fields for any private claims that the
  215. // Validator requires to validate the JWT.
  216. NewPrivateClaims() interface{}
  217. }
  218. func (j *jwtTokenAuthenticator) AuthenticateToken(ctx context.Context, tokenData string) (*authenticator.Response, bool, error) {
  219. if !j.hasCorrectIssuer(tokenData) {
  220. return nil, false, nil
  221. }
  222. tok, err := jwt.ParseSigned(tokenData)
  223. if err != nil {
  224. return nil, false, nil
  225. }
  226. public := &jwt.Claims{}
  227. private := j.validator.NewPrivateClaims()
  228. // TODO: Pick the key that has the same key ID as `tok`, if one exists.
  229. var (
  230. found bool
  231. errlist []error
  232. )
  233. for _, key := range j.keys {
  234. if err := tok.Claims(key, public, private); err != nil {
  235. errlist = append(errlist, err)
  236. continue
  237. }
  238. found = true
  239. break
  240. }
  241. if !found {
  242. return nil, false, utilerrors.NewAggregate(errlist)
  243. }
  244. tokenAudiences := authenticator.Audiences(public.Audience)
  245. if len(tokenAudiences) == 0 {
  246. // only apiserver audiences are allowed for legacy tokens
  247. tokenAudiences = j.implicitAuds
  248. }
  249. requestedAudiences, ok := authenticator.AudiencesFrom(ctx)
  250. if !ok {
  251. // default to apiserver audiences
  252. requestedAudiences = j.implicitAuds
  253. }
  254. auds := authenticator.Audiences(tokenAudiences).Intersect(requestedAudiences)
  255. if len(auds) == 0 && len(j.implicitAuds) != 0 {
  256. return nil, false, fmt.Errorf("token audiences %q is invalid for the target audiences %q", tokenAudiences, requestedAudiences)
  257. }
  258. // If we get here, we have a token with a recognized signature and
  259. // issuer string.
  260. sa, err := j.validator.Validate(tokenData, public, private)
  261. if err != nil {
  262. return nil, false, err
  263. }
  264. return &authenticator.Response{
  265. User: sa.UserInfo(),
  266. Audiences: auds,
  267. }, true, nil
  268. }
  269. // hasCorrectIssuer returns true if tokenData is a valid JWT in compact
  270. // serialization format and the "iss" claim matches the iss field of this token
  271. // authenticator, and otherwise returns false.
  272. //
  273. // Note: go-jose currently does not allow access to unverified JWS payloads.
  274. // See https://github.com/square/go-jose/issues/169
  275. func (j *jwtTokenAuthenticator) hasCorrectIssuer(tokenData string) bool {
  276. parts := strings.Split(tokenData, ".")
  277. if len(parts) != 3 {
  278. return false
  279. }
  280. payload, err := base64.RawURLEncoding.DecodeString(parts[1])
  281. if err != nil {
  282. return false
  283. }
  284. claims := struct {
  285. // WARNING: this JWT is not verified. Do not trust these claims.
  286. Issuer string `json:"iss"`
  287. }{}
  288. if err := json.Unmarshal(payload, &claims); err != nil {
  289. return false
  290. }
  291. if claims.Issuer != j.iss {
  292. return false
  293. }
  294. return true
  295. }