Esempio n. 1
0
    def genConfigFiles(self, responsible):
        self.read_config()

        admin_mail = self.contact_config.admin_mail
        if not admin_mail:
            admin_mail = "root@localhost"
        template_variables = {
            "enabled": self.config.enabled,
            "syscontact": admin_mail,
            "syslocation": "EdenWall 4",
            "v2c_list": self.config.v2c_list,
            "v3_list": self.config.v3_list,
        }

        self.generate_configfile(template_variables)

        # Delete all current users and create the ones in the V3 list:
        createUser_lines = ""
        for user in self.config.v3_list:
            createUser_lines += 'createUser %s %s "%s" %s "%s"\n' % (
                user[INDEX_V3_USERNAME],
                user[INDEX_V3_AUTHENTICATION_PROTO],
                user[INDEX_V3_AUTHENTICATION_PASS],
                user[INDEX_V3_ENCRYPTION_ALGO],
                user[INDEX_V3_ENCRYPTION_PASS],
            )
        runCommand(self, ["sed", "-i", "/^usmUser/d", self.snmp_users_filename])
        with open(self.snmp_users_filename, "a") as fd:
            fd.write(createUser_lines)
Esempio n. 2
0
 def _write_model(self, license):
     model = license.get('Model', '')
     if model:
         with open(MODEL_PATH, 'w') as fd:
             fd.write(unicode(model) + '\n')
         runCommand(self, ['/usr/bin/killall', 'edenserial'])
     return model
Esempio n. 3
0
    def apply_config(self, responsible, paths, arg=None):
        self.read_config()
        self._select_rules()

        self.generate_configfile({
                "home_net": ",".join(map(str, self.ids_ips_cfg.networks))})

        if self.ids_ips_cfg.antivirus_enabled:
            if self.ids_ips_cfg.block:
                clamav = 'preprocessor clamav: action-drop\n'
            else:
                clamav = 'preprocessor clamav\n'
        else:
            clamav = ''
        with open(SNORT_CLAMAV, 'w') as fp:
            fp.write(clamav)

        started = self._is_started()
        if self.ids_ips_cfg.enabled:
            if not started:
                try:
                    os.symlink('/etc/sv/snort_inline', '/etc/service/snort_inline')
                except OSError:
                    raise IdsIpsError(IDS_IPS_START_ERROR,
                                      tr('Could not start the IDS-IPS service.'))
                yield self._open_firewall()
            else:
                # Update firewall rules, in case networks selection changed:
                yield self._open_firewall()

                # Reload the configuration (or restart the service):
                # FIXME: check exitcode?
                runCommand(self, ('sv', 'restart', 'snort_inline'))
        elif started:
            yield self._close_and_stop()
Esempio n. 4
0
 def service_restartService(self, context, service):
     """
     Restart a "restartable" service.
     """
     if service in RESTARTABLE_SERVICES:
         runCommand(self, ['/etc/init.d/%s' % service, 'restart'])
         return True
     else:
         return False
Esempio n. 5
0
    def _stop_then_start(self, template_variables):
        """template_variables can be None: that means templates be untouched"""
        context = Context.fromComponent(self)
        try:
            self.service_stop(context)
        except RunCommandError:
            self.error("Could not stop bind normally, killing named.")
            #explicitely ignoring return value
            runCommand(self, 'killall named'.split())
            runCommand(self, 'killall -9 named'.split())

        try:
            if template_variables is not None:
                self.generate_configfile(template_variables)
        finally:
            self.service_start(context)
Esempio n. 6
0
def sambaRuntimeFilesModified(component):
    """restore tdb files"""
    _samba_info(component, "Restoring Active Directory Data")
    var_dir = component.core.config.get('CORE', 'vardir')
    tdb_path = getBackupPath(var_dir)

    for tdb_file in TDB_FILES:
        tdb_bckp = tdb_file
        tdb_bckp = basename(tdb_bckp)
        tdb_bckp = join(tdb_path, tdb_bckp)
        # this command check if tdb file is ok (trying to restore if corrupt)
        cmd = [TDBBACKUP_EXE, '-v', tdb_bckp]
        runCommand(component, cmd, timeout=120)
        _samba_info(component, "move %s -> %s" % (tdb_bckp, '/var/lib/samba'))
        move(tdb_bckp, '/var/lib/samba')
        chmod(tdb_path, 0600)
        component.chownWithNames(tdb_path, 'root', 'root')
Esempio n. 7
0
def get_ip(component):
    interface_name = OPENVPN_IF
    command = "/sbin/ip addr show %s" % interface_name
    process, status = runCommand(component, command.split(), stdout=PIPE)
    for line in process.stdout:
        line = line.split()
        if line[0] in ('inet', 'inet6'):
            return line[1].split('/')[0]
    return None
