Subversion Repositories ALCASAR

Rev

Rev 2809 | Rev 2853 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

<?php
# $Id: network.php 2813 2020-04-26 21:26:32Z rexy $

// written by steweb57, Rexy & Tom HOUDAYER

/********************
*  READ CONF FILES  *
*********************/
define('CONF_FILE', '/usr/local/etc/alcasar.conf');
define('ETHERS_FILE', '/usr/local/etc/alcasar-ethers');
define('ETHERS_INFO_FILE', '/usr/local/etc/alcasar-ethers-info');
define('DNS_LOCAL_FILE', '/etc/hosts');
define('LETS_ENCRYPT_FILE', '/usr/local/etc/alcasar-letsencrypt');
$conf_files = [CONF_FILE, ETHERS_FILE, ETHERS_INFO_FILE, DNS_LOCAL_FILE, LETS_ENCRYPT_FILE];

// Files reading test
foreach ($conf_files as $file) {
        if (!file_exists($file)) {
                exit("Requested file $file isn't present");
        }
        if (!is_readable($file)) {
                exit("Can't read the file $file");
        }
}

// Read ALCASAR CONF_FILE
$file_conf = fopen(CONF_FILE, 'r');
if (!$file_conf) {
        exit('Error opening the file '.CONF_FILE);
}
while (!feof($file_conf)) {
        $buffer = fgets($file_conf, 4096);
        if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                $tmp = explode('=', $buffer, 2);
                $conf[trim($tmp[0])] = trim($tmp[1]);
        }
}
fclose($file_conf);

// Choice of language
$Language = 'en';
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $Langue   = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $Language = strtolower(substr(chop($Langue[0]), 0, 2));
}
if ($Language === 'fr') {       // French
        $l_network_title        = "Configuration réseau";
        $l_internet_legend      = "INTERNET";
        $l_ip_mask              = "Masque";
        $l_ip_router            = "Passerelle";
        $l_ip_public            = "Adresse IP publique";
        $l_ip_dns1              = "DNS n°1";
        $l_ip_dns2              = "DNS n°2";
        $l_dhcp_title           = "Service DHCP";
        $l_dhcp_state           = "Mode actuel";
        $l_DHCP_on              = "actif";
        $l_DHCP_off             = "inactif";
        $l_DHCP_off_explain     = "/!\\ Avant d'arrêter le serveur DHCP, vous devez renseigner les paramètres d'un serveur externe (cf. documentation).";
        $l_static_dhcp_title    = "Réservation d'adresses IP statiques (DHCP)";
        $l_mac_address          = "Adresse MAC";
        $l_ip_address           = "Adresse IP";
        $l_host_name            = "Nom d'hôte";
        $l_del                  = "Supprimer de la liste";
        $l_add_to_list          = "Ajouter";
        $l_apply                = "Appliquer les changements";
        $l_local_dns            = "Résolution local de nom (DNS)";
        $l_import_cert          = "Import de certificat";
        $l_private_key          = "Clé privée (.key) :";
        $l_certificate          = "Certificat (.crt ou .cer) :";
        $l_server_chain         = "Chaîne de certification (.crt, .cer ou .pem) :";
        $l_default_cert         = "Revenir au certificat d'origine :";
        $l_import               = "Importer";
        $l_current_certificate  = "Certificat actuel";
        $l_validated            = "Validé par :";
        $l_empty                = "Vide";
        $l_yes                  = "Oui";
        $l_no                   = "Non";
        $l_ssl_title            = "Chiffrer les flux d'authentification entre les utilisateurs et ALCASAR";
        $l_cert_expiration      = "Date d'expiration :";
        $l_cert_commonname      = "Nom commun :";
        $l_cert_organization    = "Organisation :";
        $l_upload_certificate   = "Importer un certificat officiel";
        $l_le_integration       = "Intégrer un certificat Let's Encrypt";
        $l_le_status            = "Status :";
        $l_disabled             = "Inactif";
        $l_pending_validation   = "En attente de validation";
        $l_enabled              = "Actif";
        $l_le_email             = "Email :";
        $l_le_domain_name       = "Nom de domaine :";
        $l_send                 = "Envoyer";
        $l_le_ask_on            = "Demandé le :";
        $l_le_dns_entry_txt     = "Entrée DNS TXT :";
        $l_le_challenge         = "Challenge :";
        $l_recheck              = "Revérifier";
        $l_cancel               = "Annuler";
        $l_le_api               = "API :";
        $l_le_next_renewal      = "Prochain renouvellement :";
        $l_renew                = "Renouveller";
        $l_renew_force          = "Renouveller (forcer)";
        $l_previous_LE_cert     = "Revenir au certificat Let's Encrypt :";
} else {                        // English
        $l_network_title        = "Network configuration";
        $l_internet_legend      = "INTERNET";
        $l_ip_mask              = "Mask";
        $l_ip_router            = "Gateway";
        $l_ip_public            = "Public IP address";
        $l_ip_dns1              = "DNS n°1";
        $l_ip_dns2              = "DNS n°2";
        $l_dhcp_title           = "DHCP service";
        $l_dhcp_state           = "Current mode";
        $l_DHCP_on              = "enabled";
        $l_DHCP_off             = "disabled";
        $l_DHCP_off_explain     = "/!\\ Before disabling the DHCP server, you must write the extern DHCP parameters in the config file (see Documentation)";
        $l_static_dhcp_title    = "Static IP addresses reservation (DHCP)";
        $l_mac_address          = "MAC address";
        $l_ip_address           = "IP address";
        $l_port                 = "Port";
        $l_host_name            = "Host name";
        $l_del                  = "Delete from list";
        $l_add_to_list          = "Add";
        $l_apply                = "Apply changes";
        $l_local_dns            = "Local name resolution (DNS";
        $l_import_cert          = "Certificate import";
        $l_private_key          = "Private key (.key) :";
        $l_certificate          = "Certificate (.crt or .cer) :";
        $l_server_chain         = "Server-chain (.crt, .cer or .pem) :";
        $l_default_cert         = "Back to default certificate :";
        $l_import               = "Import";
        $l_current_certificate  = "Current certificate";
        $l_validated            = "Validated by :";
        $l_empty                = "Empty";
        $l_yes                  = "Yes";
        $l_no                   = "No";
        $l_ssl_title            = "Cipher authentication flows between users and ALCASAR";
        $l_cert_expiration      = "Expiration date:";
        $l_cert_commonname      = "Common name:";
        $l_cert_organization    = "Organization:";
        $l_upload_certificate   = "Import an officlal certificate";
        $l_le_integration       = "Integrate a Let's Encrypt certificate";
        $l_le_status            = "Status:";
        $l_disabled             = "Disabled";
        $l_pending_validation   = "Pending validation";
        $l_enabled              = "Enabled";
        $l_le_email             = "Email:";
        $l_le_domain_name       = "Domain name:";
        $l_send                 = "Send";
        $l_le_ask_on            = "Ask on:";
        $l_le_dns_entry_txt     = "DNS TXT entry:";
        $l_le_challenge         = "Challenge:";
        $l_recheck              = "Recheck";
        $l_cancel               = "Cancel";
        $l_le_api               = "API:";
        $l_le_next_renewal      = "Next renewal:";
        $l_renew                = "Renew";
        $l_renew_force          = "Renew (force)";
        $l_previous_LE_cert     = "Back to the Let's Encrypt certificate :";
}

