How to use the defusedxml.minidom.parseString function in defusedxml

To help you get started, we’ve selected a few defusedxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PyCQA / bandit / examples / xml_minidom.py View on Github external
from xml.dom.minidom import parseString as badParseString
from defusedxml.minidom import parseString as goodParseString
a = badParseString("Some data some more data")
print(a)
b = goodParseString("Some data some more data")
print(b)


from xml.dom.minidom import parse as badParse
from defusedxml.minidom import parse as goodParse
a = badParse("somfilethatdoesntexist.xml")
print(a)
b = goodParse("somefilethatdoesntexist.xml")
print(b)
github onelogin / python-saml / src / onelogin / saml2 / utils.py View on Github external
# Prepare for encryption
            enc_data = EncData(xmlsec.TransformAes128Cbc, type=xmlsec.TypeEncElement)
            enc_data.ensureCipherValue()
            key_info = enc_data.ensureKeyInfo()
            # enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaPkcs1)
            enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaOaep)
            enc_key.ensureCipherValue()

            # Encrypt!
            enc_ctx = xmlsec.EncCtx(mngr)
            enc_ctx.encKey = xmlsec.Key.generate(xmlsec.KeyDataAes, 128, xmlsec.KeyDataTypeSession)

            edata = enc_ctx.encryptXml(enc_data, elem[0])

            newdoc = parseString(tostring(edata, encoding='unicode').encode('utf-8'), forbid_dtd=True)

            if newdoc.hasChildNodes():
                child = newdoc.firstChild
                child.removeAttribute('xmlns')
                child.removeAttribute('xmlns:saml')
                child.setAttribute('xmlns:xenc', OneLogin_Saml2_Constants.NS_XENC)
                child.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)

            nodes = newdoc.getElementsByTagName("*")
            for node in nodes:
                if node.tagName == 'ns0:KeyInfo':
                    node.tagName = 'dsig:KeyInfo'
                    node.removeAttribute('xmlns:ns0')
                    node.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)
                else:
                    node.tagName = 'xenc:' + node.tagName
github dkmstr / openuds / server / src / uds / services / OpenNebula / on / vm.py View on Github external
def getNetInfo(api: 'client.OpenNebulaClient', machineId: str, networkId: typing.Optional[str] = None) -> typing.Tuple[str, str]:
    '''
    Get the MAC and the IP for the network and machine. If network is None, for the first network
    '''
    # md = minidom.parseString(api.call('vm.info', int(machineId)))
    md = minidom.parseString(api.VMInfo(machineId).xml)
    node = md

    try:
        for nic in md.getElementsByTagName('NIC'):
            netId = nic.getElementsByTagName('NETWORK_ID')[0].childNodes[0].data
            if networkId is None or int(netId) == int(networkId):
                node = nic
                break
    except Exception:
        raise Exception('No network interface found on template. Please, add a network and republish.')

    logger.debug(node.toxml())

    # Default, returns first MAC found (or raise an exception if there is no MAC)
    try:
        try:
github opencv / dldt / model-optimizer / mo / middle / passes / tensor_names.py View on Github external
continue
                map = SubElement(mapping, 'map')
                fw = SubElement(map, 'framework')
                ie = SubElement(map, 'IR')

                fw.set('name', fw_tensor_debug_info[0])
                fw.set('out_port_id', str(fw_tensor_debug_info[1]))

                if node.has_valid('ie_tensor_name'):
                    ie.set('name', node.ie_tensor_name)
                if node.has_valid('ie_tensor_port'):
                    ie.set('out_port_id', str(node.ie_tensor_port))
                if node.has_valid('ie_tensor_id'):
                    ie.set('id', str(node.ie_tensor_id))
    with open(xml_file_name, 'w') as file:
        file.write(parseString(tostring(mapping)).toprettyxml())
github moloch-- / RootTheBox / handlers / AdminHandlers / AdminGameHandlers.py View on Github external
def post(self, *args, **kwargs):
        """ Include the requests exports in the xml dom """
        root = ET.Element("rootthebox")
        root.set("api", self.API_VERSION)
        if self.get_argument("game_config", "") == "true":
            self.export_game_config(root)
        if self.get_argument("game_objects", "") == "true":
            self.export_game_objects(root)
        xml_dom = defusedxml.minidom.parseString(ET.tostring(root))
        self.write_xml(xml_dom.toprettyxml())
github EUDAT-B2SAFE / B2SAFE-core / cmd / epicclient.py View on Github external
def __init__(self, field, debug=False):
        self.domfield = minidom.parseString(field)
        self.debug = debug
github dundua / IG-Downloader / instagram.py View on Github external
resp: JSON dictionary of reel from IG API

        Returns:
            None
        """
        try:
            for index,item in enumerate(resp["post_live"]["post_live_items"]):
                logging.debug('    ' + str(index))
                username = item["user"]["username"]
                userpk = item["user"]["pk"]
                for bindex,broadcast in enumerate(item["broadcasts"]):
                    logging.debug('        ' + str(bindex))
                    timestamp = broadcast["published_time"]
                    postid = broadcast["media_id"]
                    dash = broadcast["dash_manifest"]
                    dashxml = xml.parseString(dash)
                    elements = dashxml.getElementsByTagName("BaseURL")
                    for eindex,element in enumerate(elements):
                        for node in element.childNodes:
                            if node.nodeType == node.TEXT_NODE:
                                url = node.data
                                mediatype = 3
                                path = self.formatPath(username, userpk, timestamp, postid + "_" + str(eindex), mediatype)
                                self.getFile(url, path)
        except KeyError: # No "post_live" key
            logging.debug('    ' + 'No live stories.')
github dkmstr / openuds / server / src / uds / services / OpenNebula / on / template.py View on Github external
def remove(api: 'client.OpenNebulaClient', templateId: str) -> None:
    """
    Removes a template from ovirt server

    Returns nothing, and raises an Exception if it fails
    """
    try:
        # First, remove Images (wont be possible if there is any images already in use, but will try)
        # Now copy cloned images if possible
        try:
            imgs = {i.name: i.id for i in api.enumImages()}

            info = api.templateInfo(templateId).xml
            template = minidom.parseString(info).getElementsByTagName('TEMPLATE')[0]
            logger.debug('XML: %s', template.toxml())

            for dsk in template.getElementsByTagName('DISK'):
                imgIds = dsk.getElementsByTagName('IMAGE_ID')
                if not imgIds:
                    try:
                        node = dsk.getElementsByTagName('IMAGE')[0].childNodes[0]
                    except IndexError:
                        continue
                    imgId = imgs[node.data]
                else:
                    node = imgIds[0].childNodes[0]
                    imgId = node.data

                logger.debug('Found %s for cloning', imgId)