Exemplo n.º 1
0
    def __init__(self, configfile, scans):
        super(NessusRunner, self).__init__(configfile)
        self.scans_running = []  # Scans currently running.
        self.scans_complete = []  # Scans that have completed.
        self.scans = scans  # Scans that remain to be started.

        self.started = False  # Flag for telling when scanning has started.

        # Parse the configuration file to set everything up
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open(configfile))

        self.server = self.config.get('core', 'server')
        self.port = self.config.getint('core', 'port')
        self.report_path = self.config.get('core', 'report_path')
        self.limit = self.config.getint('core', 'limit')
        self.sleepmax = self.config.getint('core', 'sleepmax')
        self.sleepmin = self.config.getint('core', 'sleepmin')
        self.debug("PARSED scans: %s" % self.scans)

        self.info("Nessus scanner started.")
        self.scanner = Nessus(self.server, self.port)
        self.user = self.scanner.User(self.config.get('core', 'user'),
                                      self.config.get('core', 'password'))
        if self.scanner.login(self.user):
            self.info(
                "Connected to Nessus server; authenticated to server '%s' as user '%s'"
                % (self.server, self.user.username))
        else:
            self.error("An error occured when logging into nessus server.")
Exemplo n.º 2
0
class NessusTestCase(unittest.TestCase):
    def setUp(self):
        self.server = Nessus('localhost')
        user = self.server.User('XXXX', 'XXXX')
        self.server.login(user)
        self.connected = False

    def tearDown(self):
        if self.connected:
            self.assertTrue(self.server.logout())
Exemplo n.º 3
0
class NessusTestCase(unittest.TestCase):

    def setUp(self):
        self.server = Nessus('localhost')
        user = self.server.User('XXXX', 'XXXX')
        self.server.login(user)
        self.connected = False

    def tearDown(self):
        if self.connected:
            self.assertTrue(self.server.logout())
Exemplo n.º 4
0
    def run(self):
        nessus = Nessus(self.config.get('core', 'server'), self.config.get('core', 'port'))
        user = nessus.User(self.config.get('core', 'user'), self.config.get('core', 'password'))
        if nessus.login(user):
            nessus.load_scans()
            self.info("Successfully logged in.")
            self.info("%d reports will be downloaded." % (len(nessus.scans)))
            for scan in nessus.scans:
                path = scan.download(fmt=self.export_format, password=self.encryption_password)
                self.info("Report downloaded to %s" % path)

            if nessus.logout():
                self.info("Successfully logged out.")
Exemplo n.º 5
0
 def run(self):
     nessus = Nessus(self.config.get('core', 'server'), self.config.getint('core', 'port'))
     user = nessus.User(self.config.get('core', 'user'), self.config.get('core', 'password'))
     if nessus.login(user):
         nessus.load_policies()
         self.info("Successfully logged in.")
         self.info("%d policies will be downloaded." %
                   (len([policy for policy in nessus.policies if policy.id > 0])))
         for policy in [policy for policy in nessus.policies if policy.id > 0]:
             path = policy.download()
             self.info("Policy downloaded to %s" % path)
         if nessus.logout():
             self.info("Successfully logged out.")
         else:
             self.error("An error occured while login you out.")
     else:
         self.error("An error occured while login you in.")
Exemplo n.º 6
0
    def run(self):

        vid = None
        name = "CGI scanning test"
        nessus = Nessus(self.config.get('core', 'server'), self.config.getint('core', 'port'))
        user = nessus.User(self.config.get('core', 'user'), self.config.get('core', 'password'))
        if nessus.login(user):
            self.info("Successfully logged in.")
            p = nessus.Policy()
            p.name = name
            if nessus.create_policy(p):
                self.alert("Policy successfully created.")
                nessus.load_policies()
                for policy in nessus.policies:
                    if policy.name == name:
                        for preference in policy.preferences:
                            if preference.name == "Web Application Tests Settings":
                                for value in preference.values:
                                    if value.name == "Enable web applications tests":
                                        vid = value.id
                if vid is not None:
                    p.settings = {
                        "preferences.Web+Application+Tests+Settings.%d" % vid: "yes"
                    }
                    if nessus.update_policy(p):
                        self.alert("Policy settings successfully updated (Web Application Tests Settings).")
                    else:
                        self.error("An error occured when updating policy settings (Web Application Tests Settings).")
            else:
                self.error("An error occured while creating the policy.")
            if nessus.logout():
                self.info("Successfully logged out.")
