-
Notifications
You must be signed in to change notification settings - Fork 80
/
federation_client.go
561 lines (465 loc) · 18 KB
/
federation_client.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Package auth provides supporting functions and structs for authentication
package auth
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"time"
)
// federationClient is a client to retrieve the security token for an instance principal necessary to sign a request.
// It also provides the private key whose corresponding public key is used to retrieve the security token.
type federationClient interface {
ClaimHolder
PrivateKey() (*rsa.PrivateKey, error)
SecurityToken() (string, error)
}
// ClaimHolder is implemented by any token interface that provides access to the security claims embedded in the token.
type ClaimHolder interface {
GetClaim(key string) (interface{}, error)
}
type genericFederationClient struct {
SessionKeySupplier sessionKeySupplier
RefreshSecurityToken func() (securityToken, error)
securityToken securityToken
mux sync.Mutex
}
var _ federationClient = &genericFederationClient{}
func (c *genericFederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.SessionKeySupplier.PrivateKey(), nil
}
func (c *genericFederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (c *genericFederationClient) renewKeyAndSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewKeyAndSecurityToken(); err != nil {
return fmt.Errorf("failed to renew security token: %s", err.Error())
}
}
return nil
}
func (c *genericFederationClient) renewKeyAndSecurityToken() (err error) {
common.Logf("Renewing keys for file based security token at: %v\n", time.Now().Format("15:04:05.000"))
if err = c.SessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
common.Logf("Renewing security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.RefreshSecurityToken(); err != nil {
return fmt.Errorf("failed to refresh security token key: %s", err.Error())
}
common.Logf("Security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
func (c *genericFederationClient) GetClaim(key string) (interface{}, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.securityToken.GetClaim(key)
}
func newFileBasedFederationClient(securityTokenPath string, supplier sessionKeySupplier) (*genericFederationClient, error) {
return &genericFederationClient{
SessionKeySupplier: supplier,
RefreshSecurityToken: func() (token securityToken, err error) {
var content []byte
if content, err = ioutil.ReadFile(securityTokenPath); err != nil {
return nil, fmt.Errorf("failed to read security token from :%s. Due to: %s", securityTokenPath, err.Error())
}
var newToken securityToken
if newToken, err = newInstancePrincipalToken(string(content)); err != nil {
return nil, fmt.Errorf("failed to read security token from :%s. Due to: %s", securityTokenPath, err.Error())
}
return newToken, nil
},
}, nil
}
func newStaticFederationClient(sessionToken string, supplier sessionKeySupplier) (*genericFederationClient, error) {
var newToken securityToken
var err error
if newToken, err = newInstancePrincipalToken(string(sessionToken)); err != nil {
return nil, fmt.Errorf("failed to read security token. Due to: %s", err.Error())
}
return &genericFederationClient{
SessionKeySupplier: supplier,
RefreshSecurityToken: func() (token securityToken, err error) {
return newToken, nil
},
}, nil
}
// x509FederationClient retrieves a security token from Auth service.
type x509FederationClient struct {
tenancyID string
sessionKeySupplier sessionKeySupplier
leafCertificateRetriever x509CertificateRetriever
intermediateCertificateRetrievers []x509CertificateRetriever
securityToken securityToken
authClient *common.BaseClient
mux sync.Mutex
}
func newX509FederationClient(region common.Region, tenancyID string, leafCertificateRetriever x509CertificateRetriever, intermediateCertificateRetrievers []x509CertificateRetriever, modifier dispatcherModifier) (federationClient, error) {
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: leafCertificateRetriever,
intermediateCertificateRetrievers: intermediateCertificateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
func newX509FederationClientWithCerts(region common.Region, tenancyID string, leafCertificate, leafPassphrase, leafPrivateKey []byte, intermediateCertificates [][]byte, modifier dispatcherModifier) (federationClient, error) {
intermediateRetrievers := make([]x509CertificateRetriever, len(intermediateCertificates))
for i, c := range intermediateCertificates {
intermediateRetrievers[i] = &staticCertificateRetriever{Passphrase: []byte(""), CertificatePem: c, PrivateKeyPem: nil}
}
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: &staticCertificateRetriever{Passphrase: leafPassphrase, CertificatePem: leafCertificate, PrivateKeyPem: leafPrivateKey},
intermediateCertificateRetrievers: intermediateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
var (
genericHeaders = []string{"date", "(request-target)"} // "host" is not needed for the federation endpoint. Don't ask me why.
bodyHeaders = []string{"content-length", "content-type", "x-content-sha256"}
)
func newAuthClient(region common.Region, provider common.KeyProvider) *common.BaseClient {
signer := common.RequestSigner(provider, genericHeaders, bodyHeaders)
client := common.DefaultBaseClientWithSigner(signer)
if regionURL, ok := os.LookupEnv("OCI_SDK_AUTH_CLIENT_REGION_URL"); ok {
client.Host = regionURL
} else {
client.Host = region.Endpoint("auth")
}
client.BasePath = "v1/x509"
return &client
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) KeyID() (string, error) {
tenancy := c.tenancyID
fingerprint := fingerprint(c.leafCertificateRetriever.Certificate())
return fmt.Sprintf("%s/fed-x509/%s", tenancy, fingerprint), nil
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) PrivateRSAKey() (*rsa.PrivateKey, error) {
key := c.leafCertificateRetriever.PrivateKey()
if key == nil {
return nil, fmt.Errorf("can not read private key from leaf certificate. Likely an error in the metadata service")
}
return key, nil
}
func (c *x509FederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.sessionKeySupplier.PrivateKey(), nil
}
func (c *x509FederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (c *x509FederationClient) renewSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewSecurityToken(); err != nil {
return fmt.Errorf("failed to renew security token: %s", err.Error())
}
}
return nil
}
func (c *x509FederationClient) renewSecurityToken() (err error) {
if err = c.sessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
if err = c.leafCertificateRetriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh leaf certificate: %s", err.Error())
}
updatedTenancyID := extractTenancyIDFromCertificate(c.leafCertificateRetriever.Certificate())
if c.tenancyID != updatedTenancyID {
err = fmt.Errorf("unexpected update of tenancy OCID in the leaf certificate. Previous tenancy: %s, Updated: %s", c.tenancyID, updatedTenancyID)
return
}
for _, retriever := range c.intermediateCertificateRetrievers {
if err = retriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh intermediate certificate: %s", err.Error())
}
}
common.Logf("Renewing security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.getSecurityToken(); err != nil {
return fmt.Errorf("failed to get security token: %s", err.Error())
}
common.Logf("Security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
func (c *x509FederationClient) getSecurityToken() (securityToken, error) {
request := c.makeX509FederationRequest()
var err error
var httpRequest http.Request
if httpRequest, err = common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodPost, "", request); err != nil {
return nil, fmt.Errorf("failed to make http request: %s", err.Error())
}
var httpResponse *http.Response
defer common.CloseBodyIfValid(httpResponse)
if httpResponse, err = c.authClient.Call(context.Background(), &httpRequest); err != nil {
return nil, fmt.Errorf("failed to call: %s", err.Error())
}
response := x509FederationResponse{}
if err = common.UnmarshalResponse(httpResponse, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal the response: %s", err.Error())
}
return newInstancePrincipalToken(response.Token.Token)
}
func (c *x509FederationClient) GetClaim(key string) (interface{}, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.securityToken.GetClaim(key)
}
type x509FederationRequest struct {
X509FederationDetails `contributesTo:"body"`
}
// X509FederationDetails x509 federation details
type X509FederationDetails struct {
Certificate string `mandatory:"true" json:"certificate,omitempty"`
PublicKey string `mandatory:"true" json:"publicKey,omitempty"`
IntermediateCertificates []string `mandatory:"false" json:"intermediateCertificates,omitempty"`
}
type x509FederationResponse struct {
Token `presentIn:"body"`
}
// Token token
type Token struct {
Token string `mandatory:"true" json:"token,omitempty"`
}
func (c *x509FederationClient) makeX509FederationRequest() *x509FederationRequest {
certificate := c.sanitizeCertificateString(string(c.leafCertificateRetriever.CertificatePemRaw()))
publicKey := c.sanitizeCertificateString(string(c.sessionKeySupplier.PublicKeyPemRaw()))
var intermediateCertificates []string
for _, retriever := range c.intermediateCertificateRetrievers {
intermediateCertificates = append(intermediateCertificates, c.sanitizeCertificateString(string(retriever.CertificatePemRaw())))
}
details := X509FederationDetails{
Certificate: certificate,
PublicKey: publicKey,
IntermediateCertificates: intermediateCertificates,
}
return &x509FederationRequest{details}
}
func (c *x509FederationClient) sanitizeCertificateString(certString string) string {
certString = strings.Replace(certString, "-----BEGIN CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----END CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----BEGIN PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "-----END PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "\n", "", -1)
return certString
}
// sessionKeySupplier provides an RSA keypair which can be re-generated by calling Refresh().
type sessionKeySupplier interface {
Refresh() error
PrivateKey() *rsa.PrivateKey
PublicKeyPemRaw() []byte
}
//genericKeySupplier implements sessionKeySupplier and provides an arbitrary refresh mechanism
type genericKeySupplier struct {
RefreshFn func() (*rsa.PrivateKey, []byte, error)
privateKey *rsa.PrivateKey
publicKeyPemRaw []byte
}
func (s genericKeySupplier) PrivateKey() *rsa.PrivateKey {
if s.privateKey == nil {
return nil
}
c := *s.privateKey
return &c
}
func (s genericKeySupplier) PublicKeyPemRaw() []byte {
if s.publicKeyPemRaw == nil {
return nil
}
c := make([]byte, len(s.publicKeyPemRaw))
copy(c, s.publicKeyPemRaw)
return c
}
func (s *genericKeySupplier) Refresh() (err error) {
privateKey, publicPem, err := s.RefreshFn()
if err != nil {
return err
}
s.privateKey = privateKey
s.publicKeyPemRaw = publicPem
return nil
}
// create a sessionKeySupplier that reads keys from file every time it refreshes
func newFileBasedKeySessionSupplier(privateKeyPemPath string, passphrasePath *string) (*genericKeySupplier, error) {
return &genericKeySupplier{
RefreshFn: func() (*rsa.PrivateKey, []byte, error) {
var err error
var passContent []byte
if passphrasePath != nil {
if passContent, err = ioutil.ReadFile(*passphrasePath); err != nil {
return nil, nil, fmt.Errorf("can not read passphrase from file: %s, due to %s", *passphrasePath, err.Error())
}
}
var keyPemContent []byte
if keyPemContent, err = ioutil.ReadFile(privateKeyPemPath); err != nil {
return nil, nil, fmt.Errorf("can not read private privateKey pem from file: %s, due to %s", privateKeyPemPath, err.Error())
}
var privateKey *rsa.PrivateKey
if privateKey, err = common.PrivateKeyFromBytesWithPassword(keyPemContent, passContent); err != nil {
return nil, nil, fmt.Errorf("can not create private privateKey from contents of: %s, due to: %s", privateKeyPemPath, err.Error())
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return nil, nil, fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
return privateKey, publicKeyPemRaw, nil
},
}, nil
}
func newStaticKeySessionSupplier(privateKeyPemContent, passphrase []byte) (*genericKeySupplier, error) {
var err error
var privateKey *rsa.PrivateKey
if privateKey, err = common.PrivateKeyFromBytesWithPassword(privateKeyPemContent, passphrase); err != nil {
return nil, fmt.Errorf("can not create private privateKey, due to: %s", err.Error())
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return nil, fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
return &genericKeySupplier{
RefreshFn: func() (key *rsa.PrivateKey, bytes []byte, err error) {
return privateKey, publicKeyPemRaw, nil
},
}, nil
}
// inMemorySessionKeySupplier implements sessionKeySupplier to vend an RSA keypair.
// Refresh() generates a new RSA keypair with a random source, and keeps it in memory.
//
// inMemorySessionKeySupplier is not thread-safe.
type inMemorySessionKeySupplier struct {
keySize int
privateKey *rsa.PrivateKey
publicKeyPemRaw []byte
}
// newSessionKeySupplier creates and returns a sessionKeySupplier instance which generates key pairs of size 2048.
func newSessionKeySupplier() sessionKeySupplier {
return &inMemorySessionKeySupplier{keySize: 2048}
}
// Refresh() is failure atomic, i.e., PrivateKey() and PublicKeyPemRaw() would return their previous values
// if Refresh() fails.
func (s *inMemorySessionKeySupplier) Refresh() (err error) {
common.Debugln("Refreshing session key")
var privateKey *rsa.PrivateKey
privateKey, err = rsa.GenerateKey(rand.Reader, s.keySize)
if err != nil {
return fmt.Errorf("failed to generate a new keypair: %s", err)
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
s.privateKey = privateKey
s.publicKeyPemRaw = publicKeyPemRaw
return nil
}
func (s *inMemorySessionKeySupplier) PrivateKey() *rsa.PrivateKey {
if s.privateKey == nil {
return nil
}
c := *s.privateKey
return &c
}
func (s *inMemorySessionKeySupplier) PublicKeyPemRaw() []byte {
if s.publicKeyPemRaw == nil {
return nil
}
c := make([]byte, len(s.publicKeyPemRaw))
copy(c, s.publicKeyPemRaw)
return c
}
type securityToken interface {
fmt.Stringer
Valid() bool
ClaimHolder
}
type instancePrincipalToken struct {
tokenString string
jwtToken *jwtToken
}
func newInstancePrincipalToken(tokenString string) (newToken securityToken, err error) {
var jwtToken *jwtToken
if jwtToken, err = parseJwt(tokenString); err != nil {
return nil, fmt.Errorf("failed to parse the token string \"%s\": %s", tokenString, err.Error())
}
return &instancePrincipalToken{tokenString, jwtToken}, nil
}
func (t *instancePrincipalToken) String() string {
return t.tokenString
}
func (t *instancePrincipalToken) Valid() bool {
return !t.jwtToken.expired()
}
var (
// ErrNoSuchClaim is returned when a token does not hold the claim sought
ErrNoSuchClaim = errors.New("no such claim")
)
func (t *instancePrincipalToken) GetClaim(key string) (interface{}, error) {
if value, ok := t.jwtToken.payload[key]; ok {
return value, nil
}
return nil, ErrNoSuchClaim
}