-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmfa.go
100 lines (66 loc) · 1.75 KB
/
mfa.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
package main
import (
"bufio"
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/go-ini/ini"
"log"
"os"
"os/user"
)
func fatalErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
srcF := flag.String("s", "default", "Source (primary) profile")
dstF := flag.String("d", "", "MFA-enabled profile")
flag.Parse()
if *srcF == "" || *dstF == "" {
flag.Usage()
os.Exit(1)
}
conf := &aws.Config{
Credentials: credentials.NewSharedCredentials("", *srcF),
}
sess, err := session.NewSession(conf)
fatalErr(err)
_iam := iam.New(sess)
devices, err := _iam.ListMFADevices(&iam.ListMFADevicesInput{})
fatalErr(err)
if len(devices.MFADevices) == 0 {
log.Fatal("No MFA devices configured")
}
sn := devices.MFADevices[0].SerialNumber
fmt.Printf("Using device %1s\n", *sn)
_sts := sts.New(sess)
fmt.Printf("Enter MFA code: ")
r := bufio.NewReader(os.Stdin)
code, _, err := r.ReadLine()
fatalErr(err)
codeStr := string(code)
res, err := _sts.GetSessionToken(&sts.GetSessionTokenInput{
TokenCode: &codeStr,
SerialNumber: sn,
})
fatalErr(err)
usr, err := user.Current()
fatalErr(err)
filePath := usr.HomeDir + "/.aws/credentials"
credFile, err := ini.Load(filePath)
fatalErr(err)
sect, err := credFile.NewSection(*dstF)
fatalErr(err)
sect.NewKey("aws_access_key_id", *res.Credentials.AccessKeyId)
sect.NewKey("aws_secret_access_key", *res.Credentials.SecretAccessKey)
sect.NewKey("aws_session_token", *res.Credentials.SessionToken)
credFile.SaveTo(filePath)
fatalErr(err)
fmt.Printf("Access token updated for %1s\n", *dstF)
}