Exemplo n.º 7
0
    def __init__(self, configfile, scans):
        """
        :param configfile:
        :param scans:
        :return:
        """
        self.logformat = "%s %8s %s"
        self.scans_running = []  # Scans currently running.
        self.scans_complete = []  # Scans that have completed.
        self.scans = scans  # Scans that remain to be started.

        self.started = False  # Flag for telling when scanning has started.

        # Parse the configuration file to set everything up
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open(configfile))

        loglevels = {'debug': logging.DEBUG,
                     'info': logging.INFO,
                     'warning': logging.WARNING,
                     'error': logging.ERROR,
                     'critical': logging.CRITICAL}
        # Core settings
        self.logfile = self.config.get('core', 'logfile')
        self.loglevel = loglevels[self.config.get('core', 'loglevel')]

        # Setup some basic logging.
        self.logger = logging.getLogger('Nessus')
        self.logger.setLevel(self.loglevel)
        self.loghandler = WatchedFileHandler(self.logfile)
        self.logger.addHandler(self.loghandler)

        self.debug("CONF configfile = %s" % configfile)
        self.debug("Logger initiated; Logfile: %s, Loglevel: %s" % (self.logfile, self.loglevel))

        self.server = self.config.get('core', 'server')
        self.port = self.config.getint('core', 'port')
        self.report_path = self.config.get('core', 'report_path')
        self.limit = self.config.getint('core', 'limit')
        self.sleepmax = self.config.getint('core', 'sleepmax')
        self.sleepmin = self.config.getint('core', 'sleepmin')
        self.debug("PARSED scans: %s" % self.scans)

        try:
            self.info("Nessus scanner started.")
            self.scanner = Nessus(self.server, self.port)
            self.user = self.scanner.User(self.config.get('core', 'user'), self.config.get('core', 'password'))
            if self.scanner.login(self.user):
                self.info(
                    "Connected to Nessus server; authenticated to server '%s' as user '%s'" % (self.server, self.user.username))
                self.scanner.load()
            else:
                self.error("An error occured when logging into nessus server.")
        except socket.error as (errno, strerror):
            self.error(
                "Socket error encountered while connecting to Nessus server: %s. User: '******', Server: '%s', Port: %s" % (
                strerror, self.user, self.server, self.port))
Exemplo n.º 8
0
    def run(self):

        vid = None
        name = "CGI scanning test"
        nessus = Nessus(self.config.get('core', 'server'),
                        self.config.getint('core', 'port'))
        user = nessus.User(self.config.get('core', 'user'),
                           self.config.get('core', 'password'))
        if nessus.login(user):
            self.info("Successfully logged in.")
            p = nessus.Policy()
            p.name = name
            if nessus.create_policy(p):
                self.alert("Policy successfully created.")
                nessus.load_policies()
                for policy in nessus.policies:
                    if policy.name == name:
                        for preference in policy.preferences:
                            if preference.name == "Web Application Tests Settings":
                                for value in preference.values:
                                    if value.name == "Enable web applications tests":
                                        vid = value.id
                if vid is not None:
                    p.settings = {
                        "preferences.Web+Application+Tests+Settings.%d" % vid:
                        "yes"
                    }
                    if nessus.update_policy(p):
                        self.alert(
                            "Policy settings successfully updated (Web Application Tests Settings)."
                        )
                    else:
                        self.error(
                            "An error occured when updating policy settings (Web Application Tests Settings)."
                        )
            else:
                self.error("An error occured while creating the policy.")
            if nessus.logout():
                self.info("Successfully logged out.")
Exemplo n.º 9
0
    def run(self):
        nessus = Nessus(self.config.get('core', 'server'),
                        self.config.get('core', 'port'))
        user = nessus.User(self.config.get('core', 'user'),
                           self.config.get('core', 'password'))
        if nessus.login(user):
            nessus.load_scans()
            self.info("Successfully logged in.")
            self.info("%d reports will be downloaded." % (len(nessus.scans)))
            for scan in nessus.scans:
                path = scan.download(fmt=self.export_format,
                                     password=self.encryption_password)
                self.info("Report downloaded to %s" % path)

            if nessus.logout():
                self.info("Successfully logged out.")
