How to use the defusedxml.ElementTree.fromstring 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 kubernetes / test-infra / kettle / make_json.py View on Github external
def parse_junit(xml):
    """Generate failed tests as a series of dicts. Ignore skipped tests."""
    # NOTE: this is modified from gubernator/view_build.py

    try:
        tree = ET.fromstring(xml)
    except ET.ParseError:
        print("Malformed xml, skipping")
        return [] #return empty itterator to skip results for this test


    # pylint: disable=redefined-outer-name

    def make_result(name, time, failure_text):
        if failure_text:
            if time is None:
                return {'name': name, 'failed': True, 'failure_text': failure_text}
            return {'name': name, 'time': time, 'failed': True, 'failure_text': failure_text}
        if time is None:
            return {'name': name}
        return {'name': name, 'time': time}
github DefectDojo / django-DefectDojo / dojo / unittests / test_dependency_check_parser.py View on Github external
<source>Reference1
http://localhost/badvulnerability.htm
Reference Name


<source>MISC
http://localhost2/reference_for_badvulnerability.pdf
Reference for a bad vulnerability



cpe:/a:component2:component2:1.0

"""

        vulnerability = ElementTree.fromstring(finding_xml)

        expected_references = 'name: Reference Name\nsource: Reference1\nurl: http://localhost/badvulnerability.htm\n\n'
        expected_references += 'name: Reference for a bad vulnerability\nsource: MISC\n'
        expected_references += 'url: http://localhost2/reference_for_badvulnerability.pdf\n\n'

        testfile = TestFile('dp_finding.xml', finding_xml)
        parser = DependencyCheckParser(testfile, Test())
        finding = parser.get_finding_from_vulnerability(vulnerability,
                                                        'testfile.jar', Test())
        self.assertEqual('testfile.jar | CVE-0000-0001', finding.title)
        self.assertEqual('High', finding.severity)
        self.assertEqual(
                'Description of a bad vulnerability.',
                finding.description)
        self.assertEqual(expected_references, finding.references)
github kubernetes / test-infra / gubernator / view_build.py View on Github external
def parse_xml(self, xml, filename):
        if not xml:
            return  # can't extract results from nothing!
        try:
            tree = ET.fromstring(xml)
        except ET.ParseError, e:
            logging.exception('parse_junit failed for %s', filename)
            try:
                tree = ET.fromstring(re.sub(r'[\x00\x80-\xFF]+', '?', xml))
            except ET.ParseError, e:
                if re.match(r'junit.*\.xml', os.path.basename(filename)):
                    self.failed.append(
                        ('Gubernator Internal Fatal XML Parse Error', 0.0, str(e), filename, ''))
                return
        if tree.tag == 'testsuite':
            self.handle_suite(tree, filename)
        elif tree.tag == 'testsuites':
            for testsuite in tree:
                self.handle_suite(testsuite, filename)
        else:
            logging.error('unable to find failures, unexpected tag %s', tree.tag)
github modoboa / modoboa-dmarc / modoboa_dmarc / lib.py View on Github external
def import_report(content):
    """Import an aggregated report."""
    root = fromstring(content, forbid_dtd=True)
    metadata = root.find("report_metadata")
    print(
        "Importing report {} received from {}".format(
            metadata.find("report_id").text,
            metadata.find("org_name").text)
    )
    reporter, created = models.Reporter.objects.get_or_create(
        email=metadata.find("email").text,
        defaults={"org_name": metadata.find("org_name").text}
    )
    qs = models.Report.objects.filter(
        reporter=reporter, report_id=metadata.find("report_id").text)
    if qs.exists():
        print("Report already imported.")
        return
    report = models.Report(reporter=reporter)
github DDMAL / tripoli / tripoli / resource_validators / base_validator.py View on Github external
# Error and exit if XML comments are detected.
        field_contains_comments = bool(self._XML_COMMENT_REGEX.search(value))
        if field_contains_comments:
            self.log_error(field, "XML comments not allowed.")
            return

        # Error and exit if CDATA sections are detected.
        field_contains_cdata = bool(self._XML_CDATA_REGEX.search(value))
        if field_contains_cdata:
            self.log_error(field, "CDATA sections not allowed.")
            return

        # Try to parse the field and record if the field is valid xml.
        if field_contains_tags:
            try:
                et = ET.fromstring(value)
                field_is_valid_xml = True
            except ET.ParseError:
                field_is_valid_xml = False

        # Return now if no tags are found.
        if not field_contains_tags:
            return

        # Log error and return if this field is not allowed to have HTML in it.
        if (field_is_valid_xml or field_contains_tags) and not field_allowed_html:
            self.log_error(field, "HTML not allowed in this field.")
            return

        # Log error and return if the HTML is malformed in some way.
        if field_contains_tags and not field_is_valid_xml:
            self.log_error(field, "Field contains tags but is not valid HTML.")
github mideind / Greynir / doc.py View on Github external
def extract_text(self):

        zipfile = ZipFile(BytesIO(self.data), "r")

        # Verify that archive contains document.xml
        if self.DOCXML_PATH not in zipfile.namelist():
            raise MalformedDocumentError("Malformed docx file")

        # Read xml file from archive
        content = zipfile.read(self.DOCXML_PATH)
        zipfile.close()

        # Parse it
        tree = ElementTree.fromstring(content)

        # Extract text elements from all paragraphs
        # (with special handling of line breaks)
        paragraphs = []
        for p in tree.iter(self.PARAGRAPH_TAG):
            texts = []
            for node in p.iter():
                if node.tag.endswith(self.TEXT_TAG) and node.text:
                    texts.append(node.text)
                elif node.tag.endswith(self.BREAK_TAG):
                    texts.append("\n")
            if texts:
                paragraphs.append("".join(texts))

        return "\n\n".join(paragraphs)
github archerysec / archerysec / archeryapi / views.py View on Github external
"scanner": scanner,
                             "project_id": project_id,
                             "scan_id": scan_id
                             })
        elif scanner == "burp_scan":
            date_time = datetime.datetime.now()
            scan_dump = burp_scan_db(url=scan_url,
                                     scan_id=scan_id,
                                     date_time=date_time,
                                     project_id=project_id,
                                     scan_status=scan_status)
            scan_dump.save()
            # Burp scan XML parser
            root_xml = ET.fromstring(file)
            en_root_xml = ET.tostring(root_xml, encoding='utf8').decode('ascii', 'ignore')
            root_xml_en = ET.fromstring(en_root_xml)

            burp_xml_parser.burp_scan_data(root_xml_en,
                                           project_id,
                                           scan_id)
            return Response({"message": "Burp Scan Data Uploaded",
                             "project_id": project_id,
                             "scan_id": scan_id,
                             "scanner": scanner
                             })

        elif scanner == "arachni":
            date_time = datetime.datetime.now()
            scan_dump = arachni_scan_db(url=scan_url,
                                        scan_id=scan_id,
                                        date_time=date_time,
                                        project_id=project_id,
github home-assistant / home-assistant / homeassistant / components / upc_connect / device_tracker.py View on Github external
async def async_scan_devices(self):
        """Scan for new devices and return a list with found device IDs."""
        import defusedxml.ElementTree as ET

        if self.token is None:
            token_initialized = await self.async_initialize_token()
            if not token_initialized:
                _LOGGER.error("Not connected to %s", self.host)
                return []

        raw = await self._async_ws_function(CMD_DEVICES)

        try:
            xml_root = ET.fromstring(raw)
            return [mac.text for mac in xml_root.iter("MACAddr")]
        except (ET.ParseError, TypeError):
            _LOGGER.warning("Can't read device from %s", self.host)
            self.token = None
            return []
github dtag-dev-sec / PEBA / peba.py View on Github external
def decorated_function(*args, **kwargs):
        postdata = request.data.decode('utf-8')

        if len(postdata) == 0:
            app.logger.error('Authentication: No xml post data in request')
            return abort(403)
        else:
            root = ETdefused.fromstring(postdata)
            user_data = root.find("./Authentication/username")
            pass_data = root.find("./Authentication/token")

            if user_data is None or pass_data is None:
                app.logger.error('Authentication: Invalid XML, token not present or empty')
                return abort(403)

            username = user_data.text
            password = pass_data.text

            if not authenticate(username, password):
                app.logger.error("Authentication failure for user %s", username)
                return abort(403)

            return f(*args, **kwargs)
    return decorated_function