Example #1
0
def forwarding_save() -> str:
    """TODO: Doku."""
    utils = Webutils()
    if utils.check_login(request) is True:
        action = "add"
        ruletype = "tcp"
        source_port = ""
        dest_port = ""

        for key, value in request.form.items():
            if key == "remove":
                action = "remove"
                ruletype = value
            elif key == "tcpudp":
                action = "add"
                ruletype = value
            elif key == "source-port":
                source_port = str(value)
            elif key == "destination-port":
                dest_port = str(value)
            else:
                if ":" in key:
                    ruletype = key.split(":")[0]
                    source_port = key.split(":")[1]
                    dest_port = key.split(":")[2]

        if action == "add":
            add_forwarding(source_port, dest_port, ruletype)
        else:
            remove_forwarding(source_port, dest_port, ruletype)

        return forwarding(True)
    return login()
Example #2
0
def logout() -> str:
    """Remove the logged_in session variable if the user is logged in."""
    utils = Webutils()
    if utils.check_login(request) is True:
        session['logged_in'] = False
        return login("You have been logged off successfully.", "success")
    else:
        return login()
Example #3
0
def custom_save() -> str:
    """the function saves the custom rules into the corresponding rulesfile"""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request) is True:
        for key, value in request.form.items():
            key = str(key) + ""  # just for ignoring the warning
            rulelist = value.split("\n")
            rules.save_new_rules("custom", rulelist)
        return custom(True)
    return login()
Example #4
0
def options_save() -> str:
    """
    Save the options from a section using the config class.

    for example the Enabled flag in the IPv6 section is saved to the config file
    """
    utils = Webutils()
    if utils.check_login(request) is True:
        section = request.form['section']
        cfgtype = request.form['cfgtype']
        active_tab = request.form['active_tab']
        password1 = ""
        password2 = ""

        for key, value in request.form.items():
            if key != "section" and key != "cfgtype":
                if key.startswith("checkbox"):
                    key = key.replace("checkbox_", "")
                    value = correct_value_checkbox(key)
                if key.startswith("password1"):
                    password1 = value
                if key.startswith("password2"):
                    password2 = value
                if value != "on" and not key.startswith("password"):
                    if cfgtype == "easywall":
                        utils.cfg_easywall.set_value(section, key, value)
                    elif cfgtype == "web":
                        utils.cfg.set_value(section, key, value)
                    elif cfgtype == "log":
                        utils.cfg_log.set_value(section, key, value)
                    else:
                        return options(
                            saved=False,
                            error=
                            "The configuration could not be saved due to invalid parameters.",
                            active_tab=active_tab)

        if password1 and password2:
            if password1 == password2:
                hostname = node().encode("utf-8")
                salt = sha512(hostname).hexdigest()
                pw_hash = sha512(str(salt +
                                     password1).encode("utf-8")).hexdigest()
                utils.cfg.set_value("WEB", "password", pw_hash)
            else:
                return options(
                    saved=False,
                    error="The entered passwords are not identical.",
                    active_tab=active_tab)

        return options(saved=True, active_tab=active_tab)
    return login()
Example #5
0
def login(message: Union[None, str] = None,
          messagetype: Union[None, str] = None) -> str:
    """
    Return the login page which shows messages.

    also the function updates the last commit informations in the config file
    """
    utils = Webutils()
    utils.update_last_commit_infos()
    payload = utils.get_default_payload("Signin", "signin")
    if messagetype is not None:
        payload.messagetype = messagetype
    if message is not None:
        payload.message = message
    return render_template('login.html', vars=payload)
