Example #1
0
    def _detect_wait_option(self):
        wait_option = ""
        ret = runProg(self._command, ["-w", "-L", "-n"])  # since iptables-1.4.20
        if ret[0] == 0:
            wait_option = "-w"  # wait for xtables lock
            ret = runProg(self._command, ["-w2", "-L", "-n"])  # since iptables > 1.4.21
            if ret[0] == 0:
                wait_option = "-w2"  # wait max 2 seconds
            log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option)

        return wait_option
Example #2
0
 def __remove_dangling_lock(self):
     if os.path.exists(self.ebtables_lock):
         ret = runProg("pidof", ["-s", "ebtables"])
         ret2 = runProg("pidof", ["-s", "ebtables-restore"])
         if ret[1] == "" and ret2[1] == "":
             log.warning("Removing dangling ebtables lock file: '%s'" % self.ebtables_lock)
             try:
                 os.unlink(self.ebtables_lock)
             except OSError as e:
                 if e.errno != errno.ENOENT:
                     raise
Example #3
0
    def _detect_wait_option(self):
        wait_option = ""
        ret = runProg(self._command, ["-w", "-L", "-n"])  # since iptables-1.4.20
        if ret[0] == 0:
            wait_option = "-w"  # wait for xtables lock
            ret = runProg(self._command, ["-w10", "-L", "-n"])  # since iptables > 1.4.21
            if ret[0] == 0:
                wait_option = "-w10"  # wait max 10 seconds
            log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option)

        return wait_option
Example #4
0
    def _detect_wait_option(self):
        wait_option = ""
        (status, ret) = runProg(self._command, ["-w", "-L"])  # since iptables-1.4.20
        if status == 0:
            wait_option = "-w"  # wait for xtables lock
            (status, ret) = runProg(self._command, ["-w2", "-L"])  # since iptables > 1.4.21
            if status == 0:
                wait_option = "-w2"  # wait max 2 seconds
            log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option)

        return wait_option
Example #5
0
 def __remove_dangling_lock(self):
     if os.path.exists(self.ebtables_lock):
         ret = runProg("pidof", ["-s", "ebtables"])
         ret2 = runProg("pidof", ["-s", "ebtables-restore"])
         if ret[1] == "" and ret2[1] == "":
             log.warning("Removing dangling ebtables lock file: '%s'" %
                         self.ebtables_lock)
             try:
                 os.unlink(self.ebtables_lock)
             except OSError as e:
                 if e.errno != errno.ENOENT:
                     raise
