-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathauth.py
More file actions
executable file
·1605 lines (1514 loc) · 67.2 KB
/
auth.py
File metadata and controls
executable file
·1605 lines (1514 loc) · 67.2 KB
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import getpass
import sys
import json
import argparse
import base64
import datetime
import uuid
import binascii
import time
import codecs
from urllib.parse import urlparse, parse_qs, quote_plus
from urllib3.util import SKIP_HEADER
from xml.sax.saxutils import escape as xml_escape
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
import os
from cryptography.hazmat.primitives import serialization, padding, hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.kbkdf import CounterLocation, KBKDFHMAC, Mode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography import x509
from roadtools.roadlib.constants import WELLKNOWN_RESOURCES, WELLKNOWN_CLIENTS, WELLKNOWN_USER_AGENTS, \
DSSO_BODY_KERBEROS, DSSO_BODY_USERPASS
import requests
import adal
import jwt
def get_data(data):
return base64.urlsafe_b64decode(data+('='*(len(data)%4)))
class AuthenticationException(Exception):
"""
Generic exception we can throw when auth fails so that the error
goes back to the user.
"""
class Authentication():
"""
Authentication class for ROADtools
"""
def __init__(self, username=None, password=None, tenant=None, client_id='1b730954-1685-4b74-9bfd-dac224a7b894'):
self.username = username
self.password = password
self.tenant = tenant
self.client_id = None
self.origin = None
self.set_client_id(client_id)
self.resource_uri = 'https://graph.windows.net/'
self.tokendata = {}
self.refresh_token = None
self.saml_token = None
self.access_token = None
self.proxies = None
self.verify = True
self.outfile = None
self.debug = False
self.scope = None
self.user_agent = None
self.use_cae = False
# For cert based app auth
self.appprivkey = None
self.appcertificate = None
self.appkeydata = None
def get_authority_url(self, default_tenant='common'):
"""
Returns the authority URL for the tenant specified, or the
common one if no tenant was specified
"""
if self.tenant is not None:
return f'https://login.microsoftonline.com/{self.tenant}'
return f'https://login.microsoftonline.com/{default_tenant}'
def set_client_id(self, clid):
"""
Sets client ID to use (accepts aliases)
"""
self.client_id = self.lookup_client_id(clid)
def set_origin_value(self, origin):
"""
Sets Origin header to use
"""
self.origin = origin
adal.oauth2_client._REQ_OPTION['headers']['Origin'] = self.origin
def set_resource_uri(self, uri):
"""
Sets resource URI to use (accepts aliases)
"""
self.resource_uri = self.lookup_resource_uri(uri)
def set_user_agent(self, useragent):
"""
Overrides user agent (accepts aliases)
"""
self.user_agent = self.lookup_user_agent(useragent)
# Patch it in adal too in case we fall back to that
#pylint: disable=protected-access
adal.oauth2_client._REQ_OPTION['headers']['User-Agent'] = self.user_agent
def user_discovery(self, username):
"""
Discover whether this is a federated user
"""
# Tenant specific endpoint seems to not work for this?
authority_uri = 'https://login.microsoftonline.com/common'
user = quote_plus(username)
res = self.requests_get(f"{authority_uri}/UserRealm/{user}?api-version=2.0")
response = res.json()
return response
def loadappcert(self, pemfile=None, privkeyfile=None, pfxfile=None, pfxpass=None, pfxbase64=None):
"""
Load a certificate from disk for usage with application auth
"""
if pemfile and privkeyfile:
with open(pemfile, "rb") as certf:
self.appcertificate = x509.load_pem_x509_certificate(certf.read())
with open(privkeyfile, "rb") as keyf:
self.appkeydata = keyf.read()
self.appprivkey = serialization.load_pem_private_key(self.appkeydata, password=None)
return True
if privkeyfile:
with open(privkeyfile, "rb") as keyf:
self.appkeydata = keyf.read()
self.appprivkey = serialization.load_pem_private_key(self.appkeydata, password=None)
return True
if pfxfile or pfxbase64:
if pfxfile:
with open(pfxfile, 'rb') as pfxf:
pfxdata = pfxf.read()
if pfxbase64:
pfxdata = base64.b64decode(pfxbase64)
if isinstance(pfxpass, str):
pfxpass = pfxpass.encode()
self.appprivkey, self.appcertificate, _ = pkcs12.load_key_and_certificates(pfxdata, pfxpass)
# PyJWT needs the key as PEM data anyway, so encode it
self.appkeydata = self.appprivkey.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
return True
print('You must specify either a PEM certificate file and private key file or a pfx file with the device keypair.')
return False
def authenticate_device_code(self):
"""
Authenticate the end-user using device auth.
"""
authority_host_uri = self.get_authority_url()
context = adal.AuthenticationContext(authority_host_uri, api_version=None, proxies=self.proxies, verify_ssl=self.verify)
code = context.acquire_user_code(self.resource_uri, self.client_id)
print(code['message'])
self.tokendata = context.acquire_token_with_device_code(self.resource_uri, code, self.client_id)
return self.tokendata
def authenticate_username_password(self):
"""
Authenticate using user w/ username + password.
This doesn't work for users or tenants that have multi-factor authentication required.
"""
authority_uri = self.get_authority_url()
context = adal.AuthenticationContext(authority_uri, api_version=None, proxies=self.proxies, verify_ssl=self.verify)
self.tokendata = context.acquire_token_with_username_password(self.resource_uri, self.username, self.password, self.client_id)
return self.tokendata
def authenticate_device_code_native(self, additionaldata=None, returnreply=False):
"""
Authenticate with device code flow
Native version without adal
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"resource": self.resource_uri,
}
if self.scope:
data['scope'] = self.scope
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/devicecode", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
responsedata = res.json()
print(responsedata['message'])
# print(f"Code expires in {responsedata['expires_in']} seconds")
interval = float(responsedata['interval'])
device_code = responsedata['device_code']
polldata = {
"client_id": self.client_id,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"code": device_code
}
while True:
time.sleep(interval)
res = self.requests_post(f"{authority_uri}/oauth2/token", data=polldata)
tokenreply = res.json()
if res.status_code != 200:
# Keep polling
if tokenreply['error'] == 'authorization_pending':
continue
if tokenreply['error'] in ('expired_token', 'code_expired'):
raise AuthenticationException("The code has expired.")
if tokenreply['error'] == 'authorization_declined':
raise AuthenticationException("The user declined the sign-in.")
# If not handled, raise
raise AuthenticationException(res.text)
# Else break out of the loop
break
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_device_code_native_v2(self, additionaldata=None, returnreply=False):
"""
Authenticate with device code flow
Native version without adal
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"scope": self.scope,
}
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/devicecode", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
responsedata = res.json()
print(responsedata['message'])
# print(f"Code expires in {responsedata['expires_in']} seconds")
interval = float(responsedata['interval'])
device_code = responsedata['device_code']
polldata = {
"client_id": self.client_id,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"code": device_code
}
while True:
time.sleep(interval)
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=polldata)
tokenreply = res.json()
if res.status_code != 200:
# Keep polling
if tokenreply['error'] == 'authorization_pending':
continue
if tokenreply['error'] in ('expired_token', 'code_expired'):
raise AuthenticationException("The code has expired.")
if tokenreply['error'] == 'authorization_declined':
raise AuthenticationException("The user declined the sign-in.")
# If not handled, raise
raise AuthenticationException(res.text)
# Else break out of the loop
break
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_username_password_native(self, client_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate using user w/ username + password.
This doesn't work for users or tenants that have multi-factor authentication required.
Native version without adal
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "password",
"resource": self.resource_uri,
"username": self.username,
"password": self.password
}
if self.scope:
data['scope'] = self.scope
if client_secret:
data['client_secret'] = client_secret
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_username_password_native_v2(self, client_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate using user w/ username + password.
This doesn't work for users or tenants that have multi-factor authentication required.
Native version without adal, for identity platform v2 endpoint
"""
authority_uri = self.get_authority_url('organizations')
data = {
"client_id": self.client_id,
"grant_type": "password",
"scope": self.scope,
"username": self.username,
"password": self.password
}
if client_secret:
data['client_secret'] = client_secret
if additionaldata:
data = {**data, **additionaldata}
if self.use_cae:
data['claims'] = '{"access_token":{"xms_cc":{"values":["cp1"]}}}'
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_as_app(self):
"""
Authenticate with an APP id + secret (password credentials assigned to app or service principal)
"""
authority_uri = self.get_authority_url()
context = adal.AuthenticationContext(authority_uri, api_version=None, proxies=self.proxies, verify_ssl=self.verify)
self.tokendata = context.acquire_token_with_client_credentials(self.resource_uri, self.client_id, self.password)
return self.tokendata
def authenticate_as_app_native(self, client_secret=None, assertion=None, additionaldata=None, returnreply=False):
"""
Authenticate with an APP id + secret
Native ROADlib implementation
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "client_credentials",
"resource": self.resource_uri,
}
if assertion:
data['client_assertion_type'] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
data['client_assertion'] = assertion
else:
if client_secret:
data['client_secret'] = client_secret
else:
data['client_secret'] = self.password
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_as_app_native_v2(self, client_secret=None, assertion=None, additionaldata=None, returnreply=False):
"""
Authenticate with an APP id + secret (password credentials assigned to serviceprinicpal)
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "client_credentials",
"scope": self.scope,
}
if assertion:
data['client_assertion_type'] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
data['client_assertion'] = assertion
else:
if client_secret:
data['client_secret'] = client_secret
else:
data['client_secret'] = self.password
if additionaldata:
data = {**data, **additionaldata}
if self.use_cae:
data['claims'] = '{"access_token":{"xms_cc":{"values":["cp1"]}}}'
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def generate_app_assertion(self, use_v2=True):
data = self.appcertificate.public_bytes(
serialization.Encoding.DER
)
digest = hashes.Hash(hashes.SHA1())
digest.update(data)
thumbprint = digest.finalize()
headers = {
"x5t": base64.urlsafe_b64encode(thumbprint).decode('utf-8'),
}
if use_v2:
suffix = '/oauth2/v2.0/token'
else:
suffix = '/oauth2/token'
payload = {
"aud": self.get_authority_url() + suffix,
"iat": str(int(time.time())),
"nbf": str(int(time.time())),
"exp": str(int(time.time())+(300)),
"iss": self.client_id,
"jti": str(uuid.uuid4()),
"sub": self.client_id
}
return jwt.encode(payload, algorithm='RS256', key=self.appkeydata, headers=headers)
def generate_federated_assertion(self, iss, sub, kid=None, aud='api://AzureADTokenExchange'):
"""
Generate a federated assertion for the specified key ID, issuer, subject and audience.
Appkeypem should be a PEM encoded private key (as bytes), if not specified it should already be loaded
"""
if not kid:
# Calculate as thumbprint of cert
if not self.appcertificate:
raise ValueError('Either an app certificate should be specified or a manual key ID (kid) should be provided')
data = self.appcertificate.public_bytes(
serialization.Encoding.DER
)
digest = hashes.Hash(hashes.SHA1())
digest.update(data)
kid = base64.urlsafe_b64encode(digest.finalize()).decode('utf-8')
headers = {
'kid':kid
}
payload = {
"aud": aud,
"iat": str(int(time.time())),
"nbf": str(int(time.time())),
"exp": str(int(time.time())+(300)),
"iss": iss,
"jti": str(uuid.uuid4()),
"sub": sub
}
return jwt.encode(payload, algorithm='RS256', key=self.appkeydata, headers=headers)
def authenticate_with_code(self, code, redirurl, client_secret=None):
"""
Authenticate with a code plus optional secret in case of a non-public app (authorization grant)
"""
authority_uri = self.get_authority_url()
context = adal.AuthenticationContext(authority_uri, api_version=None, proxies=self.proxies, verify_ssl=self.verify)
self.tokendata = context.acquire_token_with_authorization_code(code, redirurl, self.resource_uri, self.client_id, client_secret)
return self.tokendata
def authenticate_with_refresh(self, oldtokendata):
"""
Authenticate with a refresh token, refreshes the refresh token
and obtains an access token
"""
authority_uri = self.get_authority_url()
context = adal.AuthenticationContext(authority_uri, api_version=None, proxies=self.proxies, verify_ssl=self.verify)
newtokendata = context.acquire_token_with_refresh_token(oldtokendata['refreshToken'], self.client_id, self.resource_uri)
# Overwrite fields
for ikey, ivalue in newtokendata.items():
self.tokendata[ikey] = ivalue
access_token = newtokendata['accessToken']
tokens = access_token.split('.')
inputdata = json.loads(base64.b64decode(tokens[1]+('='*(len(tokens[1])%4))))
self.tokendata['_clientId'] = self.client_id
self.tokendata['tenantId'] = inputdata['tid']
if self.origin:
self.tokendata['originheader'] = self.origin
return self.tokendata
def authenticate_with_refresh_native(self, refresh_token, client_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate with a refresh token plus optional secret in case of a non-public app (authorization grant)
Native ROADlib implementation without adal requirement
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"resource": self.resource_uri,
}
if client_secret:
data['client_secret'] = client_secret
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
access_token = tokenreply['access_token']
tokens = access_token.split('.')
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
if self.origin:
self.tokendata['originheader'] = self.origin
return self.tokendata
def authenticate_with_refresh_native_v2(self, refresh_token, client_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate with a refresh token plus optional secret in case of a non-public app (authorization grant)
Native ROADlib implementation without adal requirement
This function calls identity platform v2 and thus requires a scope instead of resource
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"scope": self.scope,
}
if client_secret:
data['client_secret'] = client_secret
if self.use_cae:
data['claims'] = '{"access_token":{"xms_cc":{"values":["cp1"]}}}'
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
if self.origin:
self.tokendata['originheader'] = self.origin
return self.tokendata
def authenticate_with_code_native(self, code, redirurl, client_secret=None, pkce_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate with a code plus optional secret in case of a non-public app (authorization grant)
Native ROADlib implementation without adal requirement - also supports PKCE
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirurl,
"resource": self.resource_uri,
}
if client_secret:
data['client_secret'] = client_secret
if additionaldata:
data = {**data, **additionaldata}
if pkce_secret:
raise NotImplementedError
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_with_code_native_v2(self, code, redirurl, client_secret=None, pkce_secret=None, additionaldata=None, returnreply=False):
"""
Authenticate with a code plus optional secret in case of a non-public app (authorization grant)
Native ROADlib implementation without adal requirement - also supports PKCE
This function calls identity platform v2 and thus requires a scope instead of resource
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirurl,
"scope": self.scope,
}
if client_secret:
data['client_secret'] = client_secret
if additionaldata:
data = {**data, **additionaldata}
if self.use_cae:
data['claims'] = '{"access_token":{"xms_cc":{"values":["cp1"]}}}'
if pkce_secret:
raise NotImplementedError
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_with_code_encrypted(self, code, sessionkey, redirurl):
'''
Encrypted code redemption. Like normal code flow but requires
session key to decrypt response.
'''
authority_uri = self.get_authority_url()
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirurl,
"client_id": self.client_id,
"client_info":1,
"windows_api_version":"2.0"
}
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
prtdata = res.text
data = self.decrypt_auth_response(prtdata, sessionkey, asjson=True)
return data
def authenticate_with_saml_native(self, saml_token, additionaldata=None, returnreply=False):
"""
Authenticate with a SAML token from the Federation Server
Native ROADlib implementation without adal requirement
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "urn:ietf:params:oauth:grant-type:saml1_1-bearer",
"assertion": base64.b64encode(saml_token.encode('utf-8')).decode('utf-8'),
"resource": self.resource_uri,
}
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def authenticate_with_saml_native_v2(self, saml_token, additionaldata=None, returnreply=False):
"""
Authenticate with a SAML token from the Federation Server
Native ROADlib implementation without adal requirement
This function calls identity platform v2 and thus requires a scope instead of resource
"""
authority_uri = self.get_authority_url()
data = {
"client_id": self.client_id,
"grant_type": "urn:ietf:params:oauth:grant-type:saml1_1-bearer",
"assertion": base64.b64encode(saml_token.encode('utf-8')).decode('utf-8'),
"scope": self.scope,
}
if self.use_cae:
data['claims'] = '{"access_token":{"xms_cc":{"values":["cp1"]}}}'
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/v2.0/token", data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def get_desktopsso_token(self, username=None, password=None, krbtoken=None):
'''
Get desktop SSO token either with plain username and password, or with a Kerberos auth token
'''
if username and password:
rbody = DSSO_BODY_USERPASS.format(username=xml_escape(username), password=xml_escape(password), tenant=self.tenant)
headers = {
'Content-Type':'application/soap+xml; charset=utf-8',
'SOAPAction': 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue',
}
res = self.requests_post(f'https://autologon.microsoftazuread-sso.com/{self.tenant}/winauth/trust/2005/usernamemixed?client-request-id=19ac39db-81d2-4713-8046-b0b7240592be', headers=headers, data=rbody)
tree = ET.fromstring(res.content)
els = tree.findall('.//DesktopSsoToken')
if len(els) > 0:
token = els[0].text
return token
else:
# Try finding error
elres = tree.iter('{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}text')
if elres:
errtext = next(elres)
raise AuthenticationException(errtext.text)
else:
raise AuthenticationException(parseString(res.content).toprettyxml(indent=' '))
elif krbtoken:
rbody = DSSO_BODY_KERBEROS.format(tenant=self.tenant)
headers = {
'Content-Type':'application/soap+xml; charset=utf-8',
'SOAPAction': 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue',
'Authorization': f'Negotiate {krbtoken}'
}
res = self.requests_post(f'https://autologon.microsoftazuread-sso.com/{self.tenant}/winauth/trust/2005/windowstransport?client-request-id=19ac39db-81d2-4713-8046-b0b7240592be', headers=headers, data=rbody)
tree = ET.fromstring(res.content)
els = tree.findall('.//DesktopSsoToken')
if len(els) > 0:
token = els[0].text
return token
else:
print(parseString(res.content).toprettyxml(indent=' '))
return False
else:
return False
def authenticate_with_desktopsso_token(self, dssotoken, returnreply=False, additionaldata=None):
'''
Authenticate with Desktop SSO token
'''
headers = {
'x-client-SKU': 'PCL.Desktop',
'x-client-Ver': '3.19.7.16602',
'x-client-CPU': 'x64',
'x-client-OS': 'Microsoft Windows NT 10.0.18363.0',
'x-ms-PKeyAuth': '1.0',
'client-request-id': '19ac39db-81d2-4713-8046-b0b7240592be',
'return-client-request-id': 'true',
}
claim = base64.b64encode('<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"><DesktopSsoToken>{0}</DesktopSsoToken></saml:Assertion>'.format(dssotoken).encode('utf-8')).decode('utf-8')
data = {
'resource': self.resource_uri,
'client_id': self.client_id,
'grant_type': 'urn:ietf:params:oauth:grant-type:saml1_1-bearer',
'assertion': claim,
}
authority_uri = self.get_authority_url()
if additionaldata:
data = {**data, **additionaldata}
res = self.requests_post(f"{authority_uri}/oauth2/token", headers=headers, data=data)
if res.status_code != 200:
raise AuthenticationException(res.text)
tokenreply = res.json()
if returnreply:
return tokenreply
self.tokendata = self.tokenreply_to_tokendata(tokenreply)
return self.tokendata
def get_bulk_enrollment_token(self, access_token):
body = {
"pid": str(uuid.uuid4()),
"name": "bulktoken",
"exp": (datetime.datetime.now() + datetime.timedelta(days=90)).strftime('%Y-%m-%d %H:%M:%S')
}
headers = {
'Authorization': f'Bearer {access_token}'
}
url = 'https://login.microsoftonline.com/webapp/bulkaadjtoken/begin'
res = self.requests_post(url, json=body, headers=headers)
data = res.json()
state = data.get('state')
if not state:
print(f'No state returned. Server said: {data}')
return False
if state == 'CompleteError':
print(f'Error occurred: {data["resultData"]}')
return False
flowtoken = data.get('flowToken')
if not flowtoken:
print(f'Error. No flow token found. Data: {data}')
return False
print('Got flow token, polling for token creation')
url = 'https://login.microsoftonline.com/webapp/bulkaadjtoken/poll'
while True:
res = self.requests_get(url, params={'flowtoken':flowtoken}, headers=headers)
data = res.json()
state = data.get('state')
if not state:
print(f'No state returned. Server said: {data}')
return False
if state == 'CompleteError':
print(f'Error occurred: {data["resultData"]}')
return False
if state == 'CompleteSuccess':
tokenresult = json.loads(data['resultData'])
# The function below needs one so lets supply it
tokenresult['access_token'] = tokenresult['id_token']
self.tokendata = self.tokenreply_to_tokendata(tokenresult, client_id='b90d5b8f-5503-4153-b545-b31cecfaece2')
return self.tokendata
time.sleep(1.0)
def build_auth_url(self, redirurl, response_type, scope=None, state=None):
'''
Build authorize URL. Can be v2 by specifying scope, otherwise defaults
to v1 with resource
'''
urlt_v2 = 'https://login.microsoftonline.com/{3}/oauth2/v2.0/authorize?response_type={4}&client_id={0}&scope={2}&redirect_uri={1}&state={5}'
urlt_v1 = 'https://login.microsoftonline.com/{3}/oauth2/authorize?response_type={4}&client_id={0}&resource={2}&redirect_uri={1}&state={5}'
if not state:
state = str(uuid.uuid4())
if not self.tenant:
tenant = 'common'
else:
tenant = self.tenant
if scope:
# Add CAE support parameters
if self.use_cae:
urlt_v2 = urlt_v2 + '&claims={0}'.format(quote_plus('{"access_token":{"xms_cc":{"values":["cp1"]}}}'))
# v2
return urlt_v2.format(
quote_plus(self.client_id),
quote_plus(redirurl),
quote_plus(scope),
quote_plus(tenant),
quote_plus(response_type),
quote_plus(state)
)
# Else default to v1 identity endpoint
return urlt_v1.format(
quote_plus(self.client_id),
quote_plus(redirurl),
quote_plus(self.resource_uri),
quote_plus(tenant),
quote_plus(response_type),
quote_plus(state)
)
def create_prt_cookie_kdf_ver_2(self, prt, sessionkey, nonce=None):
"""
KDF version 2 cookie construction
"""
context = os.urandom(24)
headers = {
'ctx': base64.b64encode(context).decode('utf-8'), #.rstrip('=')
'kdf_ver': 2
}
# Nonce should be requested by calling function, otherwise
# old time based model is used
if nonce:
payload = {
"refresh_token": prt,
"is_primary": "true",
"request_nonce": nonce
}
else:
payload = {
"refresh_token": prt,
"is_primary": "true",
"iat": str(int(time.time()))
}
# Sign with random key just to get jwt body in right encoding
tempjwt = jwt.encode(payload, os.urandom(32), algorithm='HS256', headers=headers)
jbody = tempjwt.split('.')[1]
jwtbody = base64.b64decode(jbody+('='*(len(jbody)%4)))
# Now calculate the derived key based on random context plus jwt body
_, derived_key = self.calculate_derived_key_v2(sessionkey, context, jwtbody)
cookie = jwt.encode(payload, derived_key, algorithm='HS256', headers=headers)
return cookie
def authenticate_with_prt_v2(self, prt, sessionkey):
"""
KDF version 2 PRT auth
"""
nonce = self.get_prt_cookie_nonce()
if not nonce:
return False
cookie = self.create_prt_cookie_kdf_ver_2(prt, sessionkey, nonce)
return self.authenticate_with_prt_cookie(cookie)
def authenticate_with_prt(self, prt, context, derived_key=None, sessionkey=None):
"""
Authenticate with a PRT and given context/derived key
Uses KDF version 1 (legacy)
"""
# If raw key specified, use that
if not derived_key and sessionkey:
context, derived_key = self.calculate_derived_key(sessionkey, context)
headers = {
'ctx': base64.b64encode(context).decode('utf-8'),
}
nonce = self.get_prt_cookie_nonce()
if not nonce:
return False
payload = {
"refresh_token": prt,
"is_primary": "true",
"request_nonce": nonce
}
cookie = jwt.encode(payload, derived_key, algorithm='HS256', headers=headers)
return self.authenticate_with_prt_cookie(cookie)
def calculate_derived_key_v2(self, sessionkey, context, jwtbody):
"""
Derived key calculation v2, which uses the JWT body
"""
digest = hashes.Hash(hashes.SHA256())
digest.update(context)
digest.update(jwtbody)
kdfcontext = digest.finalize()
# From here on identical to v1
return self.calculate_derived_key(sessionkey, kdfcontext)
def calculate_derived_key(self, sessionkey, context=None):
"""
Calculate the derived key given a session key and optional context using KBKDFHMAC
"""
label = b"AzureAD-SecureConversation"
if not context:
context = os.urandom(24)
backend = default_backend()
kdf = KBKDFHMAC(
algorithm=hashes.SHA256(),
mode=Mode.CounterMode,
length=32,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=label,
context=context,
fixed=None,
backend=backend
)
derived_key = kdf.derive(sessionkey)
return context, derived_key
def decrypt_auth_response(self, responsedata, sessionkey, asjson=False):
"""
Decrypt an encrypted authentication response, which is a JWE
encrypted using the sessionkey
"""
if responsedata[:2] == '{"':
# This doesn't appear encrypted
if asjson:
return json.loads(responsedata)
return responsedata
# Encrypted Key doesn't appear to be used, instead the key is the decrypted ciphertext
#pylint: disable=unused-variable
headerdata, enckey, iv, ciphertext, authtag = responsedata.split('.')
headers = json.loads(get_data(headerdata))
_, derived_key = self.calculate_derived_key(sessionkey, base64.b64decode(headers['ctx']))
return self.decrypt_auth_response_derivedkey(headerdata, ciphertext, iv, authtag, derived_key, asjson)
def decrypt_auth_response_derivedkey(self, headerdata, ciphertext, iv, authtag, derived_key, asjson=False):
"""
Decrypt an encrypted authentication response, using the derived key
"""
if len(get_data(iv)) == 12:
# This appears to be actual AES GCM
aesgcm = AESGCM(derived_key)
# JWE header is used as additional data
# Totally legit source: https://github.com/AzureAD/microsoft-authentication-library-common-for-objc/compare/dev...kedicl/swift/addframework#diff-ec15357c1b0dba2f2304f64750e5126ec910156f09c0f75eba0bb22cb83ada6dR46
# Also hinted at in RFC examples https://www.rfc-editor.org/rfc/rfc7516.txt
depadded_data = aesgcm.decrypt(get_data(iv), get_data(ciphertext) + get_data(authtag), headerdata.encode('utf-8'))
else:
cipher = Cipher(algorithms.AES(derived_key), modes.CBC(get_data(iv)))
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(get_data(ciphertext)) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
depadded_data = unpadder.update(decrypted_data) + unpadder.finalize()
if asjson:
jdata = json.loads(depadded_data)
return jdata
else:
return depadded_data
def get_srv_challenge(self):
"""
Request server challenge (nonce) to use with a PRT
"""
data = {'grant_type':'srv_challenge'}
res = self.requests_post('https://login.microsoftonline.com/common/oauth2/token', data=data)
return res.json()
def get_prt_cookie_nonce(self):
"""
Request a nonce to sign in with. This nonce is taken from the sign-in page, which
is how Chrome processes it, but it could probably also be obtained using the much
simpler request from the get_srv_challenge function.
"""
ses = requests.session()
ses.proxies = self.proxies
ses.verify = self.verify
if self.user_agent:
headers = {'User-Agent': self.user_agent}
ses.headers = headers
params = {
'resource': self.resource_uri,
'client_id': self.client_id,
'response_type': 'code',
'haschrome': '1',
'redirect_uri': 'https://login.microsoftonline.com/common/oauth2/nativeclient',
'client-request-id': str(uuid.uuid4()),
'x-client-SKU': 'PCL.Desktop',
'x-client-Ver': '3.19.7.16602',