예제 #1
0
 def clone_agent(self, agent_id: str) -> None:
     # pylint: disable=unused-argument
     deprecation("{} has been removed in GMP version {}.{}".format(
         self.clone_agent.__name__,
         self.get_protocol_version()[0],
         self.get_protocol_version()[1],
     ))
예제 #2
0
    def create_user(
        self,
        name: str,
        *,
        password: Optional[str] = None,
        hosts: Optional[List[str]] = None,
        hosts_allow: Optional[bool] = False,
        ifaces: Any = None,
        ifaces_allow: Any = None,
        role_ids: Optional[List[str]] = None,
    ) -> Any:
        """Create a new user

        Arguments:
            name: Name of the user
            password: Password of the user
            hosts: A list of host addresses (IPs, DNS names)
            hosts_allow: If True allow only access to passed hosts otherwise
                deny access. Default is False for deny hosts.
            ifaces: deprecated
            ifaces_allow: deprecated
            role_ids: A list of role UUIDs for the user

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not name:
            raise RequiredArgument(function=self.create_user.__name__,
                                   argument="name")

        cmd = XmlCommand("create_user")
        cmd.add_element("name", name)

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

        if hosts:
            cmd.add_element(
                "hosts",
                to_comma_list(hosts),
                attrs={"allow": to_bool(hosts_allow)},
            )

        if ifaces is not None:
            major, minor = self.get_protocol_version()
            deprecation("The ifaces parameter has been removed in GMP"
                        f" version {major}{minor}")

        if ifaces_allow is not None:
            major, minor = self.get_protocol_version()
            deprecation("The ifaces_allow parameter has been removed in GMP"
                        f" version {major}{minor}")

        if role_ids:
            for role in role_ids:
                cmd.add_element("role", attrs={"id": role})

        return self._send_xml_command(cmd)
예제 #3
0
    def test_deprecation(self):
        with warnings.catch_warnings(record=True) as w:
            self.assertEqual(len(w), 0)

            warnings.simplefilter("always")

            deprecation('I am deprecated')

            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            self.assertIn(str(w[0].message), 'I am deprecated')
예제 #4
0
 def modify_agent(self,
                  agent_id: str,
                  *,
                  name: Optional[str] = None,
                  comment: Optional[str] = None) -> None:
     # pylint: disable=unused-argument
     deprecation("{} has been removed in GMP version {}.{}".format(
         self.clone_agent.__name__,
         self.get_protocol_version()[0],
         self.get_protocol_version()[1],
     ))
예제 #5
0
 def delete_agent(
     self,
     agent_id: str,
     *,
     ultimate: Optional[bool] = False
     # pylint: disable=unused-argument
 ) -> None:
     deprecation("{} has been removed in GMP version {}.{}".format(
         self.delete_agent.__name__,
         self.get_protocol_version()[0],
         self.get_protocol_version()[1],
     ))
예제 #6
0
    def test_deprecation(self):
        # pylint: disable=invalid-name
        with warnings.catch_warnings(record=True) as w:
            self.assertEqual(len(w), 0)

            warnings.simplefilter("always")

            deprecation("I am deprecated")

            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            self.assertIn(str(w[0].message), "I am deprecated")
예제 #7
0
 def create_agent(self,
                  installer: str,
                  signature: str,
                  name: str,
                  *,
                  comment: Optional[str] = None,
                  howto_install: Optional[str] = None,
                  howto_use: Optional[str] = None) -> None:
     # pylint: disable=unused-argument
     deprecation("{} has been removed in GMP version {}.{}".format(
         self.create_agent.__name__,
         self.get_protocol_version()[0],
         self.get_protocol_version()[1],
     ))
예제 #8
0
    def modify_user(
        self,
        user_id: str = None,
        *,
        name: Optional[str] = None,
        comment: Optional[str] = None,
        password: Optional[str] = None,
        auth_source: Optional[UserAuthType] = None,
        role_ids: Optional[List[str]] = None,
        hosts: Optional[List[str]] = None,
        hosts_allow: Optional[bool] = False,
        ifaces: Any = None,
        ifaces_allow: Any = None,
        group_ids: Optional[List[str]] = None,
    ) -> Any:
        """Modifies an existing user.

        Most of the fields need to be supplied
        for changing a single field even if no change is wanted for those.
        Else empty values are inserted for the missing fields instead.

        Arguments:
            user_id: UUID of the user to be modified.
            name: The new name for the user.
            comment: Comment on the user.
            password: The password for the user.
            auth_source: Source allowed for authentication for this user.
            roles_id: List of roles UUIDs for the user.
            hosts: User access rules: List of hosts.
            hosts_allow: Defines how the hosts list is to be interpreted.
                If False (default) the list is treated as a deny list.
                All hosts are allowed by default except those provided by
                the hosts parameter. If True the list is treated as a
                allow list. All hosts are denied by default except those
                provided by the hosts parameter.
            ifaces: deprecated
            ifaces_allow: deprecated
            group_ids: List of group UUIDs for the user.

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not user_id:
            raise RequiredArgument(function=self.modify_user.__name__,
                                   argument="user_id")

        cmd = XmlCommand("modify_user")

        cmd.set_attribute("user_id", user_id)

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

        if role_ids:
            for role in role_ids:
                cmd.add_element("role", attrs={"id": role})

        if hosts:
            cmd.add_element(
                "hosts",
                to_comma_list(hosts),
                attrs={"allow": to_bool(hosts_allow)},
            )

        if ifaces is not None:
            major, minor = self.get_protocol_version()
            deprecation("The ifaces parameter has been removed in GMP"
                        f" version {major}{minor}")

        if ifaces_allow is not None:
            major, minor = self.get_protocol_version()
            deprecation("The ifaces_allow parameter has been removed in GMP"
                        f" version {major}{minor}")

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

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

        if auth_source:
            _xmlauthsrc = cmd.add_element("sources")
            _xmlauthsrc.add_element("source", auth_source.value)

        if group_ids:
            _xmlgroups = cmd.add_element("groups")
            for group_id in group_ids:
                _xmlgroups.add_element("group", attrs={"id": group_id})

        return self._send_xml_command(cmd)