Example #6
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = "filter"
        table_rules = {}
        for rule in rules:
            try:
                i = rule.index("-t")
            except Exception:
                pass
            else:
                if len(rule) >= i + 1:
                    rule.pop(i)
                    table = rule.pop(i)

            # we can not use joinArgs here, because it would use "'" instead
            # of '"' for the start and end of the string, this breaks
            # iptables-restore
            for i in range(len(rule)):
                for c in string.whitespace:
                    if c in rule[i] and not (rule[i].startswith('"')
                                             and rule[i].endswith('"')):
                        rule[i] = '"%s"' % rule[i]

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            temp_file.write("*%s\n" % table)
            for rule in table_rules[table]:
                temp_file.write(" ".join(rule) + "\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = []
        if not flush:
            args.append("--noflush")

        (status, ret) = runProg(self._restore_command,
                                args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            lines = readfile(temp_file.name)
            if lines is not None:
                i = 1
                for line in lines:
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" %
                             (self._restore_command, " ".join(args), ret))
        return ret
Example #7
0
def get_nf_conntrack_helpers():
    kver = os.uname()[2]
    path = "/lib/modules/%s/kernel/net/netfilter/" % kver
    helpers = {}
    if os.path.isdir(path):
        for filename in sorted(os.listdir(path)):
            if not filename.startswith("nf_conntrack_"):
                continue
            module = filename.split(".")[0]
            (status, ret) = runProg(COMMANDS["modinfo"], [
                module,
            ])
            if status != 0:
                continue
            # If module name matches "nf_conntrack_proto_*"
            # the we add it to helpers list and goto next module
            if filename.startswith("nf_conntrack_proto_"):
                helper = filename.split(".")[0].strip()
                helper = helper.replace("_", "-")
                helper = helper.replace("nf-conntrack-", "")
                helpers.setdefault(module, []).append(helper)
                continue
            # Else we get module alias and if "-helper" in the "alias:" line of modinfo
            # then we add it to helpers list and goto next module
            for line in ret.split("\n"):
                if line.startswith("alias:") and "-helper-" in line:
                    helper = line.split(":")[1].strip()
                    helper = helper.replace("nfct-helper-", "")
                    helper = helper.replace("_", "-")
                    helpers.setdefault(module, []).append(helper)
    return helpers
Example #8
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = None
        for rule in rules:
            try:
                i = rule.index("-t")
            except:
                pass
            else:
                if len(rule) >= i + 1:
                    rule.pop(i)
                    _table = rule.pop(i)
                    if _table != table:
                        table = _table
                        temp_file.write("*%s\n" % table)
                temp_file.write(" ".join(rule) + "\n")
        temp_file.close()

        log.debug2("%s: %s %s", self.__class__, self._restore_command, "...")
        (status, ret) = runProg(self._restore_command, [],
                                stdin=temp_file.name)
        if status != 0:
            os.unlink(temp_file.name)
            raise ValueError("'%s %s' failed: %s" %
                             (self._restore_command, " ".join(args), ret))
        os.unlink(temp_file.name)
        return ret
Example #9
0
def get_nf_nat_helpers():
    kver = os.uname()[2]
    helpers = {}
    for path in [
            "/lib/modules/%s/kernel/net/netfilter/" % kver,
            "/lib/modules/%s/kernel/net/ipv4/netfilter/" % kver,
            "/lib/modules/%s/kernel/net/ipv6/netfilter/" % kver
    ]:
        if os.path.isdir(path):
            for filename in sorted(os.listdir(path)):
                if not filename.startswith("nf_nat_"):
                    continue
                module = filename.split(".")[0]
                (status, ret) = runProg(COMMANDS["modinfo"], [
                    module,
                ])
                if status != 0:
                    continue
                # If module name matches "nf_nat_proto_*"
                # the we add it to helpers list and goto next module
                if filename.startswith("nf_nat_proto_"):
                    helper = filename.split(".")[0].strip()
                    helper = helper.replace("_", "-")
                    helper = helper.replace("nf-nat-", "")
                    helpers.setdefault(module, []).append(helper)
                    continue
                # Else we get module alias and if "NAT helper" in "description:" line of modinfo
                # then we add it to helpers list and goto next module
                for line in ret.split("\n"):
                    if line.startswith(
                            "description:") and "NAT helper" in line:
                        helper = module.replace("nf_nat_", "")
                        helper = helper.replace("_", "-")
                        helpers.setdefault(module, []).append(helper)
    return helpers
Example #10
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = None
        for rule in rules:
            try:
                i = rule.index("-t")
            except:
                pass
            else:
                if len(rule) >= i+1:
                    rule.pop(i)
                    _table = rule.pop(i)
                    if _table != table:
                        table = _table
                        temp_file.write("*%s\n" % table)
                temp_file.write(" ".join(rule) + "\n")
        temp_file.close()

        log.debug2("%s: %s %s", self.__class__, self._restore_command, "...")
        (status, ret) = runProg(self._restore_command, [ ],
                                stdin=temp_file.name)
        if status != 0:
            os.unlink(temp_file.name)
            raise ValueError("'%s %s' failed: %s" % (self._restore_command,
                                                     " ".join(args), ret))
        os.unlink(temp_file.name)
        return ret
Example #11
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = "filter"
        table_rules = { }
        for rule in rules:
            try:
                i = rule.index("-t")
            except Exception:
                pass
            else:
                if len(rule) >= i+1:
                    rule.pop(i)
                    table = rule.pop(i)

            # we can not use joinArgs here, because it would use "'" instead
            # of '"' for the start and end of the string, this breaks
            # iptables-restore
            for i in range(len(rule)):
                for c in string.whitespace:
                    if c in rule[i] and not (rule[i].startswith('"') and
                                             rule[i].endswith('"')):
                        rule[i] = '"%s"' % rule[i]

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            temp_file.write("*%s\n" % table)
            for rule in table_rules[table]:
                temp_file.write(" ".join(rule) + "\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = [ ]
        if not flush:
            args.append("--noflush")

        (status, ret) = runProg(self._restore_command, args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            lines = readfile(temp_file.name)
            if lines is not None:
                i = 1
                for line in lines:
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" % (self._restore_command,
                                                     " ".join(args), ret))
        return ret
Example #12
0
    def _detect_restore_wait_option(self):
        temp_file = tempFile()
        temp_file.write("#foo")
        temp_file.close()

        wait_option = ""
        ret = runProg(self._restore_command, ["-w"], stdin=temp_file.name)  # proposed for iptables-1.6.2
        if ret[0] == 0:
            wait_option = "-w"  # wait for xtables lock
            ret = runProg(self._restore_command, ["--wait=2"], stdin=temp_file.name)  # since iptables > 1.4.21
            if ret[0] == 0:
                wait_option = "--wait=2"  # wait max 2 seconds
            log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option)

        os.unlink(temp_file.name)

        return wait_option
