Beispiel #1
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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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)
Beispiel #11
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 #12
0
    def test_string_conversion(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument('foo bar', argument='foo')

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

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument='foo')

        ex = cm.exception
        self.assertEqual(str(ex), 'Invalid argument foo')

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(function='foo')

        ex = cm.exception
        self.assertEqual(str(ex), 'Invalid argument for foo')

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument='foo', function='bar')

        ex = cm.exception
        self.assertEqual(str(ex), 'Invalid argument foo for bar')
Beispiel #13
0
    def from_string(
        cls,
        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 cls[user_auth_type.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="user_auth_type",
                function=cls.from_string.__name__,
            ) from None
Beispiel #14
0
    def from_string(
        cls,
        severity_level: Optional[str],
    ) -> Optional["SeverityLevel"]:
        """Convert a severity level string into a SeverityLevel instance"""
        if not severity_level:
            return None

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

        try:
            return cls[ticket_status.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="ticket_status",
                function=cls.from_string.__name__,
            ) from None
Beispiel #16
0
    def from_string(
        cls,
        alert_event: Optional[str],
    ) -> Optional["AlertEvent"]:
        """Convert an alert event string into a AlertEvent instance"""
        if not alert_event:
            return None

        try:
            return cls[alert_event.replace(" ", "_").upper()]
        except KeyError:
            raise InvalidArgument(
                argument="alert_event",
                function=cls.from_string.__name__,
            ) from None
Beispiel #17
0
    def test_string_conversion(self):
        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument("foo bar", argument="foo")

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

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument="foo")

        ex = cm.exception
        self.assertEqual(str(ex), "Invalid argument foo")

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(function="foo")

        ex = cm.exception
        self.assertEqual(str(ex), "Invalid argument for foo")

        with self.assertRaises(InvalidArgument) as cm:
            raise InvalidArgument(argument="foo", function="bar")

        ex = cm.exception
        self.assertEqual(str(ex), "Invalid argument foo for bar")
Beispiel #18
0
    def from_string(
        cls,
        credential_type: Optional[str],
    ) -> Optional["CredentialType"]:
        """Convert a credential type string into a CredentialType instance"""
        if not credential_type:
            return None

        try:
            return cls[credential_type.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="credential_type",
                function=cls.from_string.__name__,
            ) from None
Beispiel #19
0
def get_hosts_ordering_from_string(
    hosts_ordering: Optional[str], ) -> Optional[HostsOrdering]:
    """ Convert a hosts ordering string to an actual HostsOrdering instance

    Arguments:
        hosts_ordering: Host ordering string to convert to a HostsOrdering
    """
    if not hosts_ordering:
        return None
    try:
        return HostsOrdering[hosts_ordering.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='hosts_ordering',
            function=get_hosts_ordering_from_string.__name__,
        )
Beispiel #20
0
    def from_string(
        cls,
        algorithm: Optional[str],
    ) -> Optional["SnmpAuthAlgorithm"]:
        """Convert a SNMP auth algorithm string into a
        SnmpAuthAlgorithm instance"""
        if not algorithm:
            return None

        try:
            return cls[algorithm.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="algorithm",
                function=cls.from_string.__name__,
            ) from None
Beispiel #21
0
def get_sort_order_from_string(
    sort_order: Optional[str], ) -> Optional[SortOrder]:
    """
    Convert a sort order string to an actual SortOrder instance.

    Arguments:
        sort_order: Sort order string to convert to a SortOrder
    """
    if not sort_order:
        return None

    try:
        return SortOrder[sort_order.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='sort_order',
            function=get_sort_order_from_string.__name__) from None
Beispiel #22
0
def get_port_range_type_from_string(
    port_range_type: Optional[str], ) -> Optional[PortRangeType]:
    """ Convert a port range type string to an actual PortRangeType instance

    Arguments:
        port_range_type: Port range type string to convert to a PortRangeType
    """
    if not port_range_type:
        return None

    try:
        return PortRangeType[port_range_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='port_range_type',
            function=get_port_range_type_from_string.__name__,
        )
Beispiel #23
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

    if (
        scanner_type == ScannerType.GREENBONE_SENSOR_SCANNER_TYPE.value
        or scanner_type == 'greenbone'
    ):
        return ScannerType.GREENBONE_SENSOR_SCANNER_TYPE

    raise InvalidArgument(
        argument='scanner_type', function=get_scanner_type_from_string.__name__
    )