$reg_ip      = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/';
$reg_ip_cidr = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$/';
$reg_mac     = '/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/';
$reg_host    = '/^[a-zA-Z0-9-_]+$/';

$choix = (isset($_POST['choix'])) ? $_POST['choix'] : '';

switch ($choix) {
        case 'DHCP_On':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -on');
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'DHCP_Off':
                exec('sudo /usr/local/bin/alcasar-dhcp.sh -off');
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();

        case 'new_mac':
                $new_mac_addr = trim($_POST['add_mac']);
                $new_ip_addr  = trim($_POST['add_ip']);
                if (((!empty($new_mac_addr)) && (preg_match($reg_mac, $new_mac_addr))) && ((!empty($new_ip_addr)) && (preg_match($reg_ip, $new_ip_addr)))) {
                        $tab = file(ETHERS_FILE);
                        if ($tab) { // the file isn't empty
                                $insert = true;
                                foreach ($tab as $line) { // verify that MAC or IP address doesn't exist
                                        $field = explode(' ', $line);
                                        $mac_addr = trim($field[0]);
                                        $ip_addr  = trim($field[1]);
                                        if (strcasecmp($new_mac_addr, $mac_addr) === 0) {
                                                $insert = false;
                                                break;
                                        }
                                        if (strcasecmp($new_ip_addr, $ip_addr) === 0) {
                                                $insert = false;
                                                break;
                                        }
                                }
                                if ($insert) {
                                        $line = $new_mac_addr . ' ' . $new_ip_addr . "\n";
                                        $pointeur = fopen(ETHERS_FILE, 'a');
                                        fwrite($pointeur, $line);
                                        fclose($pointeur);
                                        $pointeur = fopen(ETHERS_INFO_FILE, 'a');
                                        $line = "$new_mac_addr $new_ip_addr #" . trim($_POST['info'],"\x00..\x20") . "\n";
                                        fwrite($pointeur, $line);
                                        fclose($pointeur);
                                        exec('sudo /usr/bin/systemctl reload chilli');
                                }
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'del_mac':
                foreach ($_POST as $key => $value) {
                        if ($value == 'on') {
                                $ether_file = ETHERS_FILE;
                                $ether_file_info = ETHERS_INFO_FILE;
                                exec("/bin/sed -i ".escapeshellarg("/^$key/d")." $ether_file");
                                exec("/bin/sed -i ".escapeshellarg("/^$key/d")." $ether_file_info");
                                exec('sudo /usr/bin/systemctl reload chilli');
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();

        case 'new_host':
                $add_host = trim($_POST['add_host']);
                $add_ip   = trim($_POST['add_ip']);
                if (((!empty($add_host)) && (preg_match($reg_host, $add_host))) && ((!empty($add_ip)) && (preg_match($reg_ip, $add_ip)))) {
                        $tab = file(DNS_LOCAL_FILE);
                        if ($tab) { // the file isn't empty
                                $insert = true;
                                foreach ($tab as $line) { // verify that host or IP address doesn't exist
                                        if (preg_match('/^\d+/', $line)) {
                                                $field = preg_split("/\s+/",$line);
                                                $ip_addr = $field[0];
                                                $host_name = trim($field[1]);
                                                if (strcasecmp($add_host, $host_name) === 0) {
                                                        $insert = false;
                                                        break;
                                                }
                                        }
                                }
                                if ($insert) {
                                        exec("sudo /usr/local/bin/alcasar-dns-local.sh --add $add_ip $add_host");
                                }
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        case 'del_host':
                foreach ($_POST as $key => $value) {
                        if ($value == 'on') {
                                $del_host = explode ("|", $key);
                                $del_ip = str_replace("_",".",$del_host[0]);
                                exec("sudo /usr/local/bin/alcasar-dns-local.sh --del $del_ip $del_host[1]");
                        }
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();

        case 'set_default_cert':
                exec('sudo alcasar-importcert.sh -d');
                break;
        case 'set_last_LE_cert':
                exec('sudo alcasar-letsencrypt.sh --install-cert');
                break;
        case 'import_cert':     // Import certificate
                $maxsize = 100000;
                if (isset($_FILES['key']) && isset($_FILES['crt']) && ($_FILES['key']['error'] == 0) && ($_FILES['crt']['error'] == 0)) {
                        if ($_FILES['key']['size'] <= $maxsize && $_FILES['crt']['size'] <= $maxsize) {
                                if (pathinfo($_FILES['key']['name'])['extension'] == 'key' && ((pathinfo($_FILES['crt']['name'])['extension'] == 'crt') || (pathinfo($_FILES['crt']['name'])['extension'] == 'cer'))) {
                                        $dest = '/tmp/';
                                        $scpath = '';
                                        if (isset($_FILES['sc']) && ((pathinfo($_FILES['sc']['name'])['extension'] == 'crt') || (pathinfo($_FILES['sc']['name'])['extension'] == 'cer') || (pathinfo($_FILES['sc']['name']['extension'] == 'pem')))){
                                                $scpath = $dest.'server-chain.pem';
                                                move_uploaded_file($_FILES['sc']['tmp_name'], $scpath);
                                        }
                                        $keypath = $dest.'alcasar.key';
                                        $crtpath = $dest.'alcasar.crt';
                                        move_uploaded_file($_FILES['key']['tmp_name'], $keypath);
                                        move_uploaded_file($_FILES['crt']['tmp_name'], $crtpath);
                                        exec("sudo alcasar-importcert.sh -i $crtpath -k $keypath -c $scpath");
                                        if (file_exists($crtpath)) unlink($crtpath);
                                        if (file_exists($keypath)) unlink($keypath);
                                        if (file_exists($scpath))  unlink($scpath);
                                }
                        }
                }
                break;

        case 'https_login':     // Set HTTPS login status
                if ($_POST['https_login'] === 'on') {
                        exec('sudo /usr/local/bin/alcasar-https.sh --on');
                } else {
                        exec('sudo /usr/local/bin/alcasar-https.sh --off');
                }
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
}

// Network changes
if ($choix === 'network_change') {
        $network_modification = false;

        if (isset($_POST['dns1']) && (trim($_POST['dns1']) !== $conf['DNS1']) && preg_match($reg_ip, $_POST['dns1'])) {
                file_put_contents(CONF_FILE, str_replace('DNS1='.$conf['DNS1'], 'DNS1='.trim($_POST['dns1']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['dns2']) && (trim($_POST['dns2']) !== $conf['DNS2']) && preg_match($reg_ip, $_POST['dns2'])) {
                file_put_contents(CONF_FILE, str_replace('DNS2='.$conf['DNS2'], 'DNS2='.trim($_POST['dns2']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_public']) && (trim($_POST['ip_public']) !== $conf['PUBLIC_IP']) && preg_match($reg_ip_cidr, $_POST['ip_public'])) {
                file_put_contents(CONF_FILE, str_replace('PUBLIC_IP='.$conf['PUBLIC_IP'], 'PUBLIC_IP='.trim($_POST['ip_public']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_gw']) && (trim($_POST['ip_gw']) !== $conf['GW']) && preg_match($reg_ip, $_POST['ip_gw'])) {
                file_put_contents(CONF_FILE, str_replace('GW='.$conf['GW'], 'GW='.trim($_POST['ip_gw']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }
        if (isset($_POST['ip_private']) && (trim($_POST['ip_private']) !== $conf['PRIVATE_IP']) && preg_match($reg_ip_cidr, $_POST['ip_private'])) {
                file_put_contents(CONF_FILE, str_replace('PRIVATE_IP='.$conf['PRIVATE_IP'], 'PRIVATE_IP='.trim($_POST['ip_private']), file_get_contents(CONF_FILE)));
                $network_modification = true;
        }

        if ($network_modification) {
                exec('sudo /usr/local/bin/alcasar-conf.sh -apply');
        }

        // Read CONF_FILE updated
        $file_conf = fopen(CONF_FILE, 'r');
        if (!$file_conf) {
                exit('Error opening the file '.CONF_FILE);
        }
        while (!feof($file_conf)) {
                $buffer = fgets($file_conf, 4096);
                if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                        $tmp = explode('=', $buffer, 2);
                        $conf[trim($tmp[0])] = trim($tmp[1]);
                }
        }
        fclose($file_conf);
}

// Let's Encrypt actions
if ($choix === 'le_issueCert') {
        // TODO: check ndd & mail format
        $email      = $_POST['email'];
        $domainName = $_POST['domainname'];
        exec('sudo /usr/local/bin/alcasar-letsencrypt.sh --issue --email '.escapeshellarg($email).' --domain '.escapeshellarg($domainName), $output, $exitCode);
        $cmdResponse = implode("<br>\n", $output);
}
if ($choix === 'le_renewCert') {
        if ((isset($_POST['recheck'])) && ((!empty($_POST['recheck'])) || (!empty($_POST['recheck_force'])))) {
                $forceOpt = (!empty($_POST['recheck_force'])) ? ' --force' : '';

                exec('sudo /usr/local/bin/alcasar-letsencrypt.sh --renew' . $forceOpt, $output, $exitCode);

                $cmdResponse = implode("<br>\n", $output);
        } else if ((isset($_POST['cancel'])) && (!empty($_POST['cancel']))) {
                file_put_contents(LETS_ENCRYPT_FILE, preg_replace('/challenge=.*/','challenge=', file_get_contents(LETS_ENCRYPT_FILE)));
                file_put_contents(LETS_ENCRYPT_FILE, preg_replace('/domainRequest=.*/','domainRequest=', file_get_contents(LETS_ENCRYPT_FILE)));
        }
}

// Read Let's Encrypt configuration file
$file_conf_LE = fopen(LETS_ENCRYPT_FILE, 'r');
if (!$file_conf_LE) {
        exit('Error opening the file '.LETS_ENCRYPT_FILE);
}
while (!feof($file_conf_LE)) {
        $buffer = fgets($file_conf_LE, 4096);
        if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
                $tmp = explode('=', $buffer, 2);
                $LE_conf[trim($tmp[0])] = trim($tmp[1]);
        }
}
fclose($file_conf_LE);

// Fonction de test de connectivité internet
function internetTest() {
        $host = 'www.google.fr'; # Google Test
        $port = '80';

        if (! $sock = @fsockopen($host, $port, $num, $error, 5)) {
                return false;
        } else {
                fclose($sock);
                return true;
        }
}

$internet_connected = InternetTest();
if ($internet_connected) {
        $ch = curl_init('https://api.ipify.org/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $internet_publicIP = curl_exec($ch);
        curl_close($ch);
} else {
        $internet_publicIP = '-.-.-.-';
}

// Network interfaces
$interfacesIgnored = ['lo', 'tun[0-9]*', $conf['EXTIF'], $conf['INTIF']];
exec("ip -o link show | awk -F': ' '{print $2}' | sed '/^" . implode('\\|', $interfacesIgnored) . "$/d'", $interfacesAvailable);

// TODO: Pending the next version
$externalNetworks = [
        (object) [
                'interface' => $conf['EXTIF'],
                'ip'        => $conf['PUBLIC_IP'],
                'gateway'   => $conf['GW']
        ]
];
$internalNetworks = [
        (object) [
                'interface' => $conf['INTIF'],
                'ip'        => $conf['PRIVATE_IP']
        ]
];

?>
<!DOCTYPE HTML>
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title><?= $l_network_title ?></title>
        <link rel="stylesheet" href="/css/style.css" type="text/css">
        <script src="/js/jquery.min.js"></script>
        <script src="/js/jquery.connections.js"></script>
        <script type="text/javascript">
        function MAC_Control(formulaire){
                // MAC control (upper case and '-' separator)
                var regex_mac = /^([0-9a-fA-F]{2}(-|:)){5}[0-9a-fA-F]{2}$/;
                if (regex_mac.test(document.forms[formulaire].add_mac.value)){
                        document.forms[formulaire].add_mac.value = document.forms[formulaire].add_mac.value.toUpperCase().replace(/:/g, '-');
                        return true;
                } else {
                        alert('Invalid MAC address');
                        return false;
                }
        }
        </script>
        <style>
                .network-configurator {
                        width: 100%;
                }
                .network-configurator > * {
                        display: inline-block;
                        vertical-align: top;
                        text-align: center;
                }
                .network-configurator > .internet, .network-configurator > .alcasar {
                        width: 20%;
                }
                .network-configurator > .externals, .network-configurator > .internals {
                        width: 30%;
                }
                .network-configurator .actions {
                        position: absolute;
                        background-color: #ddd;
                        padding: 0 2px;
                }
                .network-configurator .actions a {
                        text-decoration: none;
                }
                .network-configurator .actions a:hover {
                        font-weight: bold;
                }
                .network-configurator > .alcasar .actions-externals {
                        bottom: 0;
                        left: 0;
                        border-radius: 0 5px;
                }
                .network-configurator > .alcasar .actions-internals {
                        bottom: 0;
                        right: 0;
                        border-radius: 5px 0;
                }
                .network-configurator .actions-network {
                        top: 0;
                        right: 0;
                        border-radius: 0 5px;
                }
                .network-configurator .network-box {
                        display: inline-block;
                        min-height: 100px;
                        margin: 5px;
                        padding: 3px;
                        text-align: left;
                        background-color: #f7f3ef;
                        position: relative;
                        border-radius: 5px;
                        border: 2px solid grey;
                }
                .network-configurator .network-connector {
                        display: inline-block;
                        position: absolute;
                        top: 50%;
                        margin-top: -5px;
                        margin-left: -5px;
                        width: 10px;
                        height: 10px;
                        border-radius: 5px;
                        background-color: black;
                }
                .network-configurator .network-connector[data-connector-direction="left"] {
                        border-radius: 5px 0px 0px 5px;
                }
                .network-configurator .network-connector[data-connector-direction="right"] {
                        border-radius: 0px 5px 5px 0px;
                }
                .network-configurator div[data-network-type] {
                        position: relative;
                }
        </style>
        <script>
        $(document).ready(function () {
                const interfacesAvailable = <?= ((!empty($interfacesAvailable)) ? "['".implode("', '", $interfacesAvailable)."']" : '[]') ?>;

                const wireStyles = {
                        available: { border: '5px double green' }
                };

                // Add external network
                $('.network-configurator .add-external-network').click(function (event) {
                        event.preventDefault();
                        let options = '';
                        if (interfacesAvailable.length === 0) {
                                options = '<option value=""></option>';
                        } else {
                                for (let i = 0; i < interfacesAvailable.length; i++) {
                                        options += '<option value="' + interfacesAvailable[i] + '">' + interfacesAvailable[i] + '</option>';
                                }
                        }
                        $('.network-configurator .externals').append(' \
                                <div data-network-type="external"> \
                                        <div class="network-connector" data-connector-network="internet" data-connector-direction="left"></div> \
                                        <div class="network-box"> \
                                                <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> \
                                                <label for="ext_interface_X"><?= 'Interface' ?></label> <select name="interface" id="ext_interface_X">' + options + '</select><br> \
                                                <label for="ext_ip_X"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_public" id="ext_ip_X" value="" /><br> \
                                                <label for="ext_gateway_X"><?= $l_ip_router ?></label> <input style="width:120px" type="text" name="ip_gw" id="ext_gateway_X" value="" /> \
                                        </div> \
                                        <div class="network-connector" data-connector-network="external" data-connector-direction="right"></div> \
                                </div>');
                        addWire($('div[data-network-type="external"]:last'));
                });

                // Add internal network
                $('.network-configurator .add-internal-network').click(function (event) {
                        event.preventDefault();
                        $('.network-configurator .internals').append(' \
                                        <div data-network-type="internal"> \
                                                <div class="network-connector" data-connector-network="internal" data-connector-direction="left"></div> \
                                                <div class="network-box"> \
                                                        <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> \
                                                        <label for="int_interface_X"><?= 'Interface' ?></label> <select name="interface" id="int_interface_X" disabled><option value=""></option></select><br> \
                                                        <label for="int_ip_X"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_private" id="int_ip_X" value="" /><br> \
                                                </div> \
                                        </div>');
                        addWire($('div[data-network-type="internal"]:last'));
                });

                // Remove network
                $('.network-configurator').on('click', '.remove-network', function (event) {
                        event.preventDefault();
                        $(this).parent().parent().parent().fadeOut(200, function() {
                                const networkType = $(this).data('networkType');
                                $(this).remove();

                                // Update wires
                                if (networkType === 'external') {
                                        $('div[data-network-type="internet"]>div.network-connector[data-connector-network="internet"]').connections('update');
                                        $('div[data-network-type="alcasar"]>div.network-connector[data-connector-network="external"]').connections('update');
                                } else if (networkType === 'internal') {
                                        $('div[data-network-type="alcasar"]>div.network-connector[data-connector-network="internal"]').connections('update');
                                }
                        });
                });

                const addWire = function (network) {
                        const networkType = network.data('networkType');
                        if (networkType === 'external') {
                                $().connections({ from: 'div[data-network-type="internet"]>div.network-connector[data-connector-network="internet"]', to: 'div[data-network-type="external"]>div.network-connector[data-connector-network="internet"]:last', css: wireStyles.available, within: 'div[data-network-type="external"]:last' });
                                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="external"]', to: 'div[data-network-type="external"]>div.network-connector[data-connector-network="external"]:last', css: wireStyles.available, within: 'div[data-network-type="external"]:last' });
                        } else if (networkType === 'internal') {
                                $().connections({ from: 'div[data-network-type="alcasar"]>div.network-connector[data-connector-network="internal"]', to: 'div[data-network-type="internal"]>div.network-connector[data-connector-network="internal"]:last', css: wireStyles.available, within: 'div[data-network-type="internal"]:last' });
                        }
                };

                window.addEventListener('resize', function () {
                        $('div.network-connector[data-connector-network]').connections('update');
                });

                // Add wires to existing networks
                $('div[data-network-type="external"]').add('div[data-network-type="internal"]').each(function (index, element) {
                        addWire($(this));
                });
        });
        </script>
</head>
<body>
<div class="panel">
        <div class="panel-header"><?= $l_network_title ?></div>
        <div class="panel-row">
                <form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
                        <div class="network-configurator">
                                <div class="internet">
                                        <div data-network-type="internet">
                                                <div class="network-box">
                                                        <?= $l_internet_legend ?> <img src="/images/state_<?= (($internet_connected) ? 'ok' : 'error') ?>.gif"><br>
                                                        <?= $l_ip_public ?> : <?= $internet_publicIP ?><br>
                                                        <label for="dns1"><?= $l_ip_dns1 ?></label> : <input style="width:120px" type="text" id="dns1" name="dns1" value="<?= $conf['DNS1'] ?>" /><br>
                                                        <label for="dns2"><?= $l_ip_dns2 ?></label> : <input style="width:120px" type="text" id="dns2" name="dns2" value="<?= $conf['DNS2'] ?>" />
                                                </div>
                                                <div class="network-connector" data-connector-network="internet" data-connector-direction="right"></div>
                                        </div>
                                </div><div class="externals">
                                        <?php foreach ($externalNetworks as $index => $network): ?>
                                                <div data-network-type="external">
                                                        <div class="network-connector" data-connector-network="internet" data-connector-direction="left"></div>
                                                        <div class="network-box">
                                                                <!-- <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> -->
                                                                <label for="ext_interface_<?= $index ?>"><?= 'Interface' ?></label> <select name="ext_interface[<?= $index ?>]" id="ext_interface_<?= $index ?>" disabled><option value="<?= $network->interface ?>"><?= $network->interface ?></option></select><br>
                                                                <label for="ext_ip_<?= $index ?>"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_public" id="ext_ip_<?= $index ?>" value="<?= $network->ip ?>" /><br>
                                                                <label for="ext_gateway_<?= $index ?>"><?= $l_ip_router ?></label> <input style="width:120px" type="text" name="ip_gw" id="ext_gateway_<?= $index ?>" value="<?= $network->gateway ?>" />
                                                        </div>
                                                        <div class="network-connector" data-connector-network="external" data-connector-direction="right"></div>
                                                </div>
                                        <? endforeach; ?>
                                </div><div class="alcasar">
                                        <div data-network-type="alcasar">
                                                <div class="network-connector" data-connector-network="external" data-connector-direction="left"></div>
                                                <div class="network-box">
                                                        <!-- <div class="actions actions-externals">
                                                                <div><a href="#" class="add-external-network" title="Ajouter un réseau externe">+</a></div>
                                                        </div> -->
                                                        <div class="alcasar-logo"><img src="/images/logo-alcasar.png" style="width: 100px;height: 100px;"></div>
                                                        <!-- <div class="actions actions-internals">
                                                                <div><a href="#" class="add-internal-network" title="Ajouter un réseau interne">+</a></div>
                                                                <div><a href="#" class="add-internal-wifi-network">++</a></div>
                                                        </div> -->
                                                </div>
                                                <div class="network-connector" data-connector-network="internal" data-connector-direction="right"></div>
                                        </div>
                                </div><div class="internals">
                                        <?php foreach ($internalNetworks as $network): ?>
                                                <div data-network-type="internal">
                                                        <div class="network-connector" data-connector-network="internal" data-connector-direction="left"></div>
                                                        <div class="network-box">
                                                                <!-- <div class="actions actions-network"><a href="#" class="remove-network" title="Supprimer ce réseau">-</a></div> -->
                                                                <label for="int_interface_<?= $index ?>"><?= 'Interface' ?></label> <select name="int_interface[<?= $index ?>]" id="int_interface_<?= $index ?>" disabled><option value="<?= $network->interface ?>"><?= $network->interface ?></option></select><br>
                                                                <label for="int_ip_<?= $index ?>"><?= $l_ip_address ?></label> <input style="width:150px" type="text" name="ip_private" id="int_ip_<?= $index ?>" value="<?= $network->ip ?>" /><br>
                                                        </div>
                                                </div>
                                        <? endforeach; ?>
                                </div>
                        </div>
                        <hr>
                        <div style="text-align: center; margin: 5px">
                                <input type="hidden" name="choix" value="network_change">
                                <input type="submit" value="<?= $l_apply ?>">
                        </div>
                </form>
        </div>
</div>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_static_dhcp_title ?></div>
</div>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr><td width="50%" align="center" valign="middle">
                <form action="network.php" method="POST">
                <table cellspacing="2" cellpadding="3" border="1">
                <tr><th><?= $l_mac_address ?></th><th><?= $l_ip_address ?></th><th>Info<th><?= $l_del ?></th></tr>
                <?php
                // Read the "ether" file
                exec('sudo /sbin/ip link show '.escapeshellarg($conf["INTIF"]), $output);
                $detail = explode(' ', $output[1]);
                $intif_mac_addr = strtoupper(str_replace(':', '-', $detail[5]));
                unset($output); unset($detail);
                $line_exist = false;
                $tab = file(ETHERS_INFO_FILE);
                if ($tab) { // le fichier n'est pas vide
                        foreach ($tab as $line) {
                                $fields = explode(' ', $line);
                                $mac_addr = $fields[0];
                                $ip_addr  = $fields[1];
                                $info     = (isset($fields[2])) ? implode(' ', array_slice($fields, 2)) : ' ';

                                echo '<tr>';
                                echo "<td>$mac_addr</td>";
                                echo "<td>$ip_addr</td>";
                                if ($mac_addr !== $intif_mac_addr) {
                                        echo '<td>'.ltrim($info, '#').'</td>';
                                        echo "<td><input type=\"checkbox\" name=\"$mac_addr\"></td>";
                                        $line_exist=True;
                                } else {
                                        echo '<td>ALCASAR</td>';
                                        echo '<td></td>';
                                }
                                echo '</tr>';
                        }
                }
                ?>
                </table>
                <?php if ($line_exist): ?>
                        <input type="hidden" name="choix" value="del_mac">
                        <input type="submit" value="<?= $l_apply ?>">
                <?php endif; ?>
                </form>
        </td><td width="50%" valign="middle" align="center">
                <form name="new_mac" action="network.php" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                                <tr><th><?= $l_mac_address ?></th><th><?= $l_ip_address ?></th><th>Info</th><td></td></tr>
                                <tr><td>Ex. : 12-2F-36-A4-DF-43</td><td>Ex. : 192.168.182.10</td><td>Ex. : Switch<td></td></tr>
                                <tr><td><input type="text" name="add_mac" size="17"></td>
                                <td><input type="text" name="add_ip" size="10"></td>
                                <td><input type="text" name="info" size="10"></td>
                                <td>
                                        <input type="hidden" name="choix" value="new_mac">
                                        <input type="submit" class="button" value="<?= $l_add_to_list ?>" onclick="return MAC_Control('new_mac');">
                                </td>
                        </tr></table>
                </form>
        </td></tr>
</table>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_local_dns ?></div>
</div>
<table width="100%" cellspacing="0" cellpadding="5" border="1">
        <tr>
                <td width="50%" align="center">
                        <form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                        <tr><th><?= $l_ip_address ?></th><th><?= $l_host_name ?></th><th><?= $l_del ?></th></tr>
                        <?php
                        // Read the "dns_local" file
                        $line_exist = false;
                        $tab = file(DNS_LOCAL_FILE);
                        if ($tab) { // not empty
                                foreach ($tab as $line) {
                                        if (preg_match ('/^\d+/', $line)) { # begin with one or several digit
                                                $line_exist = true;
                                                $field = preg_split("/\s+/",$line); # split with one or several whitespace (or tab)
                                                $ip_addr   = $field[0];
                                                $host_name = $field[1];
                                                echo "<tr><td>$ip_addr</td>";
                                                echo "<td>$host_name</td>";
                                                if (($ip_addr == "127.0.0.1")|($host_name == "alcasar")) {
                                                        echo "<td>";}
                                                else {
                                                        echo "<td><input type=\"checkbox\" name=\"$ip_addr|$host_name\">";
                                                }
                                                echo "</td></tr>";
                                        }
                                }
                        }
                        if (!$line_exist) {
                                echo '<tr><td colspan="3" style="text-align: center;font-style: italic;">'.$l_empty.'</td></tr>';
                        }
                        ?>
                        </table>
                        <?php if ($line_exist): ?>
                                <input type="hidden" name="choix" value="del_host">
                                <input type="submit" value="<?= $l_apply ?>">
                        <?php endif; ?>
                        </form>
                </td>
                <td width="50%" valign="middle" align="center">
                        <form name="new_host" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
                        <table cellspacing="2" cellpadding="3" border="1">
                        <tr>
                                <th><?= $l_ip_address ?></th><th><?= $l_host_name ?></th><td></td>
                        </tr>
                        <tr>
                                <td>Ex. : 192.168.182.10</td><td>Ex. : my_nas</td><td></td>
                        </tr>
                        <tr>
                                <td><input type="text" name="add_ip" size="10"><input type="hidden" name="choix" value="new_host"></td>
                                <td><input type="text" name="add_host" size="17"></td>
                                <td><input type=submit class=button value="<?= $l_add_to_list ?>"></td>
                        </tr>
                        </table>
                        </form>
                </td>
        </tr>
</table>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_ssl_title ?></div>
        <div class="panel-row">
                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                <input type="hidden" name="choix" value="https_login">
                <select name="https_login">
                        <option value="on"<?=  (($conf['HTTPS_LOGIN'] === 'on')  ? ' selected' : '') ?>><?= $l_yes ?></option>
                        <option value="off"<?= (($conf['HTTPS_LOGIN'] === 'off') ? ' selected' : '') ?>><?= $l_no ?></option>
                </select>
                <input type="submit" value="<?= $l_apply ?>"><br>
                </form>
        </div>
</div>
<br>
<div class="panel">
        <div class="panel-header"><?= $l_import_cert ?></div>
        <div class="panel-row">
                <div class="panel-cell">
                        <?php
                        $certificateInfos = openssl_x509_parse(file_get_contents('/etc/pki/tls/certs/alcasar.crt'));
                        $cert_expiration_date = date('d-m-Y H:i:s', $certificateInfos['validTo_time_t']);
                        $domain               = $certificateInfos['subject']['CN'];
                        $organization         = (isset($certificateInfos['subject']['O'])) ? $certificateInfos['subject']['O'] : '';
                        $CAdomain             = $certificateInfos['issuer']['CN'];
                        $CAorganization       = (isset($certificateInfos['issuer']['O'])) ? $certificateInfos['issuer']['O'] : '';
                        ?>
                        <h3><?= $l_current_certificate ?></h3>
                        <b><?= $l_cert_commonname ?></b> <?= $domain ?><br>
                        <b><?= $l_cert_expiration ?></b> <?= $cert_expiration_date ?><br>
                        <b><?= $l_cert_organization ?></b> <?= $organization ?><br>
                        <b><?= $l_validated ?></b> <?= $CAdomain ?> (<?= $CAorganization ?>)<br>
                </div>
                <div class="panel-cell">
                        <?
                        if (file_exists('/etc/pki/tls/certs/alcasar.crt.old') && file_exists('/etc/pki/tls/private/alcasar.key.old')){ // An old default certificate exist ?
                                echo "<form method=\"post\" action=\"".htmlspecialchars($_SERVER['PHP_SELF'])."\">\n";
                                echo "\t\t\t\t<input type=\"hidden\" name=\"choix\" value=\"set_default_cert\">\n";
                                echo "\t\t\t\t<input type=\"submit\" value=\"$l_default_cert\"> (alcasar.localdomain)<br>\n";
                                echo "\t\t\t</form>\n";}
                        if (!empty($LE_conf['domainRequest']) && ($domain != $LE_conf['domainRequest'])) { // A Let's encrypt certificate exist & it's not the active one ?
                                echo "\t\t\t<form method=\"post\" action=\"".htmlspecialchars($_SERVER['PHP_SELF'])."\">\n";
                                echo "\t\t\t\t<input type=\"hidden\" name=\"choix\" value=\"set_last_LE_cert\">\n";
                                echo "\t\t\t\t<input type=\"submit\" value=\"".$l_previous_LE_cert."\"> (".$LE_conf['domainRequest'].")\n";
                                echo "\t\t\t</form>\n";}
                        ?>
                </div>
        </div>
        <div class="panel-row">
                <div class="panel-cell">
                        <h3><?= $l_upload_certificate ?></h3>
                        <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data">
                                <?= $l_private_key;?> <input type="file" name="key"><br>
                                <?= $l_certificate;?> <input type="file" name="crt"><br>
                                <?= $l_server_chain;?> <input type="file" name="sc"><br>
                                <input type="hidden" name="choix" value="import_cert">
                                <input type="submit" value="<?= $l_import ?>">
                        </form>
                </div>
                <div class="panel-cell">
                        <?php
                        // Get step
                        if (empty($LE_conf['domainRequest'])) {
                                $step = 1;
                        } else if (!empty($LE_conf['challenge'])) {
                                $step = 2;
                        } else if (($domain === $LE_conf['domainRequest']) && (empty($LE_conf['challenge']))) {
                                $step = 3;
                        } else {
                                $step = 1;
                        }
                        ?>
                        <h3><?= $l_le_integration ?></h3>
                        <?php if ($step === 1): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_issueCert">
                                        <?= $l_le_status ?> <?= $l_disabled ?><br>
                                        <?= $l_le_email ?> <input type="text" name="email" placeholder="adresse@email.com"<?= ((!empty($LE_conf['email'])) ? ' value="'.$LE_conf['email'].'"' : '') ?>><br>
                                        <?= $l_le_domain_name ?> <input type="text" name="domainname" placeholder="alcasar.domain.tld" required><br>
                                        <input type="submit" name="issue" value="<?= $l_send ?>"><br>
                                </form>
                        <?php elseif ($step === 2): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        <?= $l_le_status ?> <?= $l_pending_validation ?><br>
                                        <?= $l_le_domain_name ?> <?= $LE_conf['domainRequest'] ?><br>
                                        <?= $l_le_ask_on ?> <?= date('d-m-Y H:i:s', $LE_conf['dateIssueRequest']) ?><br>
                                        <?= $l_le_dns_entry_txt ?> "<?= '_acme-challenge.'.$LE_conf['domainRequest'] ?>"<br>
                                        <?= $l_le_challenge ?> "<?= $LE_conf['challenge'] ?>"<br>
                                        <input type="submit" name="recheck" value="<?= $l_recheck ?>"> <input type="submit" name="cancel" value="<?= $l_cancel ?>"><br>
                                </form>
                        <?php elseif ($step === 3): ?>
                                <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                                        <input type="hidden" name="choix" value="le_renewCert">
                                        <?= $l_le_status ?> <?= $l_enabled ?><br>
                                        <?= $l_le_domain_name ?> <?= $LE_conf['domainRequest'] ?><br>
                                        <?= $l_le_api ?>  <?= $LE_conf['dnsapi'] ?><br>
                                        <?= $l_le_next_renewal ?> <?= date('d-m-Y', $LE_conf['dateNextRenewal']) ?><br>
                                        <?php if ($LE_conf['dateNextRenewal'] <= date('U')): ?>
                                                <input type="submit" name="recheck" value="<?= $l_renew ?>"><br>
                                        <?php else: ?>
                                                <input type="submit" name="recheck_force" value="<?= $l_renew_force ?>"><br>
                                        <?php endif; ?>
                                </form>
                        <?php endif; ?>
                        <?php if (isset($cmdResponse)): ?>
                                <p><?= $cmdResponse ?></p>
                        <?php endif; ?>
                </div>
        </div>
</div>
</body>
</html>