[istio源码分析][citadel] citadel之istio_ca(grpc server)

1. 前言

转载请说明原文出处, 尊重他人劳动成果!

源码位置: https://github.com/nicktming/istio
分支: tming-v1.3.6 (基于1.3.6版本)

上一篇文章 [istio源码分析][citadel] citadel之istio_ca 分析了istio_caserviceaccount controller 和 自定义签名, 本文将在此基础上继续分析istio_ca提供的一个grpc server 服务.

2. 认证(authenticate)

认证的实现体需要实现以下几个方法:

// security/pkg/server/ca/server.go
type authenticator interface {
    // 认证此client端用户并且返回client端的用户信息
    Authenticate(ctx context.Context) (*authenticate.Caller, error)
    // 返回认证类型
    AuthenticatorType() string
}
// security/pkg/server/ca/authenticate/authenticator.go
type Caller struct {
    // 认证的类型
    AuthSource AuthSource
    // client端的用户信息
    Identities []string
}

authenticator 有三个实现体:
1. KubeJWTAuthenticator (security/pkg/server/ca/authenticate/kube_jwt.go) .
2. IDTokenAuthenticator (security/pkg/server/ca/authenticate/authenticator.go)
3. ClientCertAuthenticator (security/pkg/server/ca/authenticate/authenticator.go)

这里主要分析一下KubeJWTAuthenticator的实现.

2.1 KubeJWTAuthenticator

关于jwt的知识可以参考 https://www.cnblogs.com/cjsblog/p/9277677.htmlhttp://www.imooc.com/article/264737?block_id=tuijian_wz .

// security/pkg/server/ca/authenticate/kube_jwt.go
type tokenReviewClient interface {
    // 输入一个Bearer token, 返回{namespace, serviceaccount name}
    ValidateK8sJwt(targetJWT string) ([]string, error)
}
func NewKubeJWTAuthenticator(k8sAPIServerURL, caCertPath, jwtPath, trustDomain string) (*KubeJWTAuthenticator, error) {
    // 访问k8sAPIServerURL的证书
    caCert, err := ioutil.ReadFile(caCertPath)
    ...
    // 客户端用户的信息(jwt token)
    reviewerJWT, err := ioutil.ReadFile(jwtPath)
    ...
    return &KubeJWTAuthenticator{
        client:      tokenreview.NewK8sSvcAcctAuthn(k8sAPIServerURL, caCert, string(reviewerJWT)),
        trustDomain: trustDomain,
    }, nil
}

1. tokenReviewClient是输入一个token, 返回一个字符串数组, 里面信息有namespaceserviceaccount name. 它的实现体在security/pkg/k8s/tokenreview/k8sauthn.go.
2. 生成一个KubeJWTAuthenticator对象.

Authenticate 和 AuthenticatorType
// security/pkg/server/ca/authenticate/kube_jwt.go
func (a *KubeJWTAuthenticator) AuthenticatorType() string {
    // KubeJWTAuthenticatorType = "KubeJWTAuthenticator"
    return KubeJWTAuthenticatorType
}
func (a *KubeJWTAuthenticator) Authenticate(ctx context.Context) (*Caller, error) {
    // 从header Bearer里面获得token
    targetJWT, err := extractBearerToken(ctx)
    ...
    // 认证客户端并且得到客户端的信息
    id, err := a.client.ValidateK8sJwt(targetJWT)
    ...
    if len(id) != 2 {
        return nil, fmt.Errorf("failed to parse the JWT. Validation result length is not 2, but %d", len(id))
    }
    callerNamespace := id[0]
    callerServiceAccount := id[1]
    // 返回一个Caller
    return &Caller{
        AuthSource: AuthSourceIDToken,
        // identityTemplate         = "spiffe://%s/ns/%s/sa/%s"
        Identities: []string{fmt.Sprintf(identityTemplate, a.trustDomain, callerNamespace, callerServiceAccount)},
    }, nil
}

1.header Bearer里面获得token.
2. 认证客户端并且得到客户端的信息.
3. 利用客户端信息组装成一个Caller返回. 因为在授权(authorize)的时候需要用到客户端的信息.

