-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathokta.py
469 lines (361 loc) · 13.1 KB
/
okta.py
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
import abc
import base64
import os
import sys
import time
import json
import requests
import dateutil
import subprocess
import aws_okta_processor.core.prompt as prompt
from datetime import datetime
from datetime import timedelta
from datetime import tzinfo
from requests import ConnectTimeout
from requests import ConnectionError
from collections import OrderedDict
from aws_okta_processor.core.print_tty import print_tty
from six import add_metaclass
OKTA_AUTH_URL = "https://{}/api/v1/authn"
OKTA_SESSION_URL = "https://{}/api/v1/sessions"
OKTA_REFRESH_URL = "https://{}/api/v1/sessions/me/lifecycle/refresh"
OKTA_APPLICATIONS_URL = "https://{}/api/v1/users/me/appLinks"
ZERO = timedelta(0)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
class Okta:
def __init__(
self,
user_name=None,
user_pass=None,
organization=None,
factor=None,
silent=None,
no_okta_cache=None
):
self.user_name = user_name
self.silent = silent
self.factor = factor
self.session = requests.Session()
self.organization = organization
self.okta_session_id = None
self.cache_file_path = self.get_cache_file_path()
okta_session = None
if not no_okta_cache:
okta_session = self.get_okta_session()
if okta_session:
self.read_aop_from_okta_session(okta_session)
self.refresh_okta_session_id(
okta_session=okta_session
)
if not self.organization:
print_tty(string="Organization: ", newline=False)
self.organization = input()
if not self.user_name:
print_tty(string="UserName: ", newline=False)
self.user_name = input()
if not self.okta_session_id:
# if not self.user_name:
# print_tty(string="UserName: ", newline=False)
# self.user_name = input()
getCredentialCommand = f"(Get-Credential -Message 'aws-okta-processor is requesting credentials for {self.organization}' -UserName {self.user_name}).GetNetworkCredential() | ConvertTo-Json"
encodedCommand = base64.b64encode(getCredentialCommand.encode("utf-16")[2:]).decode("utf-8")
powershellCommand = f"powershell.exe -NoProfile -NonInteractive -OutputFormat Text -EncodedCommand {encodedCommand}"
output = subprocess.check_output(powershellCommand)
wincreds = json.loads(output)
# if not user_pass:
# user_pass = getpass.getpass()
# if not self.organization:
# print_tty(string="Organization: ", newline=False)
# self.organization = input()
self.okta_single_use_token = self.get_okta_single_use_token(
user_name=wincreds['UserName'],
user_pass=wincreds['Password']
)
wincreds = None
self.get_okta_session_id()
def read_aop_from_okta_session(self, okta_session):
if "aws-okta-processor" in okta_session:
aop_options = okta_session["aws-okta-processor"]
self.user_name = aop_options.get("user_name", None)
self.organization = aop_options.get("organization", None)
del okta_session["aws-okta-processor"]
def get_cache_file_path(self):
home_directory = os.path.expanduser('~')
cache_directory = os.path.join(
home_directory,
'.aws-okta-processor',
'cache'
)
if not os.path.isdir(cache_directory):
os.makedirs(cache_directory)
cache_file_name = "{}-{}-session.json".format(
self.user_name,
self.organization
)
cache_file_path = os.path.join(cache_directory, cache_file_name)
return cache_file_path
def set_okta_session(self, okta_session=None):
session_data = dict(okta_session, **{
"aws-okta-processor": {
"user_name": self.user_name,
"organization": self.organization
}
})
with open(self.cache_file_path, "w") as file:
json.dump(session_data, file)
os.chmod(self.cache_file_path, 0o600)
def get_okta_session(self):
session = {}
if os.path.isfile(self.cache_file_path):
with open(self.cache_file_path) as file:
session = json.load(file)
return session
def get_okta_single_use_token(self, user_name=None, user_pass=None):
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache"
}
json_payload = {
"username": user_name,
"password": user_pass
}
response = self.call(
endpoint=OKTA_AUTH_URL.format(self.organization),
headers=headers,
json_payload=json_payload
)
response_json = {}
try:
response_json = response.json()
except ValueError:
send_error(response=response, json=False)
if "sessionToken" in response_json:
return response_json["sessionToken"]
if "status" in response_json:
if response_json["status"] == "MFA_REQUIRED":
return self.handle_factor(response_json=response_json)
send_error(response=response)
def handle_factor(self, response_json=None):
state_token = response_json["stateToken"]
factors = get_supported_factors(
factors=response_json["_embedded"]["factors"]
)
factor = prompt.get_item(
items=factors,
label="Factor",
key=self.factor
)
return self.verify_factor(factor=factor, state_token=state_token)
def verify_factor(self, factor=None, state_token=None):
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache"
}
json_payload = factor.payload()
json_payload.update({"stateToken": state_token})
response = self.call(
endpoint=factor.link,
headers=headers,
json_payload=json_payload
)
response_json = {}
try:
response_json = response.json()
except ValueError:
send_error(response=response, json=False)
if "sessionToken" in response_json:
return response_json["sessionToken"]
if factor.retry(response_json):
factor.link = response_json["_links"]["next"]["href"]
time.sleep(1)
return self.verify_factor(
factor=factor,
state_token=state_token
)
send_error(response=response)
def get_okta_session_id(self):
headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
json_payload = {
"sessionToken": self.okta_single_use_token
}
response = self.call(
endpoint=OKTA_SESSION_URL.format(self.organization),
json_payload=json_payload,
headers=headers
)
try:
response_json = response.json()
self.okta_session_id = response_json["id"]
self.set_okta_session(okta_session=response_json)
except KeyError:
send_error(response=response)
except ValueError:
send_error(response=response, json=False)
def refresh_okta_session_id(self, okta_session=None):
session_expires = dateutil.parser.parse(
okta_session["expiresAt"]
)
if (datetime.now(UTC()) <
(session_expires - timedelta(seconds=30))):
headers = {
"Cookie": "sid={}".format(okta_session["id"]),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = self.call(
endpoint=OKTA_REFRESH_URL.format(self.organization),
headers=headers,
json_payload={}
)
try:
response_json = response.json()
self.okta_session_id = okta_session["id"]
okta_session["expiresAt"] = response_json["expiresAt"]
self.set_okta_session(okta_session=okta_session)
except KeyError:
send_error(response=response, exit=False)
except ValueError:
send_error(response=response, json=False, exit=False)
def get_applications(self):
applications = OrderedDict()
headers = {
"Cookie": "sid={}".format(self.okta_session_id),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = self.call(
endpoint=OKTA_APPLICATIONS_URL.format(self.organization),
headers=headers
)
for application in response.json():
if application["appName"] == "amazon_aws":
label = application["label"].rstrip()
link_url = application["linkUrl"]
applications[label] = link_url
return applications
def get_saml_response(self, application_url=None):
headers = {
"Cookie": "sid={}".format(self.okta_session_id)
}
response = self.call(application_url, headers=headers)
return response.content.decode()
def call(self, endpoint=None, headers=None, json_payload=None):
print_tty(
"Info: Calling {}".format(endpoint),
silent=self.silent
)
try:
if json_payload is not None:
return self.session.post(
endpoint,
json=json_payload,
headers=headers,
timeout=10
)
else:
return self.session.get(
endpoint,
headers=headers,
timeout=10
)
except ConnectTimeout:
print_tty("Error: Timed Out")
sys.exit(1)
except ConnectionError:
print_tty("Error: Connection Error")
sys.exit(1)
def get_supported_factors(factors=None):
matching_factors = OrderedDict()
for factor in factors:
try:
supported_factor = FactorBase.factory(factor["factorType"])
key = '{}:{}'.format(
factor["factorType"], factor["provider"]).lower()
matching_factors[key] = supported_factor(
link=factor["_links"]["verify"]["href"]
)
except NotImplementedError:
pass
return matching_factors
def send_error(response=None, json=True, exit=True):
print_tty("Error: Status Code: {}".format(response.status_code))
if json:
response_json = response.json()
if "status" in response_json:
print_tty("Error: Status: {}".format(
response_json['status']
))
if "errorSummary" in response_json:
print_tty("Error: Summary: {}".format(
response_json['errorSummary']
))
else:
print_tty("Error: Invalid JSON")
if exit:
sys.exit(1)
class FactorType:
PUSH = "push"
TOTP = "token:software:totp"
HARDWARE = "token:hardware"
@add_metaclass(abc.ABCMeta)
class FactorBase(object):
def __init__(self, link=None):
self.link = link
@classmethod
def factory(cls, factor):
for impl in cls.__subclasses__():
if factor == impl.factor:
return impl
raise NotImplementedError("Factor type not implemented: %s" % factor)
@abc.abstractmethod
def payload():
"""Returns dictionary with payload to verify factor-type."""
pass
@abc.abstractmethod
def retry(self, response):
"""Returns boolean indicating whether response is retryable."""
pass
class FactorPush(FactorBase):
factor = FactorType.PUSH
def __init__(self, link=None):
super(FactorPush, self).__init__(link=link)
self.RETRYABLE_RESULTS = [
"WAITING",
]
@staticmethod
def payload():
return {}
def retry(self, response):
return response.get("factorResult") in self.RETRYABLE_RESULTS
class FactorTOTP(FactorBase):
factor = FactorType.TOTP
def __init__(self, link=None):
super(FactorTOTP, self).__init__(link=link)
@staticmethod
def payload():
print_tty("Token: ", newline=False)
return {"passCode": input()}
def retry(self, response):
return False
class FactorHardwareToken(FactorBase):
factor = FactorType.HARDWARE
def __init__(self, link=None):
super(FactorHardwareToken, self).__init__(link=link)
@staticmethod
def payload():
print_tty("Hardware Token: ", newline=False)
return {"passCode": input()}
def retry(self, response):
return False