-
Notifications
You must be signed in to change notification settings - Fork 423
/
sigver.py
1908 lines (1558 loc) · 65.8 KB
/
sigver.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
""" Functions connected to signing and verifying.
Based on the use of xmlsec1 binaries and not the python xmlsec module.
"""
import base64
import datetime
import hashlib
import itertools
import logging
import os
import re
from subprocess import PIPE
from subprocess import Popen
import sys
from tempfile import NamedTemporaryFile
from time import mktime
from uuid import uuid4 as gen_random_key
import dateutil
# importlib.resources was introduced in python 3.7
# files API from importlib.resources introduced in python 3.9
if sys.version_info[:2] >= (3, 9):
from importlib.resources import files as _resource_files
else:
from importlib_resources import files as _resource_files
from urllib import parse
from OpenSSL import crypto
import pytz
from saml2 import ExtensionElement
from saml2 import SamlBase
from saml2 import SAMLError
from saml2 import class_name
from saml2 import extension_elements_to_elements
from saml2 import saml
from saml2 import samlp
from saml2.cert import CertificateError
from saml2.cert import OpenSSLWrapper
from saml2.cert import read_cert_from_file
import saml2.cryptography.asymmetric
import saml2.cryptography.pki
import saml2.data.templates as _data_template
from saml2.extension import pefim
from saml2.extension.pefim import SPCertEnc
from saml2.s_utils import Unsupported
from saml2.saml import EncryptedAssertion
from saml2.time_util import str_to_time
from saml2.xml.schema import XMLSchemaError
from saml2.xml.schema import validate as validate_doc_with_schema
from saml2.xmldsig import ALLOWED_CANONICALIZATIONS
from saml2.xmldsig import ALLOWED_TRANSFORMS
from saml2.xmldsig import SIG_RSA_SHA1
from saml2.xmldsig import SIG_RSA_SHA224
from saml2.xmldsig import SIG_RSA_SHA256
from saml2.xmldsig import SIG_RSA_SHA384
from saml2.xmldsig import SIG_RSA_SHA512
from saml2.xmldsig import TRANSFORM_C14N
from saml2.xmldsig import TRANSFORM_ENVELOPED
import saml2.xmldsig as ds
from saml2.xmlenc import CipherData
from saml2.xmlenc import CipherValue
from saml2.xmlenc import EncryptedData
from saml2.xmlenc import EncryptedKey
from saml2.xmlenc import EncryptionMethod
logger = logging.getLogger(__name__)
SIG = f"{{{ds.NAMESPACE}#}}Signature"
# RSA_1_5 is considered deprecated
RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"
TRIPLE_DES_CBC = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
RSA_OAEP_MGF1P = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
class SigverError(SAMLError):
pass
class CertificateTooOld(SigverError):
pass
class XmlsecError(SigverError):
pass
class MissingKey(SigverError):
pass
class DecryptError(XmlsecError):
pass
class EncryptError(XmlsecError):
pass
class SignatureError(XmlsecError):
pass
class BadSignature(SigverError):
"""The signature is invalid."""
def get_pem_wrapped_unwrapped(cert):
begin_cert = "-----BEGIN CERTIFICATE-----\n"
end_cert = "\n-----END CERTIFICATE-----\n"
unwrapped_cert = re.sub(f"{begin_cert}|{end_cert}", "", cert)
wrapped_cert = f"{begin_cert}{unwrapped_cert}{end_cert}"
return wrapped_cert, unwrapped_cert
def rm_xmltag(statement):
XMLTAG = "<?xml version='1.0'?>"
PREFIX1 = "<?xml version='1.0' encoding='UTF-8'?>"
PREFIX2 = '<?xml version="1.0" encoding="UTF-8"?>'
try:
_t = statement.startswith(XMLTAG)
except TypeError:
statement = statement.decode()
_t = statement.startswith(XMLTAG)
if _t:
statement = statement[len(XMLTAG) :]
if statement[0] == "\n":
statement = statement[1:]
elif statement.startswith(PREFIX1):
statement = statement[len(PREFIX1) :]
if statement[0] == "\n":
statement = statement[1:]
elif statement.startswith(PREFIX2):
statement = statement[len(PREFIX2) :]
if statement[0] == "\n":
statement = statement[1:]
return statement
def signed(item):
"""
Is any part of the document signed ?
:param item: A Samlbase instance
:return: True if some part of it is signed
"""
if SIG in item.c_children.keys() and item.signature:
return True
else:
for prop in item.c_child_order:
child = getattr(item, prop, None)
if isinstance(child, list):
for chi in child:
if signed(chi):
return True
elif child and signed(child):
return True
return False
def get_xmlsec_binary(paths=None):
"""
Tries to find the xmlsec1 binary.
:param paths: Non-system path paths which should be searched when
looking for xmlsec1
:return: full name of the xmlsec1 binary found. If no binaries are
found then an exception is raised.
"""
if os.name == "posix":
bin_name = ["xmlsec1"]
elif os.name == "nt":
bin_name = ["xmlsec.exe", "xmlsec1.exe"]
else: # Default !?
bin_name = ["xmlsec1"]
if paths:
for bname in bin_name:
for path in paths:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
for path in os.environ["PATH"].split(os.pathsep):
for bname in bin_name:
fil = os.path.join(path, bname)
try:
if os.lstat(fil):
return fil
except OSError:
pass
raise SigverError(f"Cannot find {bin_name}")
def _get_xmlsec_cryptobackend(path=None, search_paths=None, delete_tmpfiles=True):
"""
Initialize a CryptoBackendXmlSec1 crypto backend.
This function is now internal to this module.
"""
if path is None:
path = get_xmlsec_binary(paths=search_paths)
return CryptoBackendXmlSec1(path, delete_tmpfiles=delete_tmpfiles)
NODE_NAME = "urn:oasis:names:tc:SAML:2.0:assertion:Assertion"
ENC_NODE_NAME = "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion"
ENC_KEY_CLASS = "EncryptedKey"
def _make_vals(val, klass, seccont, klass_inst=None, prop=None, part=False, base64encode=False, elements_to_sign=None):
"""
Creates a class instance with a specified value, the specified
class instance may be a value on a property in a defined class instance.
:param val: The value
:param klass: The value class
:param klass_inst: The class instance which has a property on which
what this function returns is a value.
:param prop: The property which the value should be assigned to.
:param part: If the value is one of a possible list of values it should be
handled slightly different compared to if it isn't.
:return: Value class instance
"""
cinst = None
if isinstance(val, dict):
cinst = _instance(klass, val, seccont, base64encode=base64encode, elements_to_sign=elements_to_sign)
else:
try:
cinst = klass().set_text(val)
except ValueError:
if not part:
cis = [
_make_vals(sval, klass, seccont, klass_inst, prop, True, base64encode, elements_to_sign)
for sval in val
]
setattr(klass_inst, prop, cis)
else:
raise
if part:
return cinst
else:
if cinst:
cis = [cinst]
setattr(klass_inst, prop, cis)
def _instance(klass, ava, seccont, base64encode=False, elements_to_sign=None):
instance = klass()
for prop in instance.c_attributes.values():
if prop in ava:
if isinstance(ava[prop], bool):
setattr(instance, prop, str(ava[prop]).encode())
elif isinstance(ava[prop], int):
setattr(instance, prop, str(ava[prop]))
else:
setattr(instance, prop, ava[prop])
if "text" in ava:
instance.set_text(ava["text"], base64encode)
for prop, klassdef in instance.c_children.values():
if prop in ava:
if isinstance(klassdef, list):
# means there can be a list of values
_make_vals(
ava[prop],
klassdef[0],
seccont,
instance,
prop,
base64encode=base64encode,
elements_to_sign=elements_to_sign,
)
else:
cis = _make_vals(ava[prop], klassdef, seccont, instance, prop, True, base64encode, elements_to_sign)
setattr(instance, prop, cis)
if "extension_elements" in ava:
for item in ava["extension_elements"]:
instance.extension_elements.append(ExtensionElement(item["tag"]).loadd(item))
if "extension_attributes" in ava:
for key, val in ava["extension_attributes"].items():
instance.extension_attributes[key] = val
if "signature" in ava:
elements_to_sign.append((class_name(instance), instance.id))
return instance
# XXX will actually sign the nodes
# XXX assumes pre_signature_part has already been called
# XXX calls sign without specifying sign_alg/digest_alg
# XXX this is fine as the algs are embeded in the document
# XXX as setup by pre_signature_part
# XXX !!expects instance string!!
def signed_instance_factory(instance, seccont, elements_to_sign=None):
"""
:param instance: The instance to be signed or not
:param seccont: The security context
:param elements_to_sign: Which parts if any that should be signed
:return: A class instance if not signed otherwise a string
"""
if not elements_to_sign:
return instance
signed_xml = instance
if not isinstance(instance, str):
signed_xml = instance.to_string()
for (node_name, nodeid) in elements_to_sign:
signed_xml = seccont.sign_statement(signed_xml, node_name=node_name, node_id=nodeid)
return signed_xml
def make_temp(content, suffix="", decode=True, delete_tmpfiles=True):
"""
Create a temporary file with the given content.
This is needed by xmlsec in some cases where only strings exist when files
are expected.
:param content: The information to be placed in the file
:param suffix: The temporary file might have to have a specific
suffix in certain circumstances.
:param decode: The input content might be base64 coded. If so it
must, in some cases, be decoded before being placed in the file.
:param delete_tmpfiles: Whether to keep the tmp files or delete them when they are
no longer in use
:return: 2-tuple with file pointer ( so the calling function can
close the file) and filename (which is for instance needed by the
xmlsec function).
"""
content_encoded = content.encode("utf-8") if not isinstance(content, bytes) else content
content_raw = base64.b64decode(content_encoded) if decode else content_encoded
ntf = NamedTemporaryFile(suffix=suffix, delete=delete_tmpfiles)
ntf.write(content_raw)
ntf.seek(0)
return ntf
def split_len(seq, length):
return [seq[i : i + length] for i in range(0, len(seq), length)]
M2_TIME_FORMAT = "%b %d %H:%M:%S %Y"
def to_time(_time):
if not _time.endswith(" GMT"):
raise ValueError("Time does not end with GMT")
_time = _time[:-4]
return mktime(str_to_time(_time, M2_TIME_FORMAT))
def active_cert(key):
"""
Verifies that a key is active that is present time is after not_before
and before not_after.
:param key: The Key
:return: True if the key is active else False
"""
try:
cert_str = pem_format(key)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
except AttributeError:
return False
now = pytz.UTC.localize(datetime.datetime.utcnow())
valid_from = dateutil.parser.parse(cert.get_notBefore())
valid_to = dateutil.parser.parse(cert.get_notAfter())
active = not cert.has_expired() and valid_from <= now < valid_to
return active
def cert_from_key_info(key_info, ignore_age=False):
"""Get all X509 certs from a KeyInfo instance. Care is taken to make sure
that the certs are continues sequences of bytes.
All certificates appearing in an X509Data element MUST relate to the
validation key by either containing it or being part of a certification
chain that terminates in a certificate containing the validation key.
:param key_info: The KeyInfo instance
:return: A possibly empty list of certs
"""
res = []
for x509_data in key_info.x509_data:
x509_certificate = x509_data.x509_certificate
cert = x509_certificate.text.strip()
cert = "\n".join(split_len("".join([s.strip() for s in cert.split()]), 64))
if ignore_age or active_cert(cert):
res.append(cert)
else:
logger.info("Inactive cert")
return res
def cert_from_key_info_dict(key_info, ignore_age=False):
"""Get all X509 certs from a KeyInfo dictionary. Care is taken to make sure
that the certs are continues sequences of bytes.
All certificates appearing in an X509Data element MUST relate to the
validation key by either containing it or being part of a certification
chain that terminates in a certificate containing the validation key.
:param key_info: The KeyInfo dictionary
:return: A possibly empty list of certs in their text representation
"""
res = []
if "x509_data" not in key_info:
return res
for x509_data in key_info["x509_data"]:
x509_certificate = x509_data["x509_certificate"]
cert = x509_certificate["text"].strip()
cert = "\n".join(split_len("".join([s.strip() for s in cert.split()]), 64))
if ignore_age or active_cert(cert):
res.append(cert)
else:
logger.info("Inactive cert")
return res
def cert_from_instance(instance):
"""Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates
"""
if instance.signature:
if instance.signature.key_info:
return cert_from_key_info(instance.signature.key_info, ignore_age=True)
return []
def extract_rsa_key_from_x509_cert(pem):
cert = saml2.cryptography.pki.load_pem_x509_certificate(pem)
return cert.public_key()
def pem_format(key):
return os.linesep.join(["-----BEGIN CERTIFICATE-----", key, "-----END CERTIFICATE-----"]).encode("ascii")
def import_rsa_key_from_file(filename):
with open(filename, "rb") as fd:
data = fd.read()
key = saml2.cryptography.asymmetric.load_pem_private_key(data)
return key
def parse_xmlsec_verify_output(output, version=None):
"""Parse the output from xmlsec to try to find out if the
command was successfull or not.
:param output: The output from Popen
:return: A boolean; True if the command was a success otherwise False
"""
if version is None or version < (1, 3):
for line in output.splitlines():
if line == "OK":
return True
elif line == "FAIL":
raise XmlsecError(output)
else:
for line in output.splitlines():
if line == 'Verification status: OK':
return True
elif line == 'Verification status: FAILED':
raise XmlsecError(output)
raise XmlsecError(output)
def sha1_digest(msg):
return hashlib.sha1(msg).digest()
class Signer:
"""Abstract base class for signing algorithms."""
def __init__(self, key):
self.key = key
def sign(self, msg, key):
"""Sign ``msg`` with ``key`` and return the signature."""
raise NotImplementedError
def verify(self, msg, sig, key):
"""Return True if ``sig`` is a valid signature for ``msg``."""
raise NotImplementedError
class RSASigner(Signer):
def __init__(self, digest, key=None):
Signer.__init__(self, key)
self.digest = digest
def sign(self, msg, key=None):
return saml2.cryptography.asymmetric.key_sign(key or self.key, msg, self.digest)
def verify(self, msg, sig, key=None):
return saml2.cryptography.asymmetric.key_verify(key or self.key, sig, msg, self.digest)
SIGNER_ALGS = {
SIG_RSA_SHA1: RSASigner(saml2.cryptography.asymmetric.hashes.SHA1()),
SIG_RSA_SHA224: RSASigner(saml2.cryptography.asymmetric.hashes.SHA224()),
SIG_RSA_SHA256: RSASigner(saml2.cryptography.asymmetric.hashes.SHA256()),
SIG_RSA_SHA384: RSASigner(saml2.cryptography.asymmetric.hashes.SHA384()),
SIG_RSA_SHA512: RSASigner(saml2.cryptography.asymmetric.hashes.SHA512()),
}
REQ_ORDER = [
"SAMLRequest",
"RelayState",
"SigAlg",
]
RESP_ORDER = [
"SAMLResponse",
"RelayState",
"SigAlg",
]
class RSACrypto:
def __init__(self, key):
self.key = key
def get_signer(self, sigalg, sigkey=None):
try:
signer = SIGNER_ALGS[sigalg]
except KeyError:
return None
else:
if sigkey:
signer.key = sigkey
else:
signer.key = self.key
return signer
def verify_redirect_signature(saml_msg, crypto, cert=None, sigkey=None):
"""
:param saml_msg: A dictionary with strings as values, *NOT* lists as
produced by parse_qs.
:param cert: A certificate to use when verifying the signature
:return: True, if signature verified
"""
try:
signer = crypto.get_signer(saml_msg["SigAlg"], sigkey)
except KeyError:
raise Unsupported(f"Signature algorithm: {saml_msg['SigAlg']}")
else:
if saml_msg["SigAlg"] in SIGNER_ALGS:
if "SAMLRequest" in saml_msg:
_order = REQ_ORDER
elif "SAMLResponse" in saml_msg:
_order = RESP_ORDER
else:
raise Unsupported("Verifying signature on something that should not be signed")
_args = saml_msg.copy()
del _args["Signature"] # everything but the signature
string = "&".join([parse.urlencode({k: _args[k]}) for k in _order if k in _args]).encode("ascii")
if cert:
_key = extract_rsa_key_from_x509_cert(pem_format(cert))
else:
_key = sigkey
_sign = base64.b64decode(saml_msg["Signature"])
return bool(signer.verify(string, _sign, _key))
class CryptoBackend:
@property
def version(self):
raise NotImplementedError()
@property
def version_nums(self):
try:
vns = tuple(int(t) for t in self.version.split("."))
except ValueError:
vns = (0, 0, 0)
return vns
def encrypt(self, text, recv_key, template, key_type):
raise NotImplementedError()
def encrypt_assertion(self, statement, enc_key, template, key_type, node_xpath):
raise NotImplementedError()
def decrypt(self, enctext, key_file):
raise NotImplementedError()
def sign_statement(self, statement, node_name, key_file, node_id):
raise NotImplementedError()
def validate_signature(self, enctext, cert_file, cert_type, node_name, node_id):
raise NotImplementedError()
ASSERT_XPATH = "".join([f"/*[local-name()='{n}']" for n in ["Response", "EncryptedAssertion", "Assertion"]])
class CryptoBackendXmlSec1(CryptoBackend):
"""
CryptoBackend implementation using external binary 1 to sign
and verify XML documents.
"""
__DEBUG = 0
def __init__(self, xmlsec_binary, delete_tmpfiles=True, **kwargs):
CryptoBackend.__init__(self, **kwargs)
if not isinstance(xmlsec_binary, str):
raise ValueError("xmlsec_binary should be of type string")
self.xmlsec = xmlsec_binary
self.delete_tmpfiles = delete_tmpfiles
try:
self.non_xml_crypto = RSACrypto(kwargs["rsa_key"])
except KeyError:
pass
@property
def version(self):
com_list = [self.xmlsec, "--version"]
pof = Popen(com_list, stderr=PIPE, stdout=PIPE)
content, _ = pof.communicate()
content = content.decode("ascii")
try:
return content.split(" ")[1]
except IndexError:
return "0.0.0"
def encrypt(self, text, recv_key, template, session_key_type, xpath=""):
"""
:param text: The text to be compiled
:param recv_key: Filename of a file where the key resides
:param template: Filename of a file with the pre-encryption part
:param session_key_type: Type and size of a new session key
'des-192' generates a new 192 bits DES key for DES3 encryption
:param xpath: What should be encrypted
:return:
"""
logger.debug("Encryption input len: %d", len(text))
tmp = make_temp(text, decode=False, delete_tmpfiles=self.delete_tmpfiles)
com_list = [
self.xmlsec,
"--encrypt",
"--pubkey-cert-pem",
recv_key,
"--session-key",
session_key_type,
"--xml-data",
tmp.name,
]
if xpath:
com_list.extend(["--node-xpath", xpath])
try:
(_stdout, _stderr, output) = self._run_xmlsec(com_list, [template])
except XmlsecError as e:
raise EncryptError(com_list) from e
return output
def encrypt_assertion(self, statement, enc_key, template, key_type="des-192", node_xpath=None, node_id=None):
"""
Will encrypt an assertion
:param statement: A XML document that contains the assertion to encrypt
:param enc_key: File name of a file containing the encryption key
:param template: A template for the encryption part to be added.
:param key_type: The type of session key to use.
:return: The encrypted text
"""
if isinstance(statement, SamlBase):
statement = pre_encrypt_assertion(statement)
tmp = make_temp(str(statement), decode=False, delete_tmpfiles=self.delete_tmpfiles)
tmp2 = make_temp(str(template), decode=False, delete_tmpfiles=self.delete_tmpfiles)
if not node_xpath:
node_xpath = ASSERT_XPATH
com_list = [
self.xmlsec,
"--encrypt",
"--pubkey-cert-pem",
enc_key,
"--session-key",
key_type,
"--xml-data",
tmp.name,
"--node-xpath",
node_xpath,
]
if node_id:
com_list.extend(["--node-id", node_id])
try:
(_stdout, _stderr, output) = self._run_xmlsec(com_list, [tmp2.name])
except XmlsecError as e:
raise EncryptError(com_list) from e
return output.decode("utf-8")
def decrypt(self, enctext, key_file):
"""
:param enctext: XML document containing an encrypted part
:param key_file: The key to use for the decryption
:return: The decrypted document
"""
logger.debug("Decrypt input len: %d", len(enctext))
tmp = make_temp(enctext, decode=False, delete_tmpfiles=self.delete_tmpfiles)
com_list = [
self.xmlsec,
"--decrypt",
"--privkey-pem",
key_file,
"--id-attr:Id",
ENC_KEY_CLASS,
]
try:
(_stdout, _stderr, output) = self._run_xmlsec(com_list, [tmp.name])
except XmlsecError as e:
raise DecryptError(com_list) from e
return output.decode("utf-8")
def sign_statement(self, statement, node_name, key_file, node_id):
"""
Sign an XML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key_file: The file where the key can be found
:param node_id:
:return: The signed statement
"""
if isinstance(statement, SamlBase):
statement = str(statement)
tmp = make_temp(statement, suffix=".xml", decode=False, delete_tmpfiles=self.delete_tmpfiles)
com_list = [
self.xmlsec,
"--sign",
"--privkey-pem",
key_file,
"--id-attr:ID",
node_name,
]
if node_id:
com_list.extend(["--node-id", node_id])
try:
(stdout, stderr, output) = self._run_xmlsec(com_list, [tmp.name])
except XmlsecError as e:
raise SignatureError(com_list) from e
# this does not work if --store-signatures is used
if output:
return output.decode("utf-8")
if stdout:
return stdout.decode("utf-8")
raise SignatureError(stderr)
def validate_signature(self, signedtext, cert_file, cert_type, node_name, node_id):
"""
Validate signature on XML document.
:param signedtext: The XML document as a string
:param cert_file: The public key that was used to sign the document
:param cert_type: The file type of the certificate
:param node_name: The name of the class that is signed
:param node_id: The identifier of the node
:return: Boolean True if the signature was correct otherwise False.
"""
if not isinstance(signedtext, bytes):
signedtext = signedtext.encode("utf-8")
tmp = make_temp(signedtext, suffix=".xml", decode=False, delete_tmpfiles=self.delete_tmpfiles)
com_list = [
self.xmlsec,
"--verify",
"--enabled-reference-uris",
"empty,same-doc",
"--enabled-key-data",
"raw-x509-cert",
f"--pubkey-cert-{cert_type}",
cert_file,
"--id-attr:ID",
node_name,
]
if node_id:
com_list.extend(["--node-id", node_id])
try:
(_stdout, stderr, _output) = self._run_xmlsec(com_list, [tmp.name])
except XmlsecError as e:
raise SignatureError(com_list) from e
return parse_xmlsec_verify_output(stderr, self.version_nums)
def _run_xmlsec(self, com_list, extra_args):
"""
Common code to invoke xmlsec and parse the output.
:param com_list: Key-value parameter list for xmlsec
:param extra_args: Positional parameters to be appended after all
key-value parameters
:result: Whatever xmlsec wrote to an --output temporary file
"""
with NamedTemporaryFile(suffix=".xml") as ntf:
com_list.extend(["--output", ntf.name])
if self.version_nums >= (1, 3):
com_list.extend(['--lax-key-search'])
com_list += extra_args
logger.debug("xmlsec command: %s", " ".join(com_list))
pof = Popen(com_list, stderr=PIPE, stdout=PIPE)
p_out, p_err = pof.communicate()
p_out = p_out.decode()
p_err = p_err.decode()
if pof.returncode != 0:
errmsg = f"returncode={pof.returncode}\nerror={p_err}\noutput={p_out}"
logger.error(errmsg)
raise XmlsecError(errmsg)
ntf.seek(0)
return p_out, p_err, ntf.read()
class CryptoBackendXMLSecurity(CryptoBackend):
"""
CryptoBackend implementation using pyXMLSecurity to sign and verify
XML documents.
Encrypt and decrypt is currently unsupported by pyXMLSecurity.
pyXMLSecurity uses lxml (libxml2) to parse XML data, but otherwise
try to get by with native Python code. It does native Python RSA
signatures, or alternatively PyKCS11 to offload cryptographic work
to an external PKCS#11 module.
"""
def __init__(self):
CryptoBackend.__init__(self)
@property
def version(self):
try:
import xmlsec
return xmlsec.__version__
except (ImportError, AttributeError):
return "0.0.0"
def sign_statement(self, statement, node_name, key_file, node_id):
"""
Sign an XML statement.
The parameters actually used in this CryptoBackend
implementation are :
:param statement: XML as string
:param node_name: Name of the node to sign
:param key_file: xmlsec key_spec string(), filename,
'pkcs11://' URI or PEM data
:returns: Signed XML as string
"""
import lxml.etree
import xmlsec
xml = xmlsec.parse_xml(statement)
signed = xmlsec.sign(xml, key_file)
signed_str = lxml.etree.tostring(signed, xml_declaration=False, encoding="UTF-8")
if not isinstance(signed_str, str):
signed_str = signed_str.decode("utf-8")
return signed_str
def validate_signature(self, signedtext, cert_file, cert_type, node_name, node_id):
"""
Validate signature on XML document.
The parameters actually used in this CryptoBackend
implementation are :
:param signedtext: The signed XML data as string
:param cert_file: xmlsec key_spec string(), filename,
'pkcs11://' URI or PEM data
:param cert_type: string, must be 'pem' for now
:returns: True on successful validation, False otherwise
"""
if cert_type != "pem":
raise Unsupported("Only PEM certs supported here")
import xmlsec
xml = xmlsec.parse_xml(signedtext)
try:
return xmlsec.verify(xml, cert_file)
except xmlsec.XMLSigException:
return False
def security_context(conf):
"""Creates a security context based on the configuration
:param conf: The configuration, this is a Config instance
:return: A SecurityContext instance
"""
if not conf:
return None
try:
metadata = conf.metadata
except AttributeError:
metadata = None
sec_backend = None
if conf.crypto_backend == "xmlsec1":
xmlsec_binary = conf.xmlsec_binary
if not xmlsec_binary:
try:
_path = conf.xmlsec_path
except AttributeError:
_path = []
xmlsec_binary = get_xmlsec_binary(_path)
# verify that xmlsec is where it's supposed to be
if not os.path.exists(xmlsec_binary):
# if not os.access(, os.F_OK):
err_msg = "xmlsec binary not found: {binary}"
err_msg = err_msg.format(binary=xmlsec_binary)
raise SigverError(err_msg)
crypto = _get_xmlsec_cryptobackend(xmlsec_binary, delete_tmpfiles=conf.delete_tmpfiles)
_file_name = conf.getattr("key_file", "")
if _file_name:
try:
rsa_key = import_rsa_key_from_file(_file_name)
except Exception as err:
logger.error(f"Cannot import key from {_file_name}: {err}")
raise
else:
sec_backend = RSACrypto(rsa_key)
elif conf.crypto_backend == "XMLSecurity":
# new and somewhat untested pyXMLSecurity crypto backend.
crypto = CryptoBackendXMLSecurity()
else:
err_msg = "Unknown crypto_backend {backend}"
err_msg = err_msg.format(backend=conf.crypto_backend)
raise SigverError(err_msg)