This repository has been archived by the owner on Mar 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcredentials.go
604 lines (521 loc) · 13.8 KB
/
credentials.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/realestate-com-au/goamz/aws"
"github.com/realestate-com-au/goamz/iam"
"code.google.com/p/go.crypto/ssh"
)
const FORMAT_VERSION string = "2014-06-12"
// How long to retry after rotating credentials for
// new credentials to become active (in seconds)
const ROTATE_TIMEOUT int = 30
type Credentials struct {
Version string
IamUsername string
AccountAliasOrId string
CreateTime string
LifeTime int
Encryptions []Encryption
}
type Encryption struct {
Fingerprint string
Ciphertext string
// we can do this because the field isn't exported
// and so won't be included when we call Marshal to
// save the encrypted credentials
decoded Credential
}
type Credential struct {
KeyId string
SecretKey string
EnvVars map[string]string
}
type OldCredential struct {
CreateTime string
LifeTime int
KeyId string
SecretKey string
Salt string
AccountAliasOrId string
IamUsername string
FingerPrint string
}
type SaveData struct {
cred Credential
username string
alias string
pubkeys []ssh.PublicKey
lifetime int
force bool
repo string
isRepo bool
}
func decodeOldCredential(data []byte, keyfile string) (*OldCredential, error) {
var credential OldCredential
err := json.Unmarshal(data, &credential)
if err != nil {
return nil, err
}
privKey, err := loadPrivateKey(keyfile)
if err != nil {
return nil, err
}
decoded, err := CredulousDecodeWithSalt(credential.KeyId, credential.Salt, privKey)
if err != nil {
return nil, err
}
credential.KeyId = decoded
decoded, err = CredulousDecodeWithSalt(credential.SecretKey, credential.Salt, privKey)
if err != nil {
return nil, err
}
credential.SecretKey = decoded
if credential.CreateTime == "" {
credential.CreateTime = "0"
}
return &credential, nil
}
func parseOldCredential(data []byte, keyfile string) (*Credentials, error) {
oldCred, err := decodeOldCredential(data, keyfile)
if err != nil {
return nil, err
}
// build a new Credentials structure out of the old
cred := Credential{
KeyId: oldCred.KeyId,
SecretKey: oldCred.SecretKey,
}
enc := []Encryption{}
enc = append(enc, Encryption{
decoded: cred,
})
creds := Credentials{
Version: "noversion",
IamUsername: oldCred.IamUsername,
AccountAliasOrId: oldCred.AccountAliasOrId,
CreateTime: oldCred.CreateTime,
LifeTime: oldCred.LifeTime,
Encryptions: enc,
}
return &creds, nil
}
func parseCredential(data []byte, keyfile string) (*Credentials, error) {
var creds Credentials
err := json.Unmarshal(data, &creds)
if err != nil {
return nil, err
}
privKey, err := loadPrivateKey(keyfile)
if err != nil {
return nil, err
}
fp, err := SSHPrivateFingerprint(*privKey)
if err != nil {
return nil, err
}
var offset int = -1
for i, enc := range creds.Encryptions {
if enc.Fingerprint == fp {
offset = i
break
}
}
if offset < 0 {
err := errors.New("The SSH key specified cannot decrypt those credentials")
return nil, err
}
var tmp string
switch {
case creds.Version == "2014-05-31":
log.Print("INFO: These credentials are in the old format; re-run 'credulous save' now to remove this warning")
tmp, err = CredulousDecodePureRSA(creds.Encryptions[offset].Ciphertext, privKey)
case creds.Version == "2014-06-12":
tmp, err = CredulousDecodeAES(creds.Encryptions[offset].Ciphertext, privKey)
}
if err != nil {
return nil, err
}
var cred Credential
err = json.Unmarshal([]byte(tmp), &cred)
if err != nil {
return nil, err
}
creds.Encryptions[0].decoded = cred
return &creds, nil
}
func readCredentialFile(fileName string, keyfile string) (*Credentials, error) {
b, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
if !strings.Contains(string(b), "Version") {
log.Print("INFO: These credentials are in the old format; re-run 'credulous save' now to remove this warning")
creds, err := parseOldCredential(b, keyfile)
if err != nil {
return nil, err
}
return creds, nil
}
creds, err := parseCredential(b, keyfile)
if err != nil {
return nil, err
}
return creds, nil
}
func (cred Credentials) WriteToDisk(repo, filename string) (err error) {
b, err := json.Marshal(cred)
if err != nil {
return err
}
path := filepath.Join(repo, cred.AccountAliasOrId, cred.IamUsername)
os.MkdirAll(path, 0700)
err = ioutil.WriteFile(filepath.Join(path, filename), b, 0600)
if err != nil {
return err
}
isrepo, err := isGitRepo(repo)
if err != nil {
return err
}
if !isrepo {
return nil
}
relpath := filepath.Join(cred.AccountAliasOrId, cred.IamUsername, filename)
_, err = gitAddCommitFile(repo, relpath, "Added by Credulous")
if err != nil {
return err
}
return nil
}
func (cred OldCredential) Display(output io.Writer) {
fmt.Fprintf(output, "export AWS_ACCESS_KEY_ID=\"%v\"\nexport AWS_SECRET_ACCESS_KEY=\"%v\"\n", cred.KeyId, cred.SecretKey)
}
func (cred Credentials) Display(output io.Writer) {
fmt.Fprintf(output, "export AWS_ACCESS_KEY_ID=\"%v\"\nexport AWS_SECRET_ACCESS_KEY=\"%v\"\n",
cred.Encryptions[0].decoded.KeyId, cred.Encryptions[0].decoded.SecretKey)
for key, val := range cred.Encryptions[0].decoded.EnvVars {
fmt.Fprintf(output, "export %s=\"%s\"\n", key, val)
}
}
func (creds Credentials) verifyUserAndAccount() error {
// need to check both the username and the account alias for the
// supplied creds match the passed-in username and account alias
auth := aws.Auth{
AccessKey: creds.Encryptions[0].decoded.KeyId,
SecretKey: creds.Encryptions[0].decoded.SecretKey,
}
// Note: the region is irrelevant for IAM
instance := iam.New(auth, aws.APSoutheast2)
// Make sure the account is who we expect
err := verify_account(creds.AccountAliasOrId, instance)
if err != nil {
return err
}
// Make sure the user is who we expect
// If the username is the same as the account name, then it's the root user
// and there's actually no username at all (oddly)
if creds.IamUsername == creds.AccountAliasOrId {
err = verify_user("", instance)
} else {
err = verify_user(creds.IamUsername, instance)
}
if err != nil {
return err
}
return nil
}
// Only delete the oldest key *if* the new key is valid; otherwise,
// delete the newest key
func (cred *Credential) deleteOneKey(username string) (err error) {
auth := aws.Auth{
AccessKey: cred.KeyId,
SecretKey: cred.SecretKey,
}
instance := iam.New(auth, aws.APSoutheast2)
allKeys, err := instance.AccessKeys(username)
if err != nil {
return err
}
// wtf?
if len(allKeys.AccessKeys) == 0 {
err = errors.New("Zero access keys found for this account -- cannot rotate")
return err
}
// only one key
if len(allKeys.AccessKeys) == 1 {
return nil
}
// Find out which key to delete.
var oldestId string
var oldest int64
for _, key := range allKeys.AccessKeys {
t, err := time.Parse("2006-01-02T15:04:05Z", key.CreateDate)
key_create_date := t.Unix()
if err != nil {
return err
}
// If we find an inactive one, just delete it
if key.Status == "Inactive" {
oldestId = key.Id
break
}
if oldest == 0 || key_create_date < oldest {
oldest = key_create_date
oldestId = key.Id
}
}
if oldestId == "" {
err = errors.New("Cannot find oldest key for this account, will not rotate")
return err
}
_, err = instance.DeleteAccessKey(oldestId, username)
if err != nil {
return err
}
return nil
}
func (cred *Credential) createNewAccessKey(username string) (err error) {
auth := aws.Auth{
AccessKey: cred.KeyId,
SecretKey: cred.SecretKey,
}
instance := iam.New(auth, aws.APSoutheast2)
resp, err := instance.CreateAccessKey(username)
if err != nil {
return err
}
cred.KeyId = resp.AccessKey.Id
cred.SecretKey = resp.AccessKey.Secret
return nil
}
// Potential conditions to handle here:
// * AWS has one key
// * only generate a new key, do not delete the old one
// * AWS has two keys
// * both are active and valid
// * new one is inactive
// * old one is inactive
// * We successfully delete the oldest key, but fail in creating the new key (eg network, permission issues)
func (cred *Credential) rotateCredentials(username string) (err error) {
err = cred.deleteOneKey(username)
if err != nil {
return err
}
err = cred.createNewAccessKey(username)
if err != nil {
return err
}
// Loop until the credentials are active
count := 0
for _, _, err = getAWSUsernameAndAlias(*cred); err != nil && count < ROTATE_TIMEOUT; _, _, err = getAWSUsernameAndAlias(*cred) {
time.Sleep(1 * time.Second)
count += 1
}
if err != nil {
err = errors.New("Timed out waiting for new credentials to become active")
return err
}
return nil
}
func SaveCredentials(data SaveData) (err error) {
var key_create_date int64
if data.force {
key_create_date = time.Now().Unix()
} else {
auth := aws.Auth{AccessKey: data.cred.KeyId, SecretKey: data.cred.SecretKey}
instance := iam.New(auth, aws.APSoutheast2)
if data.username == "" {
data.username, err = getAWSUsername(instance)
if err != nil {
return err
}
}
if data.alias == "" {
data.alias, err = getAWSAccountAlias(instance)
if err != nil {
return err
}
}
date, _ := getKeyCreateDate(instance)
t, err := time.Parse("2006-01-02T15:04:05Z", date)
key_create_date = t.Unix()
if err != nil {
return err
}
}
fmt.Printf("saving credentials for %s@%s\n", data.username, data.alias)
plaintext, err := json.Marshal(data.cred)
if err != nil {
return err
}
enc_slice := []Encryption{}
for _, pubkey := range data.pubkeys {
encoded, err := CredulousEncode(string(plaintext), pubkey)
if err != nil {
return err
}
enc_slice = append(enc_slice, Encryption{
Ciphertext: encoded,
Fingerprint: SSHFingerprint(pubkey),
})
}
creds := Credentials{
Version: FORMAT_VERSION,
AccountAliasOrId: data.alias,
IamUsername: data.username,
CreateTime: fmt.Sprintf("%d", key_create_date),
Encryptions: enc_slice,
LifeTime: data.lifetime,
}
filename := fmt.Sprintf("%v-%v.json", key_create_date, data.cred.KeyId[12:])
err = creds.WriteToDisk(data.repo, filename)
return err
}
type FileLister interface {
Readdir(int) ([]os.FileInfo, error)
Name() string
}
func getDirs(fl FileLister) ([]os.FileInfo, error) {
dirents, err := fl.Readdir(0) // get all the entries
if err != nil {
return nil, err
}
dirs := []os.FileInfo{}
for _, dirent := range dirents {
if dirent.IsDir() {
dirs = append(dirs, dirent)
}
}
return dirs, nil
}
func findDefaultDir(fl FileLister) (string, error) {
dirs, err := getDirs(fl)
if err != nil {
return "", err
}
switch {
case len(dirs) == 0:
return "", errors.New("No saved credentials found; please run 'credulous save' first")
case len(dirs) > 1:
return "", errors.New("More than one account found; please specify account and user")
}
return dirs[0].Name(), nil
}
func (cred Credentials) ValidateCredentials(alias string, username string) error {
if cred.IamUsername != username {
err := errors.New("FATAL: username in credential does not match requested username")
return err
}
if cred.AccountAliasOrId != alias {
err := errors.New("FATAL: account alias in credential does not match requested alias")
return err
}
err := cred.verifyUserAndAccount()
if err != nil {
return err
}
return nil
}
func RetrieveCredentials(rootPath string, alias string, username string, keyfile string) (Credentials, error) {
rootDir, err := os.Open(rootPath)
if err != nil {
panic_the_err(err)
}
if alias == "" {
if alias, err = findDefaultDir(rootDir); err != nil {
panic_the_err(err)
}
}
if username == "" {
aliasDir, err := os.Open(filepath.Join(rootPath, alias))
if err != nil {
panic_the_err(err)
}
username, err = findDefaultDir(aliasDir)
if err != nil {
panic_the_err(err)
}
}
fullPath := filepath.Join(rootPath, alias, username)
latest, err := latestFileInDir(fullPath)
if err != nil {
return Credentials{}, err
}
filePath := filepath.Join(fullPath, latest.Name())
cred, err := readCredentialFile(filePath, keyfile)
if err != nil {
return Credentials{}, err
}
return *cred, nil
}
func latestFileInDir(dir string) (os.FileInfo, error) {
entries, err := ioutil.ReadDir(dir)
panic_the_err(err)
if len(entries) == 0 {
return nil, errors.New("No credentials have been saved for that user and account; please run 'credulous save' first")
}
return entries[len(entries)-1], nil
}
func listAvailableCredentials(rootDir FileLister) ([]string, error) {
creds := make(map[string]int)
repo_dirs, err := getDirs(rootDir) // get just the directories
if err != nil {
return []string{}, err
}
if len(repo_dirs) == 0 {
return []string{}, errors.New("No saved credentials found; please run 'credulous save' first")
}
for _, repo_dirent := range repo_dirs {
repo_path := filepath.Join(rootDir.Name(), repo_dirent.Name())
repo_dir, err := os.Open(repo_path)
if err != nil {
return []string{}, err
}
alias_dirs, err := getDirs(repo_dir)
if err != nil {
return []string{}, err
}
for _, alias_dirent := range alias_dirs {
if alias_dirent.Name() == ".git" {
continue
}
alias_path := filepath.Join(repo_path, alias_dirent.Name())
alias_dir, err := os.Open(alias_path)
if err != nil {
return []string{}, err
}
user_dirs, err := getDirs(alias_dir)
if err != nil {
return []string{}, err
}
for _, user_dirent := range user_dirs {
user_path := filepath.Join(alias_path, user_dirent.Name())
latest, err := latestFileInDir(user_path)
if err != nil {
return []string{}, err
}
if latest.Name() != "" {
creds[user_dirent.Name()+"@"+alias_dirent.Name()] += 1
}
}
}
}
names := make([]string, len(creds))
i := 0
for k, _ := range creds {
names[i] = k
i++
}
sort.Strings(names)
return names, nil
}