Esempio n. 8
0
    def startstopManager(self, action):
        """
        factorisation for init scripts management, action should be one of start, stop, restart, reload

        Closes/Opens ports, starts/stop/etc the service.
        Behaviour :
           If it is a service by itself (no attribute MASTER_SERVICE):
             action the daemon (avoiding unnecessary start/stop)
           Else if the master daemon is not in the expected state already:
               action the master daemon

        see class docstring about cls.HARD_STOP_REQUIRED
        """
        START_ACTIONS = ("start", "restart", "reload")

        expected = "undefined"

        if action not in START_ACTIONS:
            expected = ServiceStatusValues.STOPPED

        if action == "start":
            expected = ServiceStatusValues.RUNNING

        daemon_status = self._status()
        if daemon_status == expected:
            self.debug("'%s' already in state '%s'" % (self.NAME, expected))
            return

        init_script = self.get_initscript()
        assert init_script is not None, "init_script not specified"
        command = "%s %s" % (init_script, action)
        try:
            runCommandAndCheck(self, command.split())
        except RunCommandError:
            if action == 'stop' and self.HARD_STOP_REQUIRED and self.EXE_NAME:
                self.error(
                    "Could not stop %s normally, killing it." % self.EXE_NAME
                    )
                command = 'killall -9 %s' % self.EXE_NAME
                runCommand(self, command.split())
            else:
                raise
Esempio n. 9
0
    def _select_rules(self):
        command = [FPSTAT, '-a' '%f' % self.ids_ips_cfg.alert_threshold]
        if self.ids_ips_cfg.block:
            command.extend(('-d', '%f' % self.ids_ips_cfg.drop_threshold))
        command.append("%s/*.rules" % RULES_SOURCE)

        with open(RULES_DEST, "w") as stdout:
            process, retcode = runCommand(self, command, stdout=stdout)
        if retcode != 0:
            raise IdsIpsError(IDS_IPS_SELECT_RULES_ERROR,
                              tr('Error while selecting rules.'))
Esempio n. 10
0
def sambaRuntimeFiles(component, files):
    """backup samba files and add them to runtimefiles"""
    _samba_info(component, "Backuping Active Directory Data")
    var_dir = component.core.config.get('CORE', 'vardir')
    sid_bckp = getLocalSidPath(var_dir)
    tdb_path = getBackupPath(var_dir)

    # before 37: never created
    # after 37: created during join
    # code needed when updating from 36 to 37, keep it just in case
    if not exists(sid_bckp):
        component.info("save missing local SID")
        saveLocalSid(component)

    delete = []
    added_files = []
    delete.append(sid_bckp)
    added_files.append((sid_bckp, RUNTIME_FILES_LOCAL_SID))

    for tdb_file in TDB_FILES:
        delete.append(tdb_file)
        cmd = [TDBBACKUP_EXE, tdb_file]
        runCommand(component, cmd, timeout=120)
        tdb_file_bckp = '%s.bak' % tdb_file

        _samba_info(component, "move %s -> %s" % (tdb_file_bckp, tdb_path))
        move(tdb_file_bckp, tdb_path)

        added_files.append(
            (join(tdb_path, basename(tdb_file_bckp)),
            RUNTIME_FILES_TDB)
            )

    for filename in delete:
        _del_runtimefile(component, files, filename)
    for filename, description in added_files:
        _add_runtimefile(component, files, filename, description)
Esempio n. 11
0
    def runCmd(self, cmd_line, arg):
        cmd_words = cmd_line.split()

        cmd = []
        for word in cmd_words:
            if word == "%%arg%%":
                word = arg
            cmd.append(word)

        try:
            process, retcode = runCommand(self, cmd, timeout = self.cmd_timeout, stdout=PIPE, stderr=STDOUT)
            if retcode != 0:
                raise CmdError(retcode)
            return process.stdout

        except OSError, err:
            self.error("Problem running '%s':\n%s", cmd_line, err)
            raise err