Exemplo n.º 10
0
 def run(self):
     nessus = Nessus(self.config.get('core', 'server'),
                     self.config.getint('core', 'port'))
     user = nessus.User(self.config.get('core', 'user'),
                        self.config.get('core', 'password'))
     if nessus.login(user):
         nessus.load_policies()
         self.info("Successfully logged in.")
         self.info(
             "%d policies will be downloaded." %
             (len([policy for policy in nessus.policies if policy.id > 0])))
         for policy in [
                 policy for policy in nessus.policies if policy.id > 0
         ]:
             path = policy.download()
             self.info("Policy downloaded to %s" % path)
         if nessus.logout():
             self.info("Successfully logged out.")
         else:
             self.error("An error occured while login you out.")
     else:
         self.error("An error occured while login you in.")
Exemplo n.º 11
0
import ConfigParser
from optparse import OptionParser
from pynessus.nessus import Nessus


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-f", dest='format', help="report file format", default="nessus.v2")
    parser.add_option("-c", dest='configfile', default='nessus.conf', help="configuration file to use")

    (options, args) = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.readfp(open(options.configfile))
    server = config.get('core', 'server')
    port = config.getint('core', 'port')

    nessus = Nessus(server, port)
    user = nessus.User(config.get('core', 'user'), config.get('core', 'password'))
    if nessus.login(user):
        nessus.load_reports()
        print "[+] Successfully logged in."
        print "[+] %d reports will be downloaded." % (len(nessus.reports))
        for report in nessus.reports:
            path = report.download()
            print "[+] Report downloaded to %s" % path

        if nessus.logout():
            print "[+] Successfully logged out."
Exemplo n.º 12
0
    parser.add_option("-c", dest='configfile', default='nessus.conf', help="configuration file to use")

    (options, args) = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.readfp(open(options.configfile))
    server = config.get('core', 'server')
    port = config.getint('core', 'port')
    user = User(config.get('core', 'user'), config.get('core', 'password'))

    if options.format is not None and options.format in ("nessus.v2", "pdf", "html", "csv"):
        fmt = options.format

    vid = None
    name = "CGI scanning test"
    nessus = Nessus(server, port)
    if nessus.login(user):
        print "[+] Successfully logged in."
        p = Policy()
        p.name = name
        if nessus.create_policy(p):
            print "[+] Policy successfully created."
            nessus.load_policies()
            for policy in nessus.policies:
                if policy.name == name:
                    nessus.get_policy_preferences(policy)
                    for preference in policy.preferences:
                        if preference.name == "Web Application Tests Settings":
                            for value in preference.values:
                                if value.name == "Enable web applications tests":
                                    vid = value.id
Exemplo n.º 13
0
 def setUp(self):
     self.server = Nessus('localhost')
     user = self.server.User('XXXX', 'XXXX')
     self.server.login(user)
     self.connected = False
Exemplo n.º 14
0
 def setUp(self):
     self.server = Nessus('localhost')
     user = self.server.User('XXXX', 'XXXX')
     self.server.login(user)
     self.connected = False
Exemplo n.º 15
0
    (options, args) = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.readfp(open(options.configfile))
    server = config.get('core', 'server')
    port = config.getint('core', 'port')
    user = User(config.get('core', 'user'), config.get('core', 'password'))

    if options.format is not None and options.format in ("nessus.v2", "pdf",
                                                         "html", "csv"):
        fmt = options.format

    vid = None
    name = "CGI scanning test"
    nessus = Nessus(server, port)
    if nessus.login(user):
        print "[+] Successfully logged in."
        p = Policy()
        p.name = name
        if nessus.create_policy(p):
            print "[+] Policy successfully created."
            nessus.load_policies()
            for policy in nessus.policies:
                if policy.name == name:
                    nessus.get_policy_preferences(policy)
                    for preference in policy.preferences:
                        if preference.name == "Web Application Tests Settings":
                            for value in preference.values:
                                if value.name == "Enable web applications tests":
                                    vid = value.id
