forked from remind101/assume-role
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
257 lines (219 loc) · 6.86 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"syscall"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"gopkg.in/yaml.v2"
)
var (
configFilePath = fmt.Sprintf("%s/.aws/roles", os.Getenv("HOME"))
roleArnRe = regexp.MustCompile(`^arn:aws:iam::(.+):role/([^/]+)(/.+)?$`)
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s <role> [<command> <args...>]\n", os.Args[0])
flag.PrintDefaults()
}
func init() {
flag.Usage = usage
}
func defaultFormat() string {
var shell = os.Getenv("SHELL")
switch runtime.GOOS {
case "windows":
if os.Getenv("SHELL") == "" {
return "powershell"
}
fallthrough
default:
if strings.HasSuffix(shell, "fish") {
return "fish"
}
return "bash"
}
}
func main() {
var (
duration = flag.Duration("duration", time.Hour, "The duration that the credentials will be valid for.")
format = flag.String("format", defaultFormat(), "Format can be 'bash' or 'powershell'.")
)
flag.Parse()
argv := flag.Args()
if len(argv) < 1 {
flag.Usage()
os.Exit(1)
}
stscreds.DefaultDuration = *duration
role := argv[0]
args := argv[1:]
// Load credentials from configFilePath if it exists, else use regular AWS config
var creds *credentials.Value
var err error
if roleArnRe.MatchString(role) {
creds, err = assumeRole(role, "", *duration)
} else if _, err = os.Stat(configFilePath); err == nil {
fmt.Fprintf(os.Stderr, "WARNING: using deprecated role file (%s), switch to config file"+
" (https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html)\n",
configFilePath)
config, err := loadConfig()
must(err)
roleConfig, ok := config[role]
if !ok {
must(fmt.Errorf("%s not in %s", role, configFilePath))
}
creds, err = assumeRole(roleConfig.Role, roleConfig.MFA, *duration)
} else {
creds, err = assumeProfile(role)
}
must(err)
if len(args) == 0 {
switch *format {
case "powershell":
printPowerShellCredentials(role, creds)
case "bash":
printCredentials(role, creds)
case "fish":
printFishCredentials(role, creds)
default:
flag.Usage()
os.Exit(1)
}
return
}
err = execWithCredentials(role, args, creds)
must(err)
}
func execWithCredentials(role string, argv []string, creds *credentials.Value) error {
argv0, err := exec.LookPath(argv[0])
if err != nil {
return err
}
os.Setenv("AWS_ACCESS_KEY_ID", creds.AccessKeyID)
os.Setenv("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", creds.SessionToken)
os.Setenv("AWS_SECURITY_TOKEN", creds.SessionToken)
os.Setenv("ASSUMED_ROLE", role)
env := os.Environ()
return syscall.Exec(argv0, argv, env)
}
// printCredentials prints the credentials in a way that can easily be sourced
// with bash.
func printCredentials(role string, creds *credentials.Value) {
fmt.Printf("export AWS_ACCESS_KEY_ID=\"%s\"\n", creds.AccessKeyID)
fmt.Printf("export AWS_SECRET_ACCESS_KEY=\"%s\"\n", creds.SecretAccessKey)
fmt.Printf("export AWS_SESSION_TOKEN=\"%s\"\n", creds.SessionToken)
fmt.Printf("export AWS_SECURITY_TOKEN=\"%s\"\n", creds.SessionToken)
fmt.Printf("export ASSUMED_ROLE=\"%s\"\n", role)
fmt.Printf("# Run this to configure your shell:\n")
fmt.Printf("# eval $(%s)\n", strings.Join(os.Args, " "))
}
// printFishCredentials prints the credentials in a way that can easily be sourced
// with fish.
func printFishCredentials(role string, creds *credentials.Value) {
fmt.Printf("set -gx AWS_ACCESS_KEY_ID \"%s\";\n", creds.AccessKeyID)
fmt.Printf("set -gx AWS_SECRET_ACCESS_KEY \"%s\";\n", creds.SecretAccessKey)
fmt.Printf("set -gx AWS_SESSION_TOKEN \"%s\";\n", creds.SessionToken)
fmt.Printf("set -gx AWS_SECURITY_TOKEN \"%s\";\n", creds.SessionToken)
fmt.Printf("set -gx ASSUMED_ROLE \"%s\";\n", role)
fmt.Printf("# Run this to configure your shell:\n")
fmt.Printf("# eval (%s)\n", strings.Join(os.Args, " "))
}
// printPowerShellCredentials prints the credentials in a way that can easily be sourced
// with Windows powershell using Invoke-Expression.
func printPowerShellCredentials(role string, creds *credentials.Value) {
fmt.Printf("$env:AWS_ACCESS_KEY_ID=\"%s\"\n", creds.AccessKeyID)
fmt.Printf("$env:AWS_SECRET_ACCESS_KEY=\"%s\"\n", creds.SecretAccessKey)
fmt.Printf("$env:AWS_SESSION_TOKEN=\"%s\"\n", creds.SessionToken)
fmt.Printf("$env:AWS_SECURITY_TOKEN=\"%s\"\n", creds.SessionToken)
fmt.Printf("$env:ASSUMED_ROLE=\"%s\"\n", role)
fmt.Printf("# Run this to configure your shell:\n")
fmt.Printf("# %s | Invoke-Expression \n", strings.Join(os.Args, " "))
}
// assumeProfile assumes the named profile which must exist in ~/.aws/config
// (https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html) and returns the temporary STS
// credentials.
func assumeProfile(profile string) (*credentials.Value, error) {
sess := session.Must(session.NewSessionWithOptions(session.Options{
Profile: profile,
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: readTokenCode,
}))
creds, err := sess.Config.Credentials.Get()
if err != nil {
return nil, err
}
return &creds, nil
}
// assumeRole assumes the given role and returns the temporary STS credentials.
func assumeRole(role, mfa string, duration time.Duration) (*credentials.Value, error) {
sess := session.Must(session.NewSession())
svc := sts.New(sess)
params := &sts.AssumeRoleInput{
RoleArn: aws.String(role),
RoleSessionName: aws.String("cli"),
DurationSeconds: aws.Int64(int64(duration / time.Second)),
}
if mfa != "" {
params.SerialNumber = aws.String(mfa)
token, err := readTokenCode()
if err != nil {
return nil, err
}
params.TokenCode = aws.String(token)
}
resp, err := svc.AssumeRole(params)
if err != nil {
return nil, err
}
var creds credentials.Value
creds.AccessKeyID = *resp.Credentials.AccessKeyId
creds.SecretAccessKey = *resp.Credentials.SecretAccessKey
creds.SessionToken = *resp.Credentials.SessionToken
return &creds, nil
}
type roleConfig struct {
Role string `yaml:"role"`
MFA string `yaml:"mfa"`
}
type config map[string]roleConfig
// readTokenCode reads the MFA token from Stdin.
func readTokenCode() (string, error) {
r := bufio.NewReader(os.Stdin)
fmt.Fprintf(os.Stderr, "MFA code: ")
text, err := r.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(text), nil
}
// loadConfig loads the ~/.aws/roles file.
func loadConfig() (config, error) {
raw, err := ioutil.ReadFile(configFilePath)
if err != nil {
return nil, err
}
roleConfig := make(config)
return roleConfig, yaml.Unmarshal(raw, &roleConfig)
}
func must(err error) {
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
// Errors are already on Stderr.
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}