Example #13
0
    def set_restore(self,
                    set_name,
                    type_name,
                    entries,
                    create_options=None,
                    entry_options=None):
        self.check_name(set_name)
        self.check_type(type_name)

        temp_file = tempFile()

        if ' ' in set_name:
            set_name = "'%s'" % set_name
        args = ["create", set_name, type_name, "-exist"]
        if create_options:
            for key, val in create_options.items():
                args.append(key)
                if val != "":
                    args.append(val)
        temp_file.write("%s\n" % " ".join(args))
        temp_file.write("flush %s\n" % set_name)

        for entry in entries:
            if ' ' in entry:
                entry = "'%s'" % entry
            if entry_options:
                temp_file.write("add %s %s %s\n" % \
                                (set_name, entry, " ".join(entry_options)))
            else:
                temp_file.write("add %s %s\n" % (set_name, entry))
        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s restore %s", self.__class__, self._command,
                   "%s: %d" % (temp_file.name, stat.st_size))

        args = ["restore"]
        (status, ret) = runProg(self._command, args, stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            try:
                readfile(temp_file.name)
            except Exception:
                pass
            else:
                i = 1
                for line in readfile(temp_file.name):
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" %
                             (self._command, " ".join(args), ret))
        return ret
Example #14
0
 def __run(self, args):
     # convert to string list
     _args = ["--concurrent"] + ["%s" % item for item in args]
     log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
     (status, ret) = runProg(self._command, _args)
     if status != 0:
         raise ValueError("'%s %s' failed: %s" %
                          (self._command, " ".join(args), ret))
     return ret
Example #15
0
    def _detect_concurrent_option(self):
        # Do not change any rules, just try to use the --concurrent option
        # with -L
        concurrent_option = ""
        ret = runProg(self._command, ["--concurrent", "-L"])
        if ret[0] == 0:
            concurrent_option = "--concurrent"  # concurrent for ebtables lock

        return concurrent_option
Example #16
0
    def _detect_concurrent_option(self):
        # Do not change any rules, just try to use the --concurrent option
        # with -L
        concurrent_option = ""
        ret = runProg(self._command, ["--concurrent", "-L"])
        if ret[0] == 0:
            concurrent_option = "--concurrent"  # concurrent for ebtables lock

        return concurrent_option
Example #17
0
 def __run(self, args):
     # convert to string list
     _args = ["%s" % item for item in args]
     log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
     (status, ret) = runProg(self._command, _args)
     if status != 0:
         raise ValueError("'%s %s' failed: %s" % (self._command,
                                                  " ".join(_args), ret))
     return ret
