-
Notifications
You must be signed in to change notification settings - Fork 123
/
saml2.py
1140 lines (946 loc) · 43.7 KB
/
saml2.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
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
"""
A pysaml2 frontend module for the satosa proxy
"""
import copy
import functools
import json
import logging
import re
from base64 import urlsafe_b64decode
from base64 import urlsafe_b64encode
from urllib.parse import quote
from urllib.parse import quote_plus
from urllib.parse import unquote
from urllib.parse import unquote_plus
from urllib.parse import urlparse
from http.cookies import SimpleCookie
from saml2 import SAMLError, xmldsig
from saml2.config import IdPConfig
from saml2.extension.mdui import NAMESPACE as UI_NAMESPACE
from saml2.metadata import create_metadata_string
from saml2.saml import NameID
from saml2.saml import NAMEID_FORMAT_TRANSIENT
from saml2.saml import NAMEID_FORMAT_PERSISTENT
from saml2.saml import NAMEID_FORMAT_EMAILADDRESS
from saml2.saml import NAMEID_FORMAT_UNSPECIFIED
from saml2.samlp import name_id_policy_from_string
from saml2.server import Server
from satosa.base import SAMLBaseModule
from satosa.context import Context
from .base import FrontendModule
from ..response import Response
from ..response import ServiceError
from ..saml_util import make_saml_response
from satosa.exception import SATOSAError
import satosa.util as util
import satosa.logging_util as lu
from satosa.internal import InternalData
logger = logging.getLogger(__name__)
subject_type_map = {
NAMEID_FORMAT_TRANSIENT: NAMEID_FORMAT_TRANSIENT,
NAMEID_FORMAT_PERSISTENT: NAMEID_FORMAT_PERSISTENT,
NAMEID_FORMAT_EMAILADDRESS: NAMEID_FORMAT_EMAILADDRESS,
NAMEID_FORMAT_UNSPECIFIED: NAMEID_FORMAT_UNSPECIFIED,
"public": NAMEID_FORMAT_PERSISTENT,
"pairwise": NAMEID_FORMAT_TRANSIENT,
}
def subject_type_to_saml_nameid_format(subject_type):
return subject_type_map.get(subject_type, NAMEID_FORMAT_PERSISTENT)
class SAMLFrontend(FrontendModule, SAMLBaseModule):
"""
A pysaml2 frontend module
"""
KEY_CUSTOM_ATTR_RELEASE = 'custom_attribute_release'
KEY_ENDPOINTS = 'endpoints'
KEY_IDP_CONFIG = 'idp_config'
def __init__(self, auth_req_callback_func, internal_attributes, config, base_url, name):
self._validate_config(config)
super().__init__(auth_req_callback_func, internal_attributes, base_url, name)
self.config = self.init_config(config)
self.endpoints = config[self.KEY_ENDPOINTS]
self.custom_attribute_release = config.get(
self.KEY_CUSTOM_ATTR_RELEASE)
self.idp = None
def handle_authn_response(self, context, internal_response):
"""
See super class method satosa.frontends.base.FrontendModule#handle_authn_response
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype satosa.response.Response
"""
return self._handle_authn_response(context, internal_response, self.idp)
def handle_authn_request(self, context, binding_in):
"""
This method is bound to the starting endpoint of the authentication.
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The binding type (http post, http redirect, ...)
:return: response
"""
return self._handle_authn_request(context, binding_in, self.idp)
def handle_backend_error(self, exception):
"""
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAError
:rtype: satosa.response.Response
"""
return self._handle_backend_error(exception, self.idp)
def register_endpoints(self, backend_names):
"""
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
"""
self.idp_config = self._build_idp_config_endpoints(
self.config[self.KEY_IDP_CONFIG], backend_names)
# Create the idp
idp_config = IdPConfig().load(copy.deepcopy(self.idp_config))
self.idp = Server(config=idp_config)
return self._register_endpoints(backend_names)
def _create_state_data(self, context, resp_args, relay_state):
"""
Returns a dict containing the state needed in the response flow.
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
:param context: The current context
:param resp_args: Response arguments
:param relay_state: Request relay state
:return: A state as a dict
"""
if "name_id_policy" in resp_args and resp_args["name_id_policy"] is not None:
resp_args["name_id_policy"] = resp_args["name_id_policy"].to_string().decode("utf-8")
return {"resp_args": resp_args, "relay_state": relay_state}
def load_state(self, state):
"""
Loads a state from state
:type state: satosa.state.State
:rtype: dict[str, Any]
:param state: The current state
:return: The dictionary given by the save_state function
"""
state_data = state[self.name]
if isinstance(state_data["resp_args"]["name_id_policy"], str):
state_data["resp_args"]["name_id_policy"] = name_id_policy_from_string(
state_data["resp_args"]["name_id_policy"])
return state_data
def _validate_config(self, config):
"""
Validates some parts of the module config
:type config: dict[str, dict[str, Any] | str]
:param config: The module config
"""
required_keys = [
self.KEY_IDP_CONFIG,
self.KEY_ENDPOINTS,
]
if not config:
raise ValueError("No configuration given")
for key in required_keys:
try:
_val = config[key]
except KeyError as e:
raise ValueError("Missing configuration key: %s" % key) from e
def _handle_authn_request(self, context, binding_in, idp):
"""
See doc for handle_authn_request method.
:type context: satosa.context.Context
:type binding_in: str
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The pysaml binding type
:param idp: The saml frontend idp server
:return: response
"""
req_info = idp.parse_authn_request(context.request["SAMLRequest"], binding_in)
authn_req = req_info.message
msg = "{}".format(authn_req)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
# keep the ForceAuthn value to be used by plugins
context.decorate(Context.KEY_FORCE_AUTHN, authn_req.force_authn)
try:
resp_args = idp.response_args(authn_req)
except SAMLError as e:
msg = "Could not find necessary info about entity: {}".format(e)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.error(logline)
return ServiceError("Incorrect request from requester: %s" % e)
requester = resp_args["sp_entity_id"]
context.state[self.name] = self._create_state_data(context, idp.response_args(authn_req),
context.request.get("RelayState"))
subject = authn_req.subject
name_id_value = subject.name_id.text if subject else None
nameid_formats = {
"from_policy": authn_req.name_id_policy and authn_req.name_id_policy.format,
"from_response": subject and subject.name_id and subject.name_id.format,
"from_metadata": (
idp.metadata[requester]
.get("spsso_descriptor", [{}])[0]
.get("name_id_format", [{}])[0]
.get("text")
),
"default": NAMEID_FORMAT_TRANSIENT,
}
name_id_format = (
nameid_formats["from_policy"]
or (
nameid_formats["from_response"] != NAMEID_FORMAT_UNSPECIFIED
and nameid_formats["from_response"]
)
or nameid_formats["from_metadata"]
or nameid_formats["from_response"]
or nameid_formats["default"]
)
requester_name = self._get_sp_display_name(idp, requester)
internal_req = InternalData(
subject_id=name_id_value,
subject_type=name_id_format,
requester=requester,
requester_name=requester_name,
)
idp_policy = idp.config.getattr("policy", "idp")
if idp_policy:
internal_req.attributes = self._get_approved_attributes(
idp, idp_policy, requester, context.state
)
authn_context_class_ref_nodes = getattr(
authn_req.requested_authn_context, 'authn_context_class_ref', []
)
authn_context = [ref.text for ref in authn_context_class_ref_nodes]
context.decorate(Context.KEY_AUTHN_CONTEXT_CLASS_REF, authn_context)
context.decorate(Context.KEY_METADATA_STORE, self.idp.metadata)
return self.auth_req_callback_func(context, internal_req)
def _get_approved_attributes(self, idp, idp_policy, sp_entity_id, state):
"""
Returns a list of approved attributes
:type idp: saml.server.Server
:type idp_policy: saml2.assertion.Policy
:type sp_entity_id: str
:type state: satosa.state.State
:rtype: list[str]
:param idp: The saml frontend idp server
:param idp_policy: The idp policy
:param sp_entity_id: The requesting sp entity id
:param state: The current state
:return: A list containing approved attributes
"""
name_format = idp_policy.get_name_form(sp_entity_id)
attrconvs = idp.config.attribute_converters
idp_policy.acs = attrconvs
attribute_filter = []
for aconv in attrconvs:
if aconv.name_format == name_format:
all_attributes = {v: None for v in aconv._fro.values()}
attribute_filter = list(idp_policy.restrict(all_attributes, sp_entity_id, idp.metadata).keys())
break
attribute_filter = self.converter.to_internal_filter(self.attribute_profile, attribute_filter)
msg = "Filter: {}".format(attribute_filter)
logline = lu.LOG_FMT.format(id=lu.get_session_id(state), message=msg)
logger.debug(logline)
return attribute_filter
def _filter_attributes(self, idp, internal_response, context,):
idp_policy = idp.config.getattr("policy", "idp")
attributes = {}
if idp_policy:
approved_attributes = self._get_approved_attributes(
idp, idp_policy, internal_response.requester, context.state
)
attributes = {
k: v
for k, v in internal_response.attributes.items()
if k in approved_attributes
}
return attributes
def _handle_authn_response(self, context, internal_response, idp):
"""
See super class satosa.frontends.base.FrontendModule
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:type idp: saml.server.Server
:param context: The current context
:param internal_response: The internal response
:param idp: The saml frontend idp server
:return: A saml response
"""
request_state = self.load_state(context.state)
resp_args = request_state["resp_args"]
sp_entity_id = resp_args["sp_entity_id"]
internal_response.attributes = self._filter_attributes(
idp, internal_response, context)
ava = self.converter.from_internal(
self.attribute_profile, internal_response.attributes)
auth_info = {}
if self.acr_mapping:
auth_info["class_ref"] = self.acr_mapping.get(
internal_response.auth_info.issuer, self.acr_mapping[""])
else:
auth_info["class_ref"] = internal_response.auth_info.auth_class_ref
auth_info["authn_auth"] = internal_response.auth_info.issuer
if self.custom_attribute_release:
custom_release = util.get_dict_defaults(
self.custom_attribute_release,
internal_response.auth_info.issuer,
sp_entity_id)
attributes_to_remove = custom_release.get("exclude", [])
for k in attributes_to_remove:
ava.pop(k, None)
nameid_value = internal_response.subject_id
nameid_format = subject_type_to_saml_nameid_format(
internal_response.subject_type
)
# If the backend did not receive a SAML <NameID> and so
# name_id is set to None then do not create a NameID instance.
# Instead pass None as the name name_id to the IdP server
# instance and it will use its configured policy to construct
# a <NameID>, with the default to create a transient <NameID>.
name_id = None if not nameid_value else NameID(
text=nameid_value,
format=nameid_format,
sp_name_qualifier=None,
name_qualifier=None,
)
msg = "returning attributes {}".format(json.dumps(ava))
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
idp_conf = self.idp_config.get('service', {}).get('idp', {})
policies = idp_conf.get('policy', {})
sp_policy = policies.get('default', {})
sp_policy.update(policies.get(sp_entity_id, {}))
sign_assertion = sp_policy.get('sign_assertion', False)
sign_response = sp_policy.get('sign_response', True)
encrypt_assertion = sp_policy.get('encrypt_assertion', False)
encrypted_advice_attributes = sp_policy.get('encrypted_advice_attributes', False)
signing_algorithm = idp_conf.get('signing_algorithm')
digest_algorithm = idp_conf.get('digest_algorithm')
sign_alg_attr = sp_policy.get('sign_alg', 'SIG_RSA_SHA256')
digest_alg_attr = sp_policy.get('digest_alg', 'DIGEST_SHA256')
# Construct arguments for method create_authn_response
# on IdP Server instance
args = {
# Add the SP details
**resp_args,
# AuthnResponse data
'identity': ava,
'name_id': name_id,
'authn': auth_info,
'sign_response': sign_response,
'sign_assertion': sign_assertion,
'encrypt_assertion': encrypt_assertion,
'encrypted_advice_attributes': encrypted_advice_attributes,
}
args['sign_alg'] = signing_algorithm
if not args['sign_alg']:
try:
args['sign_alg'] = getattr(xmldsig, sign_alg_attr)
except AttributeError as e:
msg = "Unsupported sign algorithm {}".format(sign_alg)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.error(logline)
raise Exception(msg) from e
msg = "signing with algorithm {}".format(args['sign_alg'])
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
args['digest_alg'] = digest_algorithm
if not args['digest_alg']:
try:
args['digest_alg'] = getattr(xmldsig, digest_alg_attr)
except AttributeError as e:
msg = "Unsupported digest algorithm {}".format(digest_alg)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.error(logline)
raise Exception(msg) from e
msg = "using digest algorithm {}".format(args['digest_alg'])
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
if sign_alg_attr or digest_alg_attr:
msg = (
"sign_alg and digest_alg are deprecated; "
"instead, use signing_algorithm and digest_algorithm "
"under the service/idp configuration path "
"(not under policy/default)."
)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.warning(msg)
resp = idp.create_authn_response(**args)
http_args = idp.apply_binding(
resp_args["binding"], str(resp), resp_args["destination"],
request_state["relay_state"], response=True)
# Set the common domain cookie _saml_idp if so configured.
if self.config.get('common_domain_cookie'):
self._set_common_domain_cookie(internal_response, http_args, context)
del context.state[self.name]
return make_saml_response(resp_args["binding"], http_args)
def _handle_backend_error(self, exception, idp):
"""
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAAuthenticationError
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param exception: The SATOSAAuthenticationError
:param idp: The saml frontend idp server
:return: A response
"""
loaded_state = self.load_state(exception.state)
relay_state = loaded_state["relay_state"]
resp_args = loaded_state["resp_args"]
error_resp = idp.create_error_response(resp_args["in_response_to"],
resp_args["destination"],
Exception(exception.message))
http_args = idp.apply_binding(resp_args["binding"], str(error_resp), resp_args["destination"], relay_state,
response=True)
msg = "HTTPSards: {}".format(http_args)
logline = lu.LOG_FMT.format(id=lu.get_session_id(exception.state), message=msg)
logger.debug(logline)
return make_saml_response(resp_args["binding"], http_args)
def _metadata_endpoint(self, context):
"""
Endpoint for retrieving the backend metadata
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response with metadata
"""
msg = "Sending metadata response"
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
metadata_string = create_metadata_string(None, self.idp.config, 4, None, None, None, None,
None).decode("utf-8")
return Response(metadata_string, content="text/xml")
def _register_endpoints(self, providers):
"""
Register methods to endpoints
:type providers: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:param providers: A list of backend providers
:return: A list of endpoint/method pairs
"""
url_map = []
for endp_category in self.endpoints:
for binding, endp in self.endpoints[endp_category].items():
valid_providers = ""
for provider in providers:
valid_providers = "{}|^{}".format(valid_providers, provider)
valid_providers = valid_providers.lstrip("|")
parsed_endp = urlparse(endp)
url_map.append(("(%s)/%s$" % (valid_providers, parsed_endp.path),
functools.partial(self.handle_authn_request, binding_in=binding)))
if self.expose_entityid_endpoint():
parsed_entity_id = urlparse(self.idp.config.entityid)
url_map.append(("^{0}".format(parsed_entity_id.path[1:]),
self._metadata_endpoint))
return url_map
def _set_common_domain_cookie(self, internal_response, http_args, context):
"""
"""
# Find any existing common domain cookie and deconsruct it to
# obtain the list of IdPs.
cookie = SimpleCookie(context.cookie)
if '_saml_idp' in cookie:
common_domain_cookie = cookie['_saml_idp']
msg = "Found existing common domain cookie {}".format(common_domain_cookie)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
space_separated_b64_idp_string = unquote(common_domain_cookie.value)
b64_idp_list = space_separated_b64_idp_string.split()
idp_list = [urlsafe_b64decode(b64_idp).decode('utf-8') for b64_idp in b64_idp_list]
else:
msg = "No existing common domain cookie found"
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
idp_list = []
msg = "Common domain cookie list of IdPs is {}".format(idp_list)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
# Identity the current IdP just used for authentication in this flow.
this_flow_idp = internal_response.auth_info.issuer
# Remove all occurrences of the current IdP from the list of IdPs.
idp_list = [idp for idp in idp_list if idp != this_flow_idp]
# Append the current IdP.
idp_list.append(this_flow_idp)
msg = "Added IdP {} to common domain cookie list of IdPs".format(this_flow_idp)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
msg = "Common domain cookie list of IdPs is now {}".format(idp_list)
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
# Construct the cookie.
b64_idp_list = [urlsafe_b64encode(idp.encode()).decode("utf-8") for idp in idp_list]
space_separated_b64_idp_string = " ".join(b64_idp_list)
url_encoded_space_separated_b64_idp_string = quote(space_separated_b64_idp_string)
cookie = SimpleCookie()
cookie['_saml_idp'] = url_encoded_space_separated_b64_idp_string
cookie['_saml_idp']['path'] = '/'
# Use the domain from configuration if present else use the domain
# from the base URL for the front end.
domain = urlparse(self.base_url).netloc
if isinstance(self.config['common_domain_cookie'], dict):
if 'domain' in self.config['common_domain_cookie']:
domain = self.config['common_domain_cookie']['domain']
# Ensure that the domain begins with a '.'
if domain[0] != '.':
domain = '.' + domain
cookie['_saml_idp']['domain'] = domain
cookie['_saml_idp']['secure'] = True
# Set the cookie.
msg = "Setting common domain cookie with {}".format(cookie.output())
logline = lu.LOG_FMT.format(id=lu.get_session_id(context.state), message=msg)
logger.debug(logline)
http_args['headers'].append(tuple(cookie.output().split(": ", 1)))
def _build_idp_config_endpoints(self, config, providers):
"""
Builds the final frontend module config
:type config: dict[str, Any]
:type providers: list[str]
:rtype: dict[str, Any]
:param config: The module config
:param providers: A list of backend names
:return: The final config
"""
# Add an endpoint to each provider
idp_endpoints = []
for endp_category in self.endpoints:
for func, endpoint in self.endpoints[endp_category].items():
for provider in providers:
_endpoint = "{base}/{provider}/{endpoint}".format(
base=self.base_url, provider=provider, endpoint=endpoint)
idp_endpoints.append((_endpoint, func))
config["service"]["idp"]["endpoints"][endp_category] = idp_endpoints
return config
def _get_sp_display_name(self, idp, entity_id):
extensions = idp.metadata.extension(entity_id, "spsso_descriptor", "{}&UIInfo".format(UI_NAMESPACE))
if not extensions:
return None
try:
return extensions[0]["display_name"]
except (IndexError, KeyError) as e:
pass
return None
class SAMLMirrorFrontend(SAMLFrontend):
"""
Frontend module that uses dynamic entity id and partially dynamic endpoints.
"""
def _load_endpoints_to_config(self, provider, target_entity_id, config=None):
"""
Loads approved endpoints to the config.
:type url_base: str
:type provider: str
:type target_entity_id: str
:rtype: dict[str, Any]
:param url_base: The proxy base url
:param provider: target backend name
:param target_entity_id: frontend target entity id
:return: IDP config with endpoints
"""
idp_conf = copy.deepcopy(config or self.idp_config)
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{provider}/{target_id}/{path}".format(
base=self.base_url, provider=provider,
target_id=target_entity_id, path=path)
idp_endpoints.append((url, binding))
idp_conf["service"]["idp"]["endpoints"][service] = idp_endpoints
return idp_conf
def _load_idp_dynamic_endpoints(self, context):
"""
Loads an idp server that accepts the target backend name in the endpoint url
ex: /<backend_name>/sso/redirect
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
"""
target_entity_id = context.target_entity_id_from_path()
idp_conf_file = self._load_endpoints_to_config(context.target_backend, target_entity_id)
idp_config = IdPConfig().load(idp_conf_file)
return Server(config=idp_config)
def _load_idp_dynamic_entity_id(self, state):
"""
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
"""
# Change the idp entity id dynamically
idp_config_file = copy.deepcopy(self.idp_config)
idp_config_file["entityid"] = "{}/{}".format(self.idp_config["entityid"], state[self.name]["target_entity_id"])
idp_config = IdPConfig().load(idp_config_file)
return Server(config=idp_config)
def handle_authn_request(self, context, binding_in):
"""
Loads approved endpoints dynamically
See super class satosa.frontends.saml2.SAMLFrontend#handle_authn_request
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
"""
target_entity_id = context.target_entity_id_from_path()
target_entity_id = urlsafe_b64decode(target_entity_id).decode()
context.decorate(Context.KEY_TARGET_ENTITYID, target_entity_id)
idp = self._load_idp_dynamic_endpoints(context)
return self._handle_authn_request(context, binding_in, idp)
def _create_state_data(self, context, resp_args, relay_state):
"""
Adds the frontend idp entity id to state
See super class satosa.frontends.saml2.SAMLFrontend#save_state
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
"""
state = super()._create_state_data(context, resp_args, relay_state)
state["target_entity_id"] = context.target_entity_id_from_path()
return state
def handle_backend_error(self, exception):
"""
Loads the frontend entity id dynamically.
See super class satosa.frontends.saml2.SAMLFrontend#handle_backend_error
:type exception: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
"""
idp = self._load_idp_dynamic_entity_id(exception.state)
return self._handle_backend_error(exception, idp)
def handle_authn_response(self, context, internal_response):
"""
See super class satosa.frontends.base.FrontendModule#handle_authn_response
:param context:
:param internal_response:
:return:
"""
idp = self._load_idp_dynamic_entity_id(context.state)
return self._handle_authn_response(context, internal_response, idp)
def _register_endpoints(self, providers):
"""
See super class satosa.frontends.base.FrontendModule#register_endpoints
:type providers: list[str]
:rtype list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))] |
list[(str, (satosa.context.Context) -> satosa.response.Response)]
:param providers: A list with backend names
:return: A list of url and endpoint function pairs
"""
url_map = []
for endp_category in self.endpoints:
for binding, endp in self.endpoints[endp_category].items():
valid_providers = "|^".join(providers)
parsed_endp = urlparse(endp)
url_map.append(
(
r"(^{})/\S+/{}".format(valid_providers, parsed_endp.path),
functools.partial(self.handle_authn_request, binding_in=binding)
)
)
return url_map
class SAMLVirtualCoFrontend(SAMLFrontend):
"""
Frontend module that exposes multiple virtual SAML identity providers,
each representing a collaborative organization or CO.
"""
KEY_CO = 'collaborative_organizations'
KEY_CO_NAME = 'co_name'
KEY_CO_ENTITY_ID = 'co_entity_id'
KEY_CO_ATTRIBUTES = 'co_static_saml_attributes'
KEY_CO_ATTRIBUTE_SCOPE = 'co_attribute_scope'
KEY_CONTACT_PERSON = 'contact_person'
KEY_ENCODEABLE_NAME = 'encodeable_name'
KEY_ORGANIZATION = 'organization'
KEY_ORGANIZATION_KEYS = ['display_name', 'name', 'url']
def handle_authn_request(self, context, binding_in):
"""
See super class
satosa.frontends.saml2.SAMLFrontend#handle_authn_request
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
"""
# Using the context of the current request dynamically create an
# IdP instance and then use it to handle the authentication request.
idp = self._create_co_virtual_idp(context)
return self._handle_authn_request(context, binding_in, idp)
def handle_authn_response(self, context, internal_response):
"""
See super class satosa.frontends.base.
FrontendModule#handle_authn_response
:param context:
:param internal_response:
:return:
"""
return self._handle_authn_response(context, internal_response)
def _handle_authn_response(self, context, internal_response):
"""
"""
# Using the context of the current request and saved state from the
# authentication request dynamically create an IdP instance.
idp = self._create_co_virtual_idp(context)
# Add any static attributes for the CO.
co_config = self._get_co_config(context)
if self.KEY_CO_ATTRIBUTES in co_config:
attributes = internal_response.attributes
for attribute, value in co_config[self.KEY_CO_ATTRIBUTES].items():
# XXX This should be refactored when Python 3.4 support is
# XXX no longer required to use isinstance(value, Iterable).
try:
if iter(value) and not isinstance(value, str):
attributes[attribute] = value
else:
attributes[attribute] = [value]
except TypeError:
attributes[attribute] = [value]
# Handle the authentication response.
return super()._handle_authn_response(context, internal_response, idp)
def _create_state_data(self, context, resp_args, relay_state):
"""
Adds the CO name to state
See super class satosa.frontends.saml2.SAMLFrontend#save_state
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
"""
state = super()._create_state_data(context, resp_args, relay_state)
state[self.KEY_CO_NAME] = context.get_decoration(self.KEY_CO_NAME)
state[self.KEY_CO_ENTITY_ID] = context.get_decoration(
self.KEY_CO_ENTITY_ID)
co_config = self._get_co_config(context)
state[self.KEY_CO_ATTRIBUTE_SCOPE] = co_config.get(
self.KEY_CO_ATTRIBUTE_SCOPE,
None)
return state
def _get_co_config(self, context):
"""
Obtain the configuration for the CO.
:type context: The current context
:rtype: dict
:param context: The current context
:return: CO configuration
"""
co_name = self._get_co_name(context)
for co in self.config[self.KEY_CO]:
if co[self.KEY_ENCODEABLE_NAME] == co_name:
return co
def _get_co_name_from_path(self, context):
"""
The CO name is URL encoded and obtained from the request path
for a request coming into one of the standard binding endpoints.
For example the HTTP-Redirect binding request path will have the
format
{base}/{backend}/{co_name}/sso/redirect
:type context: satosa.context.Context
:rtype: str
:param context:
"""
url_encoded_co_name = context.path.split("/")[1]
co_name = unquote_plus(url_encoded_co_name)
return co_name
def _get_co_name(self, context):
"""
Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The current context
:return: CO name
"""
try:
co_name = context.state[self.name][self.KEY_CO_NAME]
logline = "Found CO {} from state".format(co_name)
logger.debug(logline)
except KeyError:
co_name = self._get_co_name_from_path(context)
logline = "Found CO {} from request path".format(co_name)
logger.debug(logline)
return co_name
def _add_endpoints_to_config(self, config, co_name, backend_name):
"""
Use the request path from the context to determine the target backend,
then construct mappings from bindings to endpoints for the virtual
IdP for the CO.
The endpoint URLs have the form
{base}/{backend}/{co_name}/{path}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:type backend_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:param backend_name: The target backend name
:return: config with mappings for CO IdP
"""
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{backend}/{co_name}/{path}".format(
base=self.base_url,
backend=backend_name,
co_name=quote_plus(co_name),
path=path)
mapping = (url, binding)
idp_endpoints.append(mapping)
# Overwrite the IdP config with the CO specific mappings between
# SAML binding and URL endpoints.
config["service"]["idp"]["endpoints"][service] = idp_endpoints
return config
def _add_entity_id(self, config, co_name):
"""
Use the CO name to construct the entity ID for the virtual IdP
for the CO and add it to the config. Also add it to the
context.
The entity ID has the form
{base_entity_id}/{co_name}
:type context: The current context
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param context:
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated entity ID
"""
base_entity_id = config['entityid']
co_entity_id = "{}/{}".format(base_entity_id, quote_plus(co_name))
config['entityid'] = co_entity_id
return config
def _overlay_for_saml_metadata(self, config, co_name):
"""
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
"""
all_co_configs = self.config[self.KEY_CO]
co_config = next(
item for item in all_co_configs
if item[self.KEY_ENCODEABLE_NAME] == co_name
)
key = self.KEY_ORGANIZATION
if key in co_config:
if key not in config:
config[key] = {}
for org_key in self.KEY_ORGANIZATION_KEYS:
if org_key in co_config[key]:
config[key][org_key] = co_config[key][org_key]
key = self.KEY_CONTACT_PERSON