예제 #9
0
    def __create_task(self,
                      name: str,
                      config_id: str,
                      target_id: str,
                      scanner_id: str,
                      usage_type: UsageType,
                      function: str,
                      *,
                      alterable: Optional[bool] = None,
                      hosts_ordering: Optional[HostsOrdering] = None,
                      schedule_id: Optional[str] = None,
                      alert_ids: Optional[List[str]] = None,
                      comment: Optional[str] = None,
                      schedule_periods: Optional[int] = None,
                      observers: Optional[List[str]] = None,
                      preferences: Optional[dict] = None) -> Any:
        if not name:
            raise RequiredArgument(function=function, argument='name')

        if not config_id:
            raise RequiredArgument(function=function, argument='config_id')

        if not target_id:
            raise RequiredArgument(function=function, argument='target_id')

        if not scanner_id:
            raise RequiredArgument(function=function, argument='scanner_id')

        # don't allow to create a container task with create_task
        if target_id == '0':
            raise InvalidArgument(function=function, argument='target_id')

        cmd = XmlCommand("create_task")
        cmd.add_element("name", name)
        cmd.add_element("usage_type", usage_type.value)
        cmd.add_element("config", attrs={"id": config_id})
        cmd.add_element("target", attrs={"id": target_id})
        cmd.add_element("scanner", attrs={"id": scanner_id})

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

        if alterable is not None:
            cmd.add_element("alterable", _to_bool(alterable))

        if hosts_ordering:
            if not isinstance(hosts_ordering, HostsOrdering):
                raise InvalidArgumentType(
                    function=function,
                    argument='hosts_ordering',
                    arg_type=HostsOrdering.__name__,
                )
            cmd.add_element("hosts_ordering", hosts_ordering.value)

        if alert_ids:
            if isinstance(alert_ids, str):
                deprecation(
                    "Please pass a list as alert_ids parameter to {}. "
                    "Passing a string is deprecated and will be removed in "
                    "future.".format(function))

                # if a single id is given as a string wrap it into a list
                alert_ids = [alert_ids]
            if _is_list_like(alert_ids):
                # parse all given alert id's
                for alert in alert_ids:
                    cmd.add_element("alert", attrs={"id": str(alert)})

        if schedule_id:
            cmd.add_element("schedule", attrs={"id": schedule_id})

            if schedule_periods is not None:
                if (not isinstance(schedule_periods, numbers.Integral)
                        or schedule_periods < 0):
                    raise InvalidArgument(
                        "schedule_periods must be an integer greater or equal "
                        "than 0")
                cmd.add_element("schedule_periods", str(schedule_periods))

        if observers is not None:
            if not _is_list_like(observers):
                raise InvalidArgumentType(function=function,
                                          argument='observers',
                                          arg_type='list')

            # gvmd splits by comma and space
            # gvmd tries to lookup each value as user name and afterwards as
            # user id. So both user name and user id are possible
            cmd.add_element("observers", _to_comma_list(observers))

        if preferences is not None:
            if not isinstance(preferences, collections.abc.Mapping):
                raise InvalidArgumentType(
                    function=function,
                    argument='preferences',
                    arg_type=collections.abc.Mapping.__name__,
                )

            _xmlprefs = cmd.add_element("preferences")
            for pref_name, pref_value in preferences.items():
                _xmlpref = _xmlprefs.add_element("preference")
                _xmlpref.add_element("scanner_name", pref_name)
                _xmlpref.add_element("value", str(pref_value))

        return self._send_xml_command(cmd)