Example #6
0
def apply_step_two() -> None:
    """the function writes true into the accept file from easywall core"""
    write_into_file(".acceptance", "true")
    utils = Webutils()
    utils.cfg_easywall.set_value(
        "ACCEPTANCE", "timestamp",
        datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
Example #7
0
def apply_save() -> str:
    """
    the function applies the configuration and copies the rules to easywall core
    """
    utils = Webutils()
    step = 0
    if utils.check_login(request) is True:
        for key, value in request.form.items():
            if key == "step_1":
                apply_step_one()
                step = 2
            if key == "step_2":
                apply_step_two()
                step = 3
        return apply(True, step)
    return login()
Example #8
0
def login_post(ip_ban: IpBan) -> Union[Response, str]:
    """
    Handle the login post request and if all information are correct.

    a session variable is set to store the login information
    """
    utils = Webutils()
    hostname = platform.node().encode("utf-8")
    salt = hashlib.sha512(hostname).hexdigest()
    pw_hash = hashlib.sha512(
        str(salt + request.form['password']).encode("utf-8")).hexdigest()
    if request.form['username'] == utils.cfg.get_value(
            "WEB", "username") and pw_hash == utils.cfg.get_value(
                "WEB", "password"):
        session.clear()
        session['logged_in'] = True
        session['ip_address'] = request.remote_addr
        session.permanent = True
        info("Successful login for the user {}. ".format(
            request.form['username']) +
             "IP address of the remote device: {}".format(request.remote_addr))
        return redirect("/")
    else:
        warning(
            "Failed login attempt for the user {} detected. ".format(
                request.form['username']) +
            "IP address of the remote device: {}".format(request.remote_addr))
    ip_ban.add(ip=request.remote_addr)
    return login("Wrong username or password.", "danger")
Example #9
0
def blacklist(saved: bool = False) -> str:
    """Return the blacklist page when the user is logged in."""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request) is True:
        payload = utils.get_default_payload("Blacklist")
        payload.lead = """
            On this page you can list IP addresses that are not allowed to connect to this machine.
            <br />
            Please check the IP addresses carefully, as they are not checked by easywall.<br />
            You can add IPv4 and IPv6 addresses to the list.
        """
        payload.addresses = rules.get_rules_for_web("blacklist")
        payload.custom = rules.diff_new_current("blacklist")
        payload.saved = saved
        return render_template('blacklist.html', vars=payload)
    return login()
Example #10
0
def custom(saved: bool = False) -> str:
    """the function returns the custom rules page when the user is logged in"""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request) is True:
        payload = utils.get_default_payload("Custom")
        payload.lead = """
            On this page you can add your own firewall rules.<br />
            Please check the rules for accuracy, as these are not tested by easywall.<br />
            <br />
            To add your own rule, simply copy the rule into the text box. One rule per line.<br />
            It is important to omit the iptables command.<br />
            Example: <code>-P FORWARD DROP</code>
        """
        payload.rules = rules.get_rules_for_web("custom")
        payload.custom = rules.diff_new_current("custom")
        payload.saved = saved
        return render_template('custom.html', vars=payload)
    return login()
Example #11
0
def forwarding(saved: bool = False) -> str:
    """TODO: Doku."""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request):
        payload = utils.get_default_payload("Port Forwarding")
        payload.lead = """
            This page allows you to forward ports from the local system to ports on the
            Internet.<br />
            This is especially useful if the port of an application cannot be changed.<br />
            Enter the port type, source and destination.<br />
            You do not have to release the public port separately, easywall will do that for you.
        """
        payload.forwardings = rules.get_rules_for_web("forwarding")
        payload.custom = False
        if rules.diff_new_current("forwarding"):
            payload.custom = True
        payload.saved = saved
        return render_template('forwarding.html', vars=payload)
    return login()
Example #12
0
def blacklist_save() -> str:
    """Save the blacklist rules into the corresponding rulesfile."""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request) is True:
        ipaddress = ""
        rulelist = rules.get_rules_for_web("blacklist")

        for key, value in request.form.items():
            if key == "ipadr":
                # then a new ip address is blacklisted
                ipaddress = value
                rulelist.append(ipaddress)
                rules.save_new_rules("blacklist", rulelist)
            else:
                # then a old ip address is removed
                ipaddress = key
                rulelist.remove(ipaddress)
                rules.save_new_rules("blacklist", rulelist)
        return blacklist(True)
    return login()