Esempio n. 12
0
def vpnrules(logger, create):
    if create:
        runCommand(logger, ["/sbin/iptables", "-I", "FORWARD", "-i", "support", "-j", "DROP"])
        runCommand(
            logger, ["/sbin/iptables", "-I", "INPUT", "-i", "support", "-p", "udp", "--dport", "8080", "-j", "ACCEPT"]
        )
        for dport in ["8443", "22"]:
            runCommand(
                logger,
                ["/sbin/iptables", "-I", "INPUT", "-i", "support", "-p", "tcp", "--dport", dport, "-j", "ACCEPT"],
            )
        runCommand(
            logger,
            [
                "/usr/sbin/openvpn",
                "--writepid",
                VPN_SUPPORT_PIDFILE,
                "--daemon",
                "vpn-support",
                "--status",
                VPN_SUPPORT_STATUSFILE,
                "10",
                "--cd",
                "/etc/vpn-support",
                "--config",
                "/etc/vpn-support/support.conf",
            ],
        )
        return
    PID = None
    try:
        with open(VPN_SUPPORT_PIDFILE) as fd:
            PID = int(fd.read().strip())
            if PID == 1:
                return False
    except Exception:
        return False
    if PID is not None:
        runCommand(logger, ["/bin/kill", str(PID)])
        try:
            os.unlink(VPN_SUPPORT_PIDFILE)
            os.unlink(VPN_SUPPORT_STATUSFILE)
        except Exception:
            pass
    for dport in ["8443", "22"]:
        runCommand(
            logger, ["/sbin/iptables", "-D", "INPUT", "-i", "support", "-p", "tcp", "--dport", dport, "-j", "ACCEPT"]
        )
    runCommand(
        logger, ["/sbin/iptables", "-D", "INPUT", "-i", "support", "-p", "udp", "--dport", "8080", "-j", "ACCEPT"]
    )
    runCommand(logger, ["/sbin/iptables", "-D", "FORWARD", "-i", "support", "-j", "DROP"])
Esempio n. 13
0
    def service_getSelectedRulesCounts(self, context, thresholds=None):
        """Return 3 counts: selected rules for alert and drop, and available
        rules.

        If thresholds is None, then this method reads the actual rules file;
        if thresholds is a list of two floats, then this method uses these
        values to compute the count of rules, not touching or reading the
        actual file."""
        results = []
        if thresholds is None:
            file_to_read = RULES_DEST
            try:
                command = [FPSTAT, '-a', '%f' % thresholds[0]]
                if self.ids_ips_cfg.block:
                    command.append('-d %f' % thresholds[1])
                command.append('%s/*.rules' % RULES_SOURCE)
                file_to_read = '/dev/shm/selected_rules'
                with open(file_to_read, "w") as stdout:
                    process, retcode = runCommand(self, command, stdout=stdout)
            except TypeError:
                raise IdsIpsError(IDS_IPS_SELECTED_RULES_COUNTS_ERROR,
                    tr('Could not count the selected rules (type error).'))
            except IndexError:
                raise IdsIpsError(IDS_IPS_SELECTED_RULES_COUNTS_ERROR,
                    tr('Could not count the selected rules (index error).'))
            if retcode != 0:
                raise IdsIpsError(IDS_IPS_SELECTED_RULES_COUNTS_ERROR,
                    tr('Error while selecting rules for counting.'))
            # FIXME: use "grep -c" or just use Python code
            commands = ("grep '^alert ' %s |wc -l" % file_to_read,
                        "grep '^drop ' %s |wc -l" % file_to_read)
            for command in commands:
                # FIXME: don't use shell=True
                p = createProcess(self, command, shell=True, stdout=PIPE)
                stdout, stderr = p.communicate()
                retcode = p.wait()
                if retcode != 0:
                    raise IdsIpsError(
                        IDS_IPS_SELECTED_RULES_COUNTS_ERROR,
                        tr('Could not count the selected rules.'))

                first_line = stdout.splitlines()[0]
                results.append(int(first_line))
        else:
            alert_count = None
            drop_count = None
            try:
                with open(RULES_COUNTS) as fd:
                    # First threshold (alert):
                    for line in fd:
                        cols = line.split()
                        if float(cols[0]) >= thresholds[0]:
                            alert_count = int(cols[1])
                            if float(cols[0]) >= thresholds[1]:
                                drop_count = int(cols[2])
                            break
                    # Second threshold (drop):
                    if drop_count is None:
                        for line in fd:
                            cols = line.split()
                            if float(cols[0]) >= thresholds[1]:
                                drop_count = int(cols[2])
                                break
            except:
                pass  # We will test the counts anyway.
            if alert_count is None or drop_count is None:
                raise IdsIpsError(IDS_IPS_SELECTED_RULES_COUNTS_ERROR,
                                  tr('Could not count the selected rules.'))
            results.extend([alert_count, drop_count])
        results.append(self._total_rules_count())
        return results
Esempio n. 14
0
 def service_restartNucentral(self, context):
     """
     Restart ufwi_rpcd
     """
     runCommand(self, ['/etc/init.d/ufwi_rpcd-server', 'restart'])