This repository has been archived by the owner on Mar 5, 2021. It is now read-only.
/
credulous.go
463 lines (424 loc) · 11.8 KB
/
credulous.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
package main
import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"code.google.com/p/go.crypto/ssh"
"code.google.com/p/gopass"
"github.com/codegangsta/cli"
)
const ENV_PATTERN string = "^[A-Za-z_][A-Za-z0-9_]*=.*"
func decryptPEM(pemblock *pem.Block, filename string) ([]byte, error) {
var err error
if _, err = fmt.Fprintf(os.Stderr, "Enter passphrase for %s: ", filename); err != nil {
return []byte(""), err
}
// we already emit the prompt to stderr; GetPass only emits to stdout
var passwd string
passwd, err = gopass.GetPass("")
fmt.Fprintln(os.Stderr, "")
if err != nil {
return []byte(""), err
}
var decryptedBytes []byte
if decryptedBytes, err = x509.DecryptPEMBlock(pemblock, []byte(passwd)); err != nil {
return []byte(""), err
}
pemBytes := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: decryptedBytes,
}
decryptedPEM := pem.EncodeToMemory(&pemBytes)
return decryptedPEM, nil
}
func getPrivateKey(c *cli.Context) (filename string) {
if c.String("key") == "" {
filename = filepath.Join(os.Getenv("HOME"), "/.ssh/id_rsa")
} else {
filename = c.String("key")
}
return filename
}
func splitUserAndAccount(arg string) (string, string, error) {
atpos := strings.LastIndex(arg, "@")
if atpos < 1 {
err := errors.New("Invalid account format; please specify <username>@<account>")
return "", "", err
}
// pull off everything before the last '@'
return arg[atpos+1:], arg[0:atpos], nil
}
func getAccountAndUserName(c *cli.Context) (string, string, error) {
if len(c.Args()) > 0 {
user, acct, err := splitUserAndAccount(c.Args()[0])
if err != nil {
return "", "", err
}
return user, acct, nil
}
if c.String("credentials") != "" {
user, acct, err := splitUserAndAccount(c.String("credentials"))
if err != nil {
return "", "", err
}
return user, acct, nil
} else {
return c.String("account"), c.String("username"), nil
}
}
func parseUserAndAccount(c *cli.Context) (username string, account string, err error) {
if (c.String("username") == "" || c.String("account") == "") && c.Bool("force") {
err = errors.New("Must specify both username and account with force")
return "", "", err
}
// if username OR account were specified, but not both, complain
if (c.String("username") != "" && c.String("account") == "") ||
(c.String("username") == "" && c.String("account") != "") {
if c.Bool("force") {
err = errors.New("Must specify both username and account for force save")
} else {
err = errors.New("Must use force save when specifying username or account")
}
return "", "", err
}
// if username/account were specified, but force wasn't set, complain
if c.String("username") != "" && c.String("account") != "" {
if !c.Bool("force") {
err = errors.New("Cannot specify username and/or account without force")
return "", "", err
} else {
log.Print("WARNING: saving credentials without verifying username or account alias")
username = c.String("username")
account = c.String("account")
}
}
return username, account, nil
}
func parseEnvironmentArgs(c *cli.Context) (map[string]string, error) {
if len(c.StringSlice("env")) == 0 {
return nil, nil
}
envMap := make(map[string]string)
for _, arg := range c.StringSlice("env") {
match, err := regexp.Match(ENV_PATTERN, []byte(arg))
if err != nil {
return nil, err
}
if !match {
log.Print("WARNING: Skipping env argument " + arg + " -- not in NAME=value format")
continue
}
parts := strings.SplitN(arg, "=", 2)
envMap[parts[0]] = parts[1]
}
return envMap, nil
}
func readSSHPubkeyFile(filename string) (pubkey ssh.PublicKey, err error) {
pubkeyString, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
pubkey, _, _, _, err = ssh.ParseAuthorizedKey([]byte(pubkeyString))
if err != nil {
return nil, err
}
return pubkey, nil
}
func parseKeyArgs(c *cli.Context) (pubkeys []ssh.PublicKey, err error) {
// no args, so just use the default
if len(c.StringSlice("key")) == 0 {
pubkey, err := readSSHPubkeyFile(filepath.Join(os.Getenv("HOME"), "/.ssh/id_rsa.pub"))
if err != nil {
return nil, err
}
pubkeys = append(pubkeys, pubkey)
return pubkeys, nil
}
for _, arg := range c.StringSlice("key") {
pubkey, err := readSSHPubkeyFile(arg)
if err != nil {
return nil, err
}
pubkeys = append(pubkeys, pubkey)
}
return pubkeys, nil
}
// parseLifetimeArgs attempts to be a little clever in determining what credential
// lifetime you've chosen. It returns a number of hours and an error. It assumes that
// the argument was passed in as hours.
func parseLifetimeArgs(c *cli.Context) (lifetime int, err error) {
// the default is zero, which is our default
if c.Int("lifetime") < 0 {
return 0, nil
}
return c.Int("lifetime"), nil
}
func parseRepoArgs(c *cli.Context) (repo string, err error) {
// the default is 'local' which is set below, so not much to do here
if c.String("repo") == "local" {
repo = path.Join(getRootPath(), "local")
} else {
repo = c.String("repo")
}
return repo, nil
}
func parseSaveArgs(c *cli.Context) (cred Credential, username, account string, pubkeys []ssh.PublicKey, lifetime int, repo string, err error) {
pubkeys, err = parseKeyArgs(c)
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
username, account, err = parseUserAndAccount(c)
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
envmap, err := parseEnvironmentArgs(c)
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
lifetime, err = parseLifetimeArgs(c)
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
repo, err = parseRepoArgs(c)
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
AWSAccessKeyId := os.Getenv("AWS_ACCESS_KEY_ID")
AWSSecretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
if AWSAccessKeyId == "" || AWSSecretAccessKey == "" {
err := errors.New("Can't save, no credentials in the environment")
if err != nil {
return Credential{}, "", "", nil, 0, "", err
}
}
cred = Credential{
KeyId: AWSAccessKeyId,
SecretKey: AWSSecretAccessKey,
EnvVars: envmap,
}
return cred, username, account, pubkeys, lifetime, repo, nil
}
func main() {
app := cli.NewApp()
app.Name = "credulous"
app.Usage = "Secure AWS Credential Management"
app.Version = "0.2.2"
app.Commands = []cli.Command{
{
Name: "save",
Usage: "Save AWS credentials",
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: "key, k",
Value: &cli.StringSlice{},
Usage: "\n SSH public keys for encryption",
},
cli.StringSliceFlag{
Name: "env, e",
Value: &cli.StringSlice{},
Usage: "\n Environment variables to set in the form VAR=value",
},
cli.IntFlag{
Name: "lifetime, l",
Value: 0,
Usage: "\n Credential lifetime in seconds (0 means forever)",
},
cli.BoolFlag{
Name: "force, f",
Usage: "\n Force saving without validating username or account." +
"\n You MUST specify -u username -a account",
},
cli.StringFlag{
Name: "username, u",
Value: "",
Usage: "\n Username (for use with '--force')",
},
cli.StringFlag{
Name: "account, a",
Value: "",
Usage: "\n Account alias (for use with '--force')",
},
cli.StringFlag{
Name: "repo, r",
Value: "local",
Usage: "\n Repository location ('local' by default)",
},
},
Action: func(c *cli.Context) {
cred, username, account, pubkeys, lifetime, repo, err := parseSaveArgs(c)
panic_the_err(err)
err = SaveCredentials(SaveData{
cred: cred,
username: username,
alias: account,
pubkeys: pubkeys,
lifetime: lifetime,
force: c.Bool("force"),
repo: repo,
})
panic_the_err(err)
},
},
{
Name: "source",
Usage: "Source AWS credentials",
Flags: []cli.Flag{
cli.StringFlag{
Name: "account, a",
Value: "",
Usage: "\n AWS Account alias or id",
},
cli.StringFlag{
Name: "key, k",
Value: "",
Usage: "\n SSH private key",
},
cli.StringFlag{
Name: "username, u",
Value: "",
Usage: "\n IAM User",
},
cli.StringFlag{
Name: "credentials, c",
Value: "",
Usage: "\n Credentials, for example username@account",
},
cli.BoolFlag{
Name: "force, f",
Usage: "\n Force sourcing of credentials without validating username or account",
},
cli.StringFlag{
Name: "repo, r",
Value: "local",
Usage: "\n Repository location ('local' by default)",
},
},
Action: func(c *cli.Context) {
keyfile := getPrivateKey(c)
account, username, err := getAccountAndUserName(c)
if err != nil {
panic_the_err(err)
}
repo, err := parseRepoArgs(c)
if err != nil {
panic_the_err(err)
}
creds, err := RetrieveCredentials(repo, account, username, keyfile)
if err != nil {
panic_the_err(err)
}
if !c.Bool("force") {
err = creds.ValidateCredentials(account, username)
if err != nil {
panic_the_err(err)
}
}
creds.Display(os.Stdout)
},
},
{
Name: "current",
Usage: "Show the username and alias of the currently-loaded credentials",
Action: func(c *cli.Context) {
AWSAccessKeyId := os.Getenv("AWS_ACCESS_KEY_ID")
AWSSecretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
if AWSAccessKeyId == "" || AWSSecretAccessKey == "" {
err := errors.New("No amazon credentials are currently in your environment")
panic_the_err(err)
}
cred := Credential{
KeyId: AWSAccessKeyId,
SecretKey: AWSSecretAccessKey,
}
username, alias, err := getAWSUsernameAndAlias(cred)
if err != nil {
panic_the_err(err)
}
fmt.Printf("%s@%s\n", username, alias)
},
},
{
Name: "display",
Usage: "Display loaded AWS credentials",
Action: func(c *cli.Context) {
AWSAccessKeyId := os.Getenv("AWS_ACCESS_KEY_ID")
AWSSecretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
fmt.Printf("AWS_ACCESS_KEY_ID: %s\n", AWSAccessKeyId)
fmt.Printf("AWS_SECRET_ACCESS_KEY: %s\n", AWSSecretAccessKey)
},
},
{
Name: "list",
Usage: "List available AWS credentials",
Action: func(c *cli.Context) {
rootDir, err := os.Open(getRootPath())
if err != nil {
panic_the_err(err)
}
set, err := listAvailableCredentials(rootDir)
if err != nil {
panic_the_err(err)
}
for _, cred := range set {
fmt.Println(cred)
}
},
},
{
Name: "rotate",
Usage: "Rotate current AWS credentials, deleting the oldest",
Flags: []cli.Flag{
cli.IntFlag{
Name: "lifetime, l",
Value: 0,
Usage: "\n New credential lifetime in seconds (0 means forever)",
},
cli.StringSliceFlag{
Name: "key, k",
Value: &cli.StringSlice{},
Usage: "\n SSH public keys for encryption",
},
cli.StringSliceFlag{
Name: "env, e",
Value: &cli.StringSlice{},
Usage: "\n Environment variables to set in the form VAR=value",
},
cli.StringFlag{
Name: "repo, r",
Value: "local",
Usage: "\n Repository location ('local' by default)",
},
},
Action: func(c *cli.Context) {
cred, _, _, pubkeys, lifetime, repo, err := parseSaveArgs(c)
panic_the_err(err)
username, account, err := getAWSUsernameAndAlias(cred)
panic_the_err(err)
err = (&cred).rotateCredentials(username)
panic_the_err(err)
err = SaveCredentials(SaveData{
cred: cred,
username: username,
alias: account,
pubkeys: pubkeys,
lifetime: lifetime,
force: c.Bool("force"),
repo: repo,
})
panic_the_err(err)
},
},
}
app.Run(os.Args)
}
func rotate(cred Credential) (err error) {
return nil
}