-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.go
495 lines (431 loc) · 18.2 KB
/
authenticate.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
package okta
/*
Please see https://developer.okta.com/docs/api/resources/authn.html for documentation on how the okta auth flow works.
The authentication flow works by recursively calling the handleAuthUserFlow function.
After every auth operation against Okta, a new AuthenticationTransaction is returned, which gives us a few things:
1. The current state of the transaction (ex: MFA required, MFA Challenge, Locked out, etc.)
2. The links to issue post requests to in order to advance the transaction to the next step, or go to the previous step.
Given that the transaction state has everything we need to know how to proceed (or reverse), we don't need to hold
any internal state, and can instead continually evaluate the state of the transaction in a loop until we succeed
or hit a terminal error condition.
In general for an MFA flow we will first call handleMFARequired.
In this state we are given a list of all possible MFA factors that can be used.
This will prompt the user to select a factor, and post to okta to "activate" that factor for verification.
If that succeeds, the next state will call handleMFAChallenge.
Depending on the factor that was chosen, this might required the user to provide some sort of input.
If the factor is successfully verified, then we will hit the success state, and the okta session token will be returned
by the handleAuthUserFlow function.
*/
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/cenkalti/backoff"
"github.com/wearefair/okta-auth/api"
"github.com/wearefair/okta-auth/factors"
)
const unexpectedErrorMessage = "Encountered an unexpected error."
const timeoutErrorMessage = "Authentication Timed Out"
// Custom error for handling auth timeout and rejection
type NonFatalAuthError struct {
ErrorSummary string
}
func (nonFatalAuthError NonFatalAuthError) Error() string {
return nonFatalAuthError.ErrorSummary
}
// Given a username and password, returns a session token or an error.
// You can then use the session token to obtain a session id.
// https://developer.okta.com/docs/api/resources/sessions#session-token
//
// If a second factor is required, the configured callbacks on the client will be invoked.
func (c *OktaClient) Authenticate(username, password string) (string, error) {
url := c.rootURL + "/api/v1/authn"
c.log("Posting auth request to %q with username %q ", url, username)
transaction, apiError, err := c.sendTransactionRequest(url, &api.AuthenticationRequest{
Username: username,
Password: password,
})
if err != nil {
return "", err
}
if apiError != nil {
c.log(apiError.ErrorSummary)
return "", errors.New("Failed to authenticate")
}
return c.handleAuthUserFlow(transaction, true)
}
// Given an AuthenticationTransaction executes the state machine, and eventually returns
// an error or a Okta session token.
//
// This is the entrypoint to the main recursive loop.
// All methods will eventually call this method, or return the session token or error.
func (c *OktaClient) handleAuthUserFlow(transaction api.AuthenticationTransaction, autoAttemptU2F bool) (string, error) {
c.log("Handling auth user flow: status %q", transaction.Status)
switch transaction.Status {
case api.StateSuccess:
return transaction.SessionToken, nil
case api.StatePasswordExpired:
return "", TerminalError(fmt.Sprintf("Your password is expired, login to %s to resolve.", c.rootURL))
case api.StateRecovery:
return "", TerminalError(fmt.Sprintf("Your account is in recovery, login to %s to resolve.", c.rootURL))
case api.StateLockedOut:
return "", TerminalError("Your account has been locked, please contact your administrator for assistance.")
case api.StateMFAEnroll, api.StateMFAEnrollActivate:
return "", TerminalError(fmt.Sprintf("You are required to enroll an MFA method, login to %s to resolve.", c.rootURL))
case api.StateMFARequired:
return c.handleMFARequired(transaction, autoAttemptU2F)
case api.StateMFAChallenge:
return c.handleMFAChallenge(transaction)
default:
return "", TerminalError(fmt.Sprintf("Unknown user state %s, contact your administrator for assistance.", transaction.Status))
}
}
// If autoAttemptU2F is true, calls the user provided U2F callback to check if the device is present,
// and if so will start the U2F flow for that factor.
// Otherwise calls the user provided callback with the list of factors, which should return the user specified factor
// or an error which will cancel the flow.
func (c *OktaClient) handleMFARequired(transaction api.AuthenticationTransaction, autoAttemptU2F bool) (string, error) {
supported := transaction.Embedded.Factors.SupportedFactors()
if len(supported) == 0 {
return "", TerminalError("No supported MFA types found")
}
// Start the mfa factor automatically if it is present, and the u2f token is connected.
for _, factor := range supported {
if factor.FactorType == factors.FactorTypeU2F && autoAttemptU2F &&
c.prompts.CheckU2FPresence(u2fProfileToChallenge(c.domain, "", factor.Profile.(api.FactorProfileU2F))) {
return c.startMFA(transaction, factor)
}
if factor.FactorType == factors.FactorTypeWebAuthN && autoAttemptU2F &&
c.prompts.CheckU2FPresence(webAuthNProfileToChallenge(c.domain, "", factor.Profile.(api.FactorProfileWebAuthN))) {
return c.startMFA(transaction, factor)
}
}
publicFactors := apiFactorsToPublicFactors(supported)
factor, err := c.prompts.ChooseFactor(publicFactors)
if err != nil {
return "", err
}
for _, apiFactor := range supported {
if apiFactor.Id == factor.Id {
return c.startMFA(transaction, apiFactor)
}
}
return "", TerminalError(fmt.Sprintf("Factor with id %q was not found", factor.Id))
}
// Starts the verification flow for the given factor.
func (c *OktaClient) startMFA(transaction api.AuthenticationTransaction, factor api.Factor) (string, error) {
newTransaction, apiError, err := c.sendTransactionRequest(factor.Links.Verify.HREF, api.FactorVerify{
StateToken: transaction.StateToken,
})
if err != nil {
return "", err
}
if apiError != nil {
c.prompts.PresentUserError(fmt.Sprintf("Got error trying to use MFA %s: %s", factor.FactorType, apiError.ErrorSummary))
}
return c.handleAuthUserFlow(newTransaction, false)
}
// Captures user input (if required) to verify the active factor challenge.
func (c *OktaClient) handleMFAChallenge(transaction api.AuthenticationTransaction) (string, error) {
switch transaction.Embedded.Factor.FactorType {
case factors.FactorTypeU2F:
return c.handleFactorTypeU2F(transaction)
case factors.FactorTypeWebAuthN:
return c.handleFactorTypeWebAuthn(transaction)
case factors.FactorTypeTokenSoftwareTOTP, factors.FactorTypeSMS, factors.FactorTypeCall:
return c.handleFactorTypeCode(transaction)
case factors.FactorTypePush:
return c.handleFactorTypePush(transaction)
default:
return c.cancelCurrentFactorWithErrorMessage(transaction, "Sorry, that factor is not supported yet.")
}
}
// Presents the user with the error message, and then cancels the current factor.
func (c *OktaClient) cancelCurrentFactorWithErrorMessage(transaction api.AuthenticationTransaction, msg string) (string, error) {
c.prompts.PresentUserError(msg)
return c.cancelCurrentFactor(transaction)
}
// Cancels the current factor, and goes back into the authentication transaction loop.
func (c *OktaClient) cancelCurrentFactor(transaction api.AuthenticationTransaction) (string, error) {
request := &api.FactorVerify{transaction.StateToken}
newTransaction, apiError, err := c.sendTransactionRequest(transaction.Links.Prev.HREF, request)
if err != nil {
return "", err
}
if apiError != nil {
c.log("Got error trying to cancel MFA factor: uri %q, error: %q", transaction.Links.Prev.HREF, apiError.ErrorSummary)
return "", TerminalError(unexpectedErrorMessage)
}
return c.handleAuthUserFlow(newTransaction, false)
}
func (c *OktaClient) handleFactorTypeWebAuthn(transaction api.AuthenticationTransaction) (string, error) {
profile, ok := transaction.Embedded.Factor.Profile.(api.FactorProfileWebAuthN)
if !ok {
c.log("Profile was not of type FactorProfileWebAuthN: %s", transaction.Embedded.Factor.Profile)
return c.cancelCurrentFactorWithErrorMessage(transaction, unexpectedErrorMessage)
}
// Setup a context with the timeout set to the value provided by Okta
timeoutSeconds := 30
ctx, _ := context.WithTimeout(context.Background(), time.Second*time.Duration(timeoutSeconds))
req := VerifyU2FRequest{
Facet: "https://" + c.domain,
AppId: c.domain,
KeyHandle: profile.CredentialId,
Challenge: transaction.Embedded.Factor.Embedded.Challenge.Challenge,
WebAuthn: true,
}
authResp, err := c.prompts.VerifyU2F(ctx, req)
if err != nil {
c.prompts.PresentUserError(fmt.Sprintf("Failed to authenticate: %s\n", err))
return c.cancelCurrentFactor(transaction)
}
verifyReq := api.FactorVerifyWebAuthN{
FactorVerify: api.FactorVerify{
StateToken: transaction.StateToken,
},
ClientData: authResp.ClientData,
SignatureData: authResp.SignatureData,
AuthenticatorData: authResp.AuthenticatorData,
}
newTransaction, apiError, err := c.sendTransactionRequest(transaction.Links.Next.HREF, &verifyReq)
if err != nil {
return "", err
}
if apiError != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, apiError.ErrorSummary)
}
return c.handleAuthUserFlow(newTransaction, false)
}
func (c *OktaClient) handleFactorTypeU2F(transaction api.AuthenticationTransaction) (string, error) {
profile, ok := transaction.Embedded.Factor.Profile.(api.FactorProfileU2F)
if !ok {
c.log("Profile was not of type FactorProfileU2F: %s", transaction.Embedded.Factor.Profile)
return c.cancelCurrentFactorWithErrorMessage(transaction, unexpectedErrorMessage)
}
// Setup a context with the timeout set to the value provided by Okta
timeoutSeconds := transaction.Embedded.Factor.Embedded.Challenge.TimeoutSeconds
ctx, _ := context.WithTimeout(context.Background(), time.Second*time.Duration(timeoutSeconds))
authResp, err := c.prompts.VerifyU2F(ctx, VerifyU2FRequest{
Facet: "https://" + c.domain,
AppId: profile.AppId,
KeyHandle: profile.CredentialId,
Challenge: transaction.Embedded.Factor.Embedded.Challenge.Nonce,
})
if err != nil {
c.prompts.PresentUserError(fmt.Sprintf("Failed to authenticate: %s\n", err))
return c.cancelCurrentFactor(transaction)
}
verifyReq := api.FactorVerifyU2F{
FactorVerify: api.FactorVerify{
StateToken: transaction.StateToken,
},
ClientData: authResp.ClientData,
SignatureData: authResp.SignatureData,
}
newTransaction, apiError, err := c.sendTransactionRequest(transaction.Links.Next.HREF, &verifyReq)
if err != nil {
return "", err
}
if apiError != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, apiError.ErrorSummary)
}
return c.handleAuthUserFlow(newTransaction, false)
}
func (c *OktaClient) handleFactorTypeCode(transaction api.AuthenticationTransaction) (string, error) {
code, err := c.prompts.VerifyCode(apiFactorToPublicFactor(transaction.Embedded.Factor))
if err != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, "Cancelled")
}
verifyReq := api.FactorVerifyCode{
FactorVerify: api.FactorVerify{
StateToken: transaction.StateToken,
},
PassCode: code,
}
newTransaction, apiError, err := c.sendTransactionRequest(transaction.Links.Next.HREF, &verifyReq)
if err != nil {
return "", err
}
if apiError != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, apiError.ErrorSummary)
}
return c.handleAuthUserFlow(newTransaction, false)
}
// Logic for handling Okta Verify Push. Given a Authentication Transaction, will make an initial call to send a push notification
// to user's device then prompts them to accept it. Uses a backoff policy to poll the verify endpoint while waiting on a user to accept.
// Important to note that if a user times out, the initial verify request will still be on their phone and they'll have to accept/reject it
// before trying again.
// TODO: Configurable timeouts
func (c *OktaClient) handleFactorTypePush(transaction api.AuthenticationTransaction) (string, error) {
var newTransaction api.AuthenticationTransaction
// Sends a request to Okta to push a notification to user's device
verifyReq := api.FactorVerifyPush{
FactorVerify: api.FactorVerify{
StateToken: transaction.StateToken,
},
}
transaction, apiError, err := c.sendTransactionRequest(transaction.Links.Next.HREF, &verifyReq)
if err != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, "Cancelled")
}
if apiError != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, apiError.ErrorSummary)
}
// Prompt user to check their device for an Okta Verify notification
c.prompts.VerifyPush()
// Setup and begin constant backoff policy that retries every 3 seconds with a maximum of 10 attempts (timeout after 30 seconds)
backoffPolicy := backoff.WithMaxRetries(backoff.NewConstantBackOff(3*time.Second), 10)
operation := func() error {
newTransaction, apiError, err = c.sendTransactionRequest(transaction.Links.Next.HREF, &verifyReq)
if err != nil {
return backoff.Permanent(err)
}
if apiError != nil {
return backoff.Permanent(apiError)
}
if newTransaction.Status == api.StateSuccess {
return nil
}
if newTransaction.FactorResult == api.FactorResultRejected {
fmt.Println("Authentication Request rejected")
return backoff.Permanent(&NonFatalAuthError{"Authentication Rejected"})
}
return &NonFatalAuthError{timeoutErrorMessage}
}
err = backoff.Retry(operation, backoffPolicy)
// If error is a NonFatalAuthError (timeout or rejection) then cancel the transaction so we can go through the auth flow again
if _, ok := err.(*NonFatalAuthError); ok {
if err.Error() == timeoutErrorMessage {
fmt.Println("Authentication Timed Out - please reject the current Okta Auth Request on your phone then try again")
}
c.sendTransactionRequest(newTransaction.Links.Cancel.HREF, &verifyReq)
return "", err
}
if err != nil {
return c.cancelCurrentFactorWithErrorMessage(transaction, err.Error())
}
return c.handleAuthUserFlow(newTransaction, false)
}
// Given a url and a pointer to a struct, serializes the request to JSON and POSTs it to the given url.
// If the status code is 200, returns a new AuthenticationTransaction.
// If the status code is 4xx returns an APIError.
// For any other error condition (5xx, JSON marshaling, etc) returns a TerminalError
func (c *OktaClient) sendTransactionRequest(url string, request interface{}) (api.AuthenticationTransaction, *api.APIError, error) {
transaction := api.AuthenticationTransaction{}
status, body, err := c.sendRequest(http.MethodPost, url, request)
if err != nil {
// Don't log the AuthenticationRequest, as that will contain a password
if _, ok := request.(*api.AuthenticationRequest); ok {
c.log("Got error sending transaction request: error: %s", request)
} else {
c.log("Got error sending transaction request: request %#+v, error: %s", request, err)
}
return transaction, nil, TerminalError(err.Error())
}
if status == http.StatusOK {
err = json.Unmarshal(body, &transaction)
if err != nil {
c.log("Got error unmarshaling authentication transaction: body %q, error %s", string(body), err)
return transaction, nil, TerminalError(unexpectedErrorMessage)
}
return transaction, nil, nil
}
if status == http.StatusTooManyRequests {
return transaction, nil, TerminalError("Too many requests to Okta, try again later")
}
if status >= 400 && status < 500 {
apiError := api.APIError{}
err = json.Unmarshal(body, &apiError)
if err != nil {
c.log("Got error unmarshaling api error: body %q, error %s", string(body), err)
return transaction, nil, TerminalError(unexpectedErrorMessage)
}
return transaction, &apiError, nil
}
c.log("Got unexpected server status code: body %q, status %d", string(body), status)
return transaction, nil, TerminalError(unexpectedErrorMessage)
}
// Sends an http request to with the given method and url, serializing the body to json.
// Returns the resulting status code, the body, or an error if the request failed.
func (c *OktaClient) sendRequest(method, url string, body interface{}) (int, []byte, error) {
c.log("Sending http request %s %s", method, url)
requestBytes, err := json.Marshal(body)
if err != nil {
c.log("Error marshaling body for request %s %s: %s", method, url, err)
return 0, nil, err
}
request, err := http.NewRequest(method, url, bytes.NewBuffer(requestBytes))
if err != nil {
c.log("Error creating request %s %s: %s", method, url, err)
return 0, nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := c.httpClient.Do(request)
if err != nil {
c.log("Error sending request %s %s: %s", method, url, err)
return 0, nil, err
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return 0, nil, err
}
c.log("Got http response: status %d, body %q", response.StatusCode, string(bodyBytes))
return response.StatusCode, bodyBytes, nil
}
func u2fProfileToChallenge(facet, challenge string, profile api.FactorProfileU2F) VerifyU2FRequest {
return VerifyU2FRequest{
AppId: profile.AppId,
Facet: facet,
KeyHandle: profile.CredentialId,
Challenge: challenge,
}
}
func webAuthNProfileToChallenge(facet, challenge string, profile api.FactorProfileWebAuthN) VerifyU2FRequest {
return VerifyU2FRequest{
AppId: facet,
Facet: facet,
KeyHandle: profile.CredentialId,
Challenge: challenge,
WebAuthn: true,
}
}
func apiFactorsToPublicFactors(facs []api.Factor) []factors.Factor {
re := make([]factors.Factor, 0, len(facs))
for _, f := range facs {
re = append(re, apiFactorToPublicFactor(f))
}
return re
}
func apiFactorToPublicFactor(factor api.Factor) factors.Factor {
re := factors.Factor{
Id: factor.Id,
FactorType: factor.FactorType,
Provider: factor.Provider,
}
switch profile := factor.Profile.(type) {
case api.FactorProfileQuestion:
re.ProfileQuestion = &factors.ProfileQuestion{
QuestionText: profile.QuestionText,
}
case api.FactorProfileSMS:
re.ProfileSMS = &factors.ProfileSMS{
PhoneNumber: profile.PhoneNumber,
}
case api.FactorProfileCall:
re.ProfileCall = &factors.ProfileCall{
PhoneNumber: profile.PhoneNumber,
PhoneExtension: profile.PhoneExtension,
}
case api.FactorProfileToken:
re.ProfileToken = &factors.ProfileToken{
CredentialId: profile.CredentialId,
}
}
return re
}