def extract_component_and_version_from_cpe_string(cpe_string): result = None try: cpep = cpe_module.CPE(cpe_string, cpe_module.CPE.VERSION_2_2) except: try: cpep = cpe_module.CPE(cpe_string, cpe_module.CPE.VERSION_2_3) except: try: cpep = cpe_module.CPE(cpe_string, cpe_module.CPE.VERSION_UNDEFINED) except: cpep = None if cpep is not None: c22_product = cpep.get_product() if cpep is not None else [] c22_version = cpep.get_version() if cpep is not None else [] result = dict() result["component"] = c22_product[0] if isinstance( c22_product, list) and len(c22_product) > 0 else None result["version"] = c22_version[0] if isinstance( c22_version, list) and len(c22_version) > 0 else None if result["component"] is None or result["version"] is None: result = None if result["component"] == "" or result["version"] == "": result = None return result
def filter_cpe_string__json(element): """ Filter CPE strings in CVE Items for valid component and version values :param element: :return: json """ result = {"component": None, "version": None} try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_2_2) except ValueError: try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_2_3) except ValueError: try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_UNDEFINED) except NotImplementedError: c22 = None c22_product = c22.get_product() if c22 is not None else [] c22_version = c22.get_version() if c22 is not None else [] result["component"] = c22_product[0] if isinstance( c22_product, list) and len(c22_product) > 0 else None result["version"] = c22_version[0] if isinstance( c22_version, list) and len(c22_version) > 0 else None return result
def get_affected_versions( self, filter_by: typing.Union[tuple, str]) -> typing.List[str]: """Get affected versions. :param filter_by: typing.Union[tuple, str] Either tuple of (vendor, product) or cpe string to uniquely identify which affected products should be returned. :returns: List[str], list of affected versions of a given product """ if isinstance(filter_by, tuple): v_name, p_name = filter_by elif isinstance(filter_by, str): parsed_cpe = cpe.CPE(filter_by) v_name, = parsed_cpe.get_vendor() p_name, = parsed_cpe.get_product() else: raise TypeError("Argument `by` expected to be {}, got {}".format( typing.Union[tuple, str], type(filter_by))) affected_versions = list() for product in self.affects[v_name]: if product.name.startswith(p_name): affected_versions.extend( [version for version in product.version_data]) return affected_versions
def filter_cpe_string__json(self, element): result = {"component": None, "version": None} try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_2_2) except ValueError as value_error: try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_2_3) except ValueError as another_value_error: try: c22 = cpe_module.CPE(element, cpe_module.CPE.VERSION_UNDEFINED) except NotImplementedError as not_implemented_error: c22 = None c22_product = c22.get_product() if c22 is not None else [] c22_version = c22.get_version() if c22 is not None else [] result["component"] = c22_product[0] if isinstance(c22_product, list) and len(c22_product) > 0 else None result["version"] = c22_version[0] if isinstance(c22_version, list) and len(c22_version) > 0 else None return result
def __init__(self, cve=None, **kwargs): ''' Initialze a Holder for CVE Things ''' if cve is None: raise ValueError("CVE ID Required") try: cve_parts = re.search(self._cve_regex, cve, re.I) except Exception as cve_parse_error: self.logger.error("Unable to Parse CVE : {}".format(cve)) raise ValueError("Badly Formatted CVE") else: if cve_parts is not None: self.cve_id = cve.upper() self.cve_year = int(cve_parts.group(1)) self.cve_num = int(cve_parts.group(2)) else: raise ValueError( "Valid CVE ID Required, Recieved {}".format(cve)) self.description = kwargs.get("description", None) self.title = kwargs.get("title", None) if isinstance(kwargs.get("cvss2", None), str): self.cvss2 = cvss.CVSS2(kwargs["cvss2"]) elif isinstance(kwargs.get("cvss2", None), cvss.CVSS2): self.cvss2 = kwargs["cvss2"] else: self.cvss2 = None if isinstance(kwargs.get("cvss3", None), str): self.cvss3 = cvss.CVSS3(kwargs["cvss3"]) elif isinstance(kwargs.get("cvss3", None), cvss.CVSS3): self.cvss3 = kwargs["cvss3"] else: self.cvss3 = None self.severity_override = kwargs.get("severity_override", None) self.score_override = kwargs.get("score_override", None) self.cpe_list = [ cpe.CPE(indv_cpe) for indv_cpe in kwargs.get("cpe_list", list()) ] self.capec_list = kwargs.get("capec_list", list()) self.cwe_list = kwargs.get("cwe_list", list()) self.references = kwargs.get("references", dict()) self.primary_reference = kwargs.get("primary_reference", None) self.last_updated = kwargs.get("last_updated", None) self.published = kwargs.get("published", None) # Updated Now! self.self_updated = int(time.time()) # Audit Items self.filters = kwargs.get("bucket_def", {}) self.comparisons = kwargs.get("comparisons", {})
def __init__(self, vulnerable: bool, cpe22Uri: str, cpe23Uri: str, versionStartIncluding: str = None, versionStartExcluding: str = None, versionEndIncluding: str = None, versionEndExcluding: str = None): self._vulnerable = vulnerable self._cpe22Uri = cpe22Uri self._cpe23Uri = cpe23Uri self._cpe_parser = cpe.CPE(cpe22Uri) self._versionExact = cpe.CPE(cpe22Uri).get_version()[0] or None self._versionStartIncluding = versionStartIncluding self._versionStartExcluding = versionStartExcluding self._versionEndIncluding = versionEndIncluding self._versionEndExcluding = versionEndExcluding
def add(self, data_entry): """ Generates table entries for above tables from entry standard to json file provided for the exercise :param data_entry: (str) string in json format :return: None """ cve = self.generate_cve(data_entry) cpes = self.generate_cpes(data_entry) for cpe_match in cpes: existing_cpe = self.session.query(CPE).filter_by( id=cpe_match).first() if existing_cpe: existing_cpe.cve_lst.append(cve) else: product = ' '.join(cpe.CPE(cpe_match).get_product()) vendor = ' '.join(cpe.CPE(cpe_match).get_vendor()) new_cpe = CPE(id=cpe_match, product=product, vendor=vendor) new_cpe.cve_lst.append(cve) self.session.add(new_cpe) self.session.add(cve)
def get_affected_from_cpe(cpe_string): """ Returns string formatted for using in the platform -> affected in an oval definition metadata (SSG naming scheme). ... >>> print(get_affected_from_cpe('cpe:/o:canonical:ubuntu_linux:16.04')) >>> Ubuntu 1604 >>> print(get_affected_from_cpe('cpe:/o:canonical:ubuntu_linux:14.04')) >>> Ubuntu 1404 >>> print(get_affected_from_cpe('cpe:/o:debianproject:debian:8')) >>> Debian 8 >>> print(get_affected_from_cpe('cpe:/o:fedoraproject:fedora:28')) >>> Fedora 28 >>> print(get_affected_from_cpe('cpe:/o:novell:leap:42.0')) >>> OpenSUSE 420 >>> print(get_affected_from_cpe('cpe:/o:redhat:enterprise_linux:6')) >>> Red Hat Enterprise Linux 6 >>> print(get_affected_from_cpe('cpe:/o:suse:linux_enterprise_server:11')) >>> SUSE Linux Enterprise 11 """ __products_version_exclude__ = ['leap'] __mapping__ = { 'redhat': { 'enterprise_linux': 'Red Hat Enterprise Linux', }, 'canonical': { 'ubuntu_linux': 'Ubuntu', }, 'suse': { 'linux_enterprise_server': 'SUSE Linux Enterprise', }, 'novell': { 'leap': 'OpenSUSE', }, } cpeobject = cpe.CPE(cpe_string) vendor = cpeobject.get_vendor()[0] product = cpeobject.get_product()[0] affected_string = __mapping__.get(vendor, {}).get(product, product.capitalize()) if product in __products_version_exclude__: return affected_string version = cpeobject.get_version()[0].replace('.', '') affected_string = '{} {}'.format(affected_string, version) return affected_string
def filter_cpe_2_3_string(element): result = {"id": 0, "component": None, "version": None} item = element.get("cpe22", None) result["id"] = element.get("id", 0) if item is not None: try: c22 = cpe.CPE(item, cpe.CPE.VERSION_2_2) except ValueError as value_error: try: c22 = cpe.CPE(item, cpe.CPE.VERSION_UNDEFINED) except NotImplementedError as not_implemented_error: c22 = None c22_product = c22.get_product() if c22 is not None else [] c22_version = c22.get_version() if c22 is not None else [] result["component"] = c22_product[0] if isinstance( c22_product, list) and len(c22_product) > 0 else None result["version"] = c22_version[0] if isinstance( c22_version, list) and len(c22_version) > 0 else None return result
def enhance_cve(self, parsed_cve_data=None, rh_url=None): ''' Takes the parsed Data and Updates all the various bits ''' self.title = parsed_cve_data["name"] self.description = "\n\n".join(parsed_cve_data["details"]) if "cvss3" in parsed_cve_data.keys(): self.cvss3 = cvss.CVSS3(parsed_cve_data["cvss3"]["cvss3_scoring_vector"]) if "cwe" in parsed_cve_data.keys(): self.cwe_list = parsed_cve_data["cwe"].split("->") readable_url = urljoin(self.__redhat_cve_hr, self.cve_id) self.references = {"Red Hat {}".format(self.cve_id) : readable_url, "{} API".format(self.cve_id) : rh_url} self.primary_reference = readable_url if "bugzilla" in parsed_cve_data.keys(): self.references["RH Bugzilla {}".format(parsed_cve_data["bugzilla"]["id"])] = parsed_cve_data["bugzilla"]["url"] try: updated_date = datetime.datetime.strptime(parsed_cve_data["public_date"], "%Y-%m-%dT%H:%M:%SZ") except Exception as date_error: self.logger.warning("Unable to Read date of {}".format(parsed_cve_data["publicdate"])) self.logger.debug("Date Error {}".format(date_error)) else: self.published = int(updated_date.timestamp()) for package in [*parsed_cve_data.get("package_state", list()), *parsed_cve_data.get("affected_release", list())]: try: self.cpe_list.append(cpe.CPE(package["cpe"])) except Exception as cpe_error: self.logger.error("CPE Error {} with CPE {}".format(cpe_error, package["cpe"])) else: if "package" in package.keys() and "advisory" in package.keys(): self.logger.debug("Found package fix for package {} and advisory {}".format(package["package"], package["advisory"])) if package["advisory"] not in self.rh_cust_package_fixed.keys(): self.rh_cust_package_fixed[package["advisory"]] = list() self.rh_cust_package_fixed[package["advisory"]].append(package["package"])
def cpe(self): return pycpe.CPE(self.bind_to_fs())