本文整理汇总了Python中onelogin.saml2.xml_utils.OneLogin_Saml2_XML类的典型用法代码示例。如果您正苦于以下问题:Python OneLogin_Saml2_XML类的具体用法?Python OneLogin_Saml2_XML怎么用?Python OneLogin_Saml2_XML使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OneLogin_Saml2_XML类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_metadata
def get_metadata(url):
"""
Gets the metadata XML from the provided URL
:param url: Url where the XML of the Identity Provider Metadata is published.
:type url: string
:returns: metadata XML
:rtype: string
"""
valid = False
response = urllib2.urlopen(url)
xml = response.read()
if xml:
try:
dom = OneLogin_Saml2_XML.to_etree(xml)
idp_descriptor_nodes = OneLogin_Saml2_XML.query(dom, '//md:IDPSSODescriptor')
if idp_descriptor_nodes:
valid = True
except:
pass
if not valid:
raise Exception('Not valid IdP XML found from URL: %s' % (url))
return xml
示例2: get_status
def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) != 1:
raise Exception('Missing valid Status on response')
code_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) != 1:
raise Exception('Missing valid Status Code on response')
code = code_entry[0].values()[0]
status['code'] = code
status['msg'] = ''
message_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) == 1:
status['msg'] = subcode_entry[0].values()[0]
elif len(message_entry) == 1:
status['msg'] = message_entry[0].text
return status
示例3: add_x509_key_descriptors
def add_x509_key_descriptors(metadata, cert=None):
"""
Adds the x509 descriptors (sign/encriptation) to the metadata
The same cert will be used for sign/encrypt
:param metadata: SAML Metadata XML
:type metadata: string
:param cert: x509 cert
:type cert: string
:returns: Metadata with KeyDescriptors
:rtype: string
"""
if cert is None or cert == '':
return metadata
try:
root = OneLogin_Saml2_XML.to_etree(metadata)
except Exception as e:
raise Exception('Error parsing metadata. ' + str(e))
assert root.tag == '{%s}EntityDescriptor' % OneLogin_Saml2_Constants.NS_MD
try:
sp_sso_descriptor = next(root.iterfind('.//md:SPSSODescriptor', namespaces=OneLogin_Saml2_Constants.NSMAP))
except StopIteration:
raise Exception('Malformed metadata.')
OneLogin_Saml2_Metadata.__add_x509_key_descriptors(sp_sso_descriptor, cert, False)
OneLogin_Saml2_Metadata.__add_x509_key_descriptors(sp_sso_descriptor, cert, True)
return OneLogin_Saml2_XML.to_string(root)
示例4: generate_name_id
def generate_name_id(value, sp_nq, sp_format, cert=None, debug=False, nq=None):
"""
Generates a nameID.
:param value: fingerprint
:type: string
:param sp_nq: SP Name Qualifier
:type: string
:param sp_format: SP Format
:type: string
:param cert: IdP Public Cert to encrypt the nameID
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:returns: DOMElement | XMLSec nameID
:rtype: string
:param nq: IDP Name Qualifier
:type: string
"""
root = OneLogin_Saml2_XML.make_root("{%s}container" % OneLogin_Saml2_Constants.NS_SAML)
name_id = OneLogin_Saml2_XML.make_child(root, '{%s}NameID' % OneLogin_Saml2_Constants.NS_SAML)
if sp_nq is not None:
name_id.set('SPNameQualifier', sp_nq)
name_id.set('Format', sp_format)
if nq is not None:
name_id.set('NameQualifier', nq)
name_id.text = value
if cert is not None:
xmlsec.enable_debug_trace(debug)
# Load the public cert
manager = xmlsec.KeysManager()
manager.add_key(xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None))
# Prepare for encryption
enc_data = xmlsec.template.encrypted_data_create(
root, xmlsec.Transform.AES128, type=xmlsec.EncryptionType.ELEMENT, ns="xenc")
xmlsec.template.encrypted_data_ensure_cipher_value(enc_data)
key_info = xmlsec.template.encrypted_data_ensure_key_info(enc_data, ns="dsig")
enc_key = xmlsec.template.add_encrypted_key(key_info, xmlsec.Transform.RSA_OAEP)
xmlsec.template.encrypted_data_ensure_cipher_value(enc_key)
# Encrypt!
enc_ctx = xmlsec.EncryptionContext(manager)
enc_ctx.key = xmlsec.Key.generate(xmlsec.KeyData.AES, 128, xmlsec.KeyDataType.SESSION)
enc_data = enc_ctx.encrypt_xml(enc_data, name_id)
return '<saml:EncryptedID>' + compat.to_string(OneLogin_Saml2_XML.to_string(enc_data)) + '</saml:EncryptedID>'
else:
return OneLogin_Saml2_XML.extract_tag_text(root, "saml:NameID")
示例5: validate_node_sign
def validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False):
"""
Validates a signature node.
:param signature_node: The signature node
:type: Node
:param xml: The element we should validate
:type: Document
:param cert: The public cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm used to build the fingerprint
:type: string
:param validatecert: If true, will verify the signature and if the cert is valid.
:type: bool
:param debug: Activate the xmlsec debug
:type: bool
"""
try:
if (cert is None or cert == '') and fingerprint:
x509_certificate_nodes = OneLogin_Saml2_XML.query(signature_node, '//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate')
if len(x509_certificate_nodes) > 0:
x509_certificate_node = x509_certificate_nodes[0]
x509_cert_value = x509_certificate_node.text
x509_fingerprint_value = OneLogin_Saml2_Utils.calculate_x509_fingerprint(x509_cert_value, fingerprintalg)
if fingerprint == x509_fingerprint_value:
cert = OneLogin_Saml2_Utils.format_cert(x509_cert_value)
if cert is None or cert == '':
return False
# Check if Reference URI is empty
reference_elem = OneLogin_Saml2_XML.query(signature_node, '//ds:Reference')
if len(reference_elem) > 0:
if reference_elem[0].get('URI') == '':
reference_elem[0].set('URI', '#%s' % signature_node.getparent().get('ID'))
if validatecert:
manager = xmlsec.KeysManager()
manager.load_cert_from_memory(cert, xmlsec.KeyFormat.CERT_PEM, xmlsec.KeyDataType.TRUSTED)
dsig_ctx = xmlsec.SignatureContext(manager)
else:
dsig_ctx = xmlsec.SignatureContext()
dsig_ctx.key = xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None)
dsig_ctx.set_enabled_key_data([xmlsec.KeyData.X509])
dsig_ctx.verify(signature_node)
return True
except xmlsec.Error as e:
if debug:
print(e)
示例6: validate_metadata_sign
def validate_metadata_sign(
xml, cert=None, fingerprint=None, fingerprintalg="sha1", validatecert=False, debug=False
):
"""
Validates a signature of a EntityDescriptor.
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm used to build the fingerprint
:type: string
:param validatecert: If true, will verify the signature and if the cert is valid.
:type: bool
:param debug: Activate the xmlsec debug
:type: bool
"""
try:
if xml is None or xml == "":
raise Exception("Empty string supplied as input")
elem = OneLogin_Saml2_XML.to_etree(xml)
xmlsec.enable_debug_trace(debug)
xmlsec.tree.add_ids(elem, ["ID"])
signature_nodes = OneLogin_Saml2_XML.query(elem, "/md:EntitiesDescriptor/ds:Signature")
if len(signature_nodes) == 0:
signature_nodes += OneLogin_Saml2_XML.query(elem, "/md:EntityDescriptor/ds:Signature")
if len(signature_nodes) == 0:
signature_nodes += OneLogin_Saml2_XML.query(
elem, "/md:EntityDescriptor/md:SPSSODescriptor/ds:Signature"
)
signature_nodes += OneLogin_Saml2_XML.query(
elem, "/md:EntityDescriptor/md:IDPSSODescriptor/ds:Signature"
)
if len(signature_nodes) > 0:
for signature_node in signature_nodes:
if not OneLogin_Saml2_Utils.validate_node_sign(
signature_node, elem, cert, fingerprint, fingerprintalg, validatecert, debug
):
return False
return True
else:
return False
except Exception:
return False
示例7: validate_num_assertions
def validate_num_assertions(self):
"""
Verifies that the document only contains a single Assertion (encrypted or not)
:returns: True if only 1 assertion encrypted or not
:rtype: bool
"""
encrypted_assertion_nodes = OneLogin_Saml2_XML.query(self.document, '//saml:EncryptedAssertion')
assertion_nodes = OneLogin_Saml2_XML.query(self.document, '//saml:Assertion')
return (len(encrypted_assertion_nodes) + len(assertion_nodes)) == 1
示例8: __add_x509_key_descriptors
def __add_x509_key_descriptors(root, cert, signing):
key_descriptor = OneLogin_Saml2_XML.make_child(root, '{%s}KeyDescriptor' % OneLogin_Saml2_Constants.NS_MD)
root.remove(key_descriptor)
root.insert(0, key_descriptor)
key_info = OneLogin_Saml2_XML.make_child(key_descriptor, '{%s}KeyInfo' % OneLogin_Saml2_Constants.NS_DS)
key_data = OneLogin_Saml2_XML.make_child(key_info, '{%s}X509Data' % OneLogin_Saml2_Constants.NS_DS)
x509_certificate = OneLogin_Saml2_XML.make_child(key_data, '{%s}X509Certificate' % OneLogin_Saml2_Constants.NS_DS)
x509_certificate.text = OneLogin_Saml2_Utils.format_cert(cert, False)
key_descriptor.set('use', ('encryption', 'signing')[signing])
示例9: validate_sign
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False, xpath=None):
"""
Validates a signature (Message or Assertion).
:param xml: The element we should validate
:type: string | Document
:param cert: The public cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm used to build the fingerprint
:type: string
:param validatecert: If true, will verify the signature and if the cert is valid.
:type: bool
:param debug: Activate the xmlsec debug
:type: bool
:param xpath: The xpath of the signed element
:type: string
"""
try:
if xml is None or xml == '':
raise Exception('Empty string supplied as input')
elem = OneLogin_Saml2_XML.to_etree(xml)
xmlsec.enable_debug_trace(debug)
xmlsec.tree.add_ids(elem, ["ID"])
if xpath:
signature_nodes = OneLogin_Saml2_XML.query(elem, xpath)
else:
signature_nodes = OneLogin_Saml2_XML.query(elem, OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
if len(signature_nodes) == 0:
signature_nodes = OneLogin_Saml2_XML.query(elem, OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
if len(signature_nodes) == 1:
signature_node = signature_nodes[0]
return OneLogin_Saml2_Utils.validate_node_sign(signature_node, elem, cert, fingerprint, fingerprintalg, validatecert, debug)
else:
return False
except xmlsec.Error as e:
if debug:
print(e)
return False
示例10: validate_sign
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg="sha1", validatecert=False, debug=False):
"""
Validates a signature (Message or Assertion).
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm used to build the fingerprint
:type: string
:param validatecert: If true, will verify the signature and if the cert is valid.
:type: bool
:param debug: Activate the xmlsec debug
:type: bool
"""
try:
if xml is None or xml == "":
raise Exception("Empty string supplied as input")
elem = OneLogin_Saml2_XML.to_etree(xml)
xmlsec.enable_debug_trace(debug)
xmlsec.tree.add_ids(elem, ["ID"])
signature_nodes = OneLogin_Saml2_XML.query(elem, "/samlp:Response/ds:Signature")
if not len(signature_nodes) > 0:
signature_nodes += OneLogin_Saml2_XML.query(
elem, "/samlp:Response/saml:EncryptedAssertion/saml:Assertion/ds:Signature"
)
signature_nodes += OneLogin_Saml2_XML.query(elem, "/samlp:Response/saml:Assertion/ds:Signature")
if len(signature_nodes) == 1:
signature_node = signature_nodes[0]
return OneLogin_Saml2_Utils.validate_node_sign(
signature_node, elem, cert, fingerprint, fingerprintalg, validatecert, debug
)
else:
return False
except xmlsec.Error as e:
if debug:
print(e)
return False
示例11: get_issuer
def get_issuer(request):
"""
Gets the Issuer of the Logout Request Message
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The Issuer
:rtype: string
"""
elem = OneLogin_Saml2_XML.to_etree(request)
issuer = None
issuer_nodes = OneLogin_Saml2_XML.query(elem, '/samlp:LogoutRequest/saml:Issuer')
if len(issuer_nodes) == 1:
issuer = issuer_nodes[0].text
return issuer
示例12: get_session_indexes
def get_session_indexes(request):
"""
Gets the SessionIndexes from the Logout Request
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The SessionIndex value
:rtype: list
"""
elem = OneLogin_Saml2_XML.to_etree(request)
session_indexes = []
session_index_nodes = OneLogin_Saml2_XML.query(elem, '/samlp:LogoutRequest/samlp:SessionIndex')
for session_index_node in session_index_nodes:
session_indexes.append(session_index_node.text)
return session_indexes
示例13: validate_signed_elements
def validate_signed_elements(self, signed_elements):
"""
Verifies that the document has the expected signed nodes.
"""
if len(signed_elements) > 2:
return False
response_tag = '{%s}Response' % OneLogin_Saml2_Constants.NS_SAMLP
assertion_tag = '{%s}Assertion' % OneLogin_Saml2_Constants.NS_SAML
if (response_tag in signed_elements and signed_elements.count(response_tag) > 1) or \
(assertion_tag in signed_elements and signed_elements.count(assertion_tag) > 1) or \
(response_tag not in signed_elements and assertion_tag not in signed_elements):
return False
# Check that the signed elements found here, are the ones that will be verified
# by OneLogin_Saml2_Utils.validate_sign
if response_tag in signed_elements:
expected_signature_nodes = OneLogin_Saml2_XML.query(self.document, OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise Exception('Unexpected number of Response signatures found. SAML Response rejected.')
if assertion_tag in signed_elements:
expected_signature_nodes = self.__query(OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise Exception('Unexpected number of Assertion signatures found. SAML Response rejected.')
return True
示例14: __query
def __query(self, query):
"""
Extracts a node from the Etree (Logout Response Message)
:param query: Xpath Expression
:type query: string
:return: The queried node
:rtype: Element
"""
return OneLogin_Saml2_XML.query(self.document, query)
示例15: __decrypt_assertion
def __decrypt_assertion(self, xml):
"""
Decrypts the Assertion
:raises: Exception if no private key available
:param xml: Encrypted Assertion
:type xml: Element
:returns: Decrypted Assertion
:rtype: Element
"""
key = self.__settings.get_sp_key()
debug = self.__settings.is_debug_active()
if not key:
raise Exception('No private key available, check settings')
encrypted_assertion_nodes = OneLogin_Saml2_XML.query(xml, '/samlp:Response/saml:EncryptedAssertion')
if encrypted_assertion_nodes:
encrypted_data_nodes = OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData')
if encrypted_data_nodes:
keyinfo = OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo')
if not keyinfo:
raise Exception('No KeyInfo present, invalid Assertion')
keyinfo = keyinfo[0]
children = keyinfo.getchildren()
if not children:
raise Exception('No child to KeyInfo, invalid Assertion')
for child in children:
if 'RetrievalMethod' in child.tag:
if child.attrib['Type'] != 'http://www.w3.org/2001/04/xmlenc#EncryptedKey':
raise Exception('Unsupported Retrieval Method found')
uri = child.attrib['URI']
if not uri.startswith('#'):
break
uri = uri.split('#')[1]
encrypted_key = OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0], './xenc:EncryptedKey[@Id="' + uri + '"]')
if encrypted_key:
keyinfo.append(encrypted_key[0])
encrypted_data = encrypted_data_nodes[0]
decrypted = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key, debug)
xml.replace(encrypted_assertion_nodes[0], decrypted)
return xml