Beispiel #24
0
def __get_usage_type_from_string(
    usage_type: Optional[str], ) -> Optional[_UsageType]:
    """ Convert a usage type string to an actual _UsageType instance

    Arguments:
        entity_type: Usage type string to convert to a _UsageType
    """
    if not usage_type:
        return None

    try:
        return _UsageType[usage_type.upper()]
    except KeyError:
        raise InvalidArgument(
            argument='usage_type',
            function=__get_usage_type_from_string.__name__,
        )
Beispiel #25
0
    def modify_filter(self,
                      filter_id: str,
                      *,
                      comment: Optional[str] = None,
                      name: Optional[str] = None,
                      term: Optional[str] = None,
                      filter_type: Optional[FilterType] = None) -> Any:
        """Modifies an existing filter.

        Arguments:
            filter_id: UUID of the filter to be modified
            comment: Comment on filter.
            name: Name of filter.
            term: Filter term.
            filter_type: Resource type filter applies to.

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not filter_id:
            raise RequiredArgument(function="modify_filter",
                                   argument="filter_id")

        cmd = XmlCommand("modify_filter")
        cmd.set_attribute("filter_id", filter_id)

        if comment:
            cmd.add_element("comment", comment)

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

        if term:
            cmd.add_element("term", term)

        if filter_type:
            if not isinstance(filter_type, FilterType):
                raise InvalidArgument(
                    "modify_filter requires type to be a FilterType instance. "
                    "was {}".format(filter_type),
                    function="modify_filter",
                    argument="filter_type",
                )
            cmd.add_element("type", filter_type.value)

        return self._send_xml_command(cmd)
Beispiel #26
0
    def from_string(
        cls,
        alive_test: Optional[str],
    ) -> Optional["AliveTest"]:
        """Convert an alive test string into a AliveTest instance"""
        if not alive_test:
            return None

        alive_test = alive_test.lower()

        try:
            return cls[alive_test.replace(",", "").replace(" ", "_").replace(
                "-", "_").replace("&", "and").upper()]
        except KeyError:
            raise InvalidArgument(
                argument="alive_test",
                function=cls.from_string.__name__,
            ) from None
Beispiel #27
0
    def from_string(
        cls,
        sort_order: Optional[str],
    ) -> Optional["SortOrder"]:
        """
        Convert a sort order string to an actual SortOrder instance.

        Arguments:
            sort_order: Sort order string to convert to a SortOrder
        """
        if not sort_order:
            return None

        try:
            return cls[sort_order.upper()]
        except KeyError:
            raise InvalidArgument(argument="sort_order",
                                  function=cls.from_string.__name__) from None
Beispiel #28
0
    def test_alert(self, alert_id: str) -> Any:
        """Run an alert

        Invoke a test run of an alert

        Arguments:
            alert_id: UUID of the alert to be tested

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not alert_id:
            raise InvalidArgument("test_alert requires an alert_id argument")

        cmd = XmlCommand("test_alert")
        cmd.set_attribute("alert_id", alert_id)

        return self._send_xml_command(cmd)
Beispiel #29
0
    def from_string(
        cls,
        hosts_ordering: Optional[str],
    ) -> Optional["HostsOrdering"]:
        """Convert a hosts ordering string to an actual HostsOrdering instance

        Arguments:
            hosts_ordering: Host ordering string to convert to a HostsOrdering
        """
        if not hosts_ordering:
            return None
        try:
            return cls[hosts_ordering.upper()]
        except KeyError:
            raise InvalidArgument(
                argument="hosts_ordering",
                function=cls.from_string.__name__,
            ) from None
Beispiel #30
0
def create_vt_selection_element(_xmlvtselection, vt_selection):
    """Generates an xml element with a selection of Vulnerability tests."""
    for vt_id, vt_values in vt_selection.items():
        if vt_id != "vt_groups" and isinstance(vt_values, dict):
            _xmlvt = _xmlvtselection.add_element("vt_single",
                                                 attrs={"id": vt_id})
            if vt_values:
                for key, value in vt_values.items():
                    _xmlvt.add_element("vt_value", value, attrs={"id": key})
        elif vt_id == "vt_groups" and isinstance(vt_values, list):
            for group in vt_values:
                _xmlvt = _xmlvtselection.add_element("vt_group",
                                                     attrs={"filter": group})
        else:
            raise InvalidArgument("It was not possible to add {} to the VTs "
                                  "selection.".format(vt_id))

    return _xmlvtselection