Example #18
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = "filter"
        table_rules = {}
        for rule in rules:
            try:
                i = rule.index("-t")
            except:
                pass
            else:
                if len(rule) >= i + 1:
                    rule.pop(i)
                    table = rule.pop(i)

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            temp_file.write("*%s\n" % table)
            for rule in table_rules[table]:
                temp_file.write(" ".join(rule) + "\n")
            temp_file.write("COMMIT\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = []
        if not flush:
            args.append("-n")

        (status, ret) = runProg(self._restore_command,
                                args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            try:
                lines = readfile(temp_file.name)
            except:
                pass
            else:
                i = 1
                for line in readfile(temp_file.name):
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" %
                             (self._restore_command, " ".join(args), ret))
        return ret
Example #19
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = "filter"
        table_rules = { }
        for rule in rules:
            try:
                i = rule.index("-t")
            except:
                pass
            else:
                if len(rule) >= i+1:
                    rule.pop(i)
                    table = rule.pop(i)

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            temp_file.write("*%s\n" % table)
            for rule in table_rules[table]:
                temp_file.write(" ".join(rule) + "\n")
            temp_file.write("COMMIT\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = [ ]
        if not flush:
            args.append("-n")

        (status, ret) = runProg(self._restore_command, args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            try:
                lines = readfile(temp_file.name)
            except:
                pass
            else:
                i = 1
                for line in readfile(temp_file.name):
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" % (self._restore_command,
                                                     " ".join(args), ret))
        return ret
Example #20
0
    def restore(self, set_name, type_name, entries,
                create_options=None, entry_options=None):
        self.check_name(set_name)
        self.check_type(type_name)

        temp_file = tempFile()

        if ' ' in set_name:
            set_name = "'%s'" % set_name
        args = [ "create", set_name, type_name, "-exist" ]
        if create_options:
            for key, val in create_options.items():
                args.append(key)
                if val != "":
                    args.append(val)
        temp_file.write("%s\n" % " ".join(args))

        for entry in entries:
            if ' ' in entry:
                entry = "'%s'" % entry
            if entry_options:
                temp_file.write("add %s %s %s -exist\n" % \
                                (set_name, entry, " ".join(entry_options)))
            else:
                temp_file.write("add %s %s -exist\n" % (set_name, entry))
        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s restore %s", self.__class__, self._command,
                   "%s: %d" % (temp_file.name, stat.st_size))

        args = [ "restore" ]
        (status, ret) = runProg(self._command, args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            try:
                readfile(temp_file.name)
            except Exception:
                pass
            else:
                i = 1
                for line in readfile(temp_file.name):
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" % (self._command,
                                                     " ".join(args), ret))
        return ret
Example #21
0
 def __run(self, args):
     # convert to string list
     _args = [ ]
     if self.concurrent_option and self.concurrent_option not in args:
         _args.append(self.concurrent_option)
     _args += ["%s" % item for item in args]
     log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
     (status, ret) = runProg(self._command, _args)
     if status != 0:
         raise ValueError("'%s %s' failed: %s" % (self._command,
                                                  " ".join(args), ret))
     return ret
Example #22
0
 def __run(self, args):
     # convert to string list
     if self.wait_option and self.wait_option not in args:
         _args = [self.wait_option] + ["%s" % item for item in args]
     else:
         _args = ["%s" % item for item in args]
     log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
     (status, ret) = runProg(self._command, _args)
     if status != 0:
         raise ValueError("'%s %s' failed: %s" %
                          (self._command, " ".join(_args), ret))
     return ret
Example #23
0
 def __run(self, args):
     # convert to string list
     _args = [ ]
     if self.concurrent_option and self.concurrent_option not in args:
         _args.append(self.concurrent_option)
     _args += ["%s" % item for item in args]
     log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
     (status, ret) = runProg(self._command, _args)
     if status != 0:
         raise ValueError("'%s %s' failed: %s" % (self._command,
                                                  " ".join(args), ret))
     return ret
Example #24
0
    def _detect_restore_wait_option(self):
        temp_file = tempFile()
        temp_file.write("#foo")
        temp_file.close()

        wait_option = ""
        for test_option in ["-w", "--wait=2"]:
            ret = runProg(self._restore_command, [test_option], stdin=temp_file.name)
            if ret[0] == 0 and "invalid option" not in ret[1] \
                           and "unrecognized option" not in ret[1]:
                wait_option = test_option
                break

        log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option)

        os.unlink(temp_file.name)

        return wait_option
Example #25
0
    def _detect_restore_wait_option(self):
        temp_file = tempFile()
        temp_file.write("#foo")
        temp_file.close()

        wait_option = ""
        for test_option in ["-w", "--wait=2"]:
            ret = runProg(self._restore_command, [test_option], stdin=temp_file.name)
            if ret[0] == 0 and "invalid option" not in ret[1] \
                           and "unrecognized option" not in ret[1]:
                wait_option = test_option
                break

        log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option)

        os.unlink(temp_file.name)

        return wait_option
Example #26
0
def get_nf_conntrack_helpers():
    kver = os.uname()[2]
    path = "/lib/modules/%s/kernel/net/netfilter/" % kver
    helpers = { }
    if os.path.isdir(path):
        for filename in sorted(os.listdir(path)):
            if not filename.startswith("nf_conntrack_"):
                continue
            module = filename.split(".")[0]
            (status, ret) = runProg(COMMANDS["modinfo"], [ module, ])
            if status != 0:
                continue
            for line in ret.split("\n"):
                if line.startswith("alias:") and "-helper-" in line:
                    helper = line.split(":")[1].strip()
                    helper = helper.replace("nfct-helper-", "")
                    helper = helper.replace("_", "-")
                    helpers.setdefault(module, [ ]).append(helper)
    return helpers
