Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if elt is not None:
nslist = elt.get('PrefixList', '').split()
return _c14n(t, exclusive=True, with_comments=True, inclusive_prefix_list=nslist, schema=schema)
if uri == constants.TRANSFORM_C14N_EXCLUSIVE:
nslist = None
if tr is not None:
elt = tr.find(".//{%s}InclusiveNamespaces" % 'http://www.w3.org/2001/10/xml-exc-c14n#')
if elt is not None:
nslist = elt.get('PrefixList', '').split()
return _c14n(t, exclusive=True, with_comments=False, inclusive_prefix_list=nslist, schema=schema)
if uri == constants.TRANSFORM_C14N_INCLUSIVE:
return _c14n(t, exclusive=False, with_comments=False, schema=schema)
raise XMLSigException("unknown or unimplemented transform %s" % uri)
logging.debug("transform: %s" % _alg(tr))
obj = _transform(_alg(tr), obj, tr=tr, sig_path=sig_path)
if not isinstance(obj, basestring):
if config.debug_write_to_files:
with open("/tmp/foo-pre-serialize.xml", "w") as fd:
fd.write(etree.tostring(obj))
obj = _transform(constants.TRANSFORM_C14N_INCLUSIVE, obj)
if config.debug_write_to_files:
with open("/tmp/foo-obj.xml", "w") as fd:
fd.write(obj)
dm = ref.find(".//{%s}DigestMethod" % NS['ds'])
if dm is None:
raise XMLSigException("Unable to find DigestMethod")
hash_alg = (_alg(dm).split("#"))[1]
logging.debug("using hash algorithm %s" % hash_alg)
digest = _digest(obj, hash_alg)
logging.debug("using digest %s (%s) for ref %s" % (digest, hash_alg, uri))
dv = ref.find(".//{%s}DigestValue" % NS['ds'])
logging.debug(etree.tostring(dv))
dv.text = digest
if return_verified:
return verified_objects
else:
return None
def _try_a_to_b(dic, item):
try:
return dic[item]
except KeyError:
raise XMLSigException("Algorithm '%s' not supported." % item)
verified_objects = []
for ref in sig.findall(".//{%s}Reference" % NS['ds']):
obj = None
hash_alg = None
uri = ref.get('URI', None)
if uri is None or uri == '#' or uri == '':
ct = _remove_child_comments(_implicit_same_document(t, sig))
obj = root_elt(ct)
elif uri.startswith('#'):
ct = copy.deepcopy(t)
obj = _remove_child_comments(_get_by_id(ct, uri[1:]))
else:
raise XMLSigException("Unknown reference %s" % uri)
if obj is None:
raise XMLSigException("Unable to dereference Reference URI='%s'" % uri)
if return_verified:
verified_objects.append(copy.deepcopy(obj))
if config.debug_write_to_files:
with open("/tmp/foo-pre-transform.xml", "w") as fd:
fd.write(etree.tostring(obj))
for tr in ref.findall(".//{%s}Transform" % NS['ds']):
logging.debug("transform: %s" % _alg(tr))
obj = _transform(_alg(tr), obj, tr=tr, sig_path=sig_path)
if not isinstance(obj, basestring):
if config.debug_write_to_files:
with open("/tmp/foo-pre-serialize.xml", "w") as fd:
fd.write(etree.tostring(obj))
def sign(self, data, hash_alg, pad_alg="PKCS1v15"):
if self.is_private:
if not isinstance(data, six.binary_type):
data = unicode_to_bytes(data)
hasher = getattr(hashes, hash_alg)
padder = getattr(padding, pad_alg)
return self.key.sign(data, padder(), hasher())
else:
raise XMLSigException('Signing is only possible with a private key.')
def _cert2dict(cert):
"""
Build cert_dict similar to old rsa_x509_pem backend. Shouldn't
be used by new code.
@param cert A cryptography.x509.Certificate object
"""
key = cert.public_key()
if not isinstance(key, rsa.RSAPublicKey):
raise XMLSigException("We don't support non-RSA public keys at the moment.")
cdict = dict()
cdict['type'] = "X509 CERTIFICATE"
cdict['pem'] = cert.public_bytes(encoding=serialization.Encoding.PEM)
cdict['body'] = b64encode(cert.public_bytes(encoding=serialization.Encoding.DER))
n = key.public_numbers()
cdict['modulus'] = n.n
cdict['publicExponent'] = n.e
cdict['subject'] = cert.subject
cdict['cert'] = RSAobjShim(cert)
return cdict
def parse_uri(pk11_uri):
o = urlparse(pk11_uri)
if o.scheme != 'pkcs11':
raise XMLSigException("Bad URI scheme in pkcs11 URI %s" % pk11_uri)
logging.debug("parsed pkcs11 uri: %s" % repr(o))
slot = None
library = None
keyname = None
query = {}
if not '/' in o.path:
raise XMLSigException("Missing keyname part in pkcs11 URI (pkcs11://[library[:slot]/]keyname[?pin=])")
(module_path, sep, keyqs) = o.path.rpartition('/')
qs = o.query
if qs:
keyname = keyqs
__author__ = 'leifj'
from xmlsec.exceptions import XMLSigException
from six.moves.urllib_parse import urlparse
import os
import logging
from xmlsec.utils import b642pem
_modules = {}
try:
import PyKCS11
from PyKCS11.LowLevel import CKA_ID, CKA_LABEL, CKA_CLASS, CKO_PRIVATE_KEY, CKO_CERTIFICATE, CKK_RSA, CKA_KEY_TYPE, CKA_VALUE
except ImportError:
raise XMLSigException("pykcs11 is required for PKCS#11 keys - cf README.rst")
all_attributes = list(PyKCS11.CKA.keys())
# remove the CKR_ATTRIBUTE_SENSITIVE attributes since we can't get
all_attributes.remove(PyKCS11.LowLevel.CKA_PRIVATE_EXPONENT)
all_attributes.remove(PyKCS11.LowLevel.CKA_PRIME_1)
all_attributes.remove(PyKCS11.LowLevel.CKA_PRIME_2)
all_attributes.remove(PyKCS11.LowLevel.CKA_EXPONENT_1)
all_attributes.remove(PyKCS11.LowLevel.CKA_EXPONENT_2)
all_attributes.remove(PyKCS11.LowLevel.CKA_COEFFICIENT)
all_attributes = [e for e in all_attributes if isinstance(e, int)]
def parse_uri(pk11_uri):
o = urlparse(pk11_uri)
if o.scheme != 'pkcs11':
def _cm_alg(si):
cm = si.find(".//{%s}CanonicalizationMethod" % NS['ds'])
cm_alg = _alg(cm)
if cm is None or cm_alg is None:
raise XMLSigException("No CanonicalizationMethod")
return cm_alg