/
login.go
153 lines (138 loc) · 3.88 KB
/
login.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
package action
import (
"bufio"
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/go-ini/ini"
"github.com/spf13/viper"
"log"
"os"
"strings"
"time"
)
type CredUpdater struct {
sourceProfile string
destinationProfile string
iamClient *iam.Client
stsClient *sts.Client
}
func UpdateSessionCredentials() {
updater := &CredUpdater{
sourceProfile: viper.GetString("source"),
destinationProfile: viper.GetString("destination"),
}
updater.init()
username := updater.getUsername()
serial := updater.getMfaSerial(username)
code := updater.readCode()
token := updater.getSessionToken(serial, code)
updater.updateAwsConfig(token)
}
func (updater *CredUpdater) init() {
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithSharedConfigProfile(updater.sourceProfile),
config.WithRegion("eu-central-1"),
)
if err != nil {
log.Fatal(err)
}
updater.iamClient = iam.NewFromConfig(cfg)
updater.stsClient = sts.NewFromConfig(cfg)
}
func (updater *CredUpdater) getUsername() string {
callerOutput, err := updater.stsClient.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{})
if err != nil {
log.Fatal(err)
}
username, err := ParseUsername(callerOutput)
if err != nil {
log.Fatalf(err.Error())
}
return username
}
func (updater *CredUpdater) getMfaSerial(username string) string {
var mfaId string
deviceInput := &iam.ListMFADevicesInput{UserName: aws.String(username)}
devices, err := updater.iamClient.ListMFADevices(context.TODO(), deviceInput)
if err != nil {
log.Fatal(err)
}
if len(devices.MFADevices) == 0 {
log.Fatal("user has no MFA Device activated")
} else {
mfaId = *devices.MFADevices[0].SerialNumber
fmt.Printf("detected MFA device with serial number %s\n", mfaId)
}
return mfaId
}
func (updater *CredUpdater) readCode() string {
fmt.Print("enter 6-digit MFA code: ")
userInput := bufio.NewReader(os.Stdin)
in, _, err := userInput.ReadLine()
if err != nil {
log.Fatal(err)
}
return string(in)
}
func (updater *CredUpdater) getSessionToken(serial string, code string) *sts.GetSessionTokenOutput {
tokenInput := &sts.GetSessionTokenInput{
DurationSeconds: nil,
SerialNumber: &serial,
TokenCode: &code,
}
token, err := updater.stsClient.GetSessionToken(context.TODO(), tokenInput)
if err != nil {
log.Fatal(err)
}
return token
}
func (updater *CredUpdater) updateAwsConfig(token *sts.GetSessionTokenOutput) {
home, err := os.UserHomeDir()
awsFilePath := fmt.Sprintf("%s/.aws/credentials", home)
if err != nil {
log.Fatal(err)
}
awsFile, err := ini.Load(awsFilePath)
if err != nil {
log.Fatal(err)
}
section, err := awsFile.NewSection(viper.GetString("destination"))
if err != nil {
log.Fatal(err)
}
_, _ = section.NewKey("aws_access_key_id", *token.Credentials.AccessKeyId)
_, _ = section.NewKey("aws_secret_access_key", *token.Credentials.SecretAccessKey)
_, _ = section.NewKey("aws_session_token", *token.Credentials.SessionToken)
err = awsFile.SaveTo(awsFilePath)
if err != nil {
log.Fatal(err)
}
expires := int(token.Credentials.Expiration.Sub(time.Now()).Hours())
fmt.Printf(`
Successfully updated access tokens for profile %s.
Access will be valid for %d hours. You can now use that profile.
export AWS_PROFILE=%s
`,
viper.GetString("destination"),
expires,
viper.GetString("destination"),
)
}
func ParseUsername(input *sts.GetCallerIdentityOutput) (string, error) {
var arn string
arn = *input.Arn
if !strings.Contains(arn, "/") {
return "", &ArnParseException{"arn does not have expected format arn:aws:iam::123456:user/someuser"}
}
arr := strings.Split(arn, "/")
if len(arr) == 0 || arr[1] == "" {
msg := fmt.Sprintf("Could not detect user name from %v", input)
return "", &ArnParseException{msg}
}
return arr[1], nil
}