-
Notifications
You must be signed in to change notification settings - Fork 438
/
Copy pathentity.py
1746 lines (1514 loc) · 60.9 KB
/
entity.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 base64
from binascii import hexlify
import copy
from hashlib import sha1
import logging
import zlib
import requests
from saml2 import BINDING_HTTP_ARTIFACT
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import BINDING_PAOS
from saml2 import BINDING_SOAP
from saml2 import BINDING_URI
from saml2 import VERSION
from saml2 import SamlBase
from saml2 import SAMLError
from saml2 import class_name
from saml2 import element_to_extension_element
from saml2 import extension_elements_to_elements
from saml2 import request as saml_request
from saml2 import response as saml_response
from saml2 import saml
from saml2 import samlp
from saml2 import soap
from saml2.config import config_factory
from saml2.httpbase import HTTPBase
from saml2.mdstore import all_locations
from saml2.metadata import ENDPOINTS
from saml2.pack import http_form_post_message
from saml2.pack import http_redirect_message
from saml2.profile import ecp
from saml2.profile import paos
from saml2.profile import samlec
from saml2.response import LogoutResponse
from saml2.response import UnsolicitedResponse
from saml2.s_utils import UnravelError
from saml2.s_utils import UnsupportedBinding
from saml2.s_utils import decode_base64_and_inflate
from saml2.s_utils import error_status_factory
from saml2.s_utils import rndbytes
from saml2.s_utils import sid
from saml2.s_utils import success_status_factory
from saml2.saml import NAMEID_FORMAT_ENTITY
from saml2.saml import EncryptedAssertion
from saml2.saml import Issuer
from saml2.saml import NameID
from saml2.samlp import Artifact
from saml2.samlp import ArtifactResolve
from saml2.samlp import ArtifactResponse
from saml2.samlp import AssertionIDRequest
from saml2.samlp import AttributeQuery
from saml2.samlp import AuthnQuery
from saml2.samlp import AuthnRequest
from saml2.samlp import AuthzDecisionQuery
from saml2.samlp import LogoutRequest
from saml2.samlp import ManageNameIDRequest
from saml2.samlp import NameIDMappingRequest
from saml2.samlp import SessionIndex
from saml2.samlp import artifact_resolve_from_string
from saml2.samlp import response_from_string
from saml2.sigver import SignatureError, XMLSEC_SESSION_KEY_URI_TO_ALG, RSA_OAEP
from saml2.sigver import SigverError
from saml2.sigver import get_pem_wrapped_unwrapped
from saml2.sigver import make_temp
from saml2.sigver import pre_encrypt_assertion
from saml2.sigver import pre_encryption_part
from saml2.sigver import pre_signature_part
from saml2.sigver import security_context
from saml2.sigver import signed_instance_factory
from saml2.soap import class_instances_from_soap_enveloped_saml_thingies
from saml2.soap import open_soap_envelope
from saml2.soap import parse_soap_enveloped_saml_artifact_resolve
from saml2.time_util import instant
from saml2.virtual_org import VirtualOrg
from saml2.xmldsig import DIGEST_ALLOWED_ALG
from saml2.xmldsig import SIG_ALLOWED_ALG
from saml2.xmldsig import DefaultSignature
logger = logging.getLogger(__name__)
__author__ = "rolandh"
ARTIFACT_TYPECODE = b"\x00\x04"
SERVICE2MESSAGE = {
"single_sign_on_service": AuthnRequest,
"attribute_service": AttributeQuery,
"authz_service": AuthzDecisionQuery,
"assertion_id_request_service": AssertionIDRequest,
"authn_query_service": AuthnQuery,
"manage_name_id_service": ManageNameIDRequest,
"name_id_mapping_service": NameIDMappingRequest,
"artifact_resolve_service": ArtifactResolve,
"single_logout_service": LogoutRequest,
}
class UnknownBinding(SAMLError):
pass
def create_artifact(entity_id, message_handle, endpoint_index=0):
"""
SAML_artifact := B64(TypeCode EndpointIndex RemainingArtifact)
TypeCode := Byte1Byte2
EndpointIndex := Byte1Byte2
RemainingArtifact := SourceID MessageHandle
SourceID := 20-byte_sequence
MessageHandle := 20-byte_sequence
:param entity_id:
:param message_handle:
:param endpoint_index:
:return:
"""
if not isinstance(entity_id, bytes):
entity_id = entity_id.encode("utf-8")
sourceid = sha1(entity_id)
if not isinstance(message_handle, bytes):
message_handle = message_handle.encode("utf-8")
ter = b"".join((ARTIFACT_TYPECODE, (f"{endpoint_index:02x}").encode("ascii"), sourceid.digest(), message_handle))
return base64.b64encode(ter).decode("ascii")
class Entity(HTTPBase):
def __init__(self, entity_type, config=None, config_file="", virtual_organization="", msg_cb=None):
self.entity_type = entity_type
self.users = None
if config:
self.config = config
elif config_file:
self.config = config_factory(entity_type, config_file)
else:
raise SAMLError("Missing configuration")
def_sig = DefaultSignature()
self.signing_algorithm = self.config.getattr("signing_algorithm") or def_sig.get_sign_alg()
self.digest_algorithm = self.config.getattr("digest_algorithm") or def_sig.get_digest_alg()
sign_config_per_entity_type = {
"sp": self.config.getattr("authn_requests_signed", "sp"),
"idp": self.config.getattr("sign_response", "idp"),
}
sign_config = sign_config_per_entity_type.get(self.entity_type, False)
self.should_sign = sign_config
for item in ["cert_file", "key_file", "ca_certs"]:
_val = getattr(self.config, item, None)
if not _val:
continue
if _val.startswith("http"):
r = requests.request("GET", _val, timeout=self.config.http_client_timeout)
if r.status_code == 200:
tmp = make_temp(r.text, ".pem", False, self.config.delete_tmpfiles)
setattr(self.config, item, tmp.name)
else:
raise Exception(f"Could not fetch certificate from {_val}")
HTTPBase.__init__(
self,
self.config.verify_ssl_cert,
self.config.ca_certs,
self.config.key_file,
self.config.cert_file,
self.config.http_client_timeout,
)
if self.config.vorg:
for vo in self.config.vorg.values():
vo.sp = self
self.metadata = self.config.metadata
self.debug = self.config.debug
self.sec = security_context(self.config)
self.encrypt_assertion_session_key_algs = self.config.encrypt_assertion_session_key_algs
self.encrypt_assertion_cert_key_algs = self.config.encrypt_assertion_cert_key_algs
self.default_rsa_oaep_mgf_alg = self.config.default_rsa_oaep_mgf_alg
if virtual_organization:
if isinstance(virtual_organization, str):
self.vorg = self.config.vorg[virtual_organization]
elif isinstance(virtual_organization, VirtualOrg):
self.vorg = virtual_organization
else:
self.vorg = None
self.artifact = {}
if self.metadata:
self.sourceid = self.metadata.construct_source_id()
else:
self.sourceid = {}
self.msg_cb = msg_cb
def reload_metadata(self, metadata_conf):
"""
Reload metadata configuration.
Load a new metadata configuration as defined by metadata_conf (by
passing this to Config.load_metadata) and make this entity (as well as
subordinate objects with own metadata reference) use the new metadata.
The structure of metadata_conf is the same as the 'metadata' entry in
the configuration passed to saml2.Config.
param metadata_conf: Metadata configuration as passed to Config.load_metadata
return: True if successfully reloaded
"""
logger.debug("Loading new metadata")
try:
self.metadata.reload(metadata_conf)
except Exception as ex:
logger.error(f"Loading metadata failed; reason: {str(ex)}")
return False
self.sourceid = self.metadata.construct_source_id()
return True
def _issuer(self, entityid=None):
"""Return an Issuer instance"""
if entityid:
if isinstance(entityid, Issuer):
return entityid
else:
return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY)
else:
return Issuer(text=self.config.entityid, format=NAMEID_FORMAT_ENTITY)
# XXX DONE will actually use sign_alg and digest_alg for the Redirect-Binding
# XXX DONE deepest level - needs to decide the sign_alg (no digest_alg here)
# XXX verify digest_alg is not needed
# XXX deprecate sigalg for sign_alg
def apply_binding(
self,
binding,
msg_str,
destination="",
relay_state="",
response=False,
sign=None,
sigalg=None,
**kwargs,
):
"""
Construct the necessary HTTP arguments dependent on Binding
:param binding: Which binding to use
:param msg_str: The return message as a string (XML) if the message is
to be signed it MUST contain the signature element.
:param destination: Where to send the message
:param relay_state: Relay_state if provided
:param response: Which type of message this is
:param kwargs: response type specific arguments
:return: A dictionary
"""
# XXX SIG_ALLOWED_ALG should be configurable
# XXX should_sign stems from authn_requests_signed and sign_response
# XXX based on the type of the entity
# XXX but should also take into account the type of message (Authn/Logout/etc)
# XXX should_sign should be split and the exact config options should be checked
sign = sign if sign is not None else self.should_sign
sign_alg = sigalg or self.signing_algorithm
if sign_alg not in [long_name for short_name, long_name in SIG_ALLOWED_ALG]:
raise Exception(f"Signature algo not in allowed list: {sign_alg}")
# unless if BINDING_HTTP_ARTIFACT
if response:
typ = "SAMLResponse"
else:
typ = "SAMLRequest"
if binding == BINDING_HTTP_POST:
logger.debug("HTTP POST")
info = http_form_post_message(msg_str, destination, relay_state, typ)
info["url"] = destination
info["method"] = "POST"
elif binding == BINDING_HTTP_REDIRECT:
logger.debug("HTTP REDIRECT")
info = http_redirect_message(
message=msg_str,
location=destination,
relay_state=relay_state,
typ=typ,
sign=sign,
sigalg=sign_alg,
backend=self.sec.sec_backend,
)
info["url"] = str(destination)
info["method"] = "GET"
elif binding == BINDING_SOAP or binding == BINDING_PAOS:
info = self.use_soap(msg_str, destination, sign=sign, sigalg=sign_alg, **kwargs)
elif binding == BINDING_URI:
info = self.use_http_uri(msg_str, typ, destination)
elif binding == BINDING_HTTP_ARTIFACT:
if response:
info = self.use_http_artifact(msg_str, destination, relay_state)
info["method"] = "GET"
info["status"] = 302 # TODO: should be 303 on >= HTTP/1.1
else:
info = self.use_http_artifact(msg_str, destination, relay_state)
else:
raise SAMLError(f"Unknown binding type: {binding}")
return info
def pick_binding(self, service, bindings=None, descr_type="", request=None, entity_id=""):
if request and not entity_id:
entity_id = request.issuer.text.strip()
sfunc = getattr(self.metadata, service)
if not bindings:
if request and request.protocol_binding:
bindings = [request.protocol_binding]
else:
bindings = self.config.preferred_binding[service]
if not descr_type:
if self.entity_type == "sp":
descr_type = "idpsso"
else:
descr_type = "spsso"
_url = getattr(request, f"{service}_url", None)
_index = getattr(request, f"{service}_index", None)
for binding in bindings:
try:
srvs = sfunc(entity_id, binding, descr_type)
if srvs:
if _url:
for srv in srvs:
if srv["location"] == _url:
return binding, _url
elif _index:
for srv in srvs:
if srv["index"] == _index:
return binding, srv["location"]
else:
destination = next(all_locations(srvs), None)
return binding, destination
except UnsupportedBinding:
pass
logger.error("Failed to find consumer URL: %s, %s, %s", entity_id, bindings, descr_type)
# logger.error("Bindings: %s", bindings)
# logger.error("Entities: %s", self.metadata)
raise SAMLError("Unknown entity or unsupported bindings")
def message_args(self, message_id=0):
if not message_id:
message_id = sid()
margs = {
"id": message_id,
"version": VERSION,
"issue_instant": instant(),
"issuer": self._issuer(),
}
return margs
def response_args(self, message, bindings=None, descr_type=""):
"""
:param message: The message to which a reply is constructed
:param bindings: Which bindings can be used.
:param descr_type: Type of descriptor (spssp, idpsso, )
:return: Dictionary
"""
info = {"in_response_to": message.id}
if isinstance(message, AuthnRequest):
rsrv = "assertion_consumer_service"
descr_type = "spsso"
info["sp_entity_id"] = message.issuer.text
info["name_id_policy"] = message.name_id_policy
elif isinstance(message, LogoutRequest):
rsrv = "single_logout_service"
elif isinstance(message, AttributeQuery):
info["sp_entity_id"] = message.issuer.text
rsrv = "attribute_consuming_service"
descr_type = "spsso"
elif isinstance(message, ManageNameIDRequest):
rsrv = "manage_name_id_service"
# The once below are solely SOAP so no return destination needed
elif isinstance(message, AssertionIDRequest):
rsrv = ""
elif isinstance(message, ArtifactResolve):
rsrv = ""
elif isinstance(message, AssertionIDRequest):
rsrv = ""
elif isinstance(message, NameIDMappingRequest):
rsrv = ""
else:
raise SAMLError("No support for this type of query")
if bindings == [BINDING_SOAP]:
info["binding"] = BINDING_SOAP
info["destination"] = ""
return info
if rsrv:
if not descr_type:
if self.entity_type == "sp":
descr_type = "idpsso"
else:
descr_type = "spsso"
binding, destination = self.pick_binding(rsrv, bindings, descr_type=descr_type, request=message)
info["binding"] = binding
info["destination"] = destination
return info
@staticmethod
def unravel(txt, binding, msgtype="response"):
"""
Will unpack the received text. Depending on the context the original
response may have been transformed before transmission.
:param txt:
:param binding:
:param msgtype:
:return:
"""
# logger.debug("unravel '%s'", txt)
if binding not in [
BINDING_HTTP_REDIRECT,
BINDING_HTTP_POST,
BINDING_SOAP,
BINDING_URI,
BINDING_HTTP_ARTIFACT,
None,
]:
raise UnknownBinding(f"Don't know how to handle '{binding}'")
else:
try:
if binding == BINDING_HTTP_REDIRECT:
xmlstr = decode_base64_and_inflate(txt)
elif binding == BINDING_HTTP_POST:
try:
xmlstr = decode_base64_and_inflate(txt)
except zlib.error:
xmlstr = base64.b64decode(txt)
elif binding == BINDING_SOAP:
func = getattr(soap, f"parse_soap_enveloped_saml_{msgtype}")
xmlstr = func(txt)
elif binding == BINDING_HTTP_ARTIFACT:
xmlstr = base64.b64decode(txt)
else:
xmlstr = txt
except Exception:
raise UnravelError(f"Unravelling binding '{binding}' failed")
return xmlstr
@staticmethod
def parse_soap_message(text):
"""
:param text: The SOAP message
:return: A dictionary with two keys "body" and "header"
"""
return class_instances_from_soap_enveloped_saml_thingies(text, [paos, ecp, samlp, samlec])
@staticmethod
def unpack_soap_message(text):
"""
Picks out the parts of the SOAP message, body and headers apart
:param text: The SOAP message
:return: A dictionary with two keys "body"/"header"
"""
return open_soap_envelope(text)
# --------------------------------------------------------------------------
# XXX DONE will actually use sign_alg and digest_alg for the POST-Binding
# XXX DONE deepest level - needs to decide the sign_alg and digest_alg value
# XXX a controler for signed_instance_factory
# XXX syncs pre_signature_part and signed_instance_factory
# XXX makes sure pre_signature_part is called before signed_instance_factory
# XXX calls pre_signature_part - must have sign_alg & digest_alg
# XXX calls signed_instance_factory - after pre_signature_part
# XXX !!expects a msg object!!
def sign(
self,
msg,
mid=None,
to_sign=None,
sign_prepare=None,
sign_alg=None,
digest_alg=None,
):
# XXX sig/digest-allowed should be configurable
sign_alg = sign_alg or self.signing_algorithm
digest_alg = digest_alg or self.digest_algorithm
if sign_alg not in [long_name for short_name, long_name in SIG_ALLOWED_ALG]:
raise Exception(f"Signature algo not in allowed list: {sign_alg}")
if digest_alg not in [long_name for short_name, long_name in DIGEST_ALLOWED_ALG]:
raise Exception(f"Digest algo not in allowed list: {digest_alg}")
if msg.signature is None:
msg.signature = pre_signature_part(msg.id, self.sec.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg)
if sign_prepare:
return msg
if mid is None:
mid = msg.id
try:
to_sign += [(class_name(msg), mid)]
except (AttributeError, TypeError):
to_sign = [(class_name(msg), mid)]
logger.debug("REQUEST: %s", msg)
return signed_instance_factory(msg, self.sec, to_sign)
# XXX DONE will actually use sign the POST-Binding
# XXX DONE deepest level - needs to decide the sign value
# XXX DONE calls self.sign must figure out sign
# XXX DONE ensure both SPs and IdPs go through this
# XXX DONE ensure this works for the POST-Binding
def _message(
self,
request_cls,
destination=None,
message_id=0,
consent=None,
extensions=None,
sign=None,
sign_prepare=None,
nsprefix=None,
sign_alg=None,
digest_alg=None,
**kwargs,
):
"""
Some parameters appear in all requests so simplify by doing
it in one place
:param request_cls: The specific request type
:param destination: The recipient
:param message_id: A message identifier
:param consent: Whether the principal have given her consent
:param extensions: Possible extensions
:param sign: Whether the request should be signed or not.
:param sign_prepare: Whether the signature should be prepared or not.
:param kwargs: Key word arguments specific to one request type
:return: A tuple containing the request ID and an instance of the
request_cls
"""
if not message_id:
message_id = sid()
for key, val in self.message_args(message_id).items():
if key not in kwargs:
kwargs[key] = val
req = request_cls(**kwargs)
if destination:
req.destination = destination
if consent:
req.consent = "true"
if extensions:
req.extensions = extensions
if nsprefix:
req.register_prefix(nsprefix)
if self.msg_cb:
req = self.msg_cb(req)
reqid = req.id
sign = sign if sign is not None else self.should_sign
if sign:
signed_req = self.sign(
req,
sign_prepare=sign_prepare,
sign_alg=sign_alg,
digest_alg=digest_alg,
)
req = signed_req
logger.debug("REQUEST: %s", req)
return reqid, req
@staticmethod
def _filter_args(instance, extensions=None, **kwargs):
args = {}
if extensions is None:
extensions = []
allowed_attributes = instance.keys()
for key, val in kwargs.items():
if key in allowed_attributes:
args[key] = val
elif isinstance(val, SamlBase):
# extension elements allowed ?
extensions.append(element_to_extension_element(val))
return args, extensions
def _add_info(self, msg, **kwargs):
"""
Add information to a SAML message. If the attribute is not part of
what's defined in the SAML standard add it as an extension.
:param msg:
:param kwargs:
:return:
"""
args, extensions = self._filter_args(msg, **kwargs)
for key, val in args.items():
setattr(msg, key, val)
if extensions:
if msg.extension_elements:
msg.extension_elements.extend(extensions)
else:
msg.extension_elements = extensions
def has_encrypt_cert_in_metadata(self, sp_entity_id):
"""Verifies if the metadata contains encryption certificates.
:param sp_entity_id: Entity ID for the calling service provider.
:return: True if encrypt cert exists in metadata, otherwise False.
"""
if sp_entity_id is not None:
_certs = self.metadata.certs(sp_entity_id, "any", "encryption")
if len(_certs) > 0:
return True
return False
def _get_first_matching_alg(self, priority_list, metadata_list):
for alg in priority_list:
for cert_method in metadata_list:
if cert_method.get("algorithm") == alg:
return cert_method
return None
def _encrypt_assertion(
self,
encrypt_cert,
sp_entity_id,
response,
node_xpath=None,
encrypt_cert_session_key_alg=None,
encrypt_cert_cert_key_alg=None,
):
"""Encryption of assertions.
:param encrypt_cert: Certificate to be used for encryption.
:param sp_entity_id: Entity ID for the calling service provider.
:param response: A samlp.Response
:param encrypt_cert_cert_key_alg: algorithm used for encrypting session key
:param encrypt_cert_session_key_alg: algorithm used for encrypting assertion
:param encrypt_cert_cert_key_alg:
:param node_xpath: Unquie path to the element to be encrypted.
:return: A new samlp.Resonse with the designated assertion encrypted.
"""
_certs = []
if encrypt_cert:
_certs.append((None, encrypt_cert, None, None))
elif sp_entity_id is not None:
_certs = self.metadata.certs(sp_entity_id, "any", "encryption", get_with_usage_and_encryption_methods=True)
exception = None
# take certs with encryption and encryption_methods first (priority 1)
sorted_certs = []
for _unpacked_cert in _certs:
_cert_name, _cert, _cert_use, _cert_encryption_methods = _unpacked_cert
if _cert_use == "encryption" and _cert_encryption_methods:
sorted_certs.append(_unpacked_cert)
# take certs with encryption or encryption_methods (priority 2)
for _unpacked_cert in _certs:
_cert_name, _cert, _cert_use, _cert_encryption_methods = _unpacked_cert
if _cert_use == "encryption" and _unpacked_cert not in sorted_certs:
sorted_certs.append(_unpacked_cert)
for _unpacked_cert in _certs:
if _unpacked_cert not in sorted_certs:
sorted_certs.append(_unpacked_cert)
for _cert_name, _cert, _cert_use, _cert_encryption_methods in sorted_certs:
wrapped_cert, unwrapped_cert = get_pem_wrapped_unwrapped(_cert)
try:
tmp = make_temp(
wrapped_cert.encode("ascii"),
decode=False,
delete_tmpfiles=self.config.delete_tmpfiles,
)
msg_enc = (
encrypt_cert_session_key_alg
if encrypt_cert_session_key_alg
else self.encrypt_assertion_session_key_algs[0]
)
key_enc = (
encrypt_cert_cert_key_alg if encrypt_cert_cert_key_alg else self.encrypt_assertion_cert_key_algs[0]
)
rsa_oaep_mgf_alg = self.default_rsa_oaep_mgf_alg if key_enc == RSA_OAEP else None
if encrypt_cert != _cert and _cert_encryption_methods:
viable_session_key_alg = self._get_first_matching_alg(
self.encrypt_assertion_session_key_algs, _cert_encryption_methods
)
if viable_session_key_alg:
msg_enc = viable_session_key_alg.get("algorithm")
viable_cert_alg = self._get_first_matching_alg(
self.encrypt_assertion_cert_key_algs, _cert_encryption_methods
)
if viable_cert_alg:
key_enc = viable_cert_alg.get("algorithm")
mgf = viable_cert_alg.get("mgf")
rsa_oaep_mgf_alg = mgf.get("algorithm") if mgf else None
key_type = XMLSEC_SESSION_KEY_URI_TO_ALG.get(msg_enc)
response = self.sec.encrypt_assertion(
response,
tmp.name,
pre_encryption_part(
key_name=_cert_name,
encrypt_cert=unwrapped_cert,
msg_enc=msg_enc,
key_enc=key_enc,
rsa_oaep_mgf_alg=rsa_oaep_mgf_alg,
),
key_type=key_type,
node_xpath=node_xpath,
)
return response
except Exception as ex:
exception = ex
if exception:
raise exception
return response
# XXX DONE calls self.sign must figure out sign
# XXX calls signed_instance_factory - must have called pre_signature_part
# XXX calls pre_signature_part - must figure out sign_alg/digest_alg
def _response(
self,
in_response_to,
consumer_url=None,
status=None,
issuer=None,
sign=None,
to_sign=None,
sp_entity_id=None,
encrypt_assertion=False,
encrypt_assertion_self_contained=False,
encrypted_advice_attributes=False,
encrypt_cert_advice=None,
encrypt_cert_advice_cert_key_alg=None,
encrypt_cert_advice_session_key_alg=None,
encrypt_cert_assertion=None,
encrypt_cert_assertion_cert_key_alg=None,
encrypt_cert_assertion_session_key_alg=None,
sign_assertion=None,
pefim=False,
sign_alg=None,
digest_alg=None,
**kwargs,
):
"""Create a Response.
Encryption:
encrypt_assertion must be true for encryption to be
performed. If encrypted_advice_attributes also is
true, then will the function try to encrypt the assertion in
the the advice element of the main
assertion. Only one assertion element is allowed in the
advice element, if multiple assertions exists
in the advice element the main assertion will be encrypted
instead, since it's no point to encrypt
If encrypted_advice_attributes is
false the main assertion will be encrypted. Since the same key
:param in_response_to: The session identifier of the request
:param consumer_url: The URL which should receive the response
:param status: An instance of samlp.Status
:param issuer: The issuer of the response
:param sign: Whether the response should be signed or not
:param to_sign: If there are other parts to sign
:param sp_entity_id: Entity ID for the calling service provider.
:param encrypt_assertion: True if assertions should be encrypted.
:param encrypt_assertion_self_contained: True if all encrypted
assertions should have alla namespaces selfcontained.
:param encrypted_advice_attributes: True if assertions in the advice
element should be encrypted.
:param encrypt_cert_advice: Certificate to be used for encryption of
assertions in the advice element.
:param encrypt_cert_advice_cert_key_alg: algorithm used for encrypting session key
by encrypt_cert_advice
:param encrypt_cert_advice_session_key_alg: algorithm used for encrypting assertion
when using encrypt_cert_advice
:param encrypt_cert_assertion: Certificate to be used for encryption
of assertions.
:param encrypt_cert_assertion_cert_key_alg: algorithm used for encrypting session key
by encrypt_cert_assertion
:param encrypt_cert_assertion_session_key_alg: algorithm used for encrypting assertion when
using encrypt_cert_assertion
:param sign_assertion: True if assertions should be signed.
:param pefim: True if a response according to the PEFIM profile
should be created.
:param kwargs: Extra key word arguments
:return: A Response instance
"""
if not status:
status = success_status_factory()
_issuer = self._issuer(issuer)
response = samlp.Response(id=sid(), version=VERSION, issue_instant=instant())
response.issuer = _issuer
response.in_response_to = in_response_to
response.status = status
if consumer_url:
response.destination = consumer_url
self._add_info(response, **kwargs)
sign = sign if sign is not None else self.should_sign
if to_sign and not sign and not encrypt_assertion:
return signed_instance_factory(response, self.sec, to_sign)
has_encrypt_cert = self.has_encrypt_cert_in_metadata(sp_entity_id)
if not has_encrypt_cert and encrypt_cert_advice is None:
encrypted_advice_attributes = False
if not has_encrypt_cert and encrypt_cert_assertion is None:
encrypt_assertion = False
# XXX if encrypt_assertion or encrypted_advice_attributes
# XXX once in, response becomes a str and uses signed_instance_factory
if (
# XXX goto part-C
encrypt_assertion
or (
# XXX goto part-B
encrypted_advice_attributes
and response.assertion.advice is not None
and len(response.assertion.advice.assertion) == 1
)
):
# XXX sig/digest-allowed should be configurable
sign_alg = sign_alg or self.signing_algorithm
digest_alg = digest_alg or self.digest_algorithm
# XXX part-A (common) prepare sign response
if sign:
response.signature = pre_signature_part(
response.id,
self.sec.my_cert,
1,
sign_alg=sign_alg,
digest_alg=digest_alg,
)
sign_class = [(class_name(response), response.id)]
else:
sign_class = []
# XXX part-B if encrypted_advice_attributes
if (
encrypted_advice_attributes
and response.assertion.advice is not None
and len(response.assertion.advice.assertion) > 0
):
_assertions = response.assertion
if not isinstance(_assertions, list):
_assertions = [_assertions]
for _assertion in _assertions:
_assertion.advice.encrypted_assertion = []
_assertion.advice.encrypted_assertion.append(EncryptedAssertion())
_advice_assertions = copy.deepcopy(_assertion.advice.assertion)
_assertion.advice.assertion = []
if not isinstance(_advice_assertions, list):
_advice_assertions = [_advice_assertions]
for tmp_assertion in _advice_assertions:
to_sign_advice = []
# XXX prepare sign assertion
if sign_assertion and not pefim:
tmp_assertion.signature = pre_signature_part(
tmp_assertion.id,
self.sec.my_cert,
1,
sign_alg=sign_alg,
digest_alg=digest_alg,
)
to_sign_advice.append(
(class_name(tmp_assertion), tmp_assertion.id),
)
# XXX prepare encrypt assertion
# tmp_assertion = response.assertion.advice.assertion[0]
_assertion.advice.encrypted_assertion[0].add_extension_element(tmp_assertion)
if encrypt_assertion_self_contained:
advice_tag = response.assertion.advice._to_element_tree().tag
assertion_tag = tmp_assertion._to_element_tree().tag
response = (
response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(
assertion_tag, advice_tag
)
)
node_xpath = "".join(
[
f'/*[local-name()="{v}"]'
for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]
]
)
# XXX sign assertion
if to_sign_advice:
response = signed_instance_factory(response, self.sec, to_sign_advice)
# XXX encrypt assertion
response = self._encrypt_assertion(
encrypt_cert_advice,
sp_entity_id,
response,
node_xpath=node_xpath,
encrypt_cert_session_key_alg=encrypt_cert_advice_session_key_alg,
encrypt_cert_cert_key_alg=encrypt_cert_advice_cert_key_alg,
)
response = response_from_string(response)
# XXX part-C if encrypt_assertion
if encrypt_assertion:
to_sign_assertion = []
# XXX prepare sign assertion
if sign_assertion:
_assertions = response.assertion
if not isinstance(_assertions, list):
_assertions = [_assertions]
for _assertion in _assertions:
_assertion.signature = pre_signature_part(
_assertion.id,
self.sec.my_cert,
2,
sign_alg=sign_alg,
digest_alg=digest_alg,
)
to_sign_assertion.append(
(class_name(_assertion), _assertion.id),
)
# XXX prepare encrypt assertion
if encrypt_assertion_self_contained:
try:
assertion_tag = response.assertion._to_element_tree().tag
except Exception:
assertion_tag = response.assertion[0]._to_element_tree().tag
response = pre_encrypt_assertion(response)
response = response.get_xml_string_with_self_contained_assertion_within_encrypted_assertion(
assertion_tag
)
else:
response = pre_encrypt_assertion(response)
# XXX sign assertion
if to_sign_assertion:
response = signed_instance_factory(response, self.sec, to_sign_assertion)
# XXX encrypt assertion
response = self._encrypt_assertion(
encrypt_cert_assertion,
sp_entity_id,
response,
encrypt_cert_session_key_alg=encrypt_cert_assertion_session_key_alg,
encrypt_cert_cert_key_alg=encrypt_cert_assertion_cert_key_alg,
)
else:
# XXX sign other parts! (defiend by to_sign)
if to_sign:
response = signed_instance_factory(response, self.sec, to_sign)