Example #13
0
def apply(saved: bool = False, step: int = 1) -> str:
    """
    the function returns the apply page when the user is logged in
    """
    utils = Webutils()
    if utils.check_login(request) is True:
        payload = utils.get_default_payload("Apply")
        payload.lead = """
            The defined firewall rules were not automatically activated for security reasons.<br>
            On this page, you can safely apply the defined rules.<br>
            The activation takes place in two steps and an exclusion from the server
            should be prevented.
            """
        payload.saved = saved
        payload.step = step
        payload.lastapplied = utils.get_last_accept_time()
        payload.running = step > 1
        payload.accepttime = str(
            utils.cfg_easywall.get_value("ACCEPTANCE", "duration"))
        return render_template('apply.html', vars=payload)
    return login()
Example #14
0
def ports(saved: bool = False) -> str:
    """Return the ports page when the user is logged in."""
    utils = Webutils()
    rules = RulesHandler()
    if utils.check_login(request) is True:
        payload = utils.get_default_payload("Open Ports")
        payload.lead = """
            On this page you can open ports for incoming connections.<br />
            You can add tcp and udp ports.<br />
            Please check whether the entries in the list are needed in the future and
            remove old entries if they are no longer needed.<br />
            To list all open ports under Linux use the command <code>netstat -ln</code>
        """
        payload.tcp = natsorted(rules.get_rules_for_web("tcp"), key=itemgetter(*['port']))
        payload.udp = natsorted(rules.get_rules_for_web("udp"), key=itemgetter(*['port']))
        payload.custom = False
        if rules.diff_new_current("tcp") is True or rules.diff_new_current("udp") is True:
            payload.custom = True
        payload.saved = saved
        return render_template('ports.html', vars=payload)
    return login()
Example #15
0
def options(saved: bool = False,
            error: str = "",
            active_tab: str = "iptables") -> str:
    """Return the options page when the user is logged in."""
    utils = Webutils()
    if utils.check_login(request) is True:
        payload = utils.get_default_payload("Options")
        payload.lead = """
            On this page you can configure easywall.<br />
            All entries from the configuration files for the core
            and the web interface are available.<br />
            Some entries require a restart of the respective program part.
        """
        payload.config = utils.cfg_easywall
        payload.config_web = utils.cfg
        payload.config_log = utils.cfg_log
        payload.saved = saved
        payload.error = error
        payload.active_tab = active_tab
        return render_template('options.html', vars=payload)
    return login()
Example #16
0
def ports_save() -> str:
    """Save the tcp and udp rules into the corresponding rulesfiles."""
    utils = Webutils()
    if utils.check_login(request) is True:
        action = "add"

        entry: dict = {}
        entry["ruletype"] = "tcp"
        entry["port"] = ""
        entry["description"] = ""
        entry["ssh"] = False

        for key, value in request.form.items():
            if key == "remove":
                action = "remove"
                entry["ruletype"] = value
            elif key == "tcpudp":
                action = "add"
                entry["ruletype"] = value
            elif key == "port":
                entry["port"] = value
            elif key == "description":
                entry["description"] = value
            elif key == "ssh":
                entry["ssh"] = True
            else:
                entry["port"] = key

        result = True
        if action == "add":
            result = add_port(entry)
        else:
            result = remove_port(entry)

        return ports(result)
    return login()
Example #17
0
def index_route() -> Union[Response, str]:
    """Call the corresponding function from the appropriate module."""
    utils = Webutils()
    if utils.check_first_run() is True:
        return firstrun()
    return index()
Example #18
0
def index() -> str:
    """Return the index page when the user is logged in."""
    utils = Webutils()
    if utils.check_login(request) is True:
        return render_template('index.html', vars=utils.get_default_payload("Home"))
    return login()