예제 #10
0
    def create_override(
        self,
        text: str,
        nvt_oid: str,
        *,
        days_active: Optional[int] = None,
        hosts: Optional[List[str]] = None,
        port: Optional[str] = None,
        result_id: Optional[str] = None,
        severity: Optional[Severity] = None,
        new_severity: Optional[Severity] = None,
        task_id: Optional[str] = None,
        threat: Any = None,
        new_threat: Any = None,
    ) -> Any:
        """Create a new override

        Arguments:
            text: Text of the new override
            nvt_id: OID of the nvt to which override applies
            days_active: Days override will be active. -1 on always, 0 off
            hosts: A list of host addresses
            port: Port to which the override applies, needs to be a string
                  in the form {number}/{protocol}
            result_id: UUID of a result to which override applies
            severity: Severity to which override applies
            new_severity: New severity for result
            task_id: UUID of task to which override applies
            threat: deprecated
            new_threat: deprecated

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not text:
            raise RequiredArgument(function=self.create_override.__name__,
                                   argument="text")

        if not nvt_oid:
            raise RequiredArgument(function=self.create_override.__name__,
                                   argument="nvt_oid")

        cmd = XmlCommand("create_override")
        cmd.add_element("text", text)
        cmd.add_element("nvt", attrs={"oid": nvt_oid})

        if days_active is not None:
            cmd.add_element("active", str(days_active))

        if hosts:
            cmd.add_element("hosts", to_comma_list(hosts))

        if port:
            if check_port(port):
                cmd.add_element("port", str(port))
            else:
                raise InvalidArgument(function=self.create_override.__name__,
                                      argument="port")

        if result_id:
            cmd.add_element("result", attrs={"id": result_id})

        if severity is not None:
            cmd.add_element("severity", str(severity))

        if new_severity is not None:
            cmd.add_element("new_severity", str(new_severity))

        if task_id:
            cmd.add_element("task", attrs={"id": task_id})

        if threat is not None:
            major, minor = self.get_protocol_version()
            deprecation("The threat parameter has been removed in GMP"
                        f" version {major}{minor}")

        if new_threat is not None:
            major, minor = self.get_protocol_version()
            deprecation("The new_threat parameter has been removed in GMP"
                        f" version {major}{minor}")

        return self._send_xml_command(cmd)
예제 #11
0
    def modify_scan_config(self,
                           config_id: str,
                           selection: Optional[str] = None,
                           **kwargs) -> Any:
        """Modifies an existing scan config.

        DEPRECATED. Please use *modify_scan_config_set_* methods instead.

        modify_config has four modes to operate depending on the selection.

        Arguments:
            config_id: UUID of scan config to modify.
            selection: one of 'scan_pref', 'nvt_pref', 'nvt_selection' or
                'family_selection'
            name: New name for preference.
            value: New value for preference.
            nvt_oids: List of NVTs associated with preference to modify.
            family: Name of family to modify.

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not config_id:
            raise RequiredArgument(
                function=self.modify_scan_config.__name__,
                argument="config_id argument",
            )

        if selection is None:
            deprecation(
                "Using modify_config to update the comment of a scan config is"
                "deprecated. Please use modify_scan_config_set_comment instead."
            )
            return self.modify_scan_config_set_comment(
                config_id, comment=kwargs.get("comment"))

        if selection not in (
                "nvt_pref",
                "scan_pref",
                "family_selection",
                "nvt_selection",
        ):
            raise InvalidArgument("selection must be one of nvt_pref, "
                                  "scan_pref, family_selection or "
                                  "nvt_selection")

        if selection == "nvt_pref":
            deprecation(
                "Using modify_scan_config to update a nvt preference of a scan "
                "config is deprecated. Please use "
                "modify_scan_config_set_nvt_preference instead.")
            return self.modify_scan_config_set_nvt_preference(
                config_id, **kwargs)

        if selection == "scan_pref":
            deprecation(
                "Using modify_scan_config to update a scanner preference of a "
                "scan config is deprecated. Please use "
                "modify_scan_config_set_scanner_preference instead.")
            return self.modify_scan_config_set_scanner_preference(
                config_id, **kwargs)

        if selection == "nvt_selection":
            deprecation(
                "Using modify_scan_config to update a nvt selection of a "
                "scan config is deprecated. Please use "
                "modify_scan_config_set_nvt_selection instead.")
            return self.modify_scan_config_set_nvt_selection(
                config_id, **kwargs)

        deprecation(
            "Using modify_scan_config to update a family selection of a "
            "scan config is deprecated. Please use "
            "modify_scan_config_set_family_selection instead.")
        return self.modify_scan_config_set_family_selection(
            config_id, **kwargs)