Example #27
0
    def restore(self, set_name, type_name, entries,
                create_options=None, entry_options=None):
        self.check_name(set_name)
        self.check_type(type_name)

        temp_file = tempFile()

        if ' ' in set_name:
            set_name = "'%s'" % set_name
        args = [ "create", set_name, type_name ]
        if create_options:
            for k,v in create_options.items():
                args.append(k)
                if v != "":
                    args.append(v)
        temp_file.write(" ".join(args))
        temp_file.write("\n")

        for entry in entries:
            if ' ' in entry:
                entry = "'%s'" % entry
            if entry_options:
                temp_file.write("add %s %s %s\n" % (set_name, entry,
                                                    " ".join(entry_options)))
            else:
                temp_file.write("add %s %s\n" % (set_name, entry))
        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s restore %s", self.__class__, self._command,
                   "%s: %d" % (temp_file.name, stat.st_size))

        args = [ "restore" ]
        (status, ret) = runProg(self._command, args,
                                stdin=temp_file.name)
        if status != 0:
            os.unlink(temp_file.name)
            raise ValueError("'%s %s' failed: %s" % (self._command,
                                                     " ".join(args), ret))
        os.unlink(temp_file.name)
        return ret
Example #28
0
def get_modinfos(path_templates, prefix):
    kver = os.uname()[2]
    modules = []
    for path in (t % kver for t in path_templates):
        if os.path.isdir(path):
            for filename in sorted(os.listdir(path)):
                if filename.startswith(prefix):
                    modules.append(filename.split(".")[0])
    if modules:
        # Ignore status as it is not 0 if even one module had problems
        (status, ret) = runProg(COMMANDS["modinfo"], modules)
        entry = {}
        for m in re.finditer(r"^(\w+):[ \t]*(\S.*?)[ \t]*$", ret, re.MULTILINE):
            key, value = m.groups()
            # Assume every entry starts with filename
            if key == "filename" and "filename" in entry:
                yield entry
                entry = {}
            entry.setdefault(key, [ ]).append(value)
        if "filename" in entry:
            yield entry
Example #29
0
def get_nf_conntrack_helpers():
    kver = os.uname()[2]
    path = "/lib/modules/%s/kernel/net/netfilter/" % kver
    helpers = {}
    if os.path.isdir(path):
        for filename in sorted(os.listdir(path)):
            if not filename.startswith("nf_conntrack_"):
                continue
            module = filename.split(".")[0]
            (status, ret) = runProg(COMMANDS["modinfo"], [
                module,
            ])
            if status != 0:
                continue
            for line in ret.split("\n"):
                if line.startswith("alias:") and "-helper-" in line:
                    helper = line.split(":")[1].strip()
                    helper = helper.replace("nfct-helper-", "")
                    helper = helper.replace("_", "-")
                    helpers.setdefault(module, []).append(helper)
    return helpers
Example #30
0
    def set_rules(self, rules, flush=False):
        temp_file = tempFile()

        table = None
        table_rules = { }
        for rule in rules:
            try:
                i = rule.index("-t")
            except:
                pass
            else:
                if len(rule) >= i+1:
                    rule.pop(i)
                    table = rule.pop(i)

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            temp_file.write("*%s\n" % table)
            for rule in table_rules[table]:
                temp_file.write(" ".join(rule) + "\n")
            temp_file.write("COMMIT\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = [ ]
        if not flush:
            args.append("-n")

        (status, ret) = runProg(self._restore_command, args,
                                stdin=temp_file.name)
        if status != 0:
            os.unlink(temp_file.name)
            raise ValueError("'%s %s' failed: %s" % (self._restore_command,
                                                     " ".join(args), ret))
        os.unlink(temp_file.name)
        return ret
Example #31
0
    def set_rules(self, rules, flush=False, log_denied="off"):
        temp_file = tempFile()

        table_rules = { }
        for _rule in rules:
            rule = _rule[:]

            # replace %%REJECT%%
            self._rule_replace(rule, "%%REJECT%%", \
                    ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]])

            # replace %%ICMP%%
            self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]])

            # replace %%LOGTYPE%%
            try:
                i = rule.index("%%LOGTYPE%%")
            except ValueError:
                pass
            else:
                if log_denied == "off":
                    continue
                if log_denied in [ "unicast", "broadcast", "multicast" ]:
                    rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ]
                else:
                    rule.pop(i)

            table = "filter"
            # get table form rule
            for opt in [ "-t", "--table" ]:
                try:
                    i = rule.index(opt)
                except ValueError:
                    pass
                else:
                    if len(rule) >= i+1:
                        rule.pop(i)
                        table = rule.pop(i)

            # we can not use joinArgs here, because it would use "'" instead
            # of '"' for the start and end of the string, this breaks
            # iptables-restore
            for i in range(len(rule)):
                for c in string.whitespace:
                    if c in rule[i] and not (rule[i].startswith('"') and
                                             rule[i].endswith('"')):
                        rule[i] = '"%s"' % rule[i]

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            rules = table_rules[table]
            rules = self.split_value(rules, [ "-s", "--source" ])
            rules = self.split_value(rules, [ "-d", "--destination" ])

            temp_file.write("*%s\n" % table)
            for rule in rules:
                temp_file.write(" ".join(rule) + "\n")
            temp_file.write("COMMIT\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = [ ]
        if self.restore_wait_option:
            args.append(self.restore_wait_option)
        if not flush:
            args.append("-n")

        (status, ret) = runProg(self._restore_command, args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            lines = readfile(temp_file.name)
            if lines is not None:
                i = 1
                for line in lines:
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" % (self._restore_command,
                                                     " ".join(args), ret))
        return ret