Exemplo n.º 16
0
    def __init__(self, configfile, scans):
        """
        :param configfile:
        :param scans:
        :return:
        """
        self.logformat = "%s %8s %s"
        self.scans_running = []  # Scans currently running.
        self.scans_complete = []  # Scans that have completed.
        self.scans = scans  # Scans that remain to be started.

        self.started = False  # Flag for telling when scanning has started.

        # Parse the configuration file to set everything up
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open(configfile))

        loglevels = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'critical': logging.CRITICAL
        }
        # Core settings
        self.logfile = self.config.get('core', 'logfile')
        self.loglevel = loglevels[self.config.get('core', 'loglevel')]

        # Setup some basic logging.
        self.logger = logging.getLogger('Nessus')
        self.logger.setLevel(self.loglevel)
        self.loghandler = WatchedFileHandler(self.logfile)
        self.logger.addHandler(self.loghandler)

        self.debug("CONF configfile = %s" % configfile)
        self.debug("Logger initiated; Logfile: %s, Loglevel: %s" %
                   (self.logfile, self.loglevel))

        self.server = self.config.get('core', 'server')
        self.port = self.config.getint('core', 'port')
        self.report_path = self.config.get('core', 'report_path')
        self.limit = self.config.getint('core', 'limit')
        self.sleepmax = self.config.getint('core', 'sleepmax')
        self.sleepmin = self.config.getint('core', 'sleepmin')
        self.debug("PARSED scans: %s" % self.scans)

        try:
            self.info("Nessus scanner started.")
            self.scanner = Nessus(self.server, self.port)
            self.user = self.scanner.User(self.config.get('core', 'user'),
                                          self.config.get('core', 'password'))
            if self.scanner.login(self.user):
                self.info(
                    "Connected to Nessus server; authenticated to server '%s' as user '%s'"
                    % (self.server, self.user.username))
                self.scanner.load()
            else:
                self.error("An error occured when logging into nessus server.")
        except socket.error as (errno, strerror):
            self.error(
                "Socket error encountered while connecting to Nessus server: %s. User: '******', Server: '%s', Port: %s"
                % (strerror, self.user, self.server, self.port))
