Example #1
0
    def _checkPermissions(self):
        dirname = os.path.dirname(self._filename)

        if not os.access(dirname, os.R_OK | os.W_OK | os.X_OK):
            raise error.UserError(
                "DownloadCache directory '%s' does not exist or has wrong permissions"
                % dirname)

        if os.path.exists(self._filename) and not os.access(
                self._filename, os.R_OK | os.W_OK):
            raise error.UserError(
                "DownloadCache file '%s' cannot be opened in read-write mode" %
                self._filename)
Example #2
0
    def _doInit(self):
        age = False
        try:
            st = os.stat(self._filename)
            age = time.time() - st.st_mtime

            # If the data didn't expire, we're good to go
            if self._reload <= 0 or age < self._reload:
                self._load(age)
                return age

        except OSError:
            pass

        try:
            self._download()
        except Exception:
            # There was an error downloading newer data, use any older data that we have, even if it's expired
            # If we don't have any older data available, then this is an error, and there is no fallback.
            if not age:
                raise error.UserError(
                    "%s data couldn't be retrieved, and no previous data available"
                    % self._name)
            self._load(age)

        return 0
Example #3
0
    def _parse_path(path):
        if not path:
            return None

        try:
            IDMEFPath(path)
        except Exception as e:
            raise error.UserError("Invalid path provided '%s': %s" % (path, e))

        return path
Example #4
0
    def _parse_criteria(criteria):
        if not criteria:
            return IDMEFCriteria("alert")

        criteria = "alert && (%s)" % criteria

        try:
            return IDMEFCriteria(criteria)
        except Exception as e:
            raise error.UserError("Invalid criteria provided '%s': %s" %
                                  (criteria, e))
    def check_dependencies(self):
        """Check that the dependency graph is acyclic."""
        all_plugins = list(self._dependencies.keys())
        while all_plugins:
            for plugin in all_plugins:
                if self._dependencies[plugin]:
                    continue

                all_plugins.remove(plugin)
                for p, depends in self._dependencies.items():
                    try:
                        depends.remove(plugin)
                    except ValueError:
                        pass
                break
            else:
                raise error.UserError("Circular dependencies detected for rules %s" % ", ".join(all_plugins))
    def load(self):
        for plugin_class in self.getPluginsClassesList():
            pname = plugin_class.__name__

            if pname in self._conflict and pname not in self._force_enable:
                logger.info("[%s]: disabled by plugin '%s' reason:%s", pname,
                            self._conflict[pname][0], self._conflict[pname][1])
                continue

            if plugin_class.autoload:
                try:
                    pi = plugin_class(env)

                except error.UserError as e:
                    logger.error("[%s]: %s", pname, e)
                    raise error.UserError(
                        "Plugin '%s' failed to load, please fix the issue or disable the plugin"
                        % pname)

                self.__plugins_instances.append(pi)

            self._count += 1
Example #7
0
def runCorrelator():
    checkVersion(LIBPRELUDE_REQUIRED_VERSION)
    config_filename = require.get_config_filename("prelude-correlator.conf")

    parser = argparse.ArgumentParser()

    parser.add_argument("-c",
                        "--config",
                        default=config_filename,
                        metavar="FILE",
                        help="Configuration file to use")
    parser.add_argument("--dry-run",
                        action="store_true",
                        help="No report to the specified Manager will occur")
    parser.add_argument("-d",
                        "--daemon",
                        action="store_true",
                        help="Run in daemon mode")
    parser.add_argument("-P",
                        "--pidfile",
                        metavar="FILE",
                        help="Write Prelude Correlator PID to specified file")
    parser.add_argument(
        "--print-input",
        metavar="FILE",
        help="Dump alert input from manager to the specified file")
    parser.add_argument("--print-output",
                        metavar="FILE",
                        help="Dump alert output to the specified file")
    parser.add_argument("-D",
                        "--debug",
                        type=int,
                        default=0,
                        metavar="LEVEL",
                        nargs="?",
                        const=1,
                        help="Enable debugging output (level from 1 to 10)")
    parser.add_argument("-v", "--version", action="version", version=VERSION)

    group = parser.add_argument_group("IDMEF Input",
                                      "Read IDMEF events from file")
    group.add_argument("--input-file",
                       metavar="FILE",
                       help="Read IDMEF events from the specified file")
    group.add_argument(
        "--input-offset",
        type=int,
        default=0,
        metavar="OFFSET",
        help="Start processing events starting at the given offset")
    group.add_argument("--input-limit",
                       type=int,
                       default=-1,
                       metavar="LIMIT",
                       help="Read events until the given limit is reached")

    group = parser.add_argument_group("Prelude", "Prelude generic options")
    group.add_argument("--profile",
                       default=_DEFAULT_PROFILE,
                       help="Profile to use for this analyzer")

    options = parser.parse_args()

    builtins.env = Env(options)
    env.load_plugins()
    SignalHandler()

    ifd = None
    if options.print_input:
        if options.print_input == "-":
            ifd = sys.stdout
        else:
            ifd = open(options.print_input, "w")

    ofd = None
    if options.print_output:
        if options.print_output == "-":
            ofd = sys.stdout
        else:
            ofd = open(options.print_output, "w")

    if options.daemon:
        if os.fork():
            os._exit(0)

        os.setsid()
        if os.fork():
            os._exit(0)

        os.umask(0o77)

        fd = os.open('/dev/null', os.O_RDWR)
        for i in range(3):
            os.dup2(fd, i)

        os.close(fd)
        if options.pidfile:
            open(options.pidfile, "w").write(str(os.getpid()))

    try:
        env.prelude_client = PreludeClient(options,
                                           print_input=ifd,
                                           print_output=ofd)
    except Exception as e:
        raise error.UserError(e)

    idmef.set_prelude_client(env.prelude_client)

    env.prelude_client.run()

    # save existing context
    context.save(options.profile)
    env.pluginmanager.save()