-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
419 lines (363 loc) · 13.7 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
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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/pkg/browser"
"github.com/jkueh/roo/cachedcredsprovider"
"github.com/jkueh/roo/config"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
)
var rooVersion string
var debug bool
var verbose bool
var configDir string
var configFile string
// cacheDir is separately configurable, as on some systems you want it to write to /tmp so that the keys are purged
// after the system is rebooted.
var cacheDir string
func main() {
var baseProfile string
var oneTimePasscode string
var showRoleList bool
var showVersionInfo bool
var targetRole string
var tokenNeedsRefresh bool
var writeToProfile bool
var targetProfile string
var openConsoleURL, showConsoleURL bool
flag.BoolVar(&debug, "debug", false, "Enables debug logging.")
flag.BoolVar(&showRoleList, "list", false, "Displays a list of configured roles, then exits.")
flag.BoolVar(&showVersionInfo, "version", false, "Show version information.")
flag.BoolVar(&tokenNeedsRefresh, "refresh", false, "Force a refresh of all tokens")
flag.BoolVar(&verbose, "verbose", false, "Enables verbose logging.")
flag.StringVar(&baseProfile, "profile", "", "The base AWS config profile to use when creating the session.")
flag.StringVar(&oneTimePasscode, "code", "", "MFA Token OTP - The 6+ digit code that refreshes every 30 seconds.")
flag.StringVar(&targetRole, "role", "", "The role name or alias to assume.")
flag.BoolVar(
&writeToProfile,
"write-profile",
false,
"If set, roo will write the credentials to an AWS profile using the AWS CLI.",
)
flag.StringVar(&targetProfile, "target-profile", "", "The name of the profile to write credentials for.")
flag.BoolVar(&openConsoleURL, "console", false, "Opens an AWS console session")
flag.BoolVar(&showConsoleURL, "console-url", false, "Prints the console URL to stdout")
flag.Parse()
config.Debug, config.Verbose = debug, verbose
if showVersionInfo {
if rooVersion == "" {
fmt.Println("unknown_version")
} else {
fmt.Println(rooVersion)
}
os.Exit(0)
}
// Some flag debugging
if debug {
log.Println("Command Line Parameters")
flag.VisitAll(func(f *flag.Flag) {
log.Println(f.Name+":", "\t", f.Value)
})
log.Println()
}
// Ensure we have a role definition for the role
conf := config.New(configFile)
if showRoleList {
conf.ListRoles()
os.Exit(0)
}
var role *config.RoleConfig
if targetRole == "" {
// See if we can pull a default
role = conf.GetDefaultRole()
if role == nil {
flag.Usage()
log.Fatalln("Role not provided (-role)")
}
} else {
role = conf.GetRole(targetRole)
}
if debug {
log.Println("role:", role)
}
if role.ARN == "" {
log.Fatalln("Unable to find role by name or alias:", targetRole)
}
// If a base profile wasn't specified on the command line, then try use a default - if configured.
if baseProfile == "" {
baseProfile = conf.DefaultProfile
}
// The cache file name we use is {{.AccountNumber}}-{{.RoleName}}.json
accountNumberRE := regexp.MustCompile("arn:aws:iam::([0-9]+)")
accountNumberMatch := accountNumberRE.FindStringSubmatch(role.ARN)
if len(accountNumberMatch) == 0 {
log.Fatalln("Unable to determine account number from ARN.")
}
accountNumber := accountNumberMatch[1]
roleNameRE := regexp.MustCompile(":role/(.*)")
roleNameMatch := roleNameRE.FindStringSubmatch(role.ARN)
if len(roleNameMatch) == 0 {
log.Fatalln("Unable to determine the role name from ARN.")
}
roleName := roleNameMatch[1]
if debug {
log.Println("Account Number:", accountNumber)
log.Println("Role Name: ", roleName)
}
cacheFileName := fmt.Sprintf("%s-%s.gob", accountNumber, roleName)
cacheFilePath := strings.Join([]string{cacheDir, cacheFileName}, string(os.PathSeparator))
// Define our credential providers
cachedProvider := cachedcredsprovider.New(cacheFilePath)
if debug {
currentCreds, _ := cachedProvider.Retrieve()
if currentCreds.AccessKeyID != "" {
log.Println("Current Access Key ID:", currentCreds.AccessKeyID)
}
}
if !tokenNeedsRefresh {
tokenNeedsRefresh = cachedProvider.IsExpired()
if debug && tokenNeedsRefresh {
log.Println("Refresh required - cachedProvider indicated credentials are expired.")
}
}
if tokenNeedsRefresh && oneTimePasscode == "" {
oneTimePasscodePrompts := 0
oneTimePasscodeValid := false
var oneTimePasscodeValidationError error
for oneTimePasscodePrompts < 3 && !oneTimePasscodeValid {
oneTimePasscodeInput := getStringInputFromUser("MFA Code")
// Ensure that trailing newline characters are removed (e.g. Windows will add \r at the end)
oneTimePasscode = strings.TrimRight(oneTimePasscodeInput, "\r\n")
if debug {
log.Println("MFA Code Provided:", oneTimePasscode)
}
oneTimePasscodeValid, oneTimePasscodeValidationError = oneTimePasscodeIsValid(oneTimePasscode)
if oneTimePasscodeValidationError != nil {
log.Println("Invalid MFA Code:", oneTimePasscodeValidationError)
}
oneTimePasscodePrompts++
}
if !oneTimePasscodeValid {
fmt.Println("Error: Please provide the MFA Token code (OTP) via the '-code' parameter.")
os.Exit(1)
}
}
// The static credentials we'll use to build the targetRole session
// At this point - Work out if we need to load the initial credentials for the authentication account, or if we can
// jump straight to exporting the existing tokens.
if tokenNeedsRefresh {
// Time to do the hard work - Get to the point where we can cache credentials to disk.
authAccountSessionOpts := session.Options{}
if baseProfile != "" {
authAccountSessionOpts.Profile = baseProfile
}
authAccountSession, err := session.NewSessionWithOptions(authAccountSessionOpts)
if err != nil {
log.Fatalln("Unable to create a session for the authentication account:", err)
}
stsClient := sts.New(authAccountSession)
callerIdentityOutput, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{})
if err != nil {
log.Fatalln("An error occurred while trying to get caller identity:", err)
}
if verbose {
log.Println("Hello world, I'm", *callerIdentityOutput.Arn, "- Time to assume another role!")
}
timeNow := time.Now()
timeNowUnixNanoString := strconv.FormatInt(timeNow.UnixNano(), 10)
assumeRoleInput := &sts.AssumeRoleInput{
SerialNumber: aws.String(conf.MFASerial),
TokenCode: aws.String(oneTimePasscode),
RoleArn: aws.String(role.ARN),
RoleSessionName: aws.String("roo-" + timeNowUnixNanoString),
}
assumeRoleOutput, err := stsClient.AssumeRole(assumeRoleInput)
if err != nil {
log.Fatalln("An error occurred while trying to assume the target role:", err)
}
if verbose {
log.Println("We have successfully assumed the role:", *assumeRoleOutput.AssumedRoleUser.Arn)
}
// Okay, time to build the cachedCredentials object.
err = cachedProvider.WriteNewCredentialsFromSTS(assumeRoleOutput.Credentials, cacheFilePath)
if err != nil {
log.Println("WARNING: An error occurred while trying to write new credentials to the cache file:", err)
} else {
if debug {
log.Println("New credentials written - New Access Key ID:", *assumeRoleOutput.Credentials.AccessKeyId)
}
}
} else {
if verbose {
log.Println("Using cached credentials!")
}
}
// Now we use the new cachedProvider to export our environment variables
retrievedCreds, err := cachedProvider.Retrieve()
if err != nil {
log.Fatalln("Unable to retrieve credentials:", err)
}
if debug {
log.Println("Retrieved credentials with Access Key ID", retrievedCreds.AccessKeyID)
}
os.Setenv("AWS_ACCESS_KEY_ID", retrievedCreds.AccessKeyID)
os.Setenv("AWS_SECRET_ACCESS_KEY", retrievedCreds.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", retrievedCreds.SessionToken)
if debug {
staticCredentials := credentials.NewStaticCredentialsFromCreds(retrievedCreds)
stsSession := session.Must(session.NewSessionWithOptions(session.Options{
Config: aws.Config{
Credentials: staticCredentials,
},
}))
stsClient := sts.New(stsSession)
callerIdentityOutput, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{})
if err != nil {
log.Fatalln(
"An error occurred while trying to get caller identity when working out who we have credentials for:",
err,
)
}
if verbose {
log.Println("Hello world, I'm", *callerIdentityOutput.Arn)
}
}
// There is an exception to evaluating commands - And that's if we've been asked to write these credentials to file.
if writeToProfile {
var targetProfileName string // We'll need to coalesce through some config , combined with flags.
if targetProfile == "" && role.TargetAWSProfile == "" {
log.Println("Please specify a target profile with -target-profile, or by specifying it in the config file.")
os.Exit(1)
}
if targetProfile != "" {
targetProfileName = targetProfile
} else {
targetProfileName = role.TargetAWSProfile
}
if verbose {
log.Println("We're going to write to profile! The profile's named", targetProfileName)
}
// Step 0 is to check that we have the AWS executable somewhere in the PATH.
cliPath, err := exec.LookPath("aws")
if err != nil {
log.Fatalln("Unable to find AWS CLI executable in PATH:", err)
}
if debug {
log.Println("Found it!", cliPath)
}
// Okay, time to execute the commands we need to execute.
baseCommand := []string{cliPath, "--profile", targetProfileName, "configure", "set"}
// Apologies for all the spread operators...
// Set: Access Key ID
err = executeCommand(append(baseCommand, []string{"aws_access_key_id", retrievedCreds.AccessKeyID}...)...)
if err != nil {
log.Println("An error occurred while trying to write the aws_access_key_id to file:", err)
}
// Set: Secret Access Key
err = executeCommand(append(baseCommand, []string{"aws_secret_access_key", retrievedCreds.SecretAccessKey}...)...)
if err != nil {
log.Println("An error occurred while trying to write the aws_secret_access_key to file:", err)
}
// Set: Session Token
err = executeCommand(append(baseCommand, []string{"aws_session_token", retrievedCreds.SessionToken}...)...)
if err != nil {
log.Println("An error occurred while trying to write the aws_access_key_id to file:", err)
}
// Set: Expiration Timestamp - Not used by the AWS CLI, but will allow the user to check.
err = executeCommand(append(baseCommand, []string{
"expiration_time", cachedProvider.GetCredentialExpiryTime().String()}...)...,
)
if err != nil {
log.Println("An error occurred while trying to write the aws_access_key_id to file:", err)
}
fmt.Println("Profile written:", targetProfileName)
} else if openConsoleURL || showConsoleURL { // We also skip command execution if
// Step one... Is to build the URL.
request, err := http.NewRequest(http.MethodGet, "https://signin.aws.amazon.com/federation", nil)
if err != nil {
log.Fatalln("Unable to construct request to federation endpoint:", err)
}
sessionData := map[string]string{
"sessionId": retrievedCreds.AccessKeyID,
"sessionKey": retrievedCreds.SecretAccessKey,
"sessionToken": retrievedCreds.SessionToken,
}
sessionDataJSON, err := json.Marshal(&sessionData)
if err != nil {
log.Fatalln("Unable to build session credentials for federation endpoint call:", err)
}
query := request.URL.Query()
query.Add("Action", "getSigninToken")
query.Add("SessionDuration", "43200")
query.Add("Session", string(sessionDataJSON))
request.URL.RawQuery = query.Encode()
resp, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatalln("An error occurred while retrieving data from federation endpoint:", err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln("An error occurred while trying to read the response body from the federation endpoint:", err)
}
var signInTokenResponse SigninTokenResponse
err = json.Unmarshal(respBody, &signInTokenResponse)
if err != nil {
log.Fatalln("Unable to unmarshal sign-in token response to JSON:", err)
}
consoleURLRequest, err := http.NewRequest(http.MethodGet, "https://signin.aws.amazon.com/federation", nil)
if err != nil {
log.Fatalln("Unable to construct console sign-in URL:", err)
}
consoleURLRequestQuery := consoleURLRequest.URL.Query()
consoleURLRequestQuery.Add("Action", "login")
consoleURLRequestQuery.Add("Issuer", "Example.org")
consoleURLRequestQuery.Add("Issuer", fmt.Sprintf("roo-%s", rooVersion))
consoleURLRequestQuery.Add("Destination", "https://console.aws.amazon.com/")
consoleURLRequestQuery.Add("SigninToken", signInTokenResponse.SigninToken)
consoleURLRequest.URL.RawQuery = consoleURLRequestQuery.Encode()
urlString := consoleURLRequest.URL.String()
if showConsoleURL { // If we're only asked to show it, print it and call it a day.
fmt.Println(urlString)
} else if openConsoleURL {
if debug {
log.Println("SigninToken:", signInTokenResponse.SigninToken)
}
err := browser.OpenURL(urlString)
if err != nil {
log.Fatalln("An error occurred while trying to get the system to open the console URL:", err)
}
} else {
log.Fatalln("Unhandled scenario: Not showConsoleURL or openConsoleURL")
}
} else {
if debug {
log.Println("flag.Args() length:", len(flag.Args()))
}
if len(flag.Args()) == 0 { // Let's make sure we have something to run here...
// println() for STDERR output
println("Please provide a command to execute, e.g.:")
println("roo -role my_role_name aws sts get-caller-identity")
os.Exit(100)
}
if debug {
log.Println("We're going to want to run the following command:", flag.Args())
}
err := executeCommand(flag.Args()...)
if err != nil {
log.Println("An error occurred while trying to execute command:", err)
}
}
}