This repository has been archived by the owner on Apr 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
332 lines (279 loc) · 7.98 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
package main
import "fmt"
import "time"
import "errors"
import "net/http"
import "github.com/jessevdk/go-flags"
import "github.com/tj/go-debug"
import "github.com/peterh/liner"
import "github.com/aws/aws-sdk-go/aws/credentials"
import "github.com/havoc-io/go-keytar"
const VERSION = "0.8.0"
const SESSION_COOKIE = "__oktad_session_cookie"
const CREDENTIALS_USERNAME = "__oktad_username"
const CREDENTIALS_PASSWORD = "__oktad_password"
func main() {
var opts struct {
ConfigFile string `short:"c" long:"config" description:"Path to config file"`
PrintVersion bool `short:"v" long:"version" description:"Print version number and exit"`
ForceNewCredentials bool `short:"f" long:"force-new" description:"force new credentials"`
}
debug := debug.Debug("oktad:main")
args, err := flags.Parse(&opts)
if err != nil {
return
}
if opts.PrintVersion {
fmt.Printf("oktad v%s\n", VERSION)
return
}
debug("loading configuration data")
// try to load configuration
oktaCfg, err := parseConfig(opts.ConfigFile)
if err != nil {
fmt.Println("Error reading config file!")
debug("cfg read err: %s", err)
return
}
if len(args) <= 0 {
fmt.Println("Hey, that command won't actually do anything.\n\nSorry.")
return
}
awsProfile := args[0]
acfg, err := readAwsProfile(
fmt.Sprintf("profile %s", awsProfile),
)
var skipSecondRole bool
if err != nil {
//fmt.Println("Error reading your AWS profile!")
debug("error reading AWS profile: %s", err)
if err == awsProfileNotFound {
// if the AWS profile isn't found, we'll assume that
// the user intends to run a command in the first account
// behind their okta auth, rather than assuming role twice
skipSecondRole = true
fmt.Printf(
"We couldn't find an AWS profile named %s,\nso we will AssumeRole into your base account.\n",
awsProfile,
)
awsProfile = BASE_PROFILE_CREDS
args = append([]string{BASE_PROFILE_CREDS}, args...)
}
}
if !opts.ForceNewCredentials {
maybeCreds, err := loadCreds(awsProfile)
if err == nil {
debug("found cached credentials, going to use them")
// if we could load creds, use them!
err := prepAndLaunch(args, maybeCreds)
if err != nil {
fmt.Println("Error launching program: ", err)
}
return
}
debug("cred load err %s", err)
}
keystore, err := keytar.GetKeychain()
if err != nil {
fmt.Println("Failed to get keychain access")
debug("error was %s", err)
return
}
var sessionToken string
var saml *OktaSamlResponse
password, err := keystore.GetPassword(APPNAME, SESSION_COOKIE)
if err != nil || password == "" {
sessionToken, err = getSessionFromLogin(&oktaCfg)
if err != nil {
return
}
saml, err = getSaml(&oktaCfg, sessionToken)
if err != nil {
fmt.Println("Error parsing SAML response")
debug("error was %s", err)
return
}
}
if saml == nil || saml.raw == "" {
// We got a saved session
cookie := http.Cookie{}
err = decodePasswordStruct(&cookie, password)
if err != nil {
debug("failed to read session cookie %s", err)
}
saml, err = getSamlSession(&oktaCfg, &cookie)
if err != nil {
debug("failed to get session from existing cookie %s", err)
}
}
if saml == nil || saml.raw == "" {
// final fallback
sessionToken, err = getSessionFromLogin(&oktaCfg)
if err != nil {
fmt.Println("Fatal error getting login session")
debug("error was %s", err)
return
}
saml, err = getSaml(&oktaCfg, sessionToken)
if err != nil {
fmt.Println("Fatal error getting saml")
debug("error was %s", err)
return
}
}
mainCreds, mExp, err := assumeFirstRole(acfg, saml)
if err != nil {
fmt.Println("Error assuming first role!")
debug("error was %s", err)
return
}
var finalCreds *credentials.Credentials
var fExp time.Time
if !skipSecondRole {
finalCreds, fExp, err = assumeDestinationRole(acfg, mainCreds)
if err != nil {
fmt.Println("Error assuming second role!")
debug("error was %s", err)
return
}
} else {
finalCreds = mainCreds
fExp = mExp
}
// all was good, so let's save credentials...
err = storeCreds(awsProfile, finalCreds, fExp)
if err != nil {
debug("err storing credentials, %s", err)
}
debug("Everything looks good; launching your program...")
err = prepAndLaunch(args, finalCreds)
if err != nil {
fmt.Println("Error launching program: ", err)
}
}
func getSessionFromLogin(oktaCfg *OktaConfig) (string, error) {
debug := debug.Debug("oktad:getSessionFromLogin")
var user, pass string
keystore, err := keytar.GetKeychain()
if err != nil {
debug("error was %s", err)
return "", errors.New("failed to get keychain access")
}
user, err = keystore.GetPassword(APPNAME, CREDENTIALS_USERNAME)
if err != nil {
debug("error getting username from keychain: %s", err)
}
pass, err = keystore.GetPassword(APPNAME, CREDENTIALS_PASSWORD)
if err != nil {
debug("error getting password from keychain: %s", err)
}
if user != "" && pass != "" {
debug("stored okta credentials found, attempting to use them")
sessionToken, err := tryLogin(oktaCfg, user, pass)
if err == nil {
return sessionToken, err
}
debug("error authenticating with stored credentials: %s", err)
user = ""
pass = ""
// give the user the chance to log in by typing in username/password
} else {
debug("stored okta credentials not found; will prompt for them")
}
err = keystore.DeletePassword(APPNAME, CREDENTIALS_USERNAME)
if err != nil {
debug("error deleting %s: %s", CREDENTIALS_USERNAME, err)
}
err = keystore.DeletePassword(APPNAME, CREDENTIALS_PASSWORD)
if err != nil {
debug("error deleting %s: %s", CREDENTIALS_PASSWORD, err)
}
user, pass, err = readUserPass()
if err != nil {
// if we got an error here, the user bailed on us
debug("control-c caught in liner, probably")
return "", errors.New("control-c")
}
if user == "" || pass == "" {
return "", errors.New("Must supply a username and password")
}
sessionToken, err := tryLogin(oktaCfg, user, pass)
if err == nil && sessionToken != "" {
keystore.AddPassword(APPNAME, CREDENTIALS_USERNAME, user)
if err != nil {
debug("err storing username: %s", err)
}
keystore.AddPassword(APPNAME, CREDENTIALS_PASSWORD, pass)
if err != nil {
debug("err storing password: %s", err)
}
}
return sessionToken, err
}
func tryLogin(oktaCfg *OktaConfig, user string, pass string) (string, error) {
debug := debug.Debug("oktad:tryLogin")
ores, err := login(oktaCfg, user, pass)
if err != nil {
fmt.Println("Error authenticating with Okta! Maybe your username or password are wrong.")
debug("login err %s", err)
return "", err
}
if ores.Status == "SUCCESS" {
return ores.SessionToken, nil
}
if ores.Status != "MFA_REQUIRED" {
return "", errors.New("MFA required to use this tool")
}
factor, err := extractTokenFactor(ores)
if err != nil {
fmt.Println("Error processing okta response!")
debug("err from extractTokenFactor was %s", err)
return "", err
}
tries := 0
var sessionToken string
TRYMFA:
mfaToken, err := readMfaToken()
if err != nil {
debug("control-c caught in liner, probably")
return "", err
}
if tries < 2 {
sessionToken, err = doMfa(ores, factor, mfaToken)
if err != nil {
tries++
fmt.Println("Invalid MFA code, please try again.")
goto TRYMFA // eat that, Djikstra!
}
} else {
fmt.Println("Error performing MFA auth!")
debug("error from doMfa was %s", err)
return "", err
}
return sessionToken, nil
}
// reads the username and password from the command line
// returns user, then pass, then an error
func readUserPass() (user string, pass string, err error) {
li := liner.NewLiner()
// remember to close or weird stuff happens
defer li.Close()
li.SetCtrlCAborts(true)
user, err = li.Prompt("Username: ")
if err != nil {
return
}
pass, err = li.PasswordPrompt("Password: ")
if err != nil {
return
}
return
}
// reads and returns an mfa token
func readMfaToken() (string, error) {
li := liner.NewLiner()
defer li.Close()
li.SetCtrlCAborts(true)
fmt.Println("Your account requires MFA; please enter a token.")
return li.Prompt("MFA token: ")
}