Example #1
0
def _enable_certificate(domain, new_cert_folder):
    logger.debug("Enabling the certificate for domain %s ...", domain)

    live_link = os.path.join(CERT_FOLDER, domain)

    # If a live link (or folder) already exists
    if os.path.exists(live_link):
        # If it's not a link ... expect if to be a folder
        if not os.path.islink(live_link):
            # Backup it and remove it
            _backup_current_cert(domain)
            shutil.rmtree(live_link)
        # Else if it's a link, simply delete it
        elif os.path.lexists(live_link):
            os.remove(live_link)

    os.symlink(new_cert_folder, live_link)

    logger.debug("Restarting services...")

    for service in ("postfix", "dovecot", "metronome"):
        _run_service_command("restart", service)

    if os.path.isfile("/etc/yunohost/installed"):
        # regen nginx conf to be sure it integrates OCSP Stapling
        # (We don't do this yet if postinstall is not finished yet)
        regen_conf(names=["nginx"])

    _run_service_command("reload", "nginx")

    from yunohost.hook import hook_callback

    hook_callback("post_cert_update", args=[domain])
Example #2
0
def _configure_for_acme_challenge(auth, domain):

    nginx_conf_folder = "/etc/nginx/conf.d/%s.d" % domain
    nginx_conf_file = "%s/000-acmechallenge.conf" % nginx_conf_folder

    nginx_configuration = '''
location '/.well-known/acme-challenge'
{
        default_type "text/plain";
        alias %s;
}
    ''' % WEBROOT_FOLDER

    # Check there isn't a conflicting file for the acme-challenge well-known
    # uri
    for path in glob.glob('%s/*.conf' % nginx_conf_folder):

        if path == nginx_conf_file:
            continue

        with open(path) as f:
            contents = f.read()

        if '/.well-known/acme-challenge' in contents:
            raise MoulinetteError(errno.EINVAL, m18n.n(
                'certmanager_conflicting_nginx_file', filepath=path))

    # Write the conf
    if os.path.exists(nginx_conf_file):
        logger.info(
            "Nginx configuration file for ACME challenge already exists for domain, skipping.")
        return

    logger.info(
        "Adding Nginx configuration file for Acme challenge for domain %s.", domain)

    with open(nginx_conf_file, "w") as f:
        f.write(nginx_configuration)

    # Assume nginx conf is okay, and reload it
    # (FIXME : maybe add a check that it is, using nginx -t, haven't found
    # any clean function already implemented in yunohost to do this though)
    _run_service_command("reload", "nginx")

    app_ssowatconf(auth)
Example #3
0
def _enable_certificate(domain, new_cert_folder):
    logger.info("Enabling the certificate for domain %s ...", domain)

    live_link = os.path.join(CERT_FOLDER, domain)

    # If a live link (or folder) already exists
    if os.path.exists(live_link):
        # If it's not a link ... expect if to be a folder
        if not os.path.islink(live_link):
            # Backup it and remove it
            _backup_current_cert(domain)
            shutil.rmtree(live_link)
        # Else if it's a link, simply delete it
        elif os.path.lexists(live_link):
            os.remove(live_link)

    os.symlink(new_cert_folder, live_link)

    logger.info("Restarting services...")

    for service in ("postfix", "dovecot", "metronome"):
        _run_service_command("restart", service)

    _run_service_command("reload", "nginx")
