This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 224
/
Copy pathokta.go
616 lines (534 loc) · 15.6 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package lib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
"golang.org/x/net/publicsuffix"
"github.com/99designs/keyring"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/segmentio/aws-okta/lib/saml"
log "github.com/sirupsen/logrus"
)
const (
OktaServerUs = "okta.com"
OktaServerEmea = "okta-emea.com"
OktaServerPreview = "oktapreview.com"
OktaServerDefault = OktaServerUs
// deprecated; use OktaServerUs
OktaServer = OktaServerUs
Timeout = time.Duration(60 * time.Second)
)
type OktaClient struct {
// Organization will be deprecated in the future
Organization string
Username string
Password string
UserAuth *OktaUserAuthn
DuoClient *DuoClient
AccessKeyId string
SecretAccessKey string
SessionToken string
Expiration time.Time
OktaAwsSAMLUrl string
CookieJar http.CookieJar
BaseURL *url.URL
Domain string
MFAConfig MFAConfig
}
type MFAConfig struct {
Provider string // Which MFA provider to use when presented with an MFA challenge
FactorType string // Which of the factor types of the MFA provider to use
DuoDevice string // Which DUO device to use for DUO MFA
}
type SAMLAssertion struct {
Resp *saml.Response
RawData []byte
}
type OktaCreds struct {
// Organization will be deprecated in the future
Organization string
Username string
Password string
Domain string
}
func (c *OktaCreds) Validate(mfaConfig MFAConfig) error {
// OktaClient assumes we're doing some AWS SAML calls, but Validate doesn't
o, err := NewOktaClient(*c, "", "", mfaConfig)
if err != nil {
return err
}
if err := o.AuthenticateUser(); err != nil {
return err
}
return nil
}
func GetOktaDomain(region string) (string, error) {
switch region {
case "us":
return OktaServerUs, nil
case "emea":
return OktaServerEmea, nil
case "preview":
return OktaServerPreview, nil
}
return "", fmt.Errorf("invalid region %s", region)
}
func NewOktaClient(creds OktaCreds, oktaAwsSAMLUrl string, sessionCookie string, mfaConfig MFAConfig) (*OktaClient, error) {
var domain string
// maintain compatibility for deprecated creds.Organization
if creds.Domain == "" && creds.Organization != "" {
domain = fmt.Sprintf("%s.%s", creds.Organization, OktaServerDefault)
} else if creds.Domain != "" {
domain = creds.Domain
} else {
return &OktaClient{}, errors.New("either creds.Organization (deprecated) or creds.Domain must be set, but not both. To remedy this, re-add your credentials with `aws-okta add`")
}
// url parse & set base
base, err := url.Parse(fmt.Sprintf(
"https://%s", domain,
))
if err != nil {
return nil, err
}
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return nil, err
}
if sessionCookie != "" {
jar.SetCookies(base, []*http.Cookie{
{
Name: "sid",
Value: sessionCookie,
},
})
}
log.Debug("domain: " + domain)
return &OktaClient{
// Setting Organization for backwards compatibility
Organization: creds.Organization,
Username: creds.Username,
Password: creds.Password,
OktaAwsSAMLUrl: oktaAwsSAMLUrl,
CookieJar: jar,
BaseURL: base,
Domain: domain,
MFAConfig: mfaConfig,
}, nil
}
func (o *OktaClient) AuthenticateUser() error {
var oktaUserAuthn OktaUserAuthn
// Step 1 : Basic authentication
user := OktaUser{
Username: o.Username,
Password: o.Password,
}
payload, err := json.Marshal(user)
if err != nil {
return err
}
log.Debug("Step: 1")
err = o.Get("POST", "api/v1/authn", payload, &oktaUserAuthn, "json")
if err != nil {
return fmt.Errorf("Failed to authenticate with okta: %#v", err)
}
o.UserAuth = &oktaUserAuthn
// Step 2 : Challenge MFA if needed
log.Debug("Step: 2")
if o.UserAuth.Status == "MFA_REQUIRED" {
log.Info("Requesting MFA. Please complete two-factor authentication with your second device")
if err = o.challengeMFA(); err != nil {
return err
}
}
if o.UserAuth.SessionToken == "" {
return fmt.Errorf("authentication failed for %s", o.Username)
}
return nil
}
func (o *OktaClient) AuthenticateProfile(profileARN string, duration time.Duration) (sts.Credentials, string, error) {
// Attempt to reuse session cookie
var assertion SAMLAssertion
err := o.Get("GET", o.OktaAwsSAMLUrl, nil, &assertion, "saml")
if err != nil {
log.Debug("Failed to reuse session token, starting flow from start")
if err := o.AuthenticateUser(); err != nil {
return sts.Credentials{}, "", err
}
// Step 3 : Get SAML Assertion and retrieve IAM Roles
log.Debug("Step: 3")
if err = o.Get("GET", o.OktaAwsSAMLUrl+"?onetimetoken="+o.UserAuth.SessionToken,
nil, &assertion, "saml"); err != nil {
return sts.Credentials{}, "", err
}
}
principal, role, err := GetRoleFromSAML(assertion.Resp, profileARN)
if err != nil {
return sts.Credentials{}, "", err
}
// Step 4 : Assume Role with SAML
samlSess := session.Must(session.NewSession())
svc := sts.New(samlSess)
samlParams := &sts.AssumeRoleWithSAMLInput{
PrincipalArn: aws.String(principal),
RoleArn: aws.String(role),
SAMLAssertion: aws.String(string(assertion.RawData)),
DurationSeconds: aws.Int64(int64(duration.Seconds())),
}
samlResp, err := svc.AssumeRoleWithSAML(samlParams)
if err != nil {
log.WithField("role", role).Errorf(
"error assuming role with SAML: %s", err.Error())
return sts.Credentials{}, "", err
}
var sessionCookie string
cookies := o.CookieJar.Cookies(o.BaseURL)
for _, cookie := range cookies {
if cookie.Name == "sid" {
sessionCookie = cookie.Value
}
}
return *samlResp.Credentials, sessionCookie, nil
}
func selectMFADeviceFromConfig(o *OktaClient) (*OktaUserAuthnFactor, error) {
log.Debugf("MFAConfig: %v\n", o.MFAConfig)
if o.MFAConfig.Provider == "" || o.MFAConfig.FactorType == "" {
return nil, nil
}
for _, f := range o.UserAuth.Embedded.Factors {
log.Debugf("%v\n", f)
if strings.EqualFold(f.Provider, o.MFAConfig.Provider) && strings.EqualFold(f.FactorType, o.MFAConfig.FactorType) {
log.Debugf("Using matching factor \"%v %v\" from config\n", f.Provider, f.FactorType)
return &f, nil
}
}
return nil, fmt.Errorf("Failed to select MFA device with Provider = \"%s\", FactorType = \"%s\"", o.MFAConfig.Provider, o.MFAConfig.FactorType)
}
func (o *OktaClient) selectMFADevice() (*OktaUserAuthnFactor, error) {
factors := o.UserAuth.Embedded.Factors
if len(factors) == 0 {
return nil, errors.New("No available MFA Factors")
} else if len(factors) == 1 {
return &factors[0], nil
}
factor, err := selectMFADeviceFromConfig(o)
if err != nil {
return nil, err
}
if factor != nil {
return factor, nil
}
log.Info("Select a MFA from the following list")
for i, f := range factors {
log.Infof("%d: %s (%s)", i, f.Provider, f.FactorType)
}
i, err := Prompt("Select MFA method", false)
if i == "" {
return nil, errors.New("Invalid selection - Please use an option that is listed")
}
if err != nil {
return nil, err
}
factorIdx, err := strconv.Atoi(i)
if err != nil {
return nil, err
}
if factorIdx > (len(factors) - 1) {
return nil, errors.New("Invalid selection - Please use an option that is listed")
}
return &factors[factorIdx], nil
}
func (o *OktaClient) preChallenge(oktaFactorId, oktaFactorType string) ([]byte, error) {
var mfaCode string
var err error
//Software and Hardware based OTP Tokens
if strings.Contains(oktaFactorType, "token") {
log.Debug("Token MFA")
mfaCode, err = Prompt("Enter MFA Code", false)
if err != nil {
return nil, err
}
} else if strings.Contains(oktaFactorType, "sms") {
log.Debug("SMS MFA")
payload, err := json.Marshal(OktaStateToken{
StateToken: o.UserAuth.StateToken,
})
if err != nil {
return nil, err
}
var sms interface{}
log.Debug("Requesting SMS Code")
err = o.Get("POST", "api/v1/authn/factors/"+oktaFactorId+"/verify",
payload, &sms, "json",
)
if err != nil {
return nil, err
}
mfaCode, err = Prompt("Enter MFA Code from SMS", false)
if err != nil {
return nil, err
}
}
payload, err := json.Marshal(OktaStateToken{
StateToken: o.UserAuth.StateToken,
PassCode: mfaCode,
})
if err != nil {
return nil, err
}
return payload, nil
}
func (o *OktaClient) postChallenge(payload []byte, oktaFactorProvider string, oktaFactorId string) error {
//Initiate Push Notification
if o.UserAuth.Status == "MFA_CHALLENGE" {
f := o.UserAuth.Embedded.Factor
errChan := make(chan error, 1)
if oktaFactorProvider == "DUO" {
// Contact the Duo to initiate Push notification
if f.Embedded.Verification.Host != "" {
o.DuoClient = &DuoClient{
Host: f.Embedded.Verification.Host,
Signature: f.Embedded.Verification.Signature,
Callback: f.Embedded.Verification.Links.Complete.Href,
Device: o.MFAConfig.DuoDevice,
StateToken: o.UserAuth.StateToken,
}
log.Debugf("Host:%s\nSignature:%s\nStateToken:%s\n",
f.Embedded.Verification.Host, f.Embedded.Verification.Signature,
o.UserAuth.StateToken)
go func() {
log.Debug("challenge u2f")
log.Info("Sending Push Notification...")
err := o.DuoClient.ChallengeU2f(f.Embedded.Verification.Host)
if err != nil {
errChan <- err
}
}()
}
}
// Poll Okta until authentication has been completed
for o.UserAuth.Status != "SUCCESS" {
select {
case duoErr := <-errChan:
log.Printf("Err: %s", duoErr)
if duoErr != nil {
return fmt.Errorf("Failed Duo challenge. Err: %s", duoErr)
}
default:
err := o.Get("POST", "api/v1/authn/factors/"+oktaFactorId+"/verify",
payload, &o.UserAuth, "json",
)
if err != nil {
return fmt.Errorf("Failed authn verification for okta. Err: %s", err)
}
}
time.Sleep(2 * time.Second)
}
}
return nil
}
func (o *OktaClient) challengeMFA() (err error) {
var oktaFactorProvider string
var oktaFactorId string
var payload []byte
var oktaFactorType string
log.Debugf("%s", o.UserAuth.StateToken)
factor, err := o.selectMFADevice()
if err != nil {
log.Debug("Failed to select MFA device")
return
}
oktaFactorProvider = factor.Provider
if oktaFactorProvider == "" {
return
}
oktaFactorId, err = GetFactorId(factor)
if err != nil {
return
}
oktaFactorType = factor.FactorType
if oktaFactorId == "" {
return
}
log.Debugf("Okta Factor Provider: %s", oktaFactorProvider)
log.Debugf("Okta Factor ID: %s", oktaFactorId)
log.Debugf("Okta Factor Type: %s", oktaFactorType)
payload, err = o.preChallenge(oktaFactorId, oktaFactorType)
err = o.Get("POST", "api/v1/authn/factors/"+oktaFactorId+"/verify",
payload, &o.UserAuth, "json",
)
if err != nil {
return
}
//Handle Push Notification
err = o.postChallenge(payload, oktaFactorProvider, oktaFactorId)
if err != nil {
return err
}
return
}
func GetFactorId(f *OktaUserAuthnFactor) (id string, err error) {
switch f.FactorType {
case "web":
id = f.Id
case "token:software:totp":
id = f.Id
case "token:hardware":
id = f.Id
case "sms":
id = f.Id
case "push":
if f.Provider == "OKTA" || f.Provider == "DUO" {
id = f.Id
} else {
err = fmt.Errorf("provider %s with factor push not supported", f.Provider)
}
default:
err = fmt.Errorf("factor %s not supported", f.FactorType)
}
return
}
func (o *OktaClient) Get(method string, path string, data []byte, recv interface{}, format string) (err error) {
var res *http.Response
var body []byte
var header http.Header
var client http.Client
url, err := url.Parse(fmt.Sprintf(
"%s/%s", o.BaseURL, path,
))
if err != nil {
return err
}
if format == "json" {
header = http.Header{
"Accept": []string{"application/json"},
"Content-Type": []string{"application/json"},
"Cache-Control": []string{"no-cache"},
}
} else {
header = http.Header{}
}
transCfg := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: Timeout,
}
client = http.Client{
Transport: transCfg,
Timeout: Timeout,
Jar: o.CookieJar,
}
req := &http.Request{
Method: method,
URL: url,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: header,
Body: ioutil.NopCloser(bytes.NewReader(data)),
ContentLength: int64(len(body)),
}
if res, err = client.Do(req); err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("%s %v: %s", method, url, res.Status)
} else if recv != nil {
switch format {
case "json":
err = json.NewDecoder(res.Body).Decode(recv)
default:
var rawData []byte
rawData, err = ioutil.ReadAll(res.Body)
if err != nil {
return
}
if err := ParseSAML(rawData, recv.(*SAMLAssertion)); err != nil {
return fmt.Errorf("Okta user %s does not have the AWS app added to their account. Please contact your Okta admin to make sure things are configured properly.", o.Username)
}
}
}
return
}
type OktaProvider struct {
Keyring keyring.Keyring
ProfileARN string
SessionDuration time.Duration
OktaAwsSAMLUrl string
// OktaSessionCookieKey represents the name of the session cookie
// to be stored in the keyring.
OktaSessionCookieKey string
MFAConfig MFAConfig
}
func (p *OktaProvider) Retrieve() (sts.Credentials, string, error) {
log.Debug("using okta provider")
item, err := p.Keyring.Get("okta-creds")
if err != nil {
log.Debugf("couldnt get okta creds from keyring: %s", err)
return sts.Credentials{}, "", err
}
var oktaCreds OktaCreds
if err = json.Unmarshal(item.Data, &oktaCreds); err != nil {
return sts.Credentials{}, "", errors.New("Failed to get okta credentials from your keyring. Please make sure you have added okta credentials with `aws-okta add`")
}
// Check for stored session cookie
var sessionCookie string
cookieItem, err := p.Keyring.Get(p.OktaSessionCookieKey)
if err == nil {
sessionCookie = string(cookieItem.Data)
}
oktaClient, err := NewOktaClient(oktaCreds, p.OktaAwsSAMLUrl, sessionCookie, p.MFAConfig)
if err != nil {
return sts.Credentials{}, "", err
}
creds, newSessionCookie, err := oktaClient.AuthenticateProfile(p.ProfileARN, p.SessionDuration)
if err != nil {
return sts.Credentials{}, "", err
}
newCookieItem := keyring.Item{
Key: p.OktaSessionCookieKey,
Data: []byte(newSessionCookie),
Label: "okta session cookie",
KeychainNotTrustApplication: false,
}
p.Keyring.Set(newCookieItem)
return creds, oktaCreds.Username, err
}
func (p *OktaProvider) GetSAMLLoginURL() (*url.URL, error) {
item, err := p.Keyring.Get("okta-creds")
if err != nil {
log.Debugf("couldnt get okta creds from keyring: %s", err)
return &url.URL{}, err
}
var oktaCreds OktaCreds
if err = json.Unmarshal(item.Data, &oktaCreds); err != nil {
return &url.URL{}, errors.New("Failed to get okta credentials from your keyring. Please make sure you have added okta credentials with `aws-okta add`")
}
var samlURL string
// maintain compatibility for deprecated creds.Organization
if oktaCreds.Domain == "" && oktaCreds.Organization != "" {
samlURL = fmt.Sprintf("%s.%s", oktaCreds.Organization, OktaServerDefault)
} else if oktaCreds.Domain != "" {
samlURL = oktaCreds.Domain
} else {
return &url.URL{}, errors.New("either oktaCreds.Organization (deprecated) or oktaCreds.Domain must be set, but not both. To remedy this, re-add your credentials with `aws-okta add`")
}
fullSamlURL, err := url.Parse(fmt.Sprintf(
"https://%s/%s",
samlURL,
p.OktaAwsSAMLUrl,
))
if err != nil {
return &url.URL{}, err
}
return fullSamlURL, nil
}