Beispiel #1
0
    def modify_policy_set_family_selection(
        self,
        policy_id: str,
        families: List[Tuple[str, bool, bool]],
        *,
        auto_add_new_families: Optional[bool] = True,
    ) -> Any:
        """
        Selected the NVTs of a policy at a family level.

        Arguments:
            policy_id: UUID of policy to modify.
            families: A list of tuples with the first entry being the name
                of the NVT family selected, second entry a boolean indicating
                whether new NVTs should be added to the family automatically,
                and third entry a boolean indicating whether all nvts from
                the family should be included.
            auto_add_new_families: Whether new families should be added to the
                policy automatically. Default: True.
        """
        if not policy_id:
            raise RequiredArgument(
                function=self.modify_policy_set_family_selection.__name__,
                argument="policy_id",
            )

        if not is_list_like(families):
            raise InvalidArgumentType(
                function=self.modify_policy_set_family_selection.__name__,
                argument="families",
                arg_type="list",
            )

        cmd = XmlCommand("modify_config")
        cmd.set_attribute("config_id", str(policy_id))

        _xmlfamsel = cmd.add_element("family_selection")
        _xmlfamsel.add_element("growing", to_bool(auto_add_new_families))

        for family in families:
            _xmlfamily = _xmlfamsel.add_element("family")
            _xmlfamily.add_element("name", family[0])

            if len(family) != 3:
                raise InvalidArgument(
                    "Family must be a tuple of 3. (str, bool, bool)")

            if not isinstance(family[1], bool) or not isinstance(
                    family[2], bool):
                raise InvalidArgumentType(
                    function=(
                        self.modify_policy_set_family_selection.__name__),
                    argument="families",
                    arg_type="[tuple(str, bool, bool)]",
                )

            _xmlfamily.add_element("all", to_bool(family[2]))
            _xmlfamily.add_element("growing", to_bool(family[1]))

        return self._send_xml_command(cmd)
Beispiel #2
0
def get_filter_type_from_string(
        filter_type: Optional[str]) -> Optional[FilterType]:
    """ Convert a filter type string to an actual FilterType instance

    Arguments:
        filter_type (str): Filter type string to convert to a FilterType
    """
    if not filter_type:
        return None

    if filter_type == 'vuln':
        return FilterType.VULNERABILITY

    if filter_type == 'os':
        return FilterType.OPERATING_SYSTEM

    if filter_type == 'config':
        return FilterType.SCAN_CONFIG

    if filter_type == 'secinfo':
        return FilterType.ALL_SECINFO

    try:
        return FilterType[filter_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='filter_type',
            function=get_filter_type_from_string.__name__,
        )
Beispiel #3
0
def get_alert_event_from_string(
    alert_event: Optional[str],
) -> Optional[AlertEvent]:
    """Convert an alert event string into a AlertEvent instance """
    if not alert_event:
        return None

    alert_event = alert_event.lower()

    if alert_event == 'task run status changed':
        return AlertEvent.TASK_RUN_STATUS_CHANGED

    if alert_event == 'updated secinfo arrived':
        return AlertEvent.UPDATED_SECINFO_ARRIVED

    if alert_event == 'new secinfo arrived':
        return AlertEvent.NEW_SECINFO_ARRIVED

    if alert_event == 'ticket received':
        return AlertEvent.TICKET_RECEIVED

    if alert_event == 'assigned ticket changed':
        return AlertEvent.ASSIGNED_TICKET_CHANGED

    if alert_event == 'owned ticket changed':
        return AlertEvent.OWNED_TICKET_CHANGED

    raise InvalidArgument(
        argument='alert_event', function=get_alert_event_from_string.__name__
    )
Beispiel #4
0
    def from_string(
        cls,
        scanner_type: Optional[str],
    ) -> Optional["ScannerType"]:
        """Convert a scanner type string to an actual ScannerType instance

        Arguments:
            scanner_type: Scanner type string to convert to a ScannerType
        """
        if not scanner_type:
            return None

        scanner_type = scanner_type.lower()

        if scanner_type == cls.OSP_SCANNER_TYPE.value or scanner_type == "osp":
            return cls.OSP_SCANNER_TYPE

        if (scanner_type == cls.OPENVAS_SCANNER_TYPE.value
                or scanner_type == "openvas"):
            return cls.OPENVAS_SCANNER_TYPE

        if scanner_type == cls.CVE_SCANNER_TYPE.value or scanner_type == "cve":
            return cls.CVE_SCANNER_TYPE

        if (scanner_type == cls.GREENBONE_SENSOR_SCANNER_TYPE.value
                or scanner_type == "greenbone"):
            return cls.GREENBONE_SENSOR_SCANNER_TYPE

        raise InvalidArgument(argument="scanner_type",
                              function=cls.from_string.__name__)
