forked from Versent/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
okta.go
568 lines (443 loc) · 16.1 KB
/
okta.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package okta
import (
"bytes"
"fmt"
"html"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/versent/saml2aws/pkg/prompter"
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/versent/saml2aws/pkg/cfg"
"github.com/versent/saml2aws/pkg/creds"
"github.com/versent/saml2aws/pkg/provider"
"encoding/json"
)
const (
IdentifierDuoMfa = "DUO WEB"
IdentifierSmsMfa = "OKTA SMS"
IdentifierPushMfa = "OKTA PUSH"
IdentifierTotpMfa = "GOOGLE TOKEN:SOFTWARE:TOTP"
IdentifierOktaTotpMfa = "OKTA TOKEN:SOFTWARE:TOTP"
)
var logger = logrus.WithField("provider", "okta")
var (
supportedMfaOptions = map[string]string{
IdentifierDuoMfa: "DUO MFA authentication",
IdentifierSmsMfa: "SMS MFA authentication",
IdentifierPushMfa: "PUSH MFA authentication",
IdentifierTotpMfa: "TOTP MFA authentication",
IdentifierOktaTotpMfa: "Okta MFA authentication",
}
)
// Client is a wrapper representing a Okta SAML client
type Client struct {
client *provider.HTTPClient
mfa string
}
// AuthRequest represents an mfa okta request
type AuthRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
// VerifyRequest represents an mfa verify request
type VerifyRequest struct {
StateToken string `json:"stateToken"`
PassCode string `json:"passCode,omitempty"`
}
// New creates a new Okta client
func New(idpAccount *cfg.IDPAccount) (*Client, error) {
tr := provider.NewDefaultTransport(idpAccount.SkipVerify)
client, err := provider.NewHTTPClient(tr)
if err != nil {
return nil, errors.Wrap(err, "error building http client")
}
// assign a response validator to ensure all responses are either success or a redirect
// this is to avoid have explicit checks for every single response
client.CheckResponseStatus = provider.SuccessOrRedirectResponseValidator
return &Client{
client: client,
mfa: idpAccount.MFA,
}, nil
}
// Authenticate logs into Okta and returns a SAML response
func (oc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
var samlAssertion string
oktaURL, err := url.Parse(loginDetails.URL)
if err != nil {
return samlAssertion, errors.Wrap(err, "error building oktaURL")
}
oktaOrgHost := oktaURL.Host
//authenticate via okta api
authReq := AuthRequest{Username: loginDetails.Username, Password: loginDetails.Password}
authBody := new(bytes.Buffer)
err = json.NewEncoder(authBody).Encode(authReq)
if err != nil {
return samlAssertion, errors.Wrap(err, "error encoding authreq")
}
authSubmitURL := fmt.Sprintf("https://%s/api/v1/authn", oktaOrgHost)
req, err := http.NewRequest("POST", authSubmitURL, authBody)
if err != nil {
return samlAssertion, errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
res, err := oc.client.Do(req)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving auth response")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp := string(body)
authStatus := gjson.Get(resp, "status").String()
oktaSessionToken := gjson.Get(resp, "sessionToken").String()
// mfa required
if authStatus == "MFA_REQUIRED" {
oktaSessionToken, err = verifyMfa(oc, oktaOrgHost, loginDetails, resp)
if err != nil {
return samlAssertion, errors.Wrap(err, "error verifying MFA")
}
}
//now call saml endpoint
oktaSessionRedirectURL := fmt.Sprintf("https://%s/login/sessionCookieRedirect", oktaOrgHost)
req, err = http.NewRequest("GET", oktaSessionRedirectURL, nil)
if err != nil {
return samlAssertion, errors.Wrap(err, "error building authentication request")
}
q := req.URL.Query()
q.Add("checkAccountSetupComplete", "true")
q.Add("token", oktaSessionToken)
q.Add("redirectUrl", loginDetails.URL)
req.URL.RawQuery = q.Encode()
res, err = oc.client.Do(req)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
//try to extract SAMLResponse
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return samlAssertion, errors.Wrap(err, "error parsing document")
}
samlAssertion, ok := doc.Find("input[name=\"SAMLResponse\"]").Attr("value")
if !ok {
return samlAssertion, errors.Wrap(err, "unable to locate saml response")
}
logger.Debug("auth complete")
return samlAssertion, nil
}
func parseMfaIdentifer(json string, arrayPosition int) string {
mfaProvider := gjson.Get(json, fmt.Sprintf("_embedded.factors.%d.provider", arrayPosition)).String()
factorType := strings.ToUpper(gjson.Get(json, fmt.Sprintf("_embedded.factors.%d.factorType", arrayPosition)).String())
return fmt.Sprintf("%s %s", mfaProvider, factorType)
}
func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, resp string) (string, error) {
stateToken := gjson.Get(resp, "stateToken").String()
// choose an mfa option if there are multiple enabled
mfaOption := 0
var mfaOptions []string
for i := range gjson.Get(resp, "_embedded.factors").Array() {
identifier := parseMfaIdentifer(resp, i)
if val, ok := supportedMfaOptions[identifier]; ok {
mfaOptions = append(mfaOptions, val)
} else {
mfaOptions = append(mfaOptions, "UNSUPPORTED: "+identifier)
}
}
if oc.mfa != "AUTO" {
for _, val := range mfaOptions {
if strings.HasPrefix(val, oc.mfa) {
mfaOptions = []string{val}
break
}
}
}
if len(mfaOptions) > 1 {
mfaOption = prompter.Choose("Select which MFA option to use", mfaOptions)
}
factorID := gjson.Get(resp, fmt.Sprintf("_embedded.factors.%d.id", mfaOption)).String()
oktaVerify := gjson.Get(resp, fmt.Sprintf("_embedded.factors.%d._links.verify.href", mfaOption)).String()
mfaIdentifer := parseMfaIdentifer(resp, mfaOption)
logger.WithField("factorID", factorID).WithField("oktaVerify", oktaVerify).WithField("mfaIdentifer", mfaIdentifer).Debug("MFA")
if _, ok := supportedMfaOptions[mfaIdentifer]; !ok {
return "", errors.New("unsupported mfa provider")
}
// get signature & callback
verifyReq := VerifyRequest{StateToken: stateToken}
verifyBody := new(bytes.Buffer)
err := json.NewEncoder(verifyBody).Encode(verifyReq)
if err != nil {
return "", errors.Wrap(err, "error encoding verifyReq")
}
req, err := http.NewRequest("POST", oktaVerify, verifyBody)
if err != nil {
return "", errors.Wrap(err, "error building verify request")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
res, err := oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
switch mfa := mfaIdentifer; mfa {
case IdentifierSmsMfa, IdentifierTotpMfa, IdentifierOktaTotpMfa:
verifyCode := prompter.StringRequired("Enter verification code")
tokenReq := VerifyRequest{StateToken: stateToken, PassCode: verifyCode}
tokenBody := new(bytes.Buffer)
json.NewEncoder(tokenBody).Encode(tokenReq)
req, err = http.NewRequest("POST", oktaVerify, tokenBody)
if err != nil {
return "", errors.Wrap(err, "error building token post request")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
res, err := oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving token post response")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
return gjson.Get(resp, "sessionToken").String(), nil
case IdentifierPushMfa:
fmt.Printf("\nWaiting for approval, please check your Okta Verify app ...")
// loop until success, error, or timeout
for {
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
// on 'success' status
if gjson.Get(string(body), "status").String() == "SUCCESS" {
fmt.Printf(" Approved\n\n")
return gjson.Get(string(body), "sessionToken").String(), nil
}
// otherwise probably still waiting
switch gjson.Get(string(body), "factorResult").String() {
case "WAITING":
time.Sleep(1000)
fmt.Printf(".")
logger.Debug("Waiting for user to authorize login")
case "TIMEOUT":
fmt.Printf(" Timeout\n")
return "", errors.New("User did not accept MFA in time")
case "REJECTED":
fmt.Printf(" Rejected\n")
return "", errors.New("MFA rejected by user")
default:
fmt.Printf(" Error\n")
return "", errors.New("Unsupported response from Okta, please raise ticket with saml2aws")
}
}
case IdentifierDuoMfa:
duoHost := gjson.Get(resp, "_embedded.factor._embedded.verification.host").String()
duoSignature := gjson.Get(resp, "_embedded.factor._embedded.verification.signature").String()
duoSiguatres := strings.Split(duoSignature, ":")
//duoSignatures[0] = TX
//duoSignatures[1] = APP
duoCallback := gjson.Get(resp, "_embedded.factor._embedded.verification._links.complete.href").String()
// initiate duo mfa to get sid
duoSubmitURL := fmt.Sprintf("https://%s/frame/web/v1/auth", duoHost)
duoForm := url.Values{}
duoForm.Add("parent", fmt.Sprintf("https://%s/signin/verify/duo/web", oktaOrgHost))
duoForm.Add("java_version", "")
duoForm.Add("java_version", "")
duoForm.Add("flash_version", "")
duoForm.Add("screen_resolution_width", "3008")
duoForm.Add("screen_resolution_height", "1692")
duoForm.Add("color_depth", "24")
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
q := req.URL.Query()
q.Add("tx", duoSiguatres[0])
req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
//try to extract sid
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "error parsing document")
}
duoSID, ok := doc.Find("input[name=\"sid\"]").Attr("value")
if !ok {
return "", errors.Wrap(err, "unable to locate saml response")
}
duoSID = html.UnescapeString(duoSID)
//prompt for mfa type
//only supporting push or passcode for now
var token string
var duoMfaOptions = []string{
"Duo Push",
"Passcode",
}
duoMfaOption := 0
if loginDetails.DuoMFAOption == "Duo Push" {
duoMfaOption = 0
} else if loginDetails.DuoMFAOption == "Passcode" {
duoMfaOption = 1
} else {
duoMfaOption = prompter.Choose("Select a DUO MFA Option", duoMfaOptions)
}
if duoMfaOptions[duoMfaOption] == "Passcode" {
//get users DUO MFA Token
token = prompter.StringRequired("Enter passcode")
}
// send mfa auth request
duoSubmitURL = fmt.Sprintf("https://%s/frame/prompt", duoHost)
duoForm = url.Values{}
duoForm.Add("sid", duoSID)
duoForm.Add("device", "phone1")
duoForm.Add("factor", duoMfaOptions[duoMfaOption])
duoForm.Add("out_of_date", "false")
if duoMfaOptions[duoMfaOption] == "Passcode" {
duoForm.Add("passcode", token)
}
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
duoTxStat := gjson.Get(resp, "stat").String()
duoTxID := gjson.Get(resp, "response.txid").String()
if duoTxStat != "OK" {
return "", errors.Wrap(err, "error authenticating mfa device")
}
// get duo cookie
duoSubmitURL = fmt.Sprintf("https://%s/frame/status", duoHost)
duoForm = url.Values{}
duoForm.Add("sid", duoSID)
duoForm.Add("txid", duoTxID)
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
duoTxResult := gjson.Get(resp, "response.result").String()
duoResultURL := gjson.Get(resp, "response.result_url").String()
fmt.Println(gjson.Get(resp, "response.status").String())
if duoTxResult != "SUCCESS" {
//poll as this is likely a push request
for {
time.Sleep(3 * time.Second)
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
resp := string(body)
duoTxResult = gjson.Get(resp, "response.result").String()
duoResultURL = gjson.Get(resp, "response.result_url").String()
fmt.Println(gjson.Get(resp, "response.status").String())
if duoTxResult == "FAILURE" {
return "", errors.Wrap(err, "failed to authenticate device")
}
if duoTxResult == "SUCCESS" {
break
}
}
}
duoRequestURL := fmt.Sprintf("https://%s%s", duoHost, duoResultURL)
req, err = http.NewRequest("POST", duoRequestURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error constructing request object to result url")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving duo result response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "duoResultSubmit: error retrieving body from response")
}
resp := string(body)
duoTxCookie := gjson.Get(resp, "response.cookie").String()
if duoTxCookie == "" {
return "", errors.Wrap(err, "duoResultSubmit: Unable to get response.cookie")
}
// callback to okta with cookie
oktaForm := url.Values{}
oktaForm.Add("id", factorID)
oktaForm.Add("stateToken", stateToken)
oktaForm.Add("sig_response", fmt.Sprintf("%s:%s", duoTxCookie, duoSiguatres[1]))
req, err = http.NewRequest("POST", duoCallback, strings.NewReader(oktaForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
// extract okta session token
verifyReq = VerifyRequest{StateToken: stateToken}
verifyBody = new(bytes.Buffer)
json.NewEncoder(verifyBody).Encode(verifyReq)
req, err = http.NewRequest("POST", oktaVerify, verifyBody)
if err != nil {
return "", errors.Wrap(err, "error building verify request")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("X-Okta-XsrfToken", "")
res, err = oc.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return "", errors.Wrap(err, "error retrieving body from response")
}
return gjson.GetBytes(body, "sessionToken").String(), nil
}
// catch all
return "", errors.New("no mfa options provided")
}