-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathcaclient.go
183 lines (157 loc) · 5.2 KB
/
caclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/*
* Copyright 2024 The Kmesh Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package security
import (
"context"
"errors"
"fmt"
"strings"
"time"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/structpb"
pb "istio.io/api/security/v1alpha1"
"istio.io/istio/pkg/security"
nodeagentutil "istio.io/istio/security/pkg/nodeagent/util"
pkiutil "istio.io/istio/security/pkg/pki/util"
"kmesh.net/kmesh/pkg/nets"
)
type caClient struct {
tlsOpts *tlsOptions
client pb.IstioCertificateServiceClient
conn *grpc.ClientConn
opts *security.Options
}
type tlsOptions struct {
RootCert string
Key string
Cert string
}
// NewCaClient create a CA client for CSR sign.
// The following function is adapted from istio NewCitadelClient
// (https://github.com/istio/istio/blob/master/security/pkg/nodeagent/caclient/providers/citadel/client.go)
func newCaClient(opts *security.Options, tlsOpts *tlsOptions) (*caClient, error) {
var err error
c := &caClient{
tlsOpts: tlsOpts,
opts: opts,
}
conn, err := nets.GrpcConnect(CSRSignAddress)
if err != nil {
return nil, fmt.Errorf("failed to create grpcconnect : %v", err)
}
c.conn = conn
c.client = pb.NewIstioCertificateServiceClient(conn)
return c, nil
}
// csrSend send a grpc request to istio and sign a CSR.
// The following function is adapted from istio CSRSign
// (https://github.com/istio/istio/blob/master/security/pkg/nodeagent/caclient/providers/citadel/client.go)
func (c *caClient) csrSend(csrPEM []byte, certValidsec int64, identity string) ([]string, error) {
crMeta := &structpb.Struct{
Fields: map[string]*structpb.Value{
security.ImpersonatedIdentity: {
Kind: &structpb.Value_StringValue{StringValue: identity},
},
},
}
req := &pb.IstioCertificateRequest{
Csr: string(csrPEM),
ValidityDuration: certValidsec,
Metadata: crMeta,
}
ctx := context.Background()
// To handle potential grpc connection disconnection and retry once
// when certificate acquisition fails. If it still fails, return an error.
resp, err := c.client.CreateCertificate(ctx, req)
if err != nil {
log.Errorf("create certificate: %v reconnect...", err)
if err := c.reconnect(); err != nil {
return nil, fmt.Errorf("reconnect error: %v", err)
}
resp, err = c.client.CreateCertificate(ctx, req)
if err != nil {
return nil, fmt.Errorf("create certificate: %v", err)
}
}
if len(resp.CertChain) <= 1 {
return nil, errors.New("invalid empty CertChain")
}
return resp.CertChain, nil
}
// Standard the PEM certificates, ensuring that each certificate starts on a new line
func standardCerts(certsPEM []string) []byte {
var certChain strings.Builder
for i, c := range certsPEM {
certChain.WriteString(c)
if i < len(certsPEM)-1 && !strings.HasSuffix(c, "\n") {
certChain.WriteString("\n")
}
}
return []byte(certChain.String())
}
// The following function is adapted from istio generateNewSecret
// (https://github.com/istio/istio/blob/master/security/pkg/nodeagent/cache/secretcache.go)
func (c *caClient) fetchCert(identity string) (*security.SecretItem, error) {
var rootCertPEM []byte
options := pkiutil.CertOptions{
Host: identity,
RSAKeySize: c.opts.WorkloadRSAKeySize,
PKCS8Key: c.opts.Pkcs8Keys,
ECSigAlg: pkiutil.SupportedECSignatureAlgorithms(c.opts.ECCSigAlg),
ECCCurve: pkiutil.SupportedEllipticCurves(c.opts.ECCCurve),
}
// Generate the cert/key, send CSR to CA.
csrPEM, keyPEM, err := pkiutil.GenCSR(options)
if err != nil {
log.Errorf("%s failed to generate key and certificate for CSR: %v", identity, err)
return nil, err
}
certChainPEM, err := c.csrSend(csrPEM, int64(c.opts.SecretTTL.Seconds()), identity)
if err != nil {
return nil, fmt.Errorf("failed to get certChainPEM")
}
certChain := standardCerts(certChainPEM)
expireTime, err := nodeagentutil.ParseCertAndGetExpiryTimestamp(certChain)
if err != nil {
return nil, fmt.Errorf("%s failed to extract expire time from server certificate in CSR response %+v: %v",
identity, certChainPEM, err)
}
rootCertPEM = []byte(certChainPEM[len(certChainPEM)-1])
log.Debugf("cert for %v ExpireTime :%v", identity, expireTime)
return &security.SecretItem{
CertificateChain: certChain,
PrivateKey: keyPEM,
ResourceName: identity,
CreatedTime: time.Now(),
ExpireTime: expireTime,
RootCert: rootCertPEM,
}, nil
}
func (c *caClient) reconnect() error {
if err := c.conn.Close(); err != nil {
return fmt.Errorf("failed to close connection: %v", err)
}
conn, err := nets.GrpcConnect(CSRSignAddress)
if err != nil {
return err
}
c.conn = conn
c.client = pb.NewIstioCertificateServiceClient(conn)
return nil
}
func (c *caClient) close() error {
return c.conn.Close()
}