-
Notifications
You must be signed in to change notification settings - Fork 426
/
Copy pathmdstore.py
1766 lines (1490 loc) · 59 KB
/
mdstore.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
import hashlib
from hashlib import sha1
import importlib
from itertools import chain
import json
import logging
import os
from os.path import isfile
from os.path import join
from re import compile as regex_compile
import sys
from warnings import warn as _warn
import requests
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import BINDING_SOAP
from saml2 import SAMLError
from saml2 import md
from saml2 import saml
from saml2 import samlp
from saml2 import xmldsig
from saml2 import xmlenc
from saml2.extension.algsupport import NAMESPACE as NS_ALGSUPPORT
from saml2.extension.algsupport import DigestMethod
from saml2.extension.algsupport import SigningMethod
from saml2.extension.idpdisc import BINDING_DISCO
from saml2.extension.idpdisc import DiscoveryResponse
from saml2.extension.mdattr import NAMESPACE as NS_MDATTR
from saml2.extension.mdattr import EntityAttributes
from saml2.extension.mdrpi import NAMESPACE as NS_MDRPI
from saml2.extension.mdrpi import RegistrationInfo
from saml2.extension.mdrpi import RegistrationPolicy
from saml2.extension.mdui import NAMESPACE as NS_MDUI
from saml2.extension.mdui import Description
from saml2.extension.mdui import DisplayName
from saml2.extension.mdui import InformationURL
from saml2.extension.mdui import Logo
from saml2.extension.mdui import PrivacyStatementURL
from saml2.extension.mdui import UIInfo
from saml2.extension.shibmd import NAMESPACE as NS_SHIBMD
from saml2.extension.shibmd import Scope
from saml2.httpbase import HTTPBase
from saml2.md import NAMESPACE as NS_MD
from saml2.md import ArtifactResolutionService
from saml2.md import EntitiesDescriptor
from saml2.md import EntityDescriptor
from saml2.md import NameIDMappingService
from saml2.md import SingleSignOnService
from saml2.mdie import to_dict
from saml2.s_utils import UnknownSystemEntity
from saml2.s_utils import UnsupportedBinding
from saml2.sigver import SignatureError
from saml2.sigver import security_context
from saml2.sigver import split_len
from saml2.time_util import add_duration
from saml2.time_util import before
from saml2.time_util import instant
from saml2.time_util import str_to_time
from saml2.time_util import valid
from saml2.validate import NotValid
from saml2.validate import valid_instance
logger = logging.getLogger(__name__)
classnames = {
"mdattr_entityattributes": f"{NS_MDATTR}&{EntityAttributes.c_tag}",
"algsupport_signing_method": f"{NS_ALGSUPPORT}&{SigningMethod.c_tag}",
"algsupport_digest_method": f"{NS_ALGSUPPORT}&{DigestMethod.c_tag}",
"mdui_uiinfo": f"{NS_MDUI}&{UIInfo.c_tag}",
"mdui_uiinfo_display_name": f"{NS_MDUI}&{DisplayName.c_tag}",
"mdui_uiinfo_description": f"{NS_MDUI}&{Description.c_tag}",
"mdui_uiinfo_information_url": f"{NS_MDUI}&{InformationURL.c_tag}",
"mdui_uiinfo_privacy_statement_url": f"{NS_MDUI}&{PrivacyStatementURL.c_tag}",
"mdui_uiinfo_logo": f"{NS_MDUI}&{Logo.c_tag}",
"service_artifact_resolution": f"{NS_MD}&{ArtifactResolutionService.c_tag}",
"service_single_sign_on": f"{NS_MD}&{SingleSignOnService.c_tag}",
"service_nameid_mapping": f"{NS_MD}&{NameIDMappingService.c_tag}",
"mdrpi_registration_info": f"{NS_MDRPI}&{RegistrationInfo.c_tag}",
"mdrpi_registration_policy": f"{NS_MDRPI}&{RegistrationPolicy.c_tag}",
"shibmd_scope": f"{NS_SHIBMD}&{Scope.c_tag}",
}
ENTITY_CATEGORY = "http://macedir.org/entity-category"
ENTITY_CATEGORY_SUPPORT = "http://macedir.org/entity-category-support"
ASSURANCE_CERTIFICATION = "urn:oasis:names:tc:SAML:attribute:assurance-certification"
SAML_METADATA_CONTENT_TYPE = "application/samlmetadata+xml"
DEFAULT_FRESHNESS_PERIOD = "P0Y0M0DT12H0M0S"
REQ2SRV = {
# IDP
"authn_request": "single_sign_on_service",
"name_id_mapping_request": "name_id_mapping_service",
# AuthnAuthority
"authn_query": "authn_query_service",
# AttributeAuthority
"attribute_query": "attribute_service",
# PDP
"authz_decision_query": "authz_service",
# AuthnAuthority + IDP + PDP + AttributeAuthority
"assertion_id_request": "assertion_id_request_service",
# IDP + SP
"logout_request": "single_logout_service",
"manage_name_id_request": "manage_name_id_service",
"artifact_query": "artifact_resolution_service",
# SP
"assertion_response": "assertion_consumer_service",
"attribute_response": "attribute_consuming_service",
"discovery_service_request": "discovery_response",
}
class ToOld(Exception):
pass
class TooOld(ToOld):
pass
class SourceNotFound(Exception):
pass
def load_extensions():
import pkgutil
from saml2 import extension
package = extension
prefix = f"{package.__name__}."
ext_map = {}
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
module = __import__(modname, fromlist="dummy")
ext_map[module.NAMESPACE] = module
return ext_map
def load_metadata_modules():
mods = {saml.NAMESPACE: saml, md.NAMESPACE: md, xmldsig.NAMESPACE: xmldsig, xmlenc.NAMESPACE: xmlenc}
mods.update(load_extensions())
return mods
def metadata_modules():
_res = [saml, md, xmldsig, xmlenc]
_res.extend(list(load_extensions().values()))
return _res
def response_locations(srvs):
"""
Return the ResponseLocation attributes mapped to the services.
ArtifactResolutionService, SingleSignOnService and NameIDMappingService MUST omit
the ResponseLocation attribute. This is enforced here, but metadata with such
service declarations and such attributes should not have been part of the metadata
store in the first place.
"""
values = (
s["response_location"]
for s in srvs
if "response_location" in s
if s["__class__"]
not in [
classnames["service_artifact_resolution"],
classnames["service_single_sign_on"],
classnames["service_nameid_mapping"],
]
)
return values
def locations(srvs):
values = (s["location"] for s in srvs if "location" in s)
return values
def destinations(srvs):
warn_msg = (
"`saml2.mdstore.destinations` function is deprecated; "
"instead, use `saml2.mdstore.locations` or `saml2.mdstore.all_locations`."
)
logger.warning(warn_msg)
_warn(warn_msg, DeprecationWarning)
values = list(locations(srvs))
return values
def all_locations(srvs):
values = chain(
response_locations(srvs),
locations(srvs),
)
return values
def attribute_requirement(entity_descriptor, index=None):
res = {"required": [], "optional": []}
acss = entity_descriptor.get("attribute_consuming_service") or []
for acs in acss:
if index is not None and acs["index"] != index:
continue
for attr in (acs.get("requested_attribute") or []):
if attr.get("is_required") == "true":
res["required"].append(attr)
else:
res["optional"].append(attr)
return res
def name(ent, langpref="en"):
try:
org = ent["organization"]
except KeyError:
return None
for info in ["organization_display_name", "organization_name", "organization_url"]:
try:
for item in org[info]:
if item["lang"] == langpref:
return item["text"]
except KeyError:
pass
return None
def repack_cert(cert):
part = cert.split("\n")
if len(part) == 1:
part = part[0].strip()
return "\n".join(split_len(part, 64))
else:
return "\n".join([s.strip() for s in part])
class MetaData:
def __init__(self, attrc, metadata="", node_name=None, check_validity=True, security=None, **kwargs):
self.attrc = attrc
self.metadata = metadata
self.entity = None
self.cert = None
self.to_old = []
self.node_name = node_name
self.check_validity = check_validity
self.security = security
def items(self):
"""
Returns list of items contained in the storage
"""
raise NotImplementedError
def keys(self):
"""
Returns keys (identifiers) of items in storage
"""
raise NotImplementedError
def values(self):
"""
Returns values of items in storage
"""
raise NotImplementedError
def __len__(self):
"""
Returns number of stored items
"""
raise NotImplementedError
def __contains__(self, item):
"""
Returns True if the storage contains item
"""
raise NotImplementedError
def __getitem__(self, item):
"""
Returns the item specified by the key
"""
raise NotImplementedError
def __setitem__(self, key, value):
"""
Sets a key to a value
"""
raise NotImplementedError
def __delitem__(self, key):
"""
Removes key from storage
"""
raise NotImplementedError
def do_entity_descriptor(self, entity_descr):
"""
#FIXME - Add description
"""
raise NotImplementedError
def parse(self, xmlstr):
"""
#FIXME - Add description
"""
raise NotImplementedError
def load(self, *args, **kwargs):
"""
Loads the metadata
"""
self.parse(self.metadata)
def service(self, entity_id, typ, service, binding=None):
"""Get me all services with a specified
entity ID and type, that supports the specified version of binding.
:param entity_id: The EntityId
:param typ: Type of service (idp, attribute_authority, ...)
:param service: which service that is sought for
:param binding: A binding identifier
:return: list of service descriptions.
Or if no binding was specified a list of 2-tuples (binding, srv)
"""
raise NotImplementedError
def ext_service(self, entity_id, typ, service, binding):
try:
srvs = self[entity_id][typ]
except KeyError:
return None
if not srvs:
return srvs
res = []
for srv in srvs:
if "extensions" in srv:
for elem in srv["extensions"]["extension_elements"]:
if elem["__class__"] == service:
if elem["binding"] == binding:
res.append(elem)
return res
def any(self, typ, service, binding=None):
"""
Return any entity that matches the specification
:param typ: Type of entity
:param service:
:param binding:
:return:
"""
res = {}
for ent in self.keys():
bind = self.service(ent, typ, service, binding)
if bind:
res[ent] = bind
return res
def any2(self, typ, service, binding=None):
"""
:param type:
:param service:
:param binding:
:return:
"""
res = {}
for entid, item in self.items():
hit = False
try:
descr = item[f"{typ}sso_descriptor"]
except KeyError:
continue
else:
for desc in descr:
try:
srvs = desc[service]
except KeyError:
continue
else:
for srv in srvs:
if srv["binding"] == binding:
res[entid] = item
hit = True
break
if hit:
break
return res
def bindings(self, entity_id, typ, service):
"""
Get me all the bindings that are registered for a service entity
:param entity_id:
:param service:
:return:
"""
return self.service(entity_id, typ, service)
def attribute_requirement(self, entity_id, index=None):
"""Returns what attributes the SP requires and which are optional
if any such demands are registered in the Metadata.
:param entity_id: The entity id of the SP
:param index: which of the attribute consumer services its all about
if index=None then return all attributes expected by all
attribute_consuming_services.
:return: 2-tuple, list of required and list of optional attributes
"""
raise NotImplementedError
def subject_id_requirement(self, entity_id):
"""
Returns what subject identifier the SP requires if any
:param entity_id: The entity id of the SP
:type entity_id: str
:return: RequestedAttribute dict or None
:rtype: Optional[dict]
"""
raise NotImplementedError
def dumps(self):
return json.dumps(list(self.items()), indent=2)
def with_descriptor(self, descriptor):
"""
Returns any entities with the specified descriptor
"""
res = {}
desc = f"{descriptor}_descriptor"
for eid, ent in self.items():
if desc in ent:
res[eid] = ent
return res
def __str__(self):
return f"{self.items()}"
def construct_source_id(self):
raise NotImplementedError
def entity_categories(self, entity_id):
res = []
if "extensions" in self[entity_id]:
for elem in self[entity_id]["extensions"]["extension_elements"]:
if elem["__class__"] == classnames["mdattr_entityattributes"]:
for attr in elem["attribute"]:
res.append(attr["text"])
return res
def __eq__(self, other):
if not isinstance(other, MetaData):
return False
if len(self.entity) != len(other.entity):
return False
if set(self.entity.keys()) != set(other.entity.keys()):
return False
for key, item in self.entity.items():
if item != other[key]:
return False
return True
def certs(self, entity_id, descriptor, use="signing"):
"""
Returns certificates for the given Entity
"""
ent = self[entity_id]
def extract_certs(srvs):
res = []
for srv in srvs:
for key in srv.get("key_descriptor", []):
key_use = key.get("use")
key_info = key.get("key_info") or {}
key_name = (key_info.get("key_name") or [{"text": None}])[0]
key_name_txt = key_name.get("text")
if "use" not in key or key_use == use:
for dat in key_info["x509_data"]:
cert = repack_cert(dat["x509_certificate"]["text"])
if cert not in res:
res.append((key_name_txt, cert))
return res
if descriptor == "any":
res = []
for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp"]:
try:
srvs = ent[f"{descr}_descriptor"]
except KeyError:
continue
res.extend(extract_certs(srvs))
else:
srvs = ent[f"{descriptor}_descriptor"]
res = extract_certs(srvs)
return res
class InMemoryMetaData(MetaData):
def __init__(self, attrc, metadata="", node_name=None, check_validity=True, security=None, **kwargs):
super().__init__(attrc, metadata=metadata)
self.entity = {}
self.security = security
self.node_name = node_name
self.entities_descr = None
self.entity_descr = None
self.check_validity = check_validity
try:
self.filter = kwargs["filter"]
except KeyError:
self.filter = None
def items(self):
return self.entity.items()
def keys(self):
return self.entity.keys()
def values(self):
return self.entity.values()
def __len__(self):
return len(self.entity)
def __contains__(self, item):
return item in self.entity.keys()
def __getitem__(self, item):
return self.entity[item]
def __setitem__(self, key, value):
self.entity[key] = value
def __delitem__(self, key):
del self.entity[key]
def do_entity_descriptor(self, entity_descr):
if self.check_validity:
try:
if not valid(entity_descr.valid_until):
logger.error("Entity descriptor (entity id:%s) too old", entity_descr.entity_id)
self.to_old.append(entity_descr.entity_id)
return
except AttributeError:
pass
# have I seen this entity_id before ? If so if log: ignore it
if entity_descr.entity_id in self.entity:
print(f"Duplicated Entity descriptor (entity id: '{entity_descr.entity_id}')", file=sys.stderr)
return
_ent = to_dict(entity_descr, metadata_modules())
flag = 0
# verify support for SAML2
for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp", "affiliation"]:
_res = []
try:
_items = _ent[f"{descr}_descriptor"]
except KeyError:
continue
if descr == "affiliation": # Not protocol specific
flag += 1
continue
for item in _items:
for prot in item["protocol_support_enumeration"].split(" "):
if prot == samlp.NAMESPACE:
item["protocol_support_enumeration"] = prot
_res.append(item)
break
if not _res:
del _ent[f"{descr}_descriptor"]
else:
flag += 1
if self.filter:
_ent = self.filter(_ent)
if not _ent:
flag = 0
if flag:
self.entity[entity_descr.entity_id] = _ent
def parse(self, xmlstr):
try:
self.entities_descr = md.entities_descriptor_from_string(xmlstr)
except Exception as e:
_md_desc = (
f"metadata file: {self.filename}"
if isinstance(self, MetaDataFile)
else f"remote metadata: {self.url}"
if isinstance(self, MetaDataExtern)
else "metadata"
)
raise SAMLError(f"Failed to parse {_md_desc}") from e
if not self.entities_descr:
self.entity_descr = md.entity_descriptor_from_string(xmlstr)
if self.entity_descr:
self.do_entity_descriptor(self.entity_descr)
else:
try:
valid_instance(self.entities_descr)
except NotValid as exc:
logger.error("Invalid XML message: %s", exc.args[0])
return
if self.check_validity:
try:
if not valid(self.entities_descr.valid_until):
raise TooOld(
"Metadata not valid anymore, it's only valid "
"until %s" % (self.entities_descr.valid_until,)
)
except AttributeError:
pass
for entity_descr in self.entities_descr.entity_descriptor:
self.do_entity_descriptor(entity_descr)
def service(self, entity_id, typ, service, binding=None):
"""Get me all services with a specified
entity ID and type, that supports the specified version of binding.
:param entity_id: The EntityId
:param typ: Type of service (idp, attribute_authority, ...)
:param service: which service that is sought for
:param binding: A binding identifier
:return: list of service descriptions.
Or if no binding was specified a list of 2-tuples (binding, srv)
"""
try:
srvs = []
for t in self[entity_id][typ]:
try:
srvs.extend(t[service])
except KeyError:
pass
except KeyError:
return None
if not srvs:
return srvs
if binding:
res = []
for srv in srvs:
if srv["binding"] == binding:
res.append(srv)
else:
res = {}
for srv in srvs:
try:
res[srv["binding"]].append(srv)
except KeyError:
res[srv["binding"]] = [srv]
logger.debug("service => %s", res)
return res
def attribute_requirement(self, entity_id, index=None):
"""
Returns what attributes the SP requires and which are optional
if any such demands are registered in the Metadata.
In case the metadata have multiple SPSSODescriptor elements,
the sum of the required and optional attributes is returned.
:param entity_id: The entity id of the SP
:param index: which of the attribute consumer services its all about
if index=None then return all attributes expected by all
attribute_consuming_services.
:return: dict of required and optional list of attributes
"""
res = {"required": [], "optional": []}
sp_descriptors = self[entity_id].get("spsso_descriptor") or []
for sp_desc in sp_descriptors:
_res = attribute_requirement(sp_desc, index)
res["required"].extend(_res.get("required") or [])
res["optional"].extend(_res.get("optional") or [])
return res
def construct_source_id(self):
res = {}
for eid, ent in self.items():
for desc in ["spsso_descriptor", "idpsso_descriptor"]:
try:
for srv in ent[desc]:
if "artifact_resolution_service" in srv:
if isinstance(eid, str):
eid = eid.encode("utf-8")
s = sha1(eid)
res[s.digest()] = ent
except KeyError:
pass
return res
def signed(self):
if self.entities_descr and self.entities_descr.signature:
return True
if self.entity_descr and self.entity_descr.signature:
return True
else:
return False
def parse_and_check_signature(self, txt):
self.parse(txt)
if not self.cert:
return True
if not self.signed():
return True
if self.node_name is not None:
try:
self.security.verify_signature(txt, node_name=self.node_name, cert_file=self.cert)
except SignatureError as e:
error_context = {
"message": "Failed to verify signature",
"node_name": self.node_name,
}
raise SignatureError(error_context) from e
else:
return True
def try_verify_signature(node_name):
try:
self.security.verify_signature(txt, node_name=node_name, cert_file=self.cert)
except SignatureError:
return False
else:
return True
descriptor_names = [
f"{ns}:{tag}"
for ns, tag in [
(EntitiesDescriptor.c_namespace, EntitiesDescriptor.c_tag),
(EntityDescriptor.c_namespace, EntityDescriptor.c_tag),
]
]
verified_w_descriptor_name = any(try_verify_signature(node_name) for node_name in descriptor_names)
if not verified_w_descriptor_name:
error_context = {
"message": "Failed to verify signature",
"descriptor_names": descriptor_names,
}
raise SignatureError(error_context)
return verified_w_descriptor_name
class MetaDataFile(InMemoryMetaData):
"""
Handles Metadata file on the same machine. The format of the file is
the SAML Metadata format.
"""
def __init__(self, attrc, filename=None, cert=None, **kwargs):
super().__init__(attrc, **kwargs)
if not filename:
raise SAMLError("No file specified.")
self.filename = filename
self.cert = cert
def get_metadata_content(self):
with open(self.filename, "rb") as fp:
return fp.read()
def load(self, *args, **kwargs):
_txt = self.get_metadata_content()
return self.parse_and_check_signature(_txt)
class MetaDataLoader(MetaDataFile):
"""
Handles Metadata file loaded by a passed in function.
The format of the file is the SAML Metadata format.
"""
def __init__(self, attrc, loader_callable, cert=None, security=None, **kwargs):
super().__init__(attrc, **kwargs)
self.metadata_provider_callable = self.get_metadata_loader(loader_callable)
self.cert = cert
self.security = security
@staticmethod
def get_metadata_loader(func):
if callable(func):
return func
i = func.rfind(".")
module, attr = func[:i], func[i + 1 :]
try:
mod = importlib.import_module(module)
except Exception as e:
raise RuntimeError(f'Cannot find metadata provider function {func}: "{e}"')
try:
metadata_loader = getattr(mod, attr)
except AttributeError:
raise RuntimeError(f'Module "{module}" does not define a "{attr}" metadata loader')
if not callable(metadata_loader):
raise RuntimeError(f"Metadata loader {module}.{attr} must be callable")
return metadata_loader
def get_metadata_content(self):
return self.metadata_provider_callable()
class MetaDataExtern(InMemoryMetaData):
"""
Class that handles metadata store somewhere on the net.
Accessible by HTTP GET.
"""
def __init__(self, attrc, url=None, security=None, cert=None, http=None, **kwargs):
"""
:params attrc:
:params url: Location of the metadata
:params security: SecurityContext()
:params cert: CertificMDloaderate used to sign the metadata
:params http:
"""
super().__init__(attrc, **kwargs)
if not url:
raise SAMLError("URL not specified.")
else:
self.url = url
# No cert is only an error if the metadata is unsigned
self.cert = cert
self.security = security
self.http = http
def load(self, *args, **kwargs):
"""Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported.
"""
response = self.http.send(self.url)
if response.status_code == 200:
_txt = response.content
return self.parse_and_check_signature(_txt)
else:
logger.error("Response status: %s", response.status_code)
raise SourceNotFound(self.url)
class MetaDataMD(InMemoryMetaData):
"""
Handles locally stored metadata, the file format is the text representation
of the Python representation of the metadata.
"""
def __init__(self, attrc, filename, **kwargs):
super().__init__(attrc, **kwargs)
self.filename = filename
def load(self, *args, **kwargs):
with open(self.filename) as fp:
data = json.load(fp)
for key, item in data:
self.entity[key] = item
class MetaDataMDX(InMemoryMetaData):
"""
Uses the MDQ protocol to fetch entity information.
The protocol is defined at:
https://datatracker.ietf.org/doc/draft-young-md-query-saml/
"""
@staticmethod
def sha1_entity_transform(entity_id):
entity_id_sha1 = hashlib.sha1(entity_id.encode("utf-8")).hexdigest()
transform = f"{{sha1}}{entity_id_sha1}"
return transform
def __init__(
self,
url=None,
security=None,
cert=None,
entity_transform=None,
freshness_period=None,
http_client_timeout=None,
**kwargs,
):
"""
:params url: mdx service url
:params security: SecurityContext()
:params cert: certificate used to check signature of signed metadata
:params entity_transform: function transforming (e.g. base64,
sha1 hash or URL quote
hash) the entity id. It is applied to the entity id before it is
concatenated with the request URL sent to the MDX server. Defaults to
sha1 transformation.
:params freshness_period: a duration in the format described at
https://www.w3.org/TR/xmlschema-2/#duration
:params http_client_timeout: timeout of http requests
"""
super().__init__(None, **kwargs)
if not url:
raise SAMLError("URL for MDQ server not specified.")
self.url = url.rstrip("/")
if entity_transform:
self.entity_transform = entity_transform
else:
self.entity_transform = MetaDataMDX.sha1_entity_transform
self.cert = cert
self.security = security
self.freshness_period = freshness_period or DEFAULT_FRESHNESS_PERIOD
self.expiration_date = {}
self.http_client_timeout = http_client_timeout
# We assume that the MDQ server will return a single entity
# described by a single <EntityDescriptor> element. The protocol
# does allow multiple entities to be returned in an
# <EntitiesDescriptor> element but we will not currently support
# that use case since it is unlikely to be leveraged for most
# flows.
self.node_name = f"{EntityDescriptor.c_namespace}:{EntityDescriptor.c_tag}"
def load(self, *args, **kwargs):
# Do nothing
pass
def _fetch_metadata(self, item):
mdx_url = f"{self.url}/entities/{self.entity_transform(item)}"
response = requests.get(
mdx_url, headers={"Accept": SAML_METADATA_CONTENT_TYPE}, timeout=self.http_client_timeout
)
if response.status_code != 200:
error_msg = f"Fething {item}: Got response status {response.status_code}"
logger.warning(error_msg)
raise KeyError(error_msg)
_txt = response.content
if not self.parse_and_check_signature(_txt):
error_msg = f"Fething {item}: invalid signature"
logger.error(error_msg)
raise KeyError(error_msg)
curr_time = str_to_time(instant())
self.expiration_date[item] = add_duration(curr_time, self.freshness_period)
return self.entity[item]
def _is_metadata_fresh(self, item):
return before(self.expiration_date[item])
def __getitem__(self, item):
if item not in self.entity:
entity = self._fetch_metadata(item)
elif not self._is_metadata_fresh(item):
msg = f"Metadata for {item} have expired; refreshing metadata"
logger.info(msg)
_ = self.entity.pop(item)
entity = self._fetch_metadata(item)
else:
entity = self.entity[item]
return entity
def single_sign_on_service(self, entity_id, binding=None, typ="idpsso"):
if binding is None:
binding = BINDING_HTTP_REDIRECT
return self.service(entity_id, "idpsso_descriptor", "single_sign_on_service", binding)
class MetadataStore(MetaData):