Example #32
0
 def load_module(self, module):
     log.debug2("%s: %s %s", self.__class__, self._load_command, module)
     return runProg(self._load_command, [ module ])
Example #33
0
    def set_rules(self, rules, log_denied):
        temp_file = tempFile()

        table_rules = {}
        for _rule in rules:
            rule = _rule[:]

            # replace %%REJECT%%
            self._rule_replace(rule, "%%REJECT%%", \
                    ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]])

            # replace %%ICMP%%
            self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]])

            # replace %%LOGTYPE%%
            try:
                i = rule.index("%%LOGTYPE%%")
            except ValueError:
                pass
            else:
                if log_denied == "off":
                    continue
                if log_denied in ["unicast", "broadcast", "multicast"]:
                    rule[i:i + 1] = ["-m", "pkttype", "--pkt-type", log_denied]
                else:
                    rule.pop(i)

            table = "filter"
            # get table form rule
            for opt in ["-t", "--table"]:
                try:
                    i = rule.index(opt)
                except ValueError:
                    pass
                else:
                    if len(rule) >= i + 1:
                        rule.pop(i)
                        table = rule.pop(i)

            # we can not use joinArgs here, because it would use "'" instead
            # of '"' for the start and end of the string, this breaks
            # iptables-restore
            for i in range(len(rule)):
                for c in string.whitespace:
                    if c in rule[i] and not (rule[i].startswith('"')
                                             and rule[i].endswith('"')):
                        rule[i] = '"%s"' % rule[i]

            table_rules.setdefault(table, []).append(rule)

        for table in table_rules:
            rules = table_rules[table]
            rules = self.split_value(rules, ["-s", "--source"])
            rules = self.split_value(rules, ["-d", "--destination"])

            temp_file.write("*%s\n" % table)
            for rule in rules:
                temp_file.write(" ".join(rule) + "\n")
            temp_file.write("COMMIT\n")

        temp_file.close()

        stat = os.stat(temp_file.name)
        log.debug2("%s: %s %s", self.__class__, self._restore_command,
                   "%s: %d" % (temp_file.name, stat.st_size))
        args = []
        if self.restore_wait_option:
            args.append(self.restore_wait_option)
        args.append("-n")

        (status, ret) = runProg(self._restore_command,
                                args,
                                stdin=temp_file.name)

        if log.getDebugLogLevel() > 2:
            lines = readfile(temp_file.name)
            if lines is not None:
                i = 1
                for line in lines:
                    log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
                    if not line.endswith("\n"):
                        log.debug3("", nofmt=1)
                    i += 1

        os.unlink(temp_file.name)

        if status != 0:
            raise ValueError("'%s %s' failed: %s" %
                             (self._restore_command, " ".join(args), ret))
        return ret
Example #34
0
 def unload_module(self, module):
     log.debug2("%s: %s %s", self.__class__, self._unload_command, module)
     return runProg(self._unload_command, [ module ])
Example #35
0
 def unload_module(self, module):
     log.debug2("%s: %s -r %s", self.__class__, self._command, module)
     return runProg(self._command, ["-r", module])