예제 #12
0
    def modify_note(
        self,
        note_id: str,
        text: str,
        *,
        days_active: Optional[int] = None,
        hosts: Optional[List[str]] = None,
        port: Optional[int] = None,
        result_id: Optional[str] = None,
        severity: Optional[Severity] = None,
        task_id: Optional[str] = None,
        threat: Any = None,
    ) -> Any:
        """Modifies an existing note.

        Arguments:
            note_id: UUID of note to modify.
            text: The text of the note.
            days_active: Days note will be active. -1 on always, 0 off.
            hosts: A list of hosts addresses
            port: Port to which the override applies, needs to be a string
                  in the form {number}/{protocol}
            result_id: Result to which note applies.
            severity: Severity to which note applies.
            task_id: Task to which note applies.
            threat: deprecated

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not note_id:
            raise RequiredArgument(
                function=self.modify_note.__name__, argument="note_id"
            )

        if not text:
            raise RequiredArgument(
                function=self.modify_note.__name__, argument="text"
            )

        cmd = XmlCommand("modify_note")
        cmd.set_attribute("note_id", note_id)
        cmd.add_element("text", text)

        if days_active is not None:
            cmd.add_element("active", str(days_active))

        if hosts:
            cmd.add_element("hosts", to_comma_list(hosts))

        if port:
            if check_port(port):
                cmd.add_element("port", str(port))
            else:
                raise InvalidArgument(
                    function=self.modify_note.__name__, argument="port"
                )

        if result_id:
            cmd.add_element("result", attrs={"id": result_id})

        if severity is not None:
            cmd.add_element("severity", str(severity))

        if task_id:
            cmd.add_element("task", attrs={"id": task_id})

        if threat is not None:
            major, minor = self.get_protocol_version()
            deprecation(
                "The threat parameter has been removed in GMP"
                f" version {major}{minor}"
            )

        return self._send_xml_command(cmd)
예제 #13
0
    def create_note(
        self,
        text: str,
        nvt_oid: str,
        *,
        days_active: Optional[int] = None,
        hosts: Optional[List[str]] = None,
        port: Optional[int] = None,
        result_id: Optional[str] = None,
        severity: Optional[Severity] = None,
        task_id: Optional[str] = None,
        threat: Optional[SeverityLevel] = None,
    ) -> Any:
        """Create a new note

        Arguments:
            text: Text of the new note
            nvt_id: OID of the nvt to which note applies
            days_active: Days note will be active. -1 on
                always, 0 off
            hosts: A list of hosts addresses
            port: Port to which the note applies
            result_id: UUID of a result to which note applies
            severity: Severity to which note applies
            task_id: UUID of task to which note applies
            threat: Severity level to which note applies. Will be converted to
                severity.

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not text:
            raise RequiredArgument(function=self.create_note.__name__,
                                   argument='text')

        if not nvt_oid:
            raise RequiredArgument(function=self.create_note.__name__,
                                   argument='nvt_oid')

        cmd = XmlCommand("create_note")
        cmd.add_element("text", text)
        cmd.add_element("nvt", attrs={"oid": nvt_oid})

        if days_active is not None:
            cmd.add_element("active", str(days_active))

        if hosts:
            cmd.add_element("hosts", to_comma_list(hosts))

        if port:
            cmd.add_element("port", str(port))

        if result_id:
            cmd.add_element("result", attrs={"id": result_id})

        if severity:
            cmd.add_element("severity", str(severity))

        if task_id:
            cmd.add_element("task", attrs={"id": task_id})

        if threat is not None:
            deprecation("The threat parameter has been removed in GMP"
                        " version {}{}".format(
                            self.get_protocol_version()[0],
                            self.get_protocol_version()[1],
                        ))

        return self._send_xml_command(cmd)
