forked from Versent/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
okta.go
454 lines (359 loc) · 13.4 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
package okta
import (
"bytes"
"crypto/tls"
"fmt"
"html"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
prompt "github.com/segmentio/go-prompt"
"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"
IdentifierTotpMfa = "GOOGLE TOKEN:SOFTWARE:TOTP"
)
var (
supportedMfaOptions = map[string]string{
IdentifierDuoMfa: "DUO MFA authentication",
IdentifierSmsMfa: "SMS MFA authentication",
IdentifierTotpMfa: "TOTP MFA authentication",
}
)
// OktaClient is a wrapper representing a Okta SAML client
type Client struct {
client *provider.HTTPClient
prompter prompter.Prompter
}
// 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 := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: idpAccount.SkipVerify},
}
client, err := provider.NewHTTPClient(tr)
if err != nil {
return nil, errors.Wrap(err, "error building http client")
}
return &Client{
client: client,
prompter: prompter.NewCli(),
}, 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)
stateToken := gjson.Get(resp, "stateToken").String()
authStatus := gjson.Get(resp, "status").String()
// mfa required
if authStatus == "MFA_REQUIRED" {
// 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 len(mfaOptions) > 1 {
mfaOption = prompt.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)
if _, ok := supportedMfaOptions[mfaIdentifer]; !ok {
return samlAssertion, errors.Wrap(err, "unsupported mfa provider")
}
// get signature & callback
verifyReq := VerifyRequest{StateToken: stateToken}
verifyBody := new(bytes.Buffer)
err = json.NewEncoder(verifyBody).Encode(verifyReq)
if err != nil {
return samlAssertion, errors.Wrap(err, "error encoding verifyReq")
}
req, err = http.NewRequest("POST", oktaVerify, verifyBody)
if err != nil {
return samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
switch mfa := mfaIdentifer; mfa {
case IdentifierSmsMfa, IdentifierTotpMfa:
verifyCode := prompt.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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving token post response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
//try to extract sid
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return samlAssertion, errors.Wrap(err, "error parsing document")
}
duoSID, ok := doc.Find("input[name=\"sid\"]").Attr("value")
if !ok {
return samlAssertion, 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{
"Passcode",
"Duo Push",
}
duoMfaOption := prompt.Choose("Select a DUO MFA Option", duoMfaOptions)
if duoMfaOptions[duoMfaOption] == "Passcode" {
//get users DUO MFA Token
token = prompt.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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, 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 samlAssertion, 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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
duoTxResult := gjson.Get(resp, "response.result").String()
duoTxCookie := gjson.Get(resp, "response.cookie").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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp := string(body)
duoTxResult = gjson.Get(resp, "response.result").String()
duoTxCookie = gjson.Get(resp, "response.cookie").String()
fmt.Println(gjson.Get(resp, "response.status").String())
if duoTxResult == "FAILURE" {
return samlAssertion, errors.Wrap(err, "failed to authenticate device")
}
if duoTxResult == "SUCCESS" {
break
}
}
}
// 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 samlAssertion, 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 samlAssertion, 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 samlAssertion, 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 samlAssertion, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
}
}
oktaSessionToken := gjson.Get(resp, "sessionToken").String()
//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")
}
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)
}