Exemplo n.º 1
0
    def test_rgetattr(self):
        """Test `utils.rgetattr` function."""

        obj = utils.AttrDict(
            **{
                'foo': {
                    'bar':
                    True,
                    'buzz': [
                        utils.AttrDict(**{'fuzz': True}),

                        # introduce inconsistency -- can happen in reality
                        utils.AttrDict(**{'no-fuzz': True})
                    ]
                }
            })

        self.assertTrue(utils.rgetattr(obj, 'foo.bar'))
        self.assertIsInstance(utils.rgetattr(obj, 'foo'), utils.AttrDict)
        self.assertIsInstance(utils.rgetattr(obj, 'foo.bar'), bool)

        # should not raise
        self.assertIsInstance(utils.rgetattr(obj, 'foo.buzz.fuzz')[0], bool)

        self.assertIn(
            'Test',
            utils.rgetattr(obj, 'foo.buzz.no_fuzz', repl_missing='Test'),
        )
Exemplo n.º 2
0
        def _fn_wrapper(obj: object, attr: str):

            attr_value = utils.rgetattr(obj, attr)

            search_space = [attr_value]
            if isinstance(attr_value, list):
                search_space = attr_value

            ret = False
            for value in search_space:

                if value is None:
                    continue

                if isinstance(value, list):
                    ret = any([
                        fn(value=v, *args, **kwargs) for v in value
                    ])

                else:
                    ret = fn(value=value, *args, **kwargs)

                if ret:
                    break

            return ret
Exemplo n.º 3
0
    def write(self):
        """Generate VictimsDB YAML file."""
        os.makedirs(self._year_dir, exist_ok=True)

        with open(
                os.path.join(self._year_dir,
                             '{id}.yaml'.format(id=self._cve_no)), 'w') as f:

            refs = utils.rgetattr(self._cve, 'references.data.url')

            description = "\n".join(
                utils.rgetattr(self._doc, 'cve.descriptions.data.value'))

            candidate_scores = []
            for result in self._candidates:
                score_str = "{package}: {score}".format(package=result.package,
                                                        score=result.score)
                candidate_scores.append(score_str)

            if self._ecosystem == 'java':
                gid, aid = self._winner.package.split(':')
            else:
                gid, aid = None, None

            cvss_score = self._doc.impact.cvss.base_score

            data = self._template.format(
                cve=self._cve_id,
                name=self._winner.package,
                cvss_v2=cvss_score,
                description=description,
                references=self.format_list(*refs),
                groupId=gid,
                artifactId=aid,
                version=self.format_list(*self._affected_versions,
                                         indent=2,
                                         quote=True),
                fixedin=self.format_list(*self._safe_versions,
                                         indent=2,
                                         quote=True))

            f.write(data)
Exemplo n.º 4
0
def get_description_by_lang(doc, lang='en'):
    """Get description for given language."""
    desc_data = rgetattr(doc, 'cve.descriptions.data')
    desc = None

    for node in desc_data:
        # if no lang value, assume english
        if getattr(node, 'lang', 'en') == lang:
            desc = getattr(node, 'value', None)
            break

    return desc
Exemplo n.º 5
0
def get_cpe(doc, cpe_type: str = None) -> list:
    """Get list of CPE objects.

    :param doc: Document, single Document object from Collection
    :param cpe_type: str, <type>
        <type>: any of (or abbreviation of) [application, hardware, operating_system]
    """
    valid_cpe_types = ['application', 'hardware', 'operating_system']
    if cpe_type and not isinstance(cpe_type, str):
        raise TypeError(
            f"`cpe_type` expected to be str, got: {type(cpe_type)}")

    type_to_check = None

    if cpe_type is not None:
        for t in valid_cpe_types:
            if t.startswith(cpe_type.lower()):
                type_to_check = t
                break

        if cpe_type and type_to_check is None:
            raise ValueError(
                f"`cpe_type` expected to be any of {valid_cpe_types}")

    cpe_str_list = rgetattr(doc, 'configurations.nodes.data.cpe') or []

    if not any(cpe_str_list):
        cpe_list = []

    else:
        cpe_list = [
            CPE(cpe_str) for cpe_str in it.chain(
                *[x for x in cpe_str_list if x is not None])
        ]

        if type_to_check:
            cpe_list = list(
                filter(lambda _cpe: eval(f"_cpe.is_{type_to_check}()"),
                       cpe_list))

    return cpe_list
Exemplo n.º 6
0
    def project(self, p_dict: typing.Dict[str, int],
                **kwargs) -> utils.AttrDict:
        """Project specific document attributes."""
        keys = p_dict.keys()

        # create projection tree
        if not p_dict.pop('id_', 1):
            projection = dict()
        else:
            projection = {'id_': self.id_}

        for key in keys:

            ptr_dict = projection

            sub_keys = key.split(sep='.')
            for sub_key in sub_keys[:-1]:
                ptr_dict[sub_key] = dict()
                ptr_dict = ptr_dict[sub_key]

            ptr_dict[sub_keys[-1]] = utils.rgetattr(self, key, **kwargs)

        return utils.AttrDict(**projection)