2.1.1 k8sauthn
func NewK8sSvcAcctAuthn(apiServerAddr string, apiServerCert []byte, callerToken string) *K8sSvcAcctAuthn {
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(apiServerCert)
    // 访问k8s api-server的证书
    httpClient := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                RootCAs: caCertPool,
            },
            MaxIdleConnsPerHost: 100,
        },
    }
    return &K8sSvcAcctAuthn{
        apiServerAddr: apiServerAddr,
        callerToken:   callerToken,
        httpClient:    httpClient,
    }
}

作用: K8sSvcAcctAuthn是负责认证 k8s JWTs.
1. apiServerAddr: the URL of k8s API Server 从上游可知是(https://kubernetes.default.svc/apis/authentication.k8s.io/v1/tokenreviews)
2. apiServerCert: the CA certificate of k8s API Serversecurity运行的这个pod中对应路径(/var/run/secrets/kubernetes.io/serviceaccount/ca.crt)的内容.
3. callerToken: the JWT of the caller to authenticate to k8s API serversecurity运行的这个pod中对应路径(/var/run/secrets/kubernetes.io/serviceaccount/token)的内容.

reviewServiceAccountAtK8sAPIServer
defaultAudience = "istio-ca"
func (authn *K8sSvcAcctAuthn) reviewServiceAccountAtK8sAPIServer(targetToken string) (*http.Response, error) {
    saReq := saValidationRequest{
        APIVersion: "authentication.k8s.io/v1",
        Kind:       "TokenReview",
        Spec: specForSaValidationRequest{
            Token: targetToken,
            Audiences: []string{defaultAudience},
        },
    }
    saReqJSON, err := json.Marshal(saReq)
    ...
    // 构造request
    req, err := http.NewRequest("POST", authn.apiServerAddr, bytes.NewBuffer(saReqJSON))
    ...
    req.Header.Set("Content-Type", "application/json")
    // authn.callerToken是security这个pod的token
    req.Header.Set("Authorization", "Bearer "+authn.callerToken)
    resp, err := authn.httpClient.Do(req)
    ...
    return resp, nil
}

1. targetToken是客户端请求的token信息, 也就是客户端向启动grpc server组件的pod来发请求, 所以saReq中的tokentargetToken.
2. authn.callerTokencitadel这个podtoken, 因为是citadel来向api-server发请求, 所以Bearer中需要写citadel这个podtoken.

例子如下: 具体关于TokenReview去研究api-server源码即可.

    // An example SA token:
    // {"alg":"RS256","typ":"JWT"}
    // {"iss":"kubernetes/serviceaccount",
    //  "kubernetes.io/serviceaccount/namespace":"default",
    //  "kubernetes.io/serviceaccount/secret.name":"example-pod-sa-token-h4jqx",
    //  "kubernetes.io/serviceaccount/service-account.name":"example-pod-sa",
    //  "kubernetes.io/serviceaccount/service-account.uid":"ff578a9e-65d3-11e8-aad2-42010a8a001d",
    //  "sub":"system:serviceaccount:default:example-pod-sa"
    //  }

    // An example token review status
    // "status":{
    //   "authenticated":true,
    //   "user":{
    //     "username":"system:serviceaccount:default:example-pod-sa",
    //     "uid":"ff578a9e-65d3-11e8-aad2-42010a8a001d",
    //     "groups":["system:serviceaccounts","system:serviceaccounts:default","system:authenticated"]
    //    }
    // }
ValidateK8sJwt
func (authn *K8sSvcAcctAuthn) ValidateK8sJwt(targetToken string) ([]string, error) {
    // 判断是否TrustworthyJwt
    // SDS requires JWT to be trustworthy (has aud, exp, and mounted to the pod).
    isTrustworthyJwt, err := isTrustworthyJwt(targetToken)
    ...
    // 返回结果
    resp, err := authn.reviewServiceAccountAtK8sAPIServer(targetToken)
    ...
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    ...
    tokenReview := &k8sauth.TokenReview{}
    err = json.Unmarshal(bodyBytes, tokenReview)
    ...
    // "username" is in the form of system:serviceaccount:{namespace}:{service account name}",
    // e.g., "username":"system:serviceaccount:default:example-pod-sa"
    subStrings := strings.Split(tokenReview.Status.User.Username, ":")
    ...
    namespace := subStrings[2]
    saName := subStrings[3]
    return []string{namespace, saName}, nil
}

1. 调用reviewServiceAccountAtK8sAPIServerapi-server返回客户端的认证信息, 也就是说向citadel发请求的客户端的token需要得到k8s的认证.
2.tokenReview.Status.User.Username中得到namespace, serviceaccount name返回.

2.2 ClientCertAuthenticator

func (cca *ClientCertAuthenticator) Authenticate(ctx context.Context) (*Caller, error) {
    peer, ok := peer.FromContext(ctx)
    ...
    tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
    chains := tlsInfo.State.VerifiedChains
    ...
    // 从extensions中获得ids
    ids, err := util.ExtractIDs(chains[0][0].Extensions)
    ...
    return &Caller{
        AuthSource: AuthSourceClientCertificate,
        Identities: ids,
    }, nil
}

ClientCertAuthenticator针对的是用x509生成的用户信息.

3. grpc server

// security/cmd/istio_ca/main.go
func runCA() {
    ...
    if opts.grpcPort > 0 {
        ...
        hostnames := append(strings.Split(opts.grpcHosts, ","), fqdn())
        caServer, startErr := caserver.New(ca, opts.maxWorkloadCertTTL, opts.signCACerts, hostnames,
            opts.grpcPort, spiffe.GetTrustDomain(), opts.sdsEnabled)
        ...
        if serverErr := caServer.Run(); serverErr != nil {
            ch <- struct{}{}
            ...
        }
    }
    ...
}
// security/pkg/server/ca/server.go
func New(ca CertificateAuthority, ttl time.Duration, forCA bool,
    hostlist []string, port int, trustDomain string, sdsEnabled bool) (*Server, error) {
    ...
    authenticators := []authenticator{&authenticate.ClientCertAuthenticator{}}
    // Only add k8s jwt authenticator if SDS is enabled.
    if sdsEnabled {
        // 添加一个k8s jwt认证
        authenticator, err := authenticate.NewKubeJWTAuthenticator(k8sAPIServerURL, caCertPath, jwtPath,
            trustDomain)
        if err == nil {
            authenticators = append(authenticators, authenticator)
            log.Info("added K8s JWT authenticator")
        } else {
            log.Warnf("failed to add JWT authenticator: %v", err)
        }
    }
    ...
    server := &Server{
        authenticators: authenticators,
        ...
    }
    return server, nil
}

由于authorize在此版本没有打开, 因此把关于authorize部分的内容都去掉了.
1. 可以看到认证的对象默认有一个ClientCertAuthenticator类型的对象, 如果sdsEnabled = true, 那么就会增加一个KubeJWTAuthenticator类型的对象.

HandleCSR
func (s *Server) HandleCSR(ctx context.Context, request *pb.CsrRequest) (*pb.CsrResponse, error) {
    s.monitoring.CSR.Inc()
    // 认证
    caller := s.authenticate(ctx)
    ...
    // 生成csr
    csr, err := util.ParsePemEncodedCSR(request.CsrPem)
    ...
    _, err = util.ExtractIDs(csr.Extensions)
    ...
    // TODO: Call authorizer. 等待要做的授权
    // 获得签名后的证书
    _, _, certChainBytes, _ := s.ca.GetCAKeyCertBundle().GetAll()
    cert, signErr := s.ca.Sign(
        request.CsrPem, caller.Identities, time.Duration(request.RequestedTtlMinutes)*time.Minute, s.forCA)
    ...
    // 组装response
    response := &pb.CsrResponse{
        IsApproved: true,
        SignedCert: cert,
        CertChain:  certChainBytes,
    }
    ...
    return response, nil
}

作用: 处理请求签名证书的request. 对请求做一些认证, 然后签名并且返回签名后的证书. 如果没有通过, 则返回错误理由.

handlecsr.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容