Beispiel #5
0
def get_scanner_type_from_string(
    scanner_type: Optional[str], ) -> Optional[ScannerType]:
    """ Convert a scanner type string to an actual ScannerType instance

    Arguments:
        scanner_type: Scanner type string to convert to a ScannerType
    """
    if not scanner_type:
        return None

    scanner_type = scanner_type.lower()

    if (scanner_type == ScannerType.OSP_SCANNER_TYPE.value
            or scanner_type == 'osp'):
        return ScannerType.OSP_SCANNER_TYPE

    if (scanner_type == ScannerType.OPENVAS_SCANNER_TYPE.value
            or scanner_type == 'openvas'):
        return ScannerType.OPENVAS_SCANNER_TYPE

    if (scanner_type == ScannerType.CVE_SCANNER_TYPE.value
            or scanner_type == 'cve'):
        return ScannerType.CVE_SCANNER_TYPE

    if (scanner_type == ScannerType.GMP_SCANNER_TYPE.value
            or scanner_type == 'gmp'):
        return ScannerType.GMP_SCANNER_TYPE

    raise InvalidArgument(argument='scanner_type',
                          function=get_scanner_type_from_string.__name__)
Beispiel #6
0
def get_alert_condition_from_string(
    alert_condition: Optional[str],
) -> Optional[AlertCondition]:
    """Convert an alert condition string into a AlertCondition instance """
    if not alert_condition:
        return None

    alert_condition = alert_condition.lower()

    if alert_condition == 'error':
        return AlertCondition.ERROR

    if alert_condition == 'always':
        return AlertCondition.ALWAYS

    if alert_condition == 'filter count changed':
        return AlertCondition.FILTER_COUNT_CHANGED

    if alert_condition == 'filter count at least':
        return AlertCondition.FILTER_COUNT_AT_LEAST

    if alert_condition == 'severity at least':
        return AlertCondition.SEVERITY_AT_LEAST

    if alert_condition == 'severity changed':
        return AlertCondition.SEVERITY_CHANGED

    raise InvalidArgument(
        argument='alert_condition',
        function=get_alert_condition_from_string.__name__,
    )