Example #4
0
    def run(self):
        # Get list of php7.0 pool files
        php70_pool_files = glob.glob("{}/*.conf".format(PHP70_POOLS))

        # Keep only basenames
        php70_pool_files = [os.path.basename(f) for f in php70_pool_files]

        # Ignore the "www.conf" (default stuff, probably don't want to touch it ?)
        php70_pool_files = [f for f in php70_pool_files if f != "www.conf"]

        for f in php70_pool_files:

            # Copy the files to the php7.3 pool
            src = "{}/{}".format(PHP70_POOLS, f)
            dest = "{}/{}".format(PHP73_POOLS, f)
            copy2(src, dest)

            # Replace the socket prefix if it's found
            c = "sed -i -e 's@{}@{}@g' {}".format(PHP70_SOCKETS_PREFIX,
                                                  PHP73_SOCKETS_PREFIX, dest)
            os.system(c)

            # Also add a comment that it was automatically moved from php7.0
            # (for human traceability and backward migration)
            c = "sed -i '1i {}' {}".format(MIGRATION_COMMENT, dest)
            os.system(c)

            app_id = os.path.basename(f)[:-len(".conf")]
            if _is_installed(app_id):
                _patch_legacy_php_versions_in_settings(
                    "/etc/yunohost/apps/%s/" % app_id)

            nginx_conf_files = glob.glob("/etc/nginx/conf.d/*.d/%s.conf" %
                                         app_id)
            for f in nginx_conf_files:
                # Replace the socket prefix if it's found
                c = "sed -i -e 's@{}@{}@g' {}".format(PHP70_SOCKETS_PREFIX,
                                                      PHP73_SOCKETS_PREFIX, f)
                os.system(c)

        os.system(
            "rm /etc/logrotate.d/php7.0-fpm"
        )  # We remove this otherwise the logrotate cron will be unhappy

        # Reload/restart the php pools
        _run_service_command("restart", "php7.3-fpm")
        _run_service_command("enable", "php7.3-fpm")
        os.system("systemctl stop php7.0-fpm")
        os.system("systemctl disable php7.0-fpm")

        # Reload nginx
        _run_service_command("reload", "nginx")
Example #5
0
def firewall_reload(skip_upnp=False):
    """
    Reload all firewall rules

    Keyword arguments:
        skip_upnp -- Do not refresh port forwarding using UPnP

    """
    from yunohost.hook import hook_callback
    from yunohost.service import _run_service_command

    reloaded = False
    errors = False

    # Check if SSH port is allowed
    ssh_port = _get_ssh_port()
    if ssh_port not in firewall_list()["opened_ports"]:
        firewall_allow("TCP", ssh_port, no_reload=True)

    # Retrieve firewall rules and UPnP status
    firewall = firewall_list(raw=True)
    upnp = firewall_upnp()["enabled"] if not skip_upnp else False

    # IPv4
    try:
        process.check_output("iptables -w -L")
    except process.CalledProcessError as e:
        logger.debug(
            "iptables seems to be not available, it outputs:\n%s",
            prependlines(e.output.rstrip(), "> "),
        )
        logger.warning(m18n.n("iptables_unavailable"))
    else:
        rules = [
            "iptables -w -F",
            "iptables -w -X",
            "iptables -w -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT",
        ]
        # Iterate over ports and add rule
        for protocol in ["TCP", "UDP"]:
            for port in firewall["ipv4"][protocol]:
                rules.append(
                    "iptables -w -A INPUT -p %s --dport %s -j ACCEPT" %
                    (protocol, process.quote(str(port))))
        rules += [
            "iptables -w -A INPUT -i lo -j ACCEPT",
            "iptables -w -A INPUT -p icmp -j ACCEPT",
            "iptables -w -P INPUT DROP",
        ]

        # Execute each rule
        if process.run_commands(rules, callback=_on_rule_command_error):
            errors = True
        reloaded = True

    # IPv6
    try:
        process.check_output("ip6tables -L")
    except process.CalledProcessError as e:
        logger.debug(
            "ip6tables seems to be not available, it outputs:\n%s",
            prependlines(e.output.rstrip(), "> "),
        )
        logger.warning(m18n.n("ip6tables_unavailable"))
    else:
        rules = [
            "ip6tables -w -F",
            "ip6tables -w -X",
            "ip6tables -w -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT",
        ]
        # Iterate over ports and add rule
        for protocol in ["TCP", "UDP"]:
            for port in firewall["ipv6"][protocol]:
                rules.append(
                    "ip6tables -w -A INPUT -p %s --dport %s -j ACCEPT" %
                    (protocol, process.quote(str(port))))
        rules += [
            "ip6tables -w -A INPUT -i lo -j ACCEPT",
            "ip6tables -w -A INPUT -p icmpv6 -j ACCEPT",
            "ip6tables -w -P INPUT DROP",
        ]

        # Execute each rule
        if process.run_commands(rules, callback=_on_rule_command_error):
            errors = True
        reloaded = True

    if not reloaded:
        raise YunohostError("firewall_reload_failed")

    hook_callback("post_iptable_rules",
                  args=[upnp, os.path.exists("/proc/net/if_inet6")])

    if upnp:
        # Refresh port forwarding with UPnP
        firewall_upnp(no_refresh=False)

    _run_service_command("reload", "fail2ban")

    if errors:
        logger.warning(m18n.n("firewall_rules_cmd_failed"))
    else:
        logger.success(m18n.n("firewall_reloaded"))
    return firewall_list()