-
Notifications
You must be signed in to change notification settings - Fork 49
/
keyring.go
430 lines (369 loc) · 12.2 KB
/
keyring.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
package storage
/*
* AWS SSO CLI
* Copyright (c) 2021-2023 Aaron Turner <synfinatic at gmail dot com>
*
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or with the authors permission any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import (
"encoding/binary"
"encoding/json"
"fmt"
"os"
"path"
"runtime"
"github.com/99designs/keyring"
// "github.com/davecgh/go-spew/spew"
"github.com/synfinatic/aws-sso-cli/internal/utils"
"golang.org/x/term"
)
const (
KEYRING_ID = "aws-sso-cli"
RECORD_KEY = "aws-sso-cli-records"
KEYRING_NAME = "awsssocli"
REGISTER_CLIENT_DATA_PREFIX = "client-data"
CREATE_TOKEN_RESPONSE_PREFIX = "token-response"
ENV_SSO_FILE_PASSWORD = "AWS_SSO_FILE_PASSWORD" // #nosec
WINCRED_MAX_LENGTH = 2000
)
// Implements SecureStorage
type KeyringStore struct {
keyring KeyringAPI
config keyring.Config
cache StorageData
}
type StorageData struct {
RegisterClientData map[string]RegisterClientData
CreateTokenResponse map[string]CreateTokenResponse
RoleCredentials map[string]RoleCredentials
StaticCredentials map[string]StaticCredentials
}
func NewStorageData() StorageData {
return StorageData{
RegisterClientData: map[string]RegisterClientData{},
CreateTokenResponse: map[string]CreateTokenResponse{},
RoleCredentials: map[string]RoleCredentials{},
StaticCredentials: map[string]StaticCredentials{},
}
}
var NewPassword string = ""
var keyringGOOS string = runtime.GOOS
// KeyringAPI is the subset of the Keyring API we use so we can do unit testing
type KeyringAPI interface {
// Returns an Item matching the key or ErrKeyNotFound
Get(key string) (keyring.Item, error)
// Returns the non-secret parts of an Item
// GetMetadata(key string) (Metadata, error)
// Stores an Item on the keyring
Set(item keyring.Item) error
// Removes the item with matching key
Remove(key string) error
// Provides a slice of all keys stored on the keyring
// Keys() ([]string, error)
}
type getPassword func(string) (string, error)
var getPasswordFunc getPassword = fileKeyringPassword
func NewKeyringConfig(name, configDir string) (*keyring.Config, error) {
securePath := path.Join(configDir, "secure")
c := keyring.Config{
ServiceName: KEYRING_ID, // generic backend provider
// macOS KeyChain
KeychainTrustApplication: true, // stop asking user for passwords
KeychainSynchronizable: false, // no iCloud sync
KeychainAccessibleWhenUnlocked: false, // no reads while device locked
// KeychainPasswordFunc: ???,
// Other systems below this line
FileDir: securePath,
FilePasswordFunc: fileKeyringPassword,
LibSecretCollectionName: KEYRING_NAME,
KWalletAppID: KEYRING_ID,
KWalletFolder: KEYRING_ID,
WinCredPrefix: KEYRING_ID,
}
if name != "" {
c.AllowedBackends = []keyring.BackendType{keyring.BackendType(name)}
rolesFile := utils.GetHomePath(path.Join(securePath, RECORD_KEY))
if name == "file" {
if _, err := os.Stat(rolesFile); os.IsNotExist(err) {
// new secure store, so we should prompt user twice for password
// if ENV var is not set
if password := os.Getenv(ENV_SSO_FILE_PASSWORD); password == "" {
pass1, err := getPasswordFunc("Select password")
if err != nil {
return &c, fmt.Errorf("Password error: %s", err.Error())
}
pass2, err := getPasswordFunc("Verify password")
if err != nil {
return &c, fmt.Errorf("Password error: %s", err.Error())
}
if pass1 != pass2 {
return &c, fmt.Errorf("Password missmatch")
}
NewPassword = pass1
}
}
}
}
return &c, nil
}
func fileKeyringPassword(prompt string) (string, error) {
if password := os.Getenv(ENV_SSO_FILE_PASSWORD); password != "" {
return password, nil
}
if NewPassword != "" {
return NewPassword, nil
}
fmt.Fprintf(os.Stderr, "%s: ", prompt)
b, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
s := string(b)
if s == "" {
fmt.Println()
log.Fatalf("Aborting with empty password")
}
fmt.Println()
return s, nil
}
func OpenKeyring(cfg *keyring.Config) (*KeyringStore, error) {
ring, err := keyring.Open(*cfg)
if err != nil {
return nil, err
}
kr := KeyringStore{
keyring: ring,
config: *cfg,
cache: NewStorageData(),
}
if err = kr.getStorageData(&kr.cache); err != nil {
return nil, err
}
return &kr, nil
}
func (kr *KeyringStore) RegisterClientKey(ssoRegion string) string {
return fmt.Sprintf("%s:%s", REGISTER_CLIENT_DATA_PREFIX, ssoRegion)
}
type Unmarshaler func([]byte, interface{}) error
var storageDataUnmarshal Unmarshaler = json.Unmarshal
// loads the entire StorageData into memory
func (kr *KeyringStore) getStorageData(s *StorageData) error {
var data []byte
var err error
switch keyringGOOS {
case "windows":
data, err = kr.joinAndGetKeyringData(RECORD_KEY)
default:
data, err = kr.getKeyringData(RECORD_KEY)
}
if err != nil {
log.Warn(err)
// Didn't find anything in our keyring
*s = NewStorageData()
return nil
}
if err = storageDataUnmarshal(data, s); err != nil {
return err
}
return nil
}
// reads a single entry of the keyring
func (kr *KeyringStore) getKeyringData(key string) ([]byte, error) {
data, err := kr.keyring.Get(key)
if err != nil {
return nil, err
}
return data.Data, nil
}
// read the chunks stored in windows credential manager
func (kr *KeyringStore) joinAndGetKeyringData(key string) ([]byte, error) {
var err error
var chunk []byte
if chunk, err = kr.getKeyringData(fmt.Sprintf("%s_%d", key, 0)); err != nil {
return nil, err
}
if len(chunk) < 8 {
return nil, fmt.Errorf("Invalid stored data in Keyring. Only %d bytes", len(chunk))
}
totalBytes, data := binary.BigEndian.Uint64(chunk[:8]), chunk[8:]
readBytes := uint64(len(data))
for i := 1; readBytes < totalBytes; i++ {
k := fmt.Sprintf("%s_%d", key, i)
if chunk, err = kr.getKeyringData(k); err != nil {
return nil, fmt.Errorf("Unable to fetch %s: %s", k, err.Error())
}
data = append(data, chunk...)
readBytes += uint64(len(chunk))
}
if readBytes != totalBytes {
return nil, fmt.Errorf("Invalid stored data in Keyring. Expected %d bytes, but read %d bytes of data",
totalBytes, readBytes)
}
return data, nil
}
// saves the entire StorageData into our KeyringStore
func (kr *KeyringStore) saveStorageData() error {
var err error
jdata, _ := json.Marshal(kr.cache)
switch keyringGOOS {
case "windows":
err = kr.splitAndSetStorageData(jdata, RECORD_KEY, KEYRING_ID)
default:
err = kr.setStorageData(jdata, RECORD_KEY, KEYRING_ID)
}
return err
}
// splitAndSetStorageData writes all the data in WINCRED_MAX_LENGTH length chunks
func (kr *KeyringStore) splitAndSetStorageData(jdata []byte, key string, label string) error {
var i int
remain := jdata
var chunk []byte
payloadSize := make([]byte, 8)
binary.BigEndian.PutUint64(payloadSize, uint64(len(jdata)))
for i = 0; len(remain) >= WINCRED_MAX_LENGTH; i++ {
chunk, remain = remain[:WINCRED_MAX_LENGTH], remain[WINCRED_MAX_LENGTH:]
if i == 0 {
chunk = append(payloadSize, chunk...)
}
if err := kr.setStorageData(chunk, fmt.Sprintf("%s_%d", key, i), label); err != nil {
return err
}
}
if len(remain) > 0 {
if i == 0 {
remain = append(payloadSize, remain...)
}
err := kr.setStorageData(remain, fmt.Sprintf("%s_%d", key, i), label)
if err != nil {
return err
}
}
return nil
}
// setStorageData writes all the data as a single entry
func (kr *KeyringStore) setStorageData(jdata []byte, key string, label string) error {
err := kr.keyring.Set(keyring.Item{
Key: key,
Data: jdata,
Label: label,
Description: "aws-sso secure storage",
})
return err
}
// Save our RegisterClientData in the key chain
func (kr *KeyringStore) SaveRegisterClientData(region string, client RegisterClientData) error {
key := kr.RegisterClientKey(region)
kr.cache.RegisterClientData[key] = client
return kr.saveStorageData()
}
// Get our RegisterClientData from the key chain
func (kr *KeyringStore) GetRegisterClientData(region string, client *RegisterClientData) error {
var ok bool
key := kr.RegisterClientKey(region)
if *client, ok = kr.cache.RegisterClientData[key]; !ok {
return fmt.Errorf("No RegisterClientData for %s", region)
}
return nil
}
// Delete the RegisterClientData from the keychain
func (kr *KeyringStore) DeleteRegisterClientData(region string) error {
key := kr.RegisterClientKey(region)
if _, ok := kr.cache.RegisterClientData[key]; !ok {
// return error if key doesn't exist
return fmt.Errorf("No RegisterClientData for key: %s", key)
}
delete(kr.cache.RegisterClientData, key)
return kr.saveStorageData()
}
func (kr *KeyringStore) CreateTokenResponseKey(key string) string {
return fmt.Sprintf("%s:%s", CREATE_TOKEN_RESPONSE_PREFIX, key)
}
// SaveCreateTokenResponse stores the token in the keyring
func (kr *KeyringStore) SaveCreateTokenResponse(key string, token CreateTokenResponse) error {
k := kr.CreateTokenResponseKey(key)
kr.cache.CreateTokenResponse[k] = token
return kr.saveStorageData()
}
// GetCreateTokenResponse retrieves the CreateTokenResponse from the keyring
func (kr *KeyringStore) GetCreateTokenResponse(key string, token *CreateTokenResponse) error {
var ok bool
k := kr.CreateTokenResponseKey(key)
if *token, ok = kr.cache.CreateTokenResponse[k]; !ok {
return fmt.Errorf("No CreateTokenResponse for %s", k)
}
return nil
}
// DeleteCreateTokenResponse deletes the CreateTokenResponse from the keyring
func (kr *KeyringStore) DeleteCreateTokenResponse(key string) error {
k := kr.CreateTokenResponseKey(key)
if _, ok := kr.cache.CreateTokenResponse[k]; !ok {
// return error if key doesn't exist
return fmt.Errorf("No CreateTokenResponse for key: %s", k)
}
delete(kr.cache.CreateTokenResponse, k)
return kr.saveStorageData()
}
// SaveRoleCredentials stores the token in the arnring
func (kr *KeyringStore) SaveRoleCredentials(arn string, token RoleCredentials) error {
kr.cache.RoleCredentials[arn] = token
return kr.saveStorageData()
}
// GetRoleCredentials retrieves the RoleCredentials from the Keyring
func (kr *KeyringStore) GetRoleCredentials(arn string, token *RoleCredentials) error {
var ok bool
if *token, ok = kr.cache.RoleCredentials[arn]; !ok {
return fmt.Errorf("No RoleCredentials for ARN: %s", arn)
}
return nil
}
// DeleteRoleCredentials deletes the RoleCredentials from the Keyring
func (kr *KeyringStore) DeleteRoleCredentials(arn string) error {
if _, ok := kr.cache.RoleCredentials[arn]; !ok {
// return error if key doesn't exist
return fmt.Errorf("No RoleCredentials for ARN: %s", arn)
}
delete(kr.cache.RoleCredentials, arn)
return kr.saveStorageData()
}
// SaveStaticCredentials stores the token in the arnring
func (kr *KeyringStore) SaveStaticCredentials(arn string, creds StaticCredentials) error {
kr.cache.StaticCredentials[arn] = creds
return kr.saveStorageData()
}
// GetStaticCredentials retrieves the StaticCredentials from the Keyring
func (kr *KeyringStore) GetStaticCredentials(arn string, creds *StaticCredentials) error {
var ok bool
if *creds, ok = kr.cache.StaticCredentials[arn]; !ok {
return fmt.Errorf("No StaticCredentials for ARN: %s", arn)
}
return nil
}
// DeleteStaticCredentials deletes the StaticCredentials from the Keyring
func (kr *KeyringStore) DeleteStaticCredentials(arn string) error {
if _, ok := kr.cache.StaticCredentials[arn]; !ok {
// return error if key doesn't exist
return fmt.Errorf("No StaticCredentials for ARN: %s", arn)
}
delete(kr.cache.StaticCredentials, arn)
return kr.saveStorageData()
}
func (kr *KeyringStore) ListStaticCredentials() []string {
ret := make([]string, len(kr.cache.StaticCredentials))
i := 0
for k := range kr.cache.StaticCredentials {
ret[i] = k
i++
}
return ret
}