Beispiel #7
0
    def test_raise_with_function(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(function="foo")

        ex = cm.exception
        self.assertEqual(ex.function, "foo")
        self.assertIsNone(ex.argument)
Beispiel #8
0
    def test_raise_with_argument_and_function(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument="foo", function="bar")

        ex = cm.exception
        self.assertEqual(ex.argument, "foo")
        self.assertEqual(ex.function, "bar")
Beispiel #9
0
def get_entity_type_from_string(
        entity_type: Optional[str]) -> Optional[EntityType]:
    """ Convert a entity type string to an actual EntityType instance

    Arguments:
        entity_type: Entity type string to convert to a EntityType
    """
    if not entity_type:
        return None

    if entity_type == 'vuln':
        return EntityType.VULNERABILITY

    if entity_type == 'os':
        return EntityType.OPERATING_SYSTEM

    if entity_type == 'config':
        return EntityType.SCAN_CONFIG

    try:
        return EntityType[entity_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='entity_type',
            function=get_entity_type_from_string.__name__,
        )
Beispiel #10
0
    def test_raise_with_argument_and_function(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument='foo', function='bar')

        ex = cm.exception
        self.assertEqual(ex.argument, 'foo')
        self.assertEqual(ex.function, 'bar')
Beispiel #11
0
def get_alert_method_from_string(
    alert_method: Optional[str], ) -> Optional[AlertMethod]:
    """ Convert an alert method string into a AlertCondition instance """
    if not alert_method:
        return None

    alert_method = alert_method.upper()

    if alert_method == 'START TASK':
        return AlertMethod.START_TASK

    if alert_method == 'HTTP GET':
        return AlertMethod.HTTP_GET

    if alert_method == 'SOURCEFIRE CONNECTOR':
        return AlertMethod.SOURCEFIRE_CONNECTOR

    if alert_method == 'VERINICE CONNECTOR':
        return AlertMethod.VERINICE_CONNECTOR

    try:
        return AlertMethod[alert_method]
    except KeyError:
        raise InvalidArgument(
            argument='alert_method',
            function=get_alert_method_from_string.__name__,
        )
Beispiel #12
0
    def test_raise_with_argument(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument='foo')

        ex = cm.exception
        self.assertEqual(ex.argument, 'foo')
        self.assertIsNone(ex.function)
Beispiel #13
0
    def from_string(
        cls,
        filter_type: Optional[str],
    ) -> Optional["FilterType"]:
        """Convert a filter type string to an actual FilterType instance

        Arguments:
            filter_type (str): Filter type string to convert to a FilterType
        """
        if not filter_type:
            return None

        if filter_type == "vuln":
            return cls.VULNERABILITY

        if filter_type == "os":
            return cls.OPERATING_SYSTEM

        if filter_type == "config":
            return cls.SCAN_CONFIG

        if filter_type == "secinfo":
            return cls.ALL_SECINFO

        try:
            return cls[filter_type.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="filter_type",
                function=cls.from_string.__name__,
            ) from None
Beispiel #14
0
    def modify_scan_config_set_family_selection(
        self,
        config_id: str,
        families: List[Tuple[str, bool, bool]],
        *,
        auto_add_new_families: Optional[bool] = True,
    ) -> Any:
        """
        Selected the NVTs of a scan config at a family level.

        Arguments:
            config_id: UUID of scan config to modify.
            families: A list of tuples (str, bool, bool):
                str: the name of the NVT family selected,
                bool: add new NVTs  to the family automatically,
                bool: include all NVTs from the family
            auto_add_new_families: Whether new families should be added to the
                scan config automatically. Default: True.
        """
        if not config_id:
            raise RequiredArgument(
                function=self.modify_scan_config_set_family_selection.__name__,
                argument="config_id",
            )

        if not is_list_like(families):
            raise InvalidArgumentType(
                function=self.modify_scan_config_set_family_selection.__name__,
                argument="families",
                arg_type="list",
            )

        cmd = XmlCommand("modify_config")
        cmd.set_attribute("config_id", str(config_id))

        _xmlfamsel = cmd.add_element("family_selection")
        _xmlfamsel.add_element("growing", to_bool(auto_add_new_families))

        for family in families:
            _xmlfamily = _xmlfamsel.add_element("family")
            _xmlfamily.add_element("name", family[0])

            if len(family) != 3:
                raise InvalidArgument(
                    "Family must be a tuple of 3. (str, bool, bool)")

            if not isinstance(family[1], bool) or not isinstance(
                    family[2], bool):
                raise InvalidArgumentType(
                    function=(
                        self.modify_scan_config_set_family_selection.__name__),
                    argument="families",
                    arg_type="[tuple(str, bool, bool)]",
                )

            _xmlfamily.add_element("all", to_bool(family[2]))
            _xmlfamily.add_element("growing", to_bool(family[1]))

        return self._send_xml_command(cmd)
Beispiel #15
0
    def test_message_precedence(self):
        with self.assertRaisesRegex(InvalidArgument, "^foo bar$") as cm:
            raise InvalidArgument("foo bar", argument="foo", function="bar")

        ex = cm.exception
        self.assertEqual(ex.argument, "foo")
        self.assertEqual(ex.function, "bar")

        self.assertEqual(str(ex), "foo bar")
Beispiel #16
0
    def test_message_precedence(self):
        with self.assertRaisesRegex(InvalidArgument, '^foo bar$') as cm:
            raise InvalidArgument('foo bar', argument='foo', function='bar')

        ex = cm.exception
        self.assertEqual(ex.argument, 'foo')
        self.assertEqual(ex.function, 'bar')

        self.assertEqual(str(ex), 'foo bar')
Beispiel #17
0
def get_feed_type_from_string(feed_type: Optional[str]) -> Optional[FeedType]:
    """ Convert a feed type string into a FeedType instance
    """
    if not feed_type:
        return None

    try:
        return FeedType[feed_type.upper()]
    except KeyError:
        raise InvalidArgument(argument='feed_type',
                              function=get_feed_type_from_string.__name__)
Beispiel #18
0
def get_time_unit_from_string(time_unit: Optional[str]) -> Optional[TimeUnit]:
    """ Convert a time unit string into a TimeUnit instance """
    if not time_unit:
        return None

    try:
        return TimeUnit[time_unit.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='severity_level',
            function=get_severity_level_from_string.__name__,
        )
Beispiel #19
0
def get_credential_format_from_string(
    credential_format: Optional[str], ) -> Optional[CredentialFormat]:
    if not credential_format:
        return None

    try:
        return CredentialFormat[credential_format.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='credential_format',
            function=get_credential_format_from_string.__name__,
        )
Beispiel #20
0
def get_info_type_from_string(info_type: Optional[str]) -> Optional[InfoType]:
    """ Convert a info type string to an actual InfoType instance

    Arguments:
        info_type: Info type string to convert to a InfoType
    """
    if not info_type:
        return None
    try:
        return InfoType[info_type.upper()]
    except KeyError:
        raise InvalidArgument(argument='info_type',
                              function=get_info_type_from_string.__name__)
Beispiel #21
0
def get_credential_type_from_string(
    credential_type: Optional[str], ) -> Optional[CredentialType]:
    """Convert a credential type string into a CredentialType instance"""
    if not credential_type:
        return None

    try:
        return CredentialType[credential_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='credential_type',
            function=get_credential_type_from_string.__name__,
        ) from None
Beispiel #22
0
def get_asset_type_from_string(
    asset_type: Optional[str], ) -> Optional[AssetType]:
    if not asset_type:
        return None

    if asset_type == 'os':
        return AssetType.OPERATING_SYSTEM

    try:
        return AssetType[asset_type.upper()]
    except KeyError:
        raise InvalidArgument(argument='asset_type',
                              function=get_asset_type_from_string.__name__)
Beispiel #23
0
def get_snmp_auth_algorithm_from_string(
    algorithm: Optional[str], ) -> Optional[SnmpAuthAlgorithm]:
    """Convert a SNMP auth algorithm string into a SnmpAuthAlgorithm instance"""
    if not algorithm:
        return None

    try:
        return SnmpAuthAlgorithm[algorithm.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='algorithm',
            function=get_snmp_auth_algorithm_from_string.__name__,
        ) from None
Beispiel #24
0
def get_user_auth_type_from_string(
    user_auth_type: Optional[str], ) -> Optional[UserAuthType]:
    """ Convert a user auth type string into a UserAuthType instance """
    if not user_auth_type:
        return None

    try:
        return UserAuthType[user_auth_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='user_auth_type',
            function=get_user_auth_type_from_string.__name__,
        ) from None
Beispiel #25
0
    def from_string(cls, info_type: Optional[str]) -> Optional["InfoType"]:
        """Convert a info type string to an actual InfoType instance

        Arguments:
            info_type: Info type string to convert to a InfoType
        """
        if not info_type:
            return None
        try:
            return cls[info_type.upper()]
        except KeyError:
            raise InvalidArgument(argument="info_type",
                                  function=cls.from_string.__name__) from None
Beispiel #26
0
def get_severity_level_from_string(
    severity_level: Optional[str], ) -> Optional[SeverityLevel]:
    """ Convert a severity level string into a SeverityLevel instance """
    if not severity_level:
        return None

    try:
        return SeverityLevel[severity_level.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='severity_level',
            function=get_severity_level_from_string.__name__,
        )
Beispiel #27
0
def get_ticket_status_from_string(
    ticket_status: Optional[str], ) -> Optional[TicketStatus]:
    """Convert a ticket status string into a TicketStatus instance"""
    if not ticket_status:
        return None

    try:
        return TicketStatus[ticket_status.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='ticket_status',
            function=get_ticket_status_from_string.__name__,
        ) from None
Beispiel #28
0
    def from_string(
            cls, alert_condition: Optional[str]) -> Optional["AlertCondition"]:
        """Convert an alert condition string into a AlertCondition instance"""
        if not alert_condition:
            return None

        try:
            return cls[alert_condition.replace(" ", "_").upper()]
        except KeyError:
            raise InvalidArgument(
                argument="alert_condition",
                function=cls.from_string.__name__,
            ) from None
Beispiel #29
0
    def from_string(
        cls,
        credential_format: Optional[str],
    ) -> Optional["CredentialFormat"]:
        if not credential_format:
            return None

        try:
            return cls[credential_format.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="credential_format",
                function=cls.from_string.__name__,
            ) from None
Beispiel #30
0
    def get_system_reports(
        self,
        *,
        name: Optional[str] = None,
        duration: Optional[int] = None,
        start_time: Optional[str] = None,
        end_time: Optional[str] = None,
        brief: Optional[bool] = None,
        slave_id: Optional[str] = None,
    ) -> Any:
        """Request a list of system reports

        Arguments:
            name: A string describing the required system report
            duration: The number of seconds into the past that the system report
                should include
            start_time: The start of the time interval the system report should
                include in ISO time format
            end_time: The end of the time interval the system report should
                include in ISO time format
            brief: Whether to include the actual system reports
            slave_id: UUID of GMP scanner from which to get the system reports

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        cmd = XmlCommand("get_system_reports")

        if name:
            cmd.set_attribute("name", name)

        if duration is not None:
            if not isinstance(duration, Integral):
                raise InvalidArgument("duration needs to be an integer number")

            cmd.set_attribute("duration", str(duration))

        if start_time:
            cmd.set_attribute("start_time", str(start_time))

        if end_time:
            cmd.set_attribute("end_time", str(end_time))

        if brief is not None:
            cmd.set_attribute("brief", to_bool(brief))

        if slave_id:
            cmd.set_attribute("slave_id", slave_id)

        return self._send_xml_command(cmd)