/
svccert.go
431 lines (367 loc) · 12 KB
/
svccert.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright 2023 LY Corporation
//
// 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 service
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"sync/atomic"
"time"
"github.com/AthenZ/athenz-client-sidecar/v2/config"
"github.com/AthenZ/athenz/clients/go/zts"
"github.com/kpango/fastime"
"github.com/kpango/glg"
"github.com/kpango/ntokend"
"github.com/pkg/errors"
"golang.org/x/sync/singleflight"
)
var (
// defaultSvcCertRefreshPeriod represents the default time to refresh the goroutine.
defaultSvcCertRefreshPeriod = time.Hour * 24
// defaultSvcCertExpiryMargin represents the default value of ExpiryMargin.
defaultSvcCertExpiryMargin = time.Hour * 24 * 10
// defaultSvcCertExpiry represents the default value of Expiry
defaultSvcCertExpiry int32
// domainReg is used to parse the Athenz domain which is contained in config
domainReg = regexp.MustCompile(`^([a-zA-Z0-9_][a-zA-Z0-9_-]*\.)*[a-zA-Z0-9_][a-zA-Z0-9_-]*$`)
// ErrCertNotFound represents an error when failed to fetch the svccert from SvcCertProvider.
ErrCertNotFound = errors.New("Failed to fetch service cert")
// ErrInvalidCert represents an error when failed to parse the svccert from SvcCertProvider.
ErrInvalidCert = errors.New("Failed to parse service cert")
// ErrLoadPrivateKey represents an error when failed to load privatekey.
ErrLoadPrivateKey = errors.New("PrivateKey does not exist")
// ErrFailedToInitialize represents an error when failed to initialize a service.
ErrFailedToInitialize = errors.New("Failed to initialize a service")
// ErrInvalidParameter represents an error when the invalid parameter is contained in config
ErrInvalidParameter = errors.New("Invalid parameter")
)
type signer struct {
key crypto.Signer
algorithm x509.SignatureAlgorithm
}
type requestTemplate struct {
req *zts.InstanceRefreshRequest
compoundName zts.CompoundName
simpleName zts.SimpleName
}
// SvcCertService represents an interface to automatically refresh the certificate.
type SvcCertService interface {
StartSvcCertUpdater(context.Context) SvcCertService
GetSvcCertProvider() SvcCertProvider
RefreshSvcCert() ([]byte, error)
}
type certCache struct {
cert []byte
exp time.Time
}
// svcCertService represents the implementation of Athenz RoleService
type svcCertService struct {
cfg config.ServiceCert
token ntokend.TokenProvider
certCache *atomic.Value
group singleflight.Group
refreshDuration time.Duration
expireMargin time.Duration
client *zts.ZTSClient
refreshRequest *requestTemplate
}
// SvcCertProvider represents a function pointer to get the svccert.
type SvcCertProvider func() ([]byte, error)
// NewSvcCertService returns a SvcCertService to update and get the svccert from Athenz.
func NewSvcCertService(cfg config.Config, token ntokend.TokenProvider) (SvcCertService, error) {
if !cfg.ServiceCert.Enable {
return nil, ErrDisabled
}
dur, err := time.ParseDuration(cfg.ServiceCert.RefreshPeriod)
if err != nil {
glg.Warnf("Failed to parse configuration value of refreshPeriod, err: %s. Using default value: %d", err.Error(), defaultSvcCertRefreshPeriod)
dur = defaultSvcCertRefreshPeriod
}
beforeDur, err := time.ParseDuration(cfg.ServiceCert.ExpiryMargin)
if err != nil {
glg.Warnf("Failed to parse configuration value of expiryMargin, err: %s. Using default value: %d", err.Error(), defaultSvcCertExpiryMargin)
beforeDur = defaultSvcCertExpiryMargin
}
// NOTE: The limitation for this expiry is not defined,
// but it returns error if user sets the exceeded value by int64 (expect less than "1<<63 - 1").
// The maximum 'cfg.ServiceCert.Expiry' is approximately 290 years.
expireDur, err := time.ParseDuration(cfg.ServiceCert.Expiry)
var expireInt int32
if err != nil {
glg.Warnf("Failed to parse configuration value of expiry, err: %s. Using default value: %d", err.Error(), defaultSvcCertExpiry)
expireInt = defaultSvcCertExpiry
} else {
expireInt = int32(expireDur.Minutes())
}
reqTemp, client, err := setup(cfg, expireInt)
if err != nil {
return nil, err
}
cache := &atomic.Value{}
cache.Store(
certCache{
cert: nil,
exp: fastime.Now(),
},
)
return &svcCertService{
cfg: cfg.ServiceCert,
certCache: cache,
token: token,
refreshDuration: dur,
expireMargin: beforeDur,
client: client,
refreshRequest: reqTemp,
}, nil
}
func isValidDomain(domain string) bool {
return domainReg.MatchString(domain)
}
func setup(cfg config.Config, expiry int32) (*requestTemplate, *zts.ZTSClient, error) {
// load private key
keyBytes, err := ioutil.ReadFile(cfg.NToken.PrivateKeyPath)
if err != nil {
return nil, nil, ErrLoadPrivateKey
}
// get our private key signer for csr
pkSigner, err := newSigner(keyBytes)
if err != nil {
return nil, nil, ErrFailedToInitialize
}
// generate a csr for this service
// note: RFC 6125 states that if the SAN (Subject Alternative Name) exists,
// it is used, not the CA. So, we will always put the Athenz name in the CN
// (it is *not* a DNS domain name), and put the host name into the SAN.
if !isValidDomain(cfg.NToken.AthenzDomain) {
return nil, nil, ErrInvalidParameter
}
hyphenDomain := strings.Replace(cfg.NToken.AthenzDomain, ".", "-", -1)
host := fmt.Sprintf("%s.%s.%s", cfg.NToken.ServiceName, hyphenDomain, cfg.ServiceCert.DNSSuffix)
commonName := fmt.Sprintf("%s.%s", cfg.NToken.AthenzDomain, cfg.NToken.ServiceName)
subj := pkix.Name{
CommonName: commonName,
OrganizationalUnit: []string{cfg.ServiceCert.Subject.OrganizationalUnit},
Organization: []string{cfg.ServiceCert.Subject.Organization},
Province: []string{cfg.ServiceCert.Subject.Province},
Country: []string{cfg.ServiceCert.Subject.Country},
}
uri := ""
if cfg.ServiceCert.Spiffe {
uri = fmt.Sprintf("spiffe://%s/sa/%s", cfg.NToken.AthenzDomain, cfg.NToken.ServiceName)
}
csrData, err := generateCSR(pkSigner, subj, host, uri)
if err != nil {
return nil, nil, ErrFailedToInitialize
}
// if we're given a certificate then we'll use that otherwise
// we're going to generate a N-token for our request unless
// we're using copper argos which only uses tls and the attestation
// data contains the authentication details
client, err := ztsClient(cfg.ServiceCert)
if err != nil {
return nil, nil, ErrFailedToInitialize
}
// if we're given provider then we're going to use our
// copper argos model to request the certificate
req := &zts.InstanceRefreshRequest{
Csr: csrData,
ExpiryTime: &expiry,
}
return &requestTemplate{
req: req,
compoundName: zts.CompoundName(cfg.NToken.AthenzDomain),
simpleName: zts.SimpleName(cfg.NToken.ServiceName),
}, client, nil
}
func newSigner(privateKeyPEM []byte) (*signer, error) {
block, _ := pem.Decode(privateKeyPEM)
if block == nil {
return nil, fmt.Errorf("Unable to load private key")
}
switch block.Type {
case "EC PRIVATE KEY":
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &signer{key: key, algorithm: x509.ECDSAWithSHA256}, nil
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &signer{key: key, algorithm: x509.SHA256WithRSA}, nil
default:
return nil, fmt.Errorf("Unsupported private key type: %s", block.Type)
}
}
func generateCSR(keySigner *signer, subj pkix.Name, host, uri string) (string, error) {
template := x509.CertificateRequest{
Subject: subj,
SignatureAlgorithm: keySigner.algorithm,
}
if host != "" {
template.DNSNames = []string{host}
}
if uri != "" {
uriptr, err := url.Parse(uri)
if err == nil {
template.URIs = []*url.URL{uriptr}
}
}
csr, err := x509.CreateCertificateRequest(rand.Reader, &template, keySigner.key)
if err != nil {
return "", fmt.Errorf("Cannot create CSR: %v", err)
}
block := &pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
var buf bytes.Buffer
err = pem.Encode(&buf, block)
if err != nil {
return "", fmt.Errorf("Cannot encode CSR to PEM: %v", err)
}
return buf.String(), nil
}
func ztsClient(cfg config.ServiceCert) (*zts.ZTSClient, error) {
_, err := url.Parse(cfg.AthenzURL)
if err != nil {
return nil, ErrInvalidParameter
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
ResponseHeaderTimeout: 30 * time.Second,
}
// TODO: refactor use NewX509CertPool() in tls.go
if cfg.AthenzCAPath != "" {
config := &tls.Config{}
certPool := x509.NewCertPool()
caCert, err := ioutil.ReadFile(cfg.AthenzCAPath)
if err != nil {
return nil, err
}
certPool.AppendCertsFromPEM(caCert)
config.RootCAs = certPool
transport.TLSClientConfig = config
}
client := zts.NewClient(cfg.AthenzURL, transport)
return &client, nil
}
func (s *svcCertService) StartSvcCertUpdater(ctx context.Context) SvcCertService {
go func() {
var err error
fch := make(chan struct{}, 1)
ticker := time.NewTicker(s.refreshDuration)
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-fch:
_, err = s.RefreshSvcCert()
if err != nil {
glg.Error(err)
time.Sleep(time.Minute * 10)
fch <- struct{}{}
}
case <-ticker.C:
_, err = s.RefreshSvcCert()
if err != nil {
glg.Error(err)
fch <- struct{}{}
}
}
}
}()
return s
}
// GetSvcCertProvider returns a function pointer to get the svccert.
func (s *svcCertService) GetSvcCertProvider() SvcCertProvider {
return s.getSvcCert
}
// getSvcCert return a token string or error
// This function is thread-safe. This function will return the svccert stored in the atomic variable,
// or return the error when the svccert is not initialized or cannot be generated
func (s *svcCertService) getSvcCert() ([]byte, error) {
cache := s.certCache.Load().(certCache)
if cache.cert == nil || cache.exp.Before(fastime.Now()) {
cert, err := s.RefreshSvcCert()
if err != nil {
// NOTE: When RefreshSvcCert is failed, return the cached certificate if it is not expired
if cache.cert != nil && cache.exp.Add(s.expireMargin).After(fastime.Now()) {
glg.Warn("Cached certificate is not expired. Return from cache. Error: " + err.Error())
return cache.cert, nil
}
glg.Error(err)
return nil, err
}
return cert, nil
}
return cache.cert, nil
}
func (s *svcCertService) RefreshSvcCert() ([]byte, error) {
svccert, err, _ := s.group.Do("", func() (interface{}, error) {
nToken, err := s.token()
if err != nil {
return nil, err
}
s.client.AddCredentials(s.cfg.PrincipalAuthHeader, nToken)
// request a tls certificate for this service
identity, err := s.client.PostInstanceRefreshRequest(
s.refreshRequest.compoundName,
s.refreshRequest.simpleName,
s.refreshRequest.req,
)
if err != nil {
return nil, err
}
block, _ := pem.Decode([]byte(identity.Certificate))
if block == nil {
return nil, ErrInvalidCert
}
certificate, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, ErrInvalidCert
}
var cert []byte
if s.cfg.IntermediateCert {
cert = []byte(identity.Certificate + identity.CaCertBundle)
} else {
cert = []byte(identity.Certificate)
}
// update cert cache and expiry
cache := certCache{
cert: cert,
exp: certificate.NotAfter.Add(-s.expireMargin),
}
s.certCache.Store(cache)
return cert, nil
})
if err != nil {
return nil, err
}
return svccert.([]byte), nil
}