예제 #14
0
    def modify_override(
        self,
        override_id: str,
        text: str,
        *,
        days_active: Optional[int] = None,
        hosts: Optional[List[str]] = None,
        port: Optional[int] = None,
        result_id: Optional[str] = None,
        severity: Optional[Severity] = None,
        new_severity: Optional[Severity] = None,
        task_id: Optional[str] = None,
        threat: Optional[SeverityLevel] = None,
        new_threat: Optional[SeverityLevel] = None,
    ) -> Any:
        """Modifies an existing override.

        Arguments:
            override_id: UUID of override to modify.
            text: The text of the override.
            days_active: Days override will be active. -1 on always,
                0 off.
            hosts: A list of host addresses
            port: Port to which override applies.
            result_id: Result to which override applies.
            severity: Severity to which override applies.
            new_severity: New severity score for result.
            task_id: Task to which override applies.
            threat: Threat level to which override applies.
                Will be converted to severity.
            new_threat: New threat level for results. Will be converted to
                new_severity.

        Returns:
            The response. See :py:meth:`send_command` for details.
        """
        if not override_id:
            raise RequiredArgument(function=self.modify_override.__name__,
                                   argument='override_id')
        if not text:
            raise RequiredArgument(function=self.modify_override.__name__,
                                   argument='text')

        cmd = XmlCommand("modify_override")
        cmd.set_attribute("override_id", override_id)
        cmd.add_element("text", text)

        if days_active is not None:
            cmd.add_element("active", str(days_active))

        if hosts:
            cmd.add_element("hosts", to_comma_list(hosts))

        if port:
            cmd.add_element("port", str(port))

        if result_id:
            cmd.add_element("result", attrs={"id": result_id})

        if severity:
            cmd.add_element("severity", str(severity))

        if new_severity:
            cmd.add_element("new_severity", str(new_severity))

        if task_id:
            cmd.add_element("task", attrs={"id": task_id})

        if threat is not None:
            deprecation("The threat parameter has been removed in GMP"
                        " version {}{}".format(
                            self.get_protocol_version()[0],
                            self.get_protocol_version()[1],
                        ))

        if new_threat is not None:
            deprecation("The new_threat parameter has been removed in GMP"
                        " version {}{}".format(
                            self.get_protocol_version()[0],
                            self.get_protocol_version()[1],
                        ))

        return self._send_xml_command(cmd)