Exemplo n.º 17
0
class NessusRunner(Framework):
    """
    NessusRunner
    """
    def __init__(self, configfile, scans):
        super(NessusRunner, self).__init__(configfile)
        self.scans_running = []  # Scans currently running.
        self.scans_complete = []  # Scans that have completed.
        self.scans = scans  # Scans that remain to be started.

        self.started = False  # Flag for telling when scanning has started.

        # Parse the configuration file to set everything up
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open(configfile))

        self.server = self.config.get('core', 'server')
        self.port = self.config.getint('core', 'port')
        self.report_path = self.config.get('core', 'report_path')
        self.limit = self.config.getint('core', 'limit')
        self.sleepmax = self.config.getint('core', 'sleepmax')
        self.sleepmin = self.config.getint('core', 'sleepmin')
        self.debug("PARSED scans: %s" % self.scans)

        self.info("Nessus scanner started.")
        self.scanner = Nessus(self.server, self.port)
        self.user = self.scanner.User(self.config.get('core', 'user'),
                                      self.config.get('core', 'password'))
        if self.scanner.login(self.user):
            self.info(
                "Connected to Nessus server; authenticated to server '%s' as user '%s'"
                % (self.server, self.user.username))
        else:
            self.error("An error occured when logging into nessus server.")

    def run(self):
        """
        Proxy for resume() really. Basically begins scanning with the current scanning list.
        """
        self.started = True
        self.info("%d scans detected. Launching ..." % len(self.scans))
        if self.scans_running is None:
            self.scans_running = []
        return self.resume()

    def stop(self):
        """
        We have a start() so we most certainly should have a stop(). This should prevent scans from being continued.
        """
        self.started = False

    def resume(self):
        """
        Basically gets scans going, observing the limit.
        """
        if self.started and len(self.scans) > 0 and len(
                self.scans_running) < self.limit:
            count = len(self.scans_running)
            for scan in self.scans:
                scan["target"] = NessusRunner.parse_nmap(scan["nmap_xml_file"])
                if self.scanner.upload_file(scan["nmap_xml_file"]):
                    self.info("%s has been uploaded." %
                              (scan["nmap_xml_file"]))
                    cp = None
                    for policy in self.scanner.policies:
                        if policy.name == scan["policy"]:
                            cp = policy
                    if cp is not None:
                        p = cp.clone()
                        if p is None:
                            self.error(
                                "An error occured while copying policy.")
                        else:
                            p.name = "%s %s %s" % (scan["name"],
                                                   scan["nmap_xml_file"],
                                                   int(time.time()))
                            prefid = None
                            for preference in p.preferences:
                                if "Nmap (XML file importer)" in preference.name:
                                    for value in preference.values:
                                        prefid = value.id
                            if prefid is None:
                                self.error(
                                    "Nmap plugin is either not installed or misconfigured."
                                )
                            else:
                                settings = {
                                    "Filedata.Nmap+(%s)." % (p.name.replace(
                                        " ", "+")):
                                    os.path.basename(scan["nmap_xml_file"]),
                                    "preferences.Nmap+(%s).%d" % (p.name.replace(
                                        " ", "+"), int(prefid)):
                                    os.path.basename(scan["nmap_xml_file"]),
                                }
                                p.settings = settings
                                if not p.save():
                                    self.error(
                                        "An error occured while updating policy."
                                    )
                                else:
                                    currentscan = self.scanner.Scan()
                                    currentscan.name = scan["name"]
                                    currentscan.custom_targets = scan["target"]
                                    currentscan.policy = p
                                    currentscan.tag = self.scanner.tags[0]

                                    if currentscan.launch():
                                        self.info(
                                            "Scan successfully started; Owner: '%s', Name: '%s'"
                                            % (currentscan.owner.name,
                                               currentscan.name))
                                        self.scans_running.append(currentscan)
                                        self.scans.remove(scan)
                                        count += 1
                                        if count == self.limit:
                                            self.warning(
                                                "Concurrent scan limit reached (currently set at %d)"
                                                % self.limit)
                                            self.warning(
                                                "Will monitor scans and continue as possible"
                                            )
                                            break
                                    else:
                                        self.error(
                                            "Unable to start scan. Name: '%s', Target: '%s', Policy: '%s'"
                                            % (currentscan.name,
                                               currentscan.custom_targets,
                                               currentscan.policy.name))
                    else:
                        self.error("That policy do not exist.")
                else:
                    self.error("An error occured while uploading file %s" %
                               (scan["nmap_xml_file"]))
        return self.scans_running

    def iscomplete(self):
        """
        Check for the completion of of running scans. Also, if there are scans left to be run, resume and run them.
        """
        for scan in self.scans_running:
            if scan.status == "completed":
                self.scans_complete.append(scan)
                self.scans_running.remove(scan)
            elif scan.status == "canceled" or scan.status == "stopped":
                self.warning("Scan '%s' has been %s." %
                             (scan.name, scan.status))
                self.scans_running.remove(scan)
        # Check to see if we're running under the limit and we have scans remaining.
        # If so, run more scans up to the limit and continue.
        if len(self.scans_running) < self.limit and len(
                self.scans) > 0 and self.started:
            self.resume()
        elif len(self.scans_running) > 0:
            return False
        else:
            return True

    def report(self):
        """
        Report on currently completed scans.
        """
        for scan in self.scans_complete:
            report = self.scanner.Report()
            report.id, report.name = scan.uuid, scan.uuid

            path = report.download(
                "%s/%s.%s" % (self.report_path, report.name, report.format))
            if path is not None:
                self.info("Report for scan %s saved at %s" % (scan.name, path))

    @staticmethod
    def parse_nmap(nmap_xml_file):
        targets = []
        tree = xml.etree.ElementTree.parse(nmap_xml_file)
        root = tree.getroot()
        for i in root.iter("host"):
            targets.append(i.find("hostnames").find("hostname").get("name"))
            targets.append(i.find("address").get("addr"))
        return ",".join(targets)

    def close(self):
        """
        End it.
        """
        return self.scanner.logout()