This repository has been archived by the owner on Jun 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
authorization.py
executable file
·718 lines (610 loc) · 25.5 KB
/
authorization.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
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
import json
import logging
from cryptojwt import BadSyntax
from cryptojwt.jwe.exception import JWEException
from cryptojwt.jws.exception import NoSuitableSigningKeys
from cryptojwt.jwt import utc_time_sans_frac
from cryptojwt.utils import as_bytes
from cryptojwt.utils import as_unicode
from cryptojwt.utils import b64d
from cryptojwt.utils import b64e
from oidcmsg import oidc
from oidcmsg.exception import ParameterError
from oidcmsg.oauth2 import AuthorizationErrorResponse
from oidcmsg.oauth2 import AuthorizationRequest
from oidcmsg.oidc import AuthorizationResponse
from oidcmsg.oidc import Claims
from oidcmsg.oidc import verified_claim_name
from oidcendpoint import rndstr
from oidcendpoint import sanitize
from oidcendpoint.authn_event import create_authn_event
from oidcendpoint.common.authorization import FORM_POST
from oidcendpoint.common.authorization import AllowedAlgorithms
from oidcendpoint.common.authorization import authn_args_gather
from oidcendpoint.common.authorization import get_uri
from oidcendpoint.common.authorization import inputs
from oidcendpoint.common.authorization import max_age
from oidcendpoint.cookie import append_cookie
from oidcendpoint.cookie import compute_session_state
from oidcendpoint.cookie import new_cookie
from oidcendpoint.endpoint import Endpoint
from oidcendpoint.exception import InvalidRequest
from oidcendpoint.exception import NoSuchAuthentication
from oidcendpoint.exception import RedirectURIError
from oidcendpoint.exception import ServiceError
from oidcendpoint.exception import TamperAllert
from oidcendpoint.exception import ToOld
from oidcendpoint.exception import UnknownClient
from oidcendpoint.session import setup_session
from oidcendpoint.user_authn.authn_context import pick_auth
logger = logging.getLogger(__name__)
def create_authn_response(endpoint, request, sid):
"""
:param endpoint:
:param request:
:param sid:
:return:
"""
# create the response
aresp = AuthorizationResponse()
if request.get("state"):
aresp["state"] = request["state"]
if "response_type" in request and request["response_type"] == ["none"]:
fragment_enc = False
else:
_context = endpoint.endpoint_context
_sinfo = _context.sdb[sid]
if request.get("scope"):
aresp["scope"] = request["scope"]
rtype = set(request["response_type"][:])
handled_response_type = []
fragment_enc = True
if len(rtype) == 1 and "code" in rtype:
fragment_enc = False
if "code" in request["response_type"]:
_code = aresp["code"] = _context.sdb[sid]["code"]
handled_response_type.append("code")
else:
_context.sdb.update(sid, code=None)
_code = None
if "token" in rtype:
_dic = _context.sdb.upgrade_to_token(issue_refresh=False, key=sid)
logger.debug("_dic: %s" % sanitize(_dic))
for key, val in _dic.items():
if key in aresp.parameters() and val is not None:
aresp[key] = val
handled_response_type.append("token")
_access_token = aresp.get("access_token", None)
if "id_token" in request["response_type"]:
kwargs = {}
if {"code", "id_token", "token"}.issubset(rtype):
kwargs = {"code": _code, "access_token": _access_token}
elif {"code", "id_token"}.issubset(rtype):
kwargs = {"code": _code}
elif {"id_token", "token"}.issubset(rtype):
kwargs = {"access_token": _access_token}
if request["response_type"] == ["id_token"]:
kwargs["user_claims"] = True
try:
id_token = _context.idtoken.make(request, _sinfo, **kwargs)
except (JWEException, NoSuitableSigningKeys) as err:
logger.warning(str(err))
resp = AuthorizationErrorResponse(
error="invalid_request",
error_description="Could not sign/encrypt id_token",
)
return {"response_args": resp, "fragment_enc": fragment_enc}
aresp["id_token"] = id_token
_sinfo["id_token"] = id_token
handled_response_type.append("id_token")
not_handled = rtype.difference(handled_response_type)
if not_handled:
resp = AuthorizationErrorResponse(
error="invalid_request", error_description="unsupported_response_type"
)
return {"response_args": resp, "fragment_enc": fragment_enc}
return {"response_args": aresp, "fragment_enc": fragment_enc}
def proposed_user(request):
cn = verified_claim_name("it_token_hint")
if request.get(cn):
return request[cn].get("sub", "")
return ""
def acr_claims(request):
acrdef = None
_claims = request.get("claims")
if isinstance(_claims, str):
_claims = Claims().from_json(_claims)
if _claims:
_id_token_claim = _claims.get("id_token")
if _id_token_claim:
acrdef = _id_token_claim.get("acr")
if isinstance(acrdef, dict):
if acrdef.get("value"):
return [acrdef["value"]]
elif acrdef.get("values"):
return acrdef["values"]
ALG_PARAMS = {
"sign": [
"request_object_signing_alg",
"request_object_signing_alg_values_supported",
],
"enc_alg": [
"request_object_encryption_alg",
"request_object_encryption_alg_values_supported",
],
"enc_enc": [
"request_object_encryption_enc",
"request_object_encryption_enc_values_supported",
],
}
def re_authenticate(request, authn):
if "prompt" in request and "login" in request["prompt"]:
if authn.done(request):
return True
return False
class Authorization(Endpoint):
request_cls = oidc.AuthorizationRequest
response_cls = oidc.AuthorizationResponse
request_format = "urlencoded"
response_format = "urlencoded"
response_placement = "url"
endpoint_name = "authorization_endpoint"
name = "authorization"
default_capabilities = {
"claims_parameter_supported": True,
"request_parameter_supported": True,
"request_uri_parameter_supported": True,
"response_types_supported": [
"code",
"token",
"id_token",
"code token",
"code id_token",
"id_token token",
"code id_token token",
],
"response_modes_supported": ["query", "fragment", "form_post"],
"request_object_signing_alg_values_supported": None,
"request_object_encryption_alg_values_supported": None,
"request_object_encryption_enc_values_supported": None,
"grant_types_supported": ["authorization_code", "implicit"],
"claim_types_supported": ["normal", "aggregated", "distributed"],
}
def __init__(self, endpoint_context, **kwargs):
Endpoint.__init__(self, endpoint_context, **kwargs)
# self.pre_construct.append(self._pre_construct)
self.post_parse_request.append(self._do_request_uri)
self.post_parse_request.append(self._post_parse_request)
self.allowed_request_algorithms = AllowedAlgorithms(ALG_PARAMS)
def filter_request(self, endpoint_context, req):
return req
def verify_response_type(self, request, cinfo):
# Checking response types
_registered = [set(rt.split(" ")) for rt in cinfo.get("response_types", [])]
if not _registered:
# If no response_type is registered by the client then we'll
# code which it the default according to the OIDC spec.
_registered = [{"code"}]
# Is the asked for response_type among those that are permitted
return set(request["response_type"]) in _registered
def _do_request_uri(self, request, client_id, endpoint_context, **kwargs):
_request_uri = request.get("request_uri")
if _request_uri:
# Do I do pushed authorization requests ?
if "pushed_authorization" in endpoint_context.endpoint:
# Is it a UUID urn
if _request_uri.startswith("urn:uuid:"):
_req = endpoint_context.par_db.get(_request_uri)
if _req:
del endpoint_context.par_db[_request_uri] # One time
# usage
return _req
else:
raise ValueError("Got a request_uri I can not resolve")
# Do I support request_uri ?
_supported = endpoint_context.provider_info.get(
"request_uri_parameter_supported", True
)
_registered = endpoint_context.cdb[client_id].get("request_uris")
# Not registered should be handled else where
if _registered:
# Before matching remove a possible fragment
_p = _request_uri.split("#")
# ignore registered fragments for now.
if _p[0] not in [l[0] for l in _registered]:
raise ValueError("A request_uri outside the registered")
# Fetch the request
_resp = endpoint_context.httpc.get(
_request_uri, **endpoint_context.httpc_params
)
if _resp.status_code == 200:
args = {"keyjar": endpoint_context.keyjar, "issuer": client_id}
_ver_request = AuthorizationRequest().from_jwt(_resp.text, **args)
self.allowed_request_algorithms(
client_id,
endpoint_context,
_ver_request.jws_header.get("alg", "RS256"),
"sign",
)
if _ver_request.jwe_header is not None:
self.allowed_request_algorithms(
client_id,
endpoint_context,
_ver_request.jws_header.get("alg"),
"enc_alg",
)
self.allowed_request_algorithms(
client_id,
endpoint_context,
_ver_request.jws_header.get("enc"),
"enc_enc",
)
# The protected info overwrites the non-protected
for k, v in _ver_request.items():
request[k] = v
request[verified_claim_name("request")] = _ver_request
else:
raise ServiceError("Got a %s response", _resp.status)
return request
def _post_parse_request(self, request, client_id, endpoint_context, **kwargs):
"""
Verify the authorization request.
:param endpoint_context:
:param request:
:param client_id:
:param kwargs:
:return:
"""
if not request:
logger.debug("No AuthzRequest")
return AuthorizationErrorResponse(
error="invalid_request", error_description="Can not parse AuthzRequest"
)
request = self.filter_request(endpoint_context, request)
_cinfo = endpoint_context.cdb.get(client_id)
if not _cinfo:
logger.error(
"Client ID ({}) not in client database".format(request["client_id"])
)
return AuthorizationErrorResponse(
error="unauthorized_client", error_description="unknown client"
)
# Is the asked for response_type among those that are permitted
if not self.verify_response_type(request, _cinfo):
return AuthorizationErrorResponse(
error="invalid_request",
error_description="Trying to use unregistered response_type",
)
# Get a verified redirect URI
try:
redirect_uri = get_uri(endpoint_context, request, "redirect_uri")
except (RedirectURIError, ParameterError, UnknownClient) as err:
return AuthorizationErrorResponse(
error="invalid_request",
error_description="{}:{}".format(err.__class__.__name__, err),
)
else:
request["redirect_uri"] = redirect_uri
return request
def pick_authn_method(self, request, redirect_uri, acr=None, **kwargs):
auth_id = kwargs.get("auth_method_id")
if auth_id:
return self.endpoint_context.authn_broker[auth_id]
if acr:
res = self.endpoint_context.authn_broker.pick(acr)
else:
res = pick_auth(self.endpoint_context, request)
if res:
return res
else:
return {
"error": "access_denied",
"error_description": "ACR I do not support",
"return_uri": redirect_uri,
"return_type": request["response_type"],
}
def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
"""
:param request: The authorization/authentication request
:param redirect_uri:
:param cinfo: client info
:param cookie:
:param acr: Default ACR, if nothing else is specified
:param kwargs:
:return:
"""
res = self.pick_authn_method(request, redirect_uri, acr, **kwargs)
authn = res["method"]
authn_class_ref = res["acr"]
session = None
try:
_auth_info = kwargs.get("authn", "")
if "upm_answer" in request and request["upm_answer"] == "true":
_max_age = 0
else:
_max_age = max_age(request)
identity, _ts = authn.authenticated_as(
cookie, authorization=_auth_info, max_age=_max_age
)
except (NoSuchAuthentication, TamperAllert):
identity = None
_ts = 0
except ToOld:
logger.info("Too old authentication")
identity = None
_ts = 0
else:
if identity:
try: # If identity['uid'] is in fact a base64 encoded JSON string
_id = b64d(as_bytes(identity["uid"]))
except BadSyntax:
pass
else:
identity = json.loads(as_unicode(_id))
session = self.endpoint_context.sdb[identity.get("sid")]
if not session or "revoked" in session:
identity = None
authn_args = authn_args_gather(request, authn_class_ref, cinfo, **kwargs)
# To authenticate or Not
if identity is None: # No!
logger.info("No active authentication")
logger.debug(
"Known clients: {}".format(list(self.endpoint_context.cdb.keys()))
)
if "prompt" in request and "none" in request["prompt"]:
# Need to authenticate but not allowed
return {
"error": "login_required",
"return_uri": redirect_uri,
"return_type": request["response_type"],
}
else:
return {"function": authn, "args": authn_args}
else:
logger.info("Active authentication")
if re_authenticate(request, authn):
# demand re-authentication
return {"function": authn, "args": authn_args}
else:
# I get back a dictionary
user = identity["uid"]
if "req_user" in kwargs:
sids = self.endpoint_context.sdb.get_sids_by_sub(kwargs["req_user"])
if (
sids
and user
!= self.endpoint_context.sdb.get_authentication_event(
sids[-1]
).uid
):
logger.debug("Wanted to be someone else!")
if "prompt" in request and "none" in request["prompt"]:
# Need to authenticate but not allowed
return {
"error": "login_required",
"return_uri": redirect_uri,
}
else:
return {"function": authn, "args": authn_args}
authn_event = None
if session:
authn_event = session.get('authn_event')
if authn_event is None:
authn_event = create_authn_event(
identity["uid"],
identity.get("salt", ""),
authn_info=authn_class_ref,
time_stamp=_ts,
)
_exp_in = authn.kwargs.get("expires_in")
if _exp_in and "valid_until" in authn_event:
authn_event["valid_until"] = utc_time_sans_frac() + _exp_in
return {"authn_event": authn_event, "identity": identity, "user": user}
def aresp_check(self, aresp, request):
return ""
def response_mode(self, request, **kwargs):
resp_mode = request["response_mode"]
if resp_mode == "form_post":
msg = FORM_POST.format(
inputs=inputs(kwargs["response_args"].to_dict()),
action=kwargs["return_uri"],
)
kwargs.update(
{
"response_msg": msg,
"content_type": "text/html",
"response_placement": "body",
}
)
elif resp_mode == "fragment":
if "fragment_enc" in kwargs:
if not kwargs["fragment_enc"]:
# Can't be done
raise InvalidRequest("wrong response_mode")
else:
kwargs["fragment_enc"] = True
elif resp_mode == "query":
if "fragment_enc" in kwargs:
if kwargs["fragment_enc"]:
# Can't be done
raise InvalidRequest("wrong response_mode")
else:
raise InvalidRequest("Unknown response_mode")
return kwargs
def error_response(self, response_info, error, error_description):
resp = AuthorizationErrorResponse(
error=error, error_description=str(error_description)
)
response_info["response_args"] = resp
return response_info
def post_authentication(self, user, request, sid, **kwargs):
"""
Things that are done after a successful authentication.
:param user:
:param request:
:param sid:
:param kwargs:
:return: A dictionary with 'response_args'
"""
response_info = {}
# Do the authorization
try:
permission = self.endpoint_context.authz(
user, client_id=request["client_id"]
)
except ToOld as err:
return self.error_response(
response_info,
"access_denied",
"Authentication to old {}".format(err.args),
)
except Exception as err:
return self.error_response(
response_info, "access_denied", "{}".format(err.args)
)
else:
try:
self.endpoint_context.sdb.update(sid, permission=permission)
except Exception as err:
return self.error_response(
response_info, "server_error", "{}".format(err.args)
)
logger.debug("response type: %s" % request["response_type"])
if self.endpoint_context.sdb.is_session_revoked(sid):
return self.error_response(
response_info, "access_denied", "Session is revoked"
)
response_info = create_authn_response(self, request, sid)
logger.debug("Known clients: {}".format(list(self.endpoint_context.cdb.keys())))
try:
redirect_uri = get_uri(self.endpoint_context, request, "redirect_uri")
except (RedirectURIError, ParameterError) as err:
return self.error_response(
response_info, "invalid_request", "{}".format(err.args)
)
else:
response_info["return_uri"] = redirect_uri
# Must not use HTTP unless implicit grant type and native application
# info = self.aresp_check(response_info['response_args'], request)
# if isinstance(info, ResponseMessage):
# return info
_cookie = new_cookie(
self.endpoint_context,
uid=user,
sid=sid,
state=request["state"],
client_id=request["client_id"],
cookie_name=self.endpoint_context.cookie_name["session"],
)
# Now about the response_mode. Should not be set if it's obvious
# from the response_type. Knows about 'query', 'fragment' and
# 'form_post'.
if "response_mode" in request:
try:
response_info = self.response_mode(request, **response_info)
except InvalidRequest as err:
return self.error_response(
response_info, "invalid_request", "{}".format(err.args)
)
response_info["cookie"] = [_cookie]
return response_info
def authz_part2(self, user, authn_event, request, **kwargs):
"""
After the authentication this is where you should end up
:param user:
:param request: The Authorization Request
:param sid: Session key
:param kwargs: possible other parameters
:return: A redirect to the redirect_uri of the client
"""
sid = setup_session(
self.endpoint_context, request, user, authn_event=authn_event
)
try:
resp_info = self.post_authentication(user, request, sid, **kwargs)
except Exception as err:
return self.error_response({}, "server_error", err)
if "check_session_iframe" in self.endpoint_context.provider_info:
ec = self.endpoint_context
salt = rndstr()
if not ec.sdb.is_session_revoked(sid):
authn_event = ec.sdb.get_authentication_event(
sid
) # use the last session
_state = b64e(
as_bytes(json.dumps({"authn_time": authn_event["authn_time"]}))
)
session_cookie = ec.cookie_dealer.create_cookie(
as_unicode(_state),
typ="session",
cookie_name=ec.cookie_name["session_management"],
same_site="None",
http_only=False,
)
opbs = session_cookie[ec.cookie_name["session_management"]]
logger.debug(
"compute_session_state: client_id=%s, origin=%s, opbs=%s, salt=%s",
request["client_id"],
resp_info["return_uri"],
opbs.value,
salt,
)
_session_state = compute_session_state(
opbs.value, salt, request["client_id"], resp_info["return_uri"]
)
if "cookie" in resp_info:
if isinstance(resp_info["cookie"], list):
resp_info["cookie"].append(session_cookie)
else:
append_cookie(resp_info["cookie"], session_cookie)
else:
resp_info["cookie"] = session_cookie
resp_info["response_args"]["session_state"] = _session_state
# Mix-Up mitigation
resp_info["response_args"]["iss"] = self.endpoint_context.issuer
resp_info["response_args"]["client_id"] = request["client_id"]
return resp_info
def process_request(self, request_info=None, **kwargs):
""" The AuthorizationRequest endpoint
:param request_info: The authorization request as a dictionary
:return: dictionary
"""
if isinstance(request_info, AuthorizationErrorResponse):
return request_info
_cid = request_info["client_id"]
cinfo = self.endpoint_context.cdb[_cid]
logger.debug("client {}: {}".format(_cid, cinfo))
cookie = kwargs.get("cookie", "")
if cookie:
del kwargs["cookie"]
if proposed_user(request_info):
kwargs["req_user"] = proposed_user(request_info)
else:
if request_info.get("login_hint"):
_login_hint = request_info["login_hint"]
if self.endpoint_context.login_hint_lookup:
kwargs["req_user"] = self.endpoint_context.login_hint_lookup[
_login_hint
]
info = self.setup_auth(
request_info, request_info["redirect_uri"], cinfo, cookie, **kwargs
)
if "error" in info:
return info
_function = info.get("function")
if not _function:
logger.debug("- authenticated -")
logger.debug("AREQ keys: %s" % request_info.keys())
res = self.authz_part2(
info["user"], info["authn_event"], request_info, cookie=cookie
)
return res
try:
# Run the authentication function
return {
"http_response": _function(**info["args"]),
"return_uri": request_info["redirect_uri"],
}
except Exception as err:
logger.exception(err)
return {"http_response": "Internal error: {}".format(err)}