Subversion Repositories ALCASAR

Rev

Rev 1192 | Rev 1210 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

#!/bin/bash
#  $Id: alcasar.sh 1201 2013-09-02 07:48:07Z crox53 $ 

# alcasar.sh

# ALCASAR Install script -  CopyLeft ALCASAR Team [Rexy + 3abtux + Steweb + Crox + ...] 
# Ce programme est un logiciel libre ; This software is free and open source
# elle que publiée par la Free Software Foundation ; soit la version 3 de la Licence. 
# Ce programme est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE ; 
# sans même une garantie implicite de COMMERCIABILITE ou DE CONFORMITE A UNE UTILISATION PARTICULIERE. 
# Voir la Licence Publique Générale GNU pour plus de détails. 

#  team@alcasar.net

# by Franck BOUIJOUX, Pascal LEVANT and Richard REY
# This script is distributed under the Gnu General Public License (GPL)

# Script d'installation d'ALCASAR (Application Libre pour le Contrôle d'Accès Sécurisé et Authentifié au Réseau)
# ALCASAR est architecturé autour d'une distribution Linux Mageia minimaliste et les logiciels libres suivants :
# Install script for ALCASAR (a secured and authenticated Internet access control captive portal)
# ALCASAR is based on a stripped Mageia (LSB) with the following open source softwares :
#
# Coovachilli (a fork of chillispot), freeradius, mysql, apache, netfilter, squid, dansguardian, ntpd, openssl, dnsmasq, havp, libclamav  and firewalleyes

# Options :
#       -i or --install
#       -u or --uninstall

# Functions :
#       testing         : Tests de connectivité et de téléchargement avant installation
#       init            : Installation des RPM et des scripts
#       network         : Paramètrage du réseau
#       gestion         : Installation de l'interface de gestion
#       AC              : Initialisation de l'autorité de certification. Création des certificats
#       init_db         : Création de la base 'radius' sur le serveur MySql
#       param_radius    : Configuration du serveur d'authentification FreeRadius
#       param_web_radius: Configuration de l'interface de gestion de FreeRadius (dialupadmin)
#       param_chilli    : Configuration du daemon 'coova-chilli' et de la page d'authentification
#       param_squid     : Configuration du proxy squid en mode 'cache'
#       param_dansguardian : Configuration de l'analyseur de contenu DansGuardian
#       antivirus       : Installation havp + libclamav
#       param_nfsen     : Configuration du grapheur nfsen pour apache 
#       dnsmasq         : Configuration du serveur de noms et du serveur dhcp de secours
#       BL              : Configuration de la BlackList
#       cron            : Mise en place des exports de logs (+ chiffrement)
#       fail2ban        : Installation et configuration de Fail2Ban
#       post_install    : Finalisation environnement ( sécurité, bannières, rotation logs, ...)

DATE=`date '+%d %B %Y - %Hh%M'`
DATE_SHORT=`date '+%d/%m/%Y'`
Lang=`echo $LANG|cut -c 1-2`
# ******* Files parameters - paramètres fichiers *********
DIR_INSTALL=`pwd`                               # current directory 
DIR_CONF="$DIR_INSTALL/conf"                    # install directory (with conf files)
DIR_SCRIPTS="$DIR_INSTALL/scripts"              # install directory (with script files)
DIR_SAVE="/var/Save"                            # backup directory (system_backup, user_db_backup, logs)
DIR_WEB="/var/www/html"                         # directory of APACHE
DIR_DG="/etc/dansguardian"                      # directory of DansGuardian
DIR_ACC="$DIR_WEB/acc"                          # directory of the 'ALCASAR Control Center'
DIR_DEST_BIN="/usr/local/bin"                   # directory of ALCASAR scripts
DIR_DEST_SBIN="/usr/local/sbin"                 # directory of ALCASAR admin scripts
DIR_DEST_ETC="/usr/local/etc"                   # directory of ALCASAR conf files
DIR_DEST_SHARE="/usr/local/share"               # directory of share files used by ALCASAR (dnsmasq for instance)
CONF_FILE="$DIR_DEST_ETC/alcasar.conf"          # central ALCASAR conf file
PASSWD_FILE="/root/ALCASAR-passwords.txt"       # text file with the passwords and shared secrets
# ******* DBMS parameters - paramètres SGBD ********
DB_RADIUS="radius"                              # nom de la base de données utilisée par le serveur FreeRadius
DB_USER="radius"                                # nom de l'utilisateur de la base de données
# ******* Network parameters - paramètres réseau *******
HOSTNAME="alcasar"                              # 
DOMAIN="localdomain"                            # domaine local
EXTIF="eth0"                                    # ETH0 est l'interface connectée à Internet (Box FAI)
MTU="1500"
ETHTOOL_OPTS='"autoneg off speed 100 duplex full"'
INTIF="eth1"                                    # ETH1 est l'interface connectée au réseau local de consultation
DEFAULT_PRIVATE_IP_MASK="192.168.182.1/24"      # adresse d'ALCASAR (+masque) proposée par défaut sur le réseau de consultation
# ****** Paths - chemin des commandes *******
SED="/bin/sed -i"
# ****************** End of global parameters *********************

license ()
{
        if [ $Lang == "fr" ]
        then cat $DIR_INSTALL/gpl-3.0.fr.txt | more
        else cat $DIR_INSTALL/gpl-3.0.txt | more
        fi
        echo "Taper sur Entrée pour continuer !"
        echo "Enter to continue."
        read a
}

header_install ()
{
        clear
        echo "-----------------------------------------------------------------------------"
        echo "                     ALCASAR V$VERSION Installation"
        echo "Application Libre pour le Contrôle d'Accès Sécurisé et Authentifié au Réseau"
        echo "-----------------------------------------------------------------------------"
} # End of header_install ()

#Launch network service (useful only when Mageia is running in SafeFail mode)
service network start

##################################################################
##                      Function TESTING                        ##
## - Test of Internet access                                    ##
##################################################################
testing ()
{
        if [ $Lang == "fr" ]
                then echo -n "Tests des paramètres réseau : "
                else echo -n "Network parameters tests : "
        fi
# We test eth0 config files
        PUBLIC_IP=`grep IPADDR /etc/sysconfig/network-scripts/ifcfg-$EXTIF|cut -d"=" -f2`
        PUBLIC_GATEWAY=`grep GATEWAY /etc/sysconfig/network-scripts/ifcfg-$EXTIF|cut -d"=" -f2`
        if [ `echo $PUBLIC_IP|wc -c` -lt 7 ] || [ `echo $PUBLIC_GATEWAY|wc -c` -lt 7 ]
                then
                if [ $Lang == "fr" ]
                then 
                        echo "Échec"
                        echo "La carte réseau connectée à Internet ($EXTIF) n'est pas correctement configurée."
                        echo "Renseignez les champs suivants dans le fichier '/etc/sysconfig/network-scripts/ifcfg-$EXTIF' :"
                        echo "Appliquez les changements : 'service network restart'"
                else
                        echo "Failed"
                        echo "The Internet connected network card ($EXTIF) isn't well configured."
                        echo "The folowing parametres must be set in the file '/etc/sysconfig/network-scripts/ifcfg-$EXTIF' :"
                        echo "Apply the new configuration 'service network restart'"
                fi
                echo "DEVICE=$EXTIF"
                echo "IPADDR="
                echo "NETMASK="
                echo "GATEWAY="
                echo "DNS1="
                echo "DNS2="
                echo "ONBOOT=yes"
                exit 0
        fi
        echo -n "."
# We test the Ethernet links state
        for i in $EXTIF $INTIF
        do
                /sbin/ip link set $i up
                sleep 3
                CMD=`/usr/sbin/ethtool $i |egrep 'Link detected'| awk '{print $NF}'`
                CMD2=`/sbin/mii-tool $i | grep link | awk '{print $NF}'`
                if [ $CMD != "yes" ] && [ $CMD2 != "ok" ]
                        then
                        if [ $Lang == "fr" ]
                        then 
                                echo "Échec"
                                echo "Le lien réseau de la carte $i n'est pas actif."
                                echo "Réglez ce problème puis relancez ce script."
                        else
                                echo "Failed"
                                echo "The link state of $i interface id down."
                                echo "Resolv this problem, then restart this script."
                        fi
                        exit 0
                fi
        echo -n "."
        done
# On teste la présence d'un routeur par défaut (Box FAI)
        if [ `ip route list|grep -c ^default` -ne "1" ] ; then
                if [ $Lang == "fr" ]
                then 
                        echo "Échec"
                        echo "Vous n'avez pas configuré l'accès à Internet ou le câble réseau n'est pas sur la bonne carte."
                        echo "Réglez ce problème puis relancez ce script."
                else
                        echo "Failed"
                        echo "You haven't configured Internet access or Internet link is on the wrong Ethernet card"
                        echo "Resolv this problem, then restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On traite le cas où l'interface configurée lors de l'installation est "eth1" au lieu de "eth0" (mystère sur certaines versions de BIOS et de VirtualBox)
        if [ `ip route list|grep ^default|grep -c eth1` -eq "1" ] ; then
                if [ $Lang == "fr" ]
                        then echo "La configuration des cartes réseau va être corrigée."
                        else echo "The Ethernet card configuration will be corrected."
                fi
                /etc/init.d/network stop
                mv -f /etc/sysconfig/network-scripts/ifcfg-eth1 /etc/sysconfig/network-scripts/ifcfg-eth0
                $SED "s?eth1?eth0?g" /etc/sysconfig/network-scripts/ifcfg-eth0
                /etc/init.d/network start
                echo 0 > /proc/sys/net/ipv4/conf/all/log_martians
                sleep 2
                if [ $Lang == "fr" ]
                        then echo "Configuration corrigée"
                        else echo "Configuration updated"
                fi
                sleep 2
                if [ $Lang == "fr" ]
                        then echo "Vous pouvez relancer ce script."
                        else echo "You can restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On teste le lien vers le routeur par defaut
        IP_GW=`ip route list|grep ^default|cut -d" " -f3`
        arp_reply=`/usr/sbin/arping -b -I$EXTIF -c1 -w2 $IP_GW|grep response|cut -d" " -f2`
        if [ $(expr $arp_reply) -eq 0 ]
                then
                if [ $Lang == "fr" ]
                then 
                        echo "Échec"
                        echo "Le routeur de site ou la Box Internet ($IP_GW) ne répond pas."
                        echo "Réglez ce problème puis relancez ce script."
                else
                        echo "Failed"
                        echo "The Internet gateway doesn't answered"
                        echo "Resolv this problem, then restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On teste la connectivité Internet
        rm -rf /tmp/con_ok.html
        /usr/bin/curl www.google.fr -s -o /tmp/con_ok.html
        if [ ! -e /tmp/con_ok.html ]
        then
                if [ $Lang == "fr" ]
                then 
                        echo "La tentative de connexion vers Internet a échoué (google.fr)."
                        echo "Vérifiez que la carte $EXTIF est bien connectée au routeur du FAI."
                        echo "Vérifiez la validité des adresses IP des DNS."
                else
                        echo "The Internet connection try failed (google.fr)."
                        echo "Please, verify that the $EXTIF card is connected with the Internet gateway."
                        echo "Verify the DNS IP addresses"
                fi
                exit 0
        fi
        rm -rf /tmp/con_ok.html
        echo ". : ok"
} # end of testing

##################################################################
##                      Fonction INIT                           ##
## - Création du fichier "/root/ALCASAR_parametres.txt"                ##
## - Installation et modification des scripts du portail        ##
##################################################################
init ()
{
        if [ "$mode" != "update" ]
        then
# On affecte le nom d'organisme
                header_install
                ORGANISME=!
                PTN='^[a-zA-Z0-9-]*$'
                until [[ $(expr $ORGANISME : $PTN) -gt 0 ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Entrez le nom de votre organisme : "
                                else echo -n "Enter the name of your organism : "
                        fi
                        read ORGANISME
                        if [ "$ORGANISME" == "" ]
                                then
                                ORGANISME=!
                        fi
                done
        fi
# On crée aléatoirement les mots de passe et les secrets partagés
        rm -f $PASSWD_FILE
        grubpwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`        # mot de passe de protection du menu Grub
        echo -n "Password to protect the boot menu (GRUB) : " > $PASSWD_FILE
        echo "$grubpwd" >> $PASSWD_FILE
        md5_grubpwd=`/usr/bin/md5pass $grubpwd`
        $SED "/^password.*/d" /boot/grub/menu.lst
        $SED "1ipassword --md5 $md5_grubpwd" /boot/grub/menu.lst
        mysqlpwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`       # mot de passe de l'administrateur Mysqld
        echo -n "Name and password of Mysql/mariadb administrator : " >> $PASSWD_FILE
        echo "root / $mysqlpwd" >> $PASSWD_FILE
        radiuspwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`      # mot de passe de l'utilisateur Mysqld (utilisé par freeradius)
        echo -n "Name and password of Mysql/mariadb user : " >> $PASSWD_FILE
        echo "$DB_USER / $radiuspwd" >> $PASSWD_FILE
        secretuam=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`      # secret partagé entre intercept.php et coova-chilli
        echo -n "Shared secret between the script 'intercept.php' and coova-chilli : " >> $PASSWD_FILE
        echo "$secretuam" >> $PASSWD_FILE
        secretradius=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`   # secret partagé entre coova-chilli et FreeRadius
        echo -n "Shared secret between coova-chilli and FreeRadius : " >> $PASSWD_FILE
        echo "$secretradius" >> $PASSWD_FILE
        chmod 640 $PASSWD_FILE
# Scripts and conf files copy 
#  - in /usr/local/bin :  alcasar-{CA.sh,conf.sh,import-clean.sh,iptables-bypass.sh,iptables.sh,log.sh,watchdog.sh}
        cp -f $DIR_SCRIPTS/alcasar* $DIR_DEST_BIN/. ; chown root:root $DIR_DEST_BIN/alcasar* ; chmod 740 $DIR_DEST_BIN/alcasar*
#  - in /usr/local/sbin :  alcasar-{bl.sh,bypass.sh,dateLog.sh,havp.sh,logout.sh,mysql.sh,nf.sh,profil.sh,uninstall.sh,version-list.sh,load-balancing.sh}
        cp -f $DIR_SCRIPTS/sbin/alcasar* $DIR_DEST_SBIN/. ; chown root:root $DIR_DEST_SBIN/alcasar* ; chmod 740 $DIR_DEST_SBIN/alcasar*
#  - in /usr/local/etc : alcasar-{bl-categories-enabled,dns-name,iptables-local.sh,services}
        cp -f $DIR_CONF/etc/alcasar* $DIR_DEST_ETC/. ; chown root:apache $DIR_DEST_ETC/alcasar* ; chmod 660 $DIR_DEST_ETC/alcasar*
        $SED "s?^radiussecret.*?radiussecret=\"$secretradius\"?g" $DIR_DEST_SBIN/alcasar-logout.sh
        $SED "s?^DB_RADIUS=.*?DB_RADIUS=\"$DB_RADIUS\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh
        $SED "s?^DB_USER=.*?DB_USER=\"$DB_USER\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh $DIR_DEST_BIN/alcasar-conf.sh
        $SED "s?^radiuspwd=.*?radiuspwd=\"$radiuspwd\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh $DIR_DEST_BIN/alcasar-conf.sh
# generate central conf file
        cat <<EOF > $CONF_FILE
##########################################
##                                      ##
##          ALCASAR Parameters          ##
##                                      ##
##########################################

INSTALL_DATE=$DATE
VERSION=$VERSION
ORGANISM=$ORGANISME
DOMAIN=$DOMAIN
EOF
        chmod o-rwx $CONF_FILE
} # End of init ()

##################################################################
##                      Fonction network                        ##
## - Définition du plan d'adressage du réseau de consultation ##
## - Nommage DNS du système                                    ##
## - Configuration de l'interface eth1 (réseau de consultation)        ##
## - Modification du fichier /etc/hosts                         ##
## - Configuration du serveur de temps (NTP)                    ##
## - Renseignement des fichiers hosts.allow et hosts.deny       ##
##################################################################
network ()
{
        header_install
        if [ "$mode" != "update" ]
                then
                if [ $Lang == "fr" ]
                        then echo "Par défaut, l'adresse IP d'ALCASAR sur le réseau de consultation est : $DEFAULT_PRIVATE_IP_MASK"
                        else echo "The default ALCASAR IP address on consultation network is : $DEFAULT_PRIVATE_IP_MASK"
                fi
                response=0
                PTN='^[oOyYnN]$'
                until [[ $(expr $response : $PTN) -gt 0 ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Voulez-vous utiliser cette adresse et ce plan d'adressage (recommandé) (O/n)? : "
                                else echo -n "Do you want to use this IP address and this IP addressing plan (recommanded) (Y/n)? : "
                        fi
                        read response
                done
                if [ "$response" = "n" ] || [ "$response" = "N" ]
                then
                        PRIVATE_IP_MASK="0"
                        PTN='^\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\)/[012]\?[[:digit:]]$'
                        until [[ $(expr $PRIVATE_IP_MASK : $PTN) -gt 0 ]]
                        do
                                if [ $Lang == "fr" ]
                                        then echo -n "Entrez l'adresse IP d'ALCASAR au format CIDR (a.b.c.d/xx) : "
                                        else echo -n "Enter ALCASAR IP address in CIDR format (a.b.c.d/xx) : "
                                fi
                                read PRIVATE_IP_MASK
                        done
                else
                        PRIVATE_IP_MASK=$DEFAULT_PRIVATE_IP_MASK
                fi
        else
                PRIVATE_IP_MASK=`grep PRIVATE_IP conf/etc/alcasar.conf|cut -d"=" -f2` 
                rm -rf conf/etc/alcasar.conf
        fi
# Define LAN side global parameters
        hostname $HOSTNAME
        echo $HOSTNAME > /etc/hostname
        PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network address (ie.: 192.168.182.0)
        PRIVATE_NETMASK=`/bin/ipcalc -m $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network mask (ie.: 255.255.255.0)
        PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`                                              # ALCASAR private ip address (consultation LAN side)
        PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP_MASK |cut -d"=" -f2`                                 # network prefix (ie. 24)
        PRIVATE_NETWORK_MASK=$PRIVATE_NETWORK/$PRIVATE_PREFIX                                           # ie.: 192.168.182.0/24
        classe=$((PRIVATE_PREFIX/8)); classe_sup=`expr $classe + 1`; classe_sup_sup=`expr $classe + 2`  # ie.: 2=classe B, 3=classe C
        PRIVATE_NETWORK_SHORT=`echo $PRIVATE_NETWORK | cut -d"." -f1-$classe`.                          # compatibility with hosts.allow et hosts.deny (ie.: 192.168.182.)
        PRIVATE_BROADCAST=`/bin/ipcalc -b $PRIVATE_NETWORK_MASK | cut -d"=" -f2`                        # private network broadcast (ie.: 192.168.182.255)
        private_network_ending=`echo $PRIVATE_NETWORK | cut -d"." -f$classe_sup`                        # last octet of LAN address
        private_broadcast_ending=`echo $PRIVATE_BROADCAST | cut -d"." -f$classe_sup`                    # last octet of LAN broadcast
        PRIVATE_FIRST_IP=`echo $PRIVATE_NETWORK | cut -d"." -f1-3`"."`expr $private_network_ending + 1`         # First network address (ex.: 192.168.182.1)
        PRIVATE_SECOND_IP=`echo $PRIVATE_NETWORK | cut -d"." -f1-3`"."`expr $private_network_ending + 2`        # second network address (ex.: 192.168.182.2)
        PRIVATE_LAST_IP=`echo $PRIVATE_BROADCAST | cut -d"." -f1-3`"."`expr $private_broadcast_ending - 1`      # last network address (ex.: 192.168.182.254)
        PRIVATE_MAC=`/sbin/ip link show $INTIF | grep ether | cut -d" " -f6`                            # MAC address of INTIF (eth1)
# Define Internet parameters
        [ -e /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF ] || cp /etc/sysconfig/network-scripts/ifcfg-$EXTIF /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF
        DNS1=`grep DNS1 /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`      # @ip 1er DNS
        DNS2=`grep DNS2 /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`      # @ip 2ème DNS
        DNS1=${DNS1:=208.67.220.220}
        DNS2=${DNS2:=208.67.222.222}
        PUBLIC_NETMASK=`grep NETMASK /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`
        DEFAULT_PUBLIC_NETMASK=`ipcalc -m $PUBLIC_IP | cut -d"=" -f2`
        PUBLIC_NETMASK=${PUBLIC_NETMASK:=$DEFAULT_PUBLIC_NETMASK}
        PUBLIC_PREFIX=`/bin/ipcalc -p $PUBLIC_IP $PUBLIC_NETMASK|cut -d"=" -f2`
        PUBLIC_NETWORK=`/bin/ipcalc -n $PUBLIC_IP/$PUBLIC_PREFIX|cut -d"=" -f2`
        echo "PUBLIC_IP=$PUBLIC_IP/$PUBLIC_PREFIX" >> $CONF_FILE
        echo "PUBLIC_MTU=$MTU" >> $CONF_FILE
        echo "GW=$PUBLIC_GATEWAY" >> $CONF_FILE 
        echo "DNS1=$DNS1" >> $CONF_FILE
        echo "DNS2=$DNS2" >> $CONF_FILE
        echo "PRIVATE_IP=$PRIVATE_IP_MASK" >> $CONF_FILE
        echo "DHCP=full" >> $CONF_FILE
        echo "EXT_DHCP_IP=none" >> $CONF_FILE
        echo "RELAY_DHCP_IP=none" >> $CONF_FILE
        echo "RELAY_DHCP_PORT=none" >> $CONF_FILE
        [ -e /etc/sysconfig/network.default ] || cp /etc/sysconfig/network /etc/sysconfig/network.default
# config network
        cat <<EOF > /etc/sysconfig/network
NETWORKING=yes
HOSTNAME="$HOSTNAME"
FORWARD_IPV4=true
EOF
# config /etc/hosts
        [ -e /etc/hosts.default ] || cp /etc/hosts /etc/hosts.default
        cat <<EOF > /etc/hosts
127.0.0.1       localhost
$PRIVATE_IP     $HOSTNAME $HOSTNAME.$DOMAIN
EOF
# Config eth0 (Internet)
        cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=static
IPADDR=$PUBLIC_IP
NETMASK=$PUBLIC_NETMASK
GATEWAY=$PUBLIC_GATEWAY
DNS1=127.0.0.1
ONBOOT=yes
METRIC=10
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
EOF
# Config eth1 (consultation LAN) in normal mode
        cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$INTIF
DEVICE=$INTIF
BOOTPROTO=static
ONBOOT=yes
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
ETHTOOL_OPTS=$ETHTOOL_OPTS
EOF
# Config of eth1 in bypass mode (see "alcasar-bypass.sh")
        cat <<EOF > /etc/sysconfig/network-scripts/default-ifcfg-$INTIF
DEVICE=$INTIF
BOOTPROTO=static
IPADDR=$PRIVATE_IP
NETMASK=$PRIVATE_NETMASK
ONBOOT=yes
METRIC=10
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
# Mise à l'heure du serveur
        [ -e /etc/ntp/step-tickers.default ] || cp /etc/ntp/step-tickers /etc/ntp/step-tickers.default
        cat <<EOF > /etc/ntp/step-tickers
0.fr.pool.ntp.org       # adapt to your country
1.fr.pool.ntp.org
2.fr.pool.ntp.org
EOF
# Configuration du serveur de temps (sur lui même)
        [ -e /etc/ntp.conf.default ] || cp /etc/ntp.conf /etc/ntp.conf.default
        cat <<EOF > /etc/ntp.conf
server 0.fr.pool.ntp.org        # adapt to your country
server 1.fr.pool.ntp.org
server 2.fr.pool.ntp.org
server 127.127.1.0              # local clock si NTP internet indisponible ...
fudge 127.127.1.0 stratum 10
restrict $PRIVATE_NETWORK mask $PRIVATE_NETMASK nomodify notrap
restrict 127.0.0.1
driftfile /var/lib/ntp/drift
logfile /var/log/ntp.log
EOF

        chown -R ntp:ntp /var/lib/ntp
# Renseignement des fichiers hosts.allow et hosts.deny
        [ -e /etc/hosts.allow.default ]  || cp /etc/hosts.allow /etc/hosts.allow.default
        cat <<EOF > /etc/hosts.allow
ALL: LOCAL, 127.0.0.1, localhost, $PRIVATE_IP
sshd: ALL
ntpd: $PRIVATE_NETWORK_SHORT
EOF
        [ -e /etc/host.deny.default ]  || cp /etc/hosts.deny /etc/hosts.deny.default
        cat <<EOF > /etc/hosts.deny
ALL: ALL: spawn ( /bin/echo "service %d demandé par %c" | /bin/mail -s "Tentative d'accès au service %d par %c REFUSE !!!" security ) &
EOF
# Firewall config
        $SED "s?^EXTIF=.*?EXTIF=\"$EXTIF\"?g" $DIR_DEST_BIN/alcasar-iptables.sh  $DIR_DEST_BIN/alcasar-iptables-bypass.sh
        $SED "s?^INTIF=.*?INTIF=\"$INTIF\"?g" $DIR_DEST_BIN/alcasar-iptables.sh  $DIR_DEST_BIN/alcasar-iptables-bypass.sh
        chmod o+r $DIR_DEST_BIN/alcasar-iptables.sh #lecture possible pour apache (interface php du filtrage réseau)
# create the filter exception file and ip_bloqued file
        touch $DIR_DEST_ETC/alcasar-filter-exceptions
# create the ip_blocked file with a first line (LAN between ALCASAR and the Internet GW)
        echo "#$PUBLIC_NETWORK/$PUBLIC_PREFIX LAN-ALCASAR-BOX" > $DIR_DEST_ETC/alcasar-ip-blocked
# load conntrack ftp module
        [ -e /etc/modprobe.preload.default ] || cp /etc/modprobe.preload /etc/modprobe.preload.default
        echo "ip_conntrack_ftp" >>  /etc/modprobe.preload
# load ipt_NETFLOW module
        echo "ipt_NETFLOW" >>  /etc/modprobe.preload
# 
# the script "$DIR_DEST_BIN/alcasar-iptables.sh" is launched at the end in order to allow update via ssh
} # End of network ()

##################################################################
##                      Fonction gestion                        ##
## - installation du centre de gestion                          ##
## - configuration du serveur web (Apache)                      ##
## - définition du 1er comptes de gestion                      ##
## - sécurisation des accès                                   ##
##################################################################
gestion()
{
        [ -d $DIR_WEB ] && rm -rf $DIR_WEB
        mkdir $DIR_WEB
# Copie et configuration des fichiers du centre de gestion
        cp -rf $DIR_INSTALL/web/* $DIR_WEB/
        echo "$VERSION" > $DIR_WEB/VERSION
        $SED "s?99/99/9999?$DATE_SHORT?g" $DIR_ACC/menu.php
        $SED "s?\$DB_RADIUS = .*?\$DB_RADIUS = \"$DB_RADIUS\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$DB_USER = .*?\$DB_USER = \"$DB_USER\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$radiuspwd = .*?\$radiuspwd = \"$radiuspwd\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$hostname =.*?\$hostname = \"$HOSTNAME\";?g" $DIR_WEB/index.php
        chmod 640 $DIR_ACC/phpsysinfo/includes/xml/portail.php
        chown -R apache:apache $DIR_WEB/*
        for i in system_backup base logs/firewall logs/httpd logs/squid logs/security;
        do
                [ -d $DIR_SAVE/$i ] || mkdir -p $DIR_SAVE/$i
        done
        chown -R root:apache $DIR_SAVE
# Configuration et sécurisation php
        [ -e /etc/php.ini.default ] || cp /etc/php.ini /etc/php.ini.default
        timezone=`cat /etc/sysconfig/clock|grep ZONE|cut -d"=" -f2`
        $SED "s?^;date.timezone =.*?date.timezone = $timezone?g" /etc/php.ini
        $SED "s?^upload_max_filesize.*?upload_max_filesize = 100M?g" /etc/php.ini
        $SED "s?^post_max_size.*?post_max_size = 100M?g" /etc/php.ini
        $SED "s?^html_errors.*?html_errors = Off?g" /etc/php.ini
        $SED "s?^expose_php.*?expose_php = Off?g" /etc/php.ini
# Configuration et sécurisation Apache
        rm -rf /var/www/cgi-bin/* /var/www/perl/* /var/www/icons/README* /var/www/error/README*
        [ -e /etc/httpd/conf/httpd.conf.default ] || cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.default
        $SED "s?^#ServerName.*?ServerName $HOSTNAME?g" /etc/httpd/conf/httpd.conf
        $SED "s?^Listen.*?Listen $PRIVATE_IP:80?g" /etc/httpd/conf/httpd.conf
        $SED "s?^ServerTokens.*?ServerTokens Prod?g" /etc/httpd/conf/httpd.conf
        $SED "s?^ServerSignature.*?ServerSignature Off?g" /etc/httpd/conf/httpd.conf
        $SED "s?^#ErrorDocument 404 /missing.html.*?ErrorDocument 404 /index.html?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule authn_anon_module.*?#LoadModule authn_anon_module modules/mod_authn_anon.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule status_module.*?#LoadModule status_module modules/mod_status.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule autoindex_module.*?#LoadModule autoindex_module modules/mod_autoindex.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule info_module.*?#LoadModule info_module modules/mod_info.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule imagemap_module.*?#LoadModule imagemap_module modules/mod_imagemap.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule rewrite_module.*?#LoadModule rewrite_module modules/mod_rewrite.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?LoadModule speling_module.*?LoadModule speling_module modules/mod_speling.so?g" /etc/httpd/conf/httpd.conf
        FIC_MOD_SSL=`find /etc/httpd/modules.d/ -type f -name *mod_ssl.conf`
        $SED "s?^Listen.*?Listen $PRIVATE_IP:443?g" $FIC_MOD_SSL # On écoute en SSL que sur INTIF
        $SED "s?background-color.*?background-color: #EFEFEF; }?g" /var/www/error/include/top.html
        [ -e /var/www/error/include/bottom.html.default ] || mv /var/www/error/include/bottom.html /var/www/error/include/bottom.html.default
        cat <<EOF > /var/www/error/include/bottom.html
</body>
</html>
EOF
# Définition du premier compte lié au profil 'admin'
        header_install
        if [ "$mode" = "install" ]
        then
                admin_portal=!
                PTN='^[a-zA-Z0-9-]*$'
                until [[ $(expr $admin_portal : $PTN) -gt 0 ]]
                        do
                        header_install
                        if [ $Lang == "fr" ]
                        then 
                                echo ""
                                echo "Définissez un premier compte d'administration du portail :"
                                echo
                                echo -n "Nom : "
                        else
                                echo ""
                                echo "Define the first account allow to administrate the portal :"
                                echo
                                echo -n "Account : "
                        fi
                        read admin_portal
                        if [ "$admin_portal" == "" ]
                                then
                                admin_portal=!
                        fi
                        done
# Création du fichier de clés de ce compte dans le profil "admin"
                [ -d $DIR_DEST_ETC/digest ] && rm -rf $DIR_DEST_ETC/digest
                mkdir -p $DIR_DEST_ETC/digest
                chmod 755 $DIR_DEST_ETC/digest
                until [ -s $DIR_DEST_ETC/digest/key_admin ]
                        do
                                /usr/sbin/htdigest -c $DIR_DEST_ETC/digest/key_admin $HOSTNAME $admin_portal
                        done
                $DIR_DEST_SBIN/alcasar-profil.sh --list
        else   # mise à jour des versions < 2.1
                if [ $MAJ_PREVIOUS_VERSION -lt 2 ] || ([ $MAJ_PREVIOUS_VERSION -eq 2 ] && [ $MIN_PREVIOUS_VERSION -lt 1 ])
                        then
                        if [ $Lang == "fr" ]
                        then 
                                echo "Cette mise à jour nécessite de redéfinir le premier compte d'administration du portail"
                                echo
                                echo -n "Nom : "
                        else
                                echo "This update need to redefine the first admin account"
                                echo
                                echo -n "Account : "
                        fi
                        read admin_portal
                        [ -d $DIR_DEST_ETC/digest ] && rm -rf $DIR_DEST_ETC/digest
                        mkdir -p $DIR_DEST_ETC/digest
                        chmod 755 $DIR_DEST_ETC/digest
                        until [ -s $DIR_DEST_ETC/digest/key_admin ]
                        do
                                /usr/sbin/htdigest -c $DIR_DEST_ETC/digest/key_admin $HOSTNAME $admin_portal
                        done
                        $DIR_DEST_SBIN/alcasar-profil.sh --list
                fi
        fi
# synchronisation horaire
        ntpd -q -g &
# Sécurisation du centre
        rm -f /etc/httpd/conf/webapps.d/alcasar*
        cat <<EOF > /etc/httpd/conf/webapps.d/alcasar.conf
<Directory $DIR_ACC>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
#       Allow from AA.BB.CC.DD/32       # Allow from specific @IP
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_all
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/admin>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
#       Allow from AA.BB.CC.DD/32       # Allow from specific @IP
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_admin
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/manager>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
#       Allow from AA.BB.CC.DD/32       # Allow from specific @IP
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_manager
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/backup>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
#       Allow from AA.BB.CC.DD/32       # Allow from specific @IP
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_backup
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
Alias /save/ "$DIR_SAVE/"
<Directory $DIR_SAVE>
        SSLRequireSSL
        Options Indexes
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
#       Allow from AA.BB.CC.DD/32       # Allow from specific @IP
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        AuthUserFile $DIR_DEST_ETC/digest/key_backup
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
EOF
} # End of gestion ()

##########################################################################################
##                              Fonction AC()                                           ##
## - Création d'une Autorité de Certification et du certificat serveur pour apache    ##
##########################################################################################
AC ()
{
        $SED "s?ifcfg-eth.?ifcfg-$INTIF?g" $DIR_DEST_BIN/alcasar-CA.sh
        $DIR_DEST_BIN/alcasar-CA.sh
        FIC_VIRTUAL_SSL=`find /etc/httpd/conf -type f -name *default_ssl_vhost.conf`
        [ -e /etc/httpd/conf/vhosts-ssl.default ]  || cp $FIC_VIRTUAL_SSL /etc/httpd/conf/vhosts-ssl.default
        $SED "s?localhost.crt?alcasar.crt?g" $FIC_VIRTUAL_SSL
        $SED "s?localhost.key?alcasar.key?g" $FIC_VIRTUAL_SSL
        $SED "s?^#SSLCertificateChainFile.*?SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt?" $FIC_VIRTUAL_SSL
        chown -R root:apache /etc/pki
        chmod -R 750 /etc/pki
} # End AC ()

##########################################################################################
##                      Fonction init_db()                                              ##
## - Initialisation de la base Mysql                                                    ##
## - Affectation du mot de passe de l'administrateur (root)                             ##
## - Suppression des bases et des utilisateurs superflus                                ##
## - Création de la base 'radius'                                                      ##
## - Installation du schéma de cette base                                              ##
## - Import des tables de comptabilité (mtotacct, totacct) et info_usagers (userinfo)  ##
##       ces table proviennent de 'dialupadmin' (paquetage freeradius-web)              ##
##########################################################################################
init_db ()
{
        mkdir -p /var/lib/mysql/.tmp
        chown -R mysql:mysql /var/lib/mysql/
        [ -e /etc/my.cnf.rpmnew ] && mv /etc/my.cnf.rpmnew /etc/my.cnf          # prend en compte les migrations de MySQL
        [ -e /etc/my.cnf.default ] || cp /etc/my.cnf /etc/my.cnf.default
        $SED "s?^#bind-address.*?bind-address=127.0.0.1?g" /etc/my.cnf
        /etc/init.d/mysqld start
        sleep 4
        mysqladmin -u root password $mysqlpwd
        MYSQL="/usr/bin/mysql -uroot -p$mysqlpwd --exec"
# Delete exemple databases if exist
        $MYSQL="DROP DATABASE IF EXISTS test;DROP DATABASE IF EXISTS tmp;CONNECT mysql;DELETE from user where user='';FLUSH PRIVILEGES;" 
# Create 'radius' database
        $MYSQL="CREATE DATABASE IF NOT EXISTS $DB_RADIUS;GRANT ALL ON $DB_RADIUS.* TO $DB_USER@localhost IDENTIFIED BY '$radiuspwd';FLUSH PRIVILEGES"
# Add an empty radius database structure
        mysql -u$DB_USER -p$radiuspwd $DB_RADIUS < $DIR_CONF/radiusd-db-vierge.sql
# modify the start script in order to close accounting connexion when the system is comming down or up
        [ -e /etc/init.d/mysqld.default ] || cp /etc/init.d/mysqld /etc/init.d/mysqld.default
        $SED "/wait_for_pid created/a echo \"Flush ALCASAR open accounting sessions\"; /usr/local/sbin/alcasar-mysql.sh -acct_stop" /etc/init.d/mysqld
        $SED "/'stop')/a echo \"Flush ALCASAR open accounting sessions\"; /usr/local/sbin/alcasar-mysql.sh -acct_stop" /etc/init.d/mysqld
} # End init_db ()

##########################################################################
##                      Fonction param_radius                           ##
## - Paramètrage des fichiers de configuration FreeRadius              ##
## - Affectation du secret partagé entre coova-chilli et freeradius    ##
## - Modification de fichier de conf pour l'accès à Mysql             ##
##########################################################################
param_radius ()
{
        cp -f $DIR_CONF/radiusd-db-vierge.sql /etc/raddb/
        chown -R radius:radius /etc/raddb
        [ -e /etc/raddb/radiusd.conf.default ] || cp /etc/raddb/radiusd.conf /etc/raddb/radiusd.conf.default
# paramètrage radius.conf
        $SED "s?^[\t ]*#[\t ]*user =.*?user = radius?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*#[\t ]*group =.*?group = radius?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*status_server =.*?status_server = no?g" /etc/raddb/radiusd.conf
# suppression de la fonction proxy
        $SED "s?^[\t ]*proxy_requests.*?proxy_requests = no?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*\$INCLUDE proxy.conf.*?#\$INCLUDE proxy.conf?g" /etc/raddb/radiusd.conf
# suppression du module EAP
        $SED "s?^[\t ]*\$INCLUDE eap.conf.*?#\$INCLUDE eap.conf?g" /etc/raddb/radiusd.conf
# écoute sur loopback uniquement (à modifier plus tard pour l'EAP)
        $SED "s?^[\t ]*ipaddr =.*?ipaddr = 127.0.0.1?g" /etc/raddb/radiusd.conf
# prise en compte du module SQL et des compteurs SQL
        $SED "s?^[\t ]*#[\t ]*\$INCLUDE sql.conf.*?\$INCLUDE sql.conf?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*#[\t ]*\$INCLUDE sql/mysql/counter.conf?\$INCLUDE sql/mysql/counter.conf?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*\$INCLUDE policy.conf?#\$INCLUDE policy.conf?g" /etc/raddb/radiusd.conf
# purge du répertoire des serveurs virtuels et copie du fichier de configuration d'Alcasar
        rm -f /etc/raddb/sites-enabled/*
        cp $DIR_CONF/alcasar-radius /etc/raddb/sites-available/alcasar
        chown radius:apache /etc/raddb/sites-available/alcasar /etc/raddb/modules/ldap # droits rw pour apache (module ldap)
        chmod 660 /etc/raddb/sites-available/alcasar /etc/raddb/modules/ldap
        chgrp apache /etc/raddb /etc/raddb/sites-available /etc/raddb/modules
        ln -s /etc/raddb/sites-available/alcasar /etc/raddb/sites-enabled/alcasar
# Inutile dans notre fonctionnement mais les liens sont recréés par un update de radius ... donc forcé en tant que fichier à 'vide'
        touch /etc/raddb/sites-enabled/{inner-tunnel,control-socket,default}
# configuration du fichier client.conf (127.0.0.1 suffit mais on laisse le deuxième client pour la future gestion de l'EAP)
        [ -e /etc/raddb/clients.conf.default ] || cp -f /etc/raddb/clients.conf /etc/raddb/clients.conf.default
        cat << EOF > /etc/raddb/clients.conf
client 127.0.0.1 {
        secret = $secretradius
        shortname = localhost
}
EOF
# modif sql.conf
        [ -e /etc/raddb/sql.conf.default ] || cp /etc/raddb/sql.conf /etc/raddb/sql.conf.default
        $SED "s?^[\t ]*login =.*?login = \"$DB_USER\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*password =.*?password = \"$radiuspwd\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*radius_db =.*?radius_db = \"$DB_RADIUS\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*sqltrace =.*?sqltrace = no?g" /etc/raddb/sql.conf
# modif dialup.conf
        [ -e /etc/raddb/sql/mysql/dialup.conf.default ] || cp /etc/raddb/sql/mysql/dialup.conf /etc/raddb/sql/mysql/dialup.conf.default
        cp -f $DIR_CONF/dialup.conf /etc/raddb/sql/mysql/dialup.conf
# insures that mysql is up before radius start
        $SED "s?^After=.*?After=syslog.target network.target mysqld.service?g" /lib/systemd/system/radiusd.service

} # End param_radius ()

##########################################################################
##                      Fonction param_web_radius                       ##
## - Import, modification et paramètrage de l'interface "dialupadmin"  ##
## - Création du lien vers la page de changement de mot de passe        ##
##########################################################################
param_web_radius ()
{
# copie de l'interface d'origine dans la structure Alcasar
        [ -d /usr/share/freeradius-web ] && cp -rf /usr/share/freeradius-web/* $DIR_ACC/manager/
        rm -f $DIR_ACC/manager/index.html $DIR_ACC/manager/readme 
        rm -f $DIR_ACC/manager/htdocs/about.html $DIR_ACC/manager/htdocs/index.html $DIR_ACC/manager/htdocs/content.html
# copie des fichiers modifiés
        cp -rf $DIR_INSTALL/web/acc/manager/* $DIR_ACC/manager/
        chown -R apache:apache $DIR_ACC/manager/
# Modification des fichiers de configuration
        [ -e /etc/freeradius-web/admin.conf.default ] || cp /etc/freeradius-web/admin.conf /etc/freeradius-web/admin.conf.default
        $SED "s?^general_domain:.*?general_domain: $DOMAIN?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_username:.*?sql_username: $DB_USER?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_password:.*?sql_password: $radiuspwd?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_debug:.*?sql_debug: false?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_usergroup_table: .*?sql_usergroup_table: radusergroup?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_password_attribute:.*?sql_password_attribute: Crypt-Password?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_finger_type.*?# general_finger_type: snmp?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_stats_use_totacct.*?general_stats_use_totacct: yes?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_charset.*?general_charset: utf-8?g" /etc/freeradius-web/admin.conf
        [ -e /etc/freeradius-web/config.php.default ] || cp /etc/freeradius-web/config.php /etc/freeradius-web/config.php.default
        cp -f $DIR_CONF/freeradiusweb-config.php /etc/freeradius-web/config.php
        cat <<EOF > /etc/freeradius-web/naslist.conf
nas1_name: alcasar-$ORGANISME
nas1_model: Portail captif
nas1_ip: $PRIVATE_IP
nas1_port_num: 0
nas1_community: public
EOF
# Modification des attributs visibles lors de la création d'un usager ou d'un groupe
        [ -e /etc/freeradius-web/user_edit.attrs.default ] || mv /etc/freeradius-web/user_edit.attrs /etc/freeradius-web/user_edit.attrs.default
        cp -f $DIR_CONF/user_edit.attrs /etc/freeradius-web/user_edit.attrs
# Ajout du mappage des attributs chillispot
        [ -e /etc/freeradius-web/sql.attrmap.default ] || mv /etc/freeradius-web/sql.attrmap /etc/freeradius-web/sql.attrmap.default
        cp -f $DIR_CONF/sql.attrmap /etc/freeradius-web/sql.attrmap
# Modification des attributs visibles sur les pages des statistiques (suppression NAS_IP et NAS_port)
        [ -e /etc/freeradius-web/sql.attrs.default ] || cp /etc/freeradius-web/sql.attrs /etc/freeradius-web/user_edit.attrs.default
        $SED "s?^NASIPAddress.*?NASIPAddress\tNas IP Address\tno?g" /etc/freeradius-web/sql.attrs
        $SED "s?^NASPortId.*?NASPortId\tNas Port\tno?g" /etc/freeradius-web/sql.attrs
        chown -R apache:apache /etc/freeradius-web
# Ajout de l'alias vers la page de "changement de mot de passe usager"
        cat <<EOF >> /etc/httpd/conf/webapps.d/alcasar.conf
<Directory $DIR_WEB/pass>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        ErrorDocument 404 https://$HOSTNAME
</Directory>
EOF
} # End of param_web_radius ()

##################################################################################
##                      Fonction param_chilli                                   ##
## - Création du fichier d'initialisation et de configuration de coova-chilli  ##
## - Paramètrage de la page d'authentification (intercept.php)                 ##
##################################################################################
param_chilli ()
{
# init file creation
        [ -e /etc/init.d/chilli.default ] || cp /etc/init.d/chilli /etc/init.d/chilli.default
        cat <<EOF > /etc/init.d/chilli
#!/bin/sh
#
# chilli CoovaChilli init
#
# chkconfig: 2345 65 35
# description: CoovaChilli
### BEGIN INIT INFO
# Provides:       chilli
# Required-Start: network 
# Should-Start: 
# Required-Stop:  network
# Should-Stop: 
# Default-Start:  2 3 5
# Default-Stop:
# Description:    CoovaChilli access controller
### END INIT INFO

[ -f /usr/sbin/chilli ] || exit 0
. /etc/init.d/functions
CONFIG=/etc/chilli.conf
pidfile=/var/run/chilli.pid
[ -f \$CONFIG ] || {
    echo "\$CONFIG Not found"
    exit 0
}
RETVAL=0
prog="chilli"
case \$1 in
    start)
        if [ -f \$pidfile ] ; then 
                gprintf "chilli is already running"
        else
                gprintf "Starting \$prog: "
                rm -f /var/run/chilli* # cleaning
                /sbin/modprobe tun >/dev/null 2>&1
                echo 1 > /proc/sys/net/ipv4/ip_forward
                [ -e /dev/net/tun ] || {
                (cd /dev; 
                        mkdir net; 
                        cd net; 
                        mknod tun c 10 200)
                }
                ifconfig eth1 0.0.0.0
                daemon /usr/sbin/chilli -c \$CONFIG --pidfile=\$pidfile &
                RETVAL=$?
        fi
        ;;

    reload)
        killall -HUP chilli
        ;;

    restart)
        \$0 stop
        sleep 2
        \$0 start
        ;;
    
    status)
        status chilli
        RETVAL=0
        ;;

    stop)
        if [ -f \$pidfile ] ; then  
                gprintf "Shutting down \$prog: "
                killproc /usr/sbin/chilli
                RETVAL=\$?
                [ \$RETVAL = 0 ] && rm -f $pidfile
        else    
                gprintf "chilli is not running"
        fi
        ;;
    
    *)
        echo "Usage: \$0 {start|stop|restart|reload|status}"
        exit 1
esac
echo
EOF

# conf file creation
        [ -e /etc/chilli.conf.default ] || cp /etc/chilli.conf /etc/chilli.conf.default
        cat <<EOF > /etc/chilli.conf
# coova config for ALCASAR
cmdsocket       /var/run/chilli.sock
unixipc         chilli.eth1.ipc
pidfile         /var/run/chilli.eth1.pid
net             $PRIVATE_NETWORK_MASK
dhcpif          $INTIF
ethers          $DIR_DEST_ETC/alcasar-ethers
#nodynip
#statip
dynip           $PRIVATE_NETWORK_MASK
domain          localdomain
dns1            $PRIVATE_IP
dns2            $PRIVATE_IP
uamlisten       $PRIVATE_IP
uamport         3990
macauth
macpasswd       password
locationname    $HOSTNAME
radiusserver1   127.0.0.1
radiusserver2   127.0.0.1
radiussecret    $secretradius
radiusauthport  1812
radiusacctport  1813
uamserver       https://$HOSTNAME/intercept.php
radiusnasid     $HOSTNAME
uamsecret       $secretuam
uamallowed      alcasar
coaport         3799
include         $DIR_DEST_ETC/alcasar-uamallowed
include         $DIR_DEST_ETC/alcasar-uamdomain
#dhcpgateway            
#dhcprelayagent
#dhcpgatewayport
EOF
# create file for DHCP static ip. Reserve the second IP address for eth1 (the first one is for tun0)
        echo "$PRIVATE_MAC $PRIVATE_SECOND_IP" > $DIR_DEST_ETC/alcasar-ethers
# create files for trusted domains and urls
        touch $DIR_DEST_ETC/alcasar-uamallowed $DIR_DEST_ETC/alcasar-uamdomain
        chown root:apache $DIR_DEST_ETC/alcasar-*
        chmod 660 $DIR_DEST_ETC/alcasar-*
# Configuration des fichier WEB d'interception (secret partagé avec coova-chilli)
        $SED "s?^\$uamsecret =.*?\$uamsecret = \"$secretuam\";?g" $DIR_WEB/intercept.php
        $SED "s?^\$userpassword=1.*?\$userpassword=1;?g" $DIR_WEB/intercept.php
# user 'chilli' creation (in order to run conup/off and up/down scripts
        chilli_exist=`grep chilli /etc/passwd|wc -l`
        if [ "$chilli_exist" == "1" ]
        then
              userdel -r chilli 2>/dev/null
        fi
        groupadd -f chilli
        useradd -r -g chilli -s /bin/false -c "system user for coova-chilli" chilli
}  # End of param_chilli ()

##########################################################
##                      Fonction param_squid            ##
## - Paramètrage du proxy 'squid' en mode 'cache'      ##
## - Initialisation de la base de données              ##
##########################################################
param_squid ()
{
# paramètrage de Squid (connecté en série derrière Dansguardian)
        [ -e /etc/squid/squid.conf.default  ] || cp /etc/squid/squid.conf /etc/squid/squid.conf.default
# suppression des références 'localnet', 'icp', 'htcp' et 'always_direct'
        $SED "/^acl localnet/d" /etc/squid/squid.conf
        $SED "/^icp_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^icp_port 3130/d" /etc/squid/squid.conf
        $SED "/^http_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^htcp_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^always_direct allow localnet/d" /etc/squid/squid.conf
# mode 'proxy transparent local'
        $SED "s?^http_port.*?http_port 127.0.0.1:3128 transparent?g" /etc/squid/squid.conf
# Configuration du cache local
        $SED "s?^#cache_dir.*?cache_dir ufs \/var\/spool\/squid 256 16 256?g" /etc/squid/squid.conf
# désactivation des "access log"
        echo '#Disable access log' >> /etc/squid/squid.conf
        echo "access_log none" >> /etc/squid/squid.conf
# anonymisation of squid version
        echo "via off" >> /etc/squid/squid.conf
# remove the 'X_forwarded' http option
        echo "forwarded_for delete" >> /etc/squid/squid.conf
# linked squid output in HAVP input
        echo "cache_peer 127.0.0.1 parent 8090 0 no-query default" >> /etc/squid/squid.conf
        echo "never_direct allow all" >> /etc/squid/squid.conf
# avoid error messages on network interfaces state changes
        $SED "s?^SQUID_AUTO_RELOAD.*?SQUID_AUTO_RELOAD=no?g" /etc/sysconfig/squid
# reduce squid shutdown time (100 to 50)
        $SED "s?^SQUID_SHUTDOWN_TIMEOUT.*?SQUID_SHUTDOWN_TIMEOUT=50?g" /etc/sysconfig/squid

# Squid cache init
        /usr/sbin/squid -z
}  # End of param_squid ()
        
##################################################################
##              Fonction param_dansguardian                     ##
## - Paramètrage du gestionnaire de contenu Dansguardian       ##
##################################################################
param_dansguardian ()
{
        mkdir /var/dansguardian
        chown dansguardian /var/dansguardian
        [ -e $DIR_DG/dansguardian.conf.default ] || cp $DIR_DG/dansguardian.conf $DIR_DG/dansguardian.conf.default
# Le filtrage est désactivé par défaut 
        $SED "s/^reportinglevel =.*/reportinglevel = -1/g" $DIR_DG/dansguardian.conf
# la page d'interception est en français
        $SED "s?^language =.*?language = french?g" $DIR_DG/dansguardian.conf
# on limite l'écoute de Dansguardian côté LAN
        $SED "s?^filterip.*?filterip = $PRIVATE_IP?g" $DIR_DG/dansguardian.conf
# on chaîne Dansguardian au proxy cache SQUID
        $SED "s?^proxyport.*?proxyport = 3128?g" $DIR_DG/dansguardian.conf
# on remplace la page d'interception (template)
        cp -f $DIR_CONF/template.html /usr/share/dansguardian/languages/ukenglish/
        cp -f $DIR_CONF/template-fr.html /usr/share/dansguardian/languages/french/template.html
# on ne loggue que les deny (pour le reste, on a squid)
        $SED "s?^loglevel =.*?loglevel = 1?g" $DIR_DG/dansguardian.conf
# lauch of 10 daemons (20 in largest server)
        $SED "s?^minchildren =.*?minchildren = 10?g" $DIR_DG/dansguardian.conf
# on désactive par défaut le controle de contenu des pages html
        $SED "s?^weightedphrasemode =.*?weightedphrasemode = 0?g" $DIR_DG/dansguardian.conf
        cp $DIR_DG/lists/bannedphraselist $DIR_DG/lists/bannedphraselist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedphraselist # (on commente ce qui ne l'est pas)
# on désactive par défaut le contrôle d'URL par expressions régulières
        cp $DIR_DG/lists/bannedregexpurllist $DIR_DG/lists/bannedregexpurllist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedregexpurllist # (on commente ce qui ne l'est pas)
# on désactive par défaut le contrôle de téléchargement de fichiers
        [ -e $DIR_DG/dansguardianf1.conf.default ] || cp $DIR_DG/dansguardianf1.conf $DIR_DG/dansguardianf1.conf.default
        $SED "s?^blockdownloads =.*?blockdownloads = off?g" $DIR_DG/dansguardianf1.conf
        [ -e $DIR_DG/lists/bannedextensionlist.default ] || mv $DIR_DG/lists/bannedextensionlist $DIR_DG/lists/bannedextensionlist.default
        [ -e $DIR_DG/lists/bannedmimetypelist.default ] || mv $DIR_DG/lists/bannedmimetypelist $DIR_DG/lists/bannedmimetypelist.default
        touch $DIR_DG/lists/bannedextensionlist
        touch $DIR_DG/lists/bannedmimetypelist
# 'Safesearch' regex actualisation
        $SED "s?images?search?g" $DIR_DG/lists/urlregexplist
# empty LAN IP list that won't be WEB filtered
        [ -e $DIR_DG/lists/exceptioniplist.default ] || mv $DIR_DG/lists/exceptioniplist $DIR_DG/lists/exceptioniplist.default
        touch $DIR_DG/lists/exceptioniplist
# Keep a copy of URL & domain filter configuration files
        [ -e $DIR_DG/lists/bannedsitelist.default ] || mv $DIR_DG/lists/bannedsitelist $DIR_DG/lists/bannedsitelist.default
        [ -e $DIR_DG/lists/bannedurllist.default ] || mv $DIR_DG/lists/bannedurllist $DIR_DG/lists/bannedurllist.default
} # End of param_dansguardian ()

##################################################################
##                      Fonction antivirus                      ##
## - configuration havp + libclamav                             ##
##################################################################
antivirus ()            
{
# création de l'usager 'havp'
        havp_exist=`grep havp /etc/passwd|wc -l`
        if [ "$havp_exist" == "1" ]
        then
              userdel -r havp 2>/dev/null
              groupdel havp 2>/dev/null
        fi
        groupadd -f havp
        useradd -r -g havp -s /bin/false -c "system user for havp" havp
        mkdir -p /var/tmp/havp /var/log/havp
        chown -R havp /var/tmp/havp /var/log/havp /var/run/havp
# configuration d'HAVP
        [ -e /etc/havp/havp.config.default ] || cp /etc/havp/havp.config /etc/havp/havp.config.default
        $SED "/^REMOVETHISLINE/d" /etc/havp/havp.config
        $SED "s?^# PORT.*?PORT 8090?g" /etc/havp/havp.config                            # datas come on 8090                    
        $SED "s?^# BIND_ADDRESS.*?BIND_ADDRESS 127.0.0.1?g" /etc/havp/havp.config       # we listen only on loopback
        $SED "s?^# TIMEFORMAT.*?TIMEFORMAT %Y %b %d %H:%M:%S?g" /etc/havp/havp.config   # Log format
        $SED "s?^ENABLECLAMLIB.*?ENABLECLAMLIB true?g" /etc/havp/havp.config            # active libclamav AV
        $SED "s?^# LOG_OKS.*?LOG_OKS false?g" /etc/havp/havp.config                     # log only when malware matches
        $SED "s?^# SERVERNUMBER.*?SERVERNUMBER 10?g" /etc/havp/havp.config              # 10 daemons are started simultaneously
        $SED "s?^# SCANIMAGES.*?SCANIMAGES false?g" /etc/havp/havp.config               # doesn't scan image files
        $SED "s?^# SKIPMIME.*?SKIPMIME image\/\* video\/\* audio\/\*?g" /etc/havp/havp.config # doesn't scan some multimedia files
# skip checking of youtube flow (too heavy load / risk too low)
        [ -e /etc/havp/whitelist.default ] || cp /etc/havp/whitelist /etc/havp/whitelist.default
        echo "# Whitelist youtube flow" >> /etc/havp/whitelist
        echo "*.youtube.com/*" >> /etc/havp/whitelist
# remplacement du fichier d'initialisation
        [ -e /etc/init.d/havp.default ] || cp /etc/init.d/havp /etc/init.d/havp.default
# if keep old init file : $SED "/$HAVP_BIN -c $HAVP_CONFIG/i chown -R havp:havp \/var\/tmp\/havp" /etc/init.d/havp
        cp -f $DIR_CONF/havp-init /etc/init.d/havp
# on remplace la page d'interception (template)
        cp -f $DIR_CONF/virus-fr.html /etc/havp/templates/fr/virus.html
        cp -f $DIR_CONF/virus-en.html /etc/havp/templates/en/virus.html
# automatisation de la mise à jour de la base antivirale (toutes les 2 heures)
        $SED "s?^Checks.*?Checks 12?g" /etc/freshclam.conf
        $SED "s?^NotifyClamd.*?# NotifyClamd /etc/clamd.conf?g" /etc/freshclam.conf
# Virus database update
        rm -f /var/lib/clamav/*.cld # in case of old database scheme
        cp -f $DIR_CONF/clamav-main.cvd /var/lib/clamav/main.cvd
        /usr/bin/freshclam
}

##################################################################################
##                      param_ulogd function                                    ##
## - Ulog config for multi-log files                                            ##
##################################################################################
param_ulogd ()
{
# Three instances of ulogd (three different logfiles)
        [ -d /var/log/firewall ] || mkdir -p /var/log/firewall
        nl=1
        for log_type in tracability ssh ext-access
        do
                [ -e /var/log/firewall/$log_type.log ] || touch /var/log/firewall/$log_type.log
                cp -f /etc/ulogd.conf /etc/ulogd-$log_type.conf
                $SED "s?^nlgroup=.*?nlgroup=$nl?g" /etc/ulogd-$log_type.conf 
                $SED '/OPRINT/,$d' /etc/ulogd-$log_type.conf
                cat << EOF >> /etc/ulogd-$log_type.conf
[LOGEMU]
file="/var/log/firewall/$log_type.log"
sync=1
EOF
                nl=`expr $nl + 1`
        done
        chown -R root:apache /var/log/firewall
        chmod 750 /var/log/firewall
        chmod 640 /var/log/firewall/*
        [ -e /etc/init.d/ulogd.default ] || cp /etc/init.d/ulogd /etc/init.d/ulogd.default
        cp -f $DIR_CONF/ulogd-init /etc/init.d/ulogd
}  # End of param_ulogd ()


##########################################################
##              Fonction param_nfsen                    ##
##########################################################
param_nfsen()
{
#Decompression tarball
tar xvzf ./conf/nfsen/nfsen-1.3.6p1.tar.gz -C /tmp/
#Création groupe et utilisteur
if grep "^www-data:" /etc/group > /dev/null; then
        echo "Group already exists !"
else
        groupadd www-data
        echo "Group 'www-data' created !"
fi
if grep "^nfsen:" /etc/passwd > /dev/null; then
        echo "User already exists !"
else
        useradd -m nfsen
        echo "User 'nfsen' created !"
fi
usermod -G www-data nfsen
#Ajout du plugin nfsen : PortTracker
mkdir -p /var/www/nfsen/plugins
chown -R nfsen:www-data /var/www/nfsen
#Ajout du plugin PortTracker
mkdir -p /var/log/netflow/porttracker 
mkdir -p /usr/share/nfsen/plugins
chown -R apache:apache /usr/share/nfsen
cp -f ./conf/nfsen/PortTracker.pm /tmp/nfsen-1.3.6p1/contrib/PortTracker/
chown apache /var/log/netflow/porttracker
#Copie du fichier de conf modifié de nfsen
cp ./conf/nfsen/nfsen.conf /tmp/nfsen-1.3.6p1/etc/
#Copie du script d'initialisation de nfsen
cp ./conf/nfsen/nfsen-init /etc/init.d/nfsen
#Installation de nfsen via le scrip Perl
cd /tmp/nfsen-1.3.6p1/
/usr/bin/perl5 install.pl etc/nfsen.conf #script lancé deux fois pour corriger,
/usr/bin/perl5 install.pl etc/nfsen.conf #un problème Perl : "Semaphore introuvable"
#Création de la DB pour rrdtool
cp /tmp/nfsen-1.3.6p1/contrib/PortTracker/PortTracker.pm /usr/share/nfsen/plugins/
cp /tmp/nfsen-1.3.6p1/contrib/PortTracker/PortTracker.php /var/www/nfsen/plugins/
sudo -u apache nftrack -I -d /var/log/netflow/porttracker
chown -R apache:www-data /var/log/netflow/porttracker/
chmod -R 775 /var/log/netflow/porttracker
#Configuration du fichier de conf d'apache
if [ -f /etc/httpd/conf.d/nfsen.conf ];then
        rm -f /etc/httpd/conf.d/nfsen.conf
fi
cat <<EOF >> /etc/httpd/conf.d/nfsen.conf
Alias /nfsen /var/www/nfsen 
<Directory /var/www/nfsen/> 
DirectoryIndex nfsen.php 
Options -Indexes 
AllowOverride all 
order allow,deny 
allow from all 
AddType application/x-httpd-php .php 
php_flag magic_quotes_gpc on 
php_flag track_vars on 
</Directory>
EOF
#Configuration du délais d'expiration des captures du profile "ALCASAR"
nfsen -m ALCASAR -e 365d
#Suppression des sources de nfsen
rm -rf /tmp/nfsen-1.3.6p1/
} # End of param_nfsen

##########################################################
##              Fonction param_dnsmasq                  ##
##########################################################
param_dnsmasq ()
{
        [ -d /var/log/dnsmasq ] || mkdir /var/log/dnsmasq
        $SED "s?^DHCP_LEASE=.*?DHCP_LEASE=/var/log/dnsmasq/lease.log?g" /etc/sysconfig/dnsmasq # fichier contenant les baux
        [ -e /etc/dnsmasq.conf.default ] || cp /etc/dnsmasq.conf /etc/dnsmasq.conf.default
# 1st dnsmasq listen on udp 53 ("dnsmasq - forward"). It's used as dhcp server only if bypass is on.
        cat << EOF > /etc/dnsmasq.conf 
# Configuration file for "dnsmasq in forward mode"
conf-file=$DIR_DEST_ETC/alcasar-dns-name        # zone de definition de noms DNS locaux
listen-address=$PRIVATE_IP
listen-address=127.0.0.1
no-dhcp-interface=$INTIF
bind-interfaces
cache-size=256
domain=$DOMAIN
domain-needed
expand-hosts
bogus-priv
filterwin2k
server=$DNS1
server=$DNS2
# le servive DHCP est configuré mais n'est exploité que pour le "bypass"
dhcp-range=$PRIVATE_FIRST_IP,$PRIVATE_LAST_IP,$PRIVATE_NETMASK,12h
dhcp-option=option:router,$PRIVATE_IP
#dhcp-option=option:ntp-server,192.168.0.4,10.10.0.5

# Exemple de configuration statique : <@MAC>,<name>,<@IP>,<MASK>,<ttl bail>
#dhcp-host=11:22:33:44:55:66,ssic-test,192.168.182.20,255.255.255.0,45m
EOF
# 2nd dnsmasq listen on udp 54 ("dnsmasq with blackhole")
        cat << EOF > /etc/dnsmasq-blackhole.conf 
        # Configuration file for "dnsmasq with blackhole"
# Inclusion de la blacklist <domains> de Toulouse dans la configuration
conf-dir=$DIR_DEST_SHARE/dnsmasq-bl-enabled
conf-file=$DIR_DEST_ETC/alcasar-dns-name        # zone de definition de noms DNS locaux
listen-address=$PRIVATE_IP
port=54
no-dhcp-interface=$INTIF
bind-interfaces
cache-size=256
domain=$DOMAIN
domain-needed
expand-hosts
bogus-priv
filterwin2k
server=$DNS1
server=$DNS2
EOF

# Init file modification
[ -e /etc/init.d/dnsmasq.default ] || cp /etc/init.d/dnsmasq /etc/init.d/dnsmasq.default
# Start and stop a 2nd process for the "DNS blackhole"
$SED "/daemon/a \$dnsmasq -C /etc/dnsmasq-blackhole.conf \$OPTIONS" /etc/init.d/dnsmasq
$SED "/killproc \$DAEMON_NAME/a killproc \$DAEMON_NAME" /etc/init.d/dnsmasq
# Start after chilli (65) which create tun0
$SED "s?^# chkconfig:.*?# chkconfig: 2345 99 40?g" /etc/init.d/dnsmasq
# Optionnellement on pré-active les logs DNS des clients
[ -e /etc/sysconfig/dnsmasq.default ] || cp /etc/sysconfig/dnsmasq /etc/sysconfig/dnsmasq.default
$SED "s?log-facility?#OPTIONS=\"-q --log-facility=/var/log/dnsmasq/queries.log\"?g"  /etc/sysconfig/dnsmasq
# Optionnellement, exemple de paramètre supplémentaire pour le cache memoire
echo '#OPTIONS="$OPTIONS --cache-size=250"' >> /etc/sysconfig/dnsmasq
# Optionnellement, exemple de configuration avec un A.D.
echo '#OPTIONS="$OPTIONS --server=/your.domain/192.168.182.3"' >> /etc/sysconfig/dnsmasq
} # End dnsmasq

##########################################################
##              Fonction BL (BlackList)                 ##
##########################################################
BL ()
{
# on copie par défaut la BL de toulouse embarqués dans l'archive d'ALCASAR
        rm -rf $DIR_DG/lists/blacklists
        tar zxf $DIR_CONF/blacklists.tar.gz --directory=$DIR_DG/lists/ > /dev/null 2>&1
# on crée le répertoire ossi (noms de domaine et URLs ajoutés à la BL)
        mkdir $DIR_DG/lists/blacklists/ossi
        touch $DIR_DG/lists/blacklists/ossi/domains $DIR_DG/lists/blacklists/ossi/domains_wl
        touch $DIR_DG/lists/blacklists/ossi/urls $DIR_DG/lists/blacklists/ossi/urls_wl
# On crée les fichiers vides de sites ou d'URL réhabilités
        [ -e $DIR_DG/lists/exceptionsitelist.default ] || mv $DIR_DG/lists/exceptionsitelist $DIR_DG/lists/exceptionsitelist.default
        [ -e $DIR_DG/lists/exceptionurllist.default ] || mv $DIR_DG/lists/exceptionurllist $DIR_DG/lists/exceptionurllist.default
        touch $DIR_DG/lists/exceptionsitelist
        touch $DIR_DG/lists/exceptionurllist
# On crée la configuration de base du filtrage de domaine et d'URL pour Dansguardian
        cat <<EOF > $DIR_DG/lists/bannedurllist
# Dansguardian filter config for ALCASAR
EOF
        cat <<EOF > $DIR_DG/lists/bannedsitelist
# Dansguardian domain filter config for ALCASAR
# block all sites except those in the exceptionsitelist --> liste blanche (désactivée)
#**
# block all SSL and CONNECT tunnels
**s
# block all SSL and CONNECT tunnels specified only as an IP
*ips
# block all sites specified only by an IP
*ip
EOF
# Add Bing and Youtube to the safesearch url regext list (parental control)
        cat <<EOF >> $DIR_DG/lists/urlregexplist
# Bing - add 'adlt=strict'
#"(^http://[0-9a-z]+\.bing\.[a-z]+[-/%.0-9a-z]*\?)(.*)"->"\1\2&adlt=strict"
# Youtube - add 'edufilter=your_ID' 
#"(^http://[0-9a-z]+\.youtube\.[a-z]+[-/%.0-9a-z]*\?)(.*)"->"\1\2&edufilter=ABCD1234567890abcdef"
EOF
# change the the google safesearch ("safe=strict" instead of "safe=vss")
        $SED "s?safe=vss?safe=strict?g" $DIR_DG/lists/urlregexplist
        chown -R dansguardian:apache $DIR_DG
        chmod -R g+rw $DIR_DG
# On adapte la BL de Toulouse à notre structure
        if [ "$mode" != "update" ]; then
                $DIR_DEST_SBIN/alcasar-bl.sh --adapt
        fi
}

##########################################################
##              Fonction cron                           ##
## - Mise en place des différents fichiers de cron     ##
##########################################################
cron ()
{
# Modif du fichier 'crontab' pour passer les cron à minuit au lieu de 04h00
        [ -e /etc/crontab.default ] || cp /etc/crontab /etc/crontab.default
        cat <<EOF > /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root nice -n 19 run-parts --report /etc/cron.hourly
02 0 * * * root nice -n 19 run-parts --report /etc/cron.daily
22 0 * * 0 root nice -n 19 run-parts --report /etc/cron.weekly
42 0 1 * * root nice -n 19 run-parts --report /etc/cron.monthly
EOF
        [ -e /etc/anacrontab.default ] || cp /etc/anacrontab /etc/anacrontab.default
        cat <<EOF >> /etc/anacrontab
7       8       cron.MysqlDump          nice /etc/cron.d/alcasar-mysql
7       10      cron.logExport          nice /etc/cron.d/alcasar-export_log
7       15      cron.logClean           nice /etc/cron.d/alcasar-clean_log
7       20      cron.importClean        nice /etc/cron.d/alcasar-clean_import
EOF
        cat <<EOF > /etc/cron.d/alcasar-clean_log
# suppression des fichiers de logs de plus d'un an (tous les lundi à 4h30)
30 4 * * 1 root $DIR_DEST_BIN/alcasar-log.sh --clean
EOF
        cat <<EOF > /etc/cron.d/alcasar-mysql
# Contrôle, réparation et export de la base des usagers (tous les lundi à 4h45)
45 4 * * 1 root $DIR_DEST_SBIN/alcasar-mysql.sh --dump
# Nettoyage des utilisateurs dont la date d'expiration du compte est supérieure à 7 jours
40 4 * * * root /usr/local/sbin/alcasar-mysql.sh --expire_user 2>&1 >/dev/null
EOF
        cat <<EOF > /etc/cron.d/alcasar-export_log
# export des log squid, firewall et apache (tous les lundi à 5h00)
00 5 * * 1 root $DIR_DEST_BIN/alcasar-log.sh --export
EOF
        cat <<EOF > /etc/cron.d/alcasar-archive
# Archive des logs et de la base de données (tous les lundi à 5h35)
35 5 * * 1 root $DIR_DEST_BIN/alcasar-archive.sh --now
EOF
        cat << EOF > /etc/cron.d/alcasar-clean_import
# suppression des fichiers de mots de passe lors d'imports massifs par fichier de plus de 24h
30 * * * *  root $DIR_DEST_BIN/alcasar-import-clean.sh
EOF
        cat << EOF > /etc/cron.d/alcasar-distrib-updates
# mise à jour automatique de la distribution tous les jours 3h30
30 3 * * *  root /usr/sbin/urpmi --auto-update --auto 2>&1
EOF
        cat << EOF > /etc/cron.d/alcasar-netflow
# mise à jour automatique du délais d'expiration des log Nertflow (tous les vendredi à 0h05)
05 0 * * 5  root /usr/bin/nfexpire -e /var/log/nfsen/profiles-data/ALCASAR/ipt_netflow/ -t 1y -w 90
EOF

# mise à jour des stats de connexion (accounting). Scripts provenant de "dialupadmin" (rpm freeradius-web) (cf. wiki.freeradius.org/Dialup_admin).
# on écrase le crontab d'origine installé par le RPM "freeradius-web" (bug remonté à qa.mandriva.com : 46739).
# 'tot_stats' (tout les jours à 01h01) : aggrégat des connexions journalières par usager (renseigne la table 'totacct') 
# 'monthly_tot_stat' (tous les jours à 01h05) : aggrégat des connexions mensuelles par usager (renseigne la table 'mtotacct')
# 'truncate_raddact' (tous les 1er du mois à 01h10) : supprime les entrées journalisées plus vieilles que '$back_days' jours (défini ci-après)
# 'clean_radacct' (tous les 1er du mois à 01h15) : ferme les session ouvertes de plus de '$back_days' jours (défini ci-après)
        $SED "s?^\$back_days.*?\$back_days = 365;?g" /usr/bin/truncate_radacct
        $SED "s?^\$back_days.*?\$back_days = 30;?g" /usr/bin/clean_radacct
        rm -f /etc/cron.daily/freeradius-web
        rm -f /etc/cron.monthly/freeradius-web
        cat << EOF > /etc/cron.d/freeradius-web
1 1 * * * root /usr/bin/tot_stats > /dev/null 2>&1
5 1 * * * root /usr/bin/monthly_tot_stats > /dev/null 2>&1
10 1 1 * * root /usr/bin/truncate_radacct > /dev/null 2>&1
15 1 1 * * root /usr/bin/clean_radacct > /dev/null 2>&1
EOF
        cat << EOF > /etc/cron.d/alcasar-watchdog
# activation du "chien de garde" (watchdog) toutes les 3'
*/3 * * * * root $DIR_DEST_BIN/alcasar-watchdog.sh > /dev/null 2>&1
EOF
# activation du "chien de garde des services" (watchdog) toutes les 18'
        cat << EOF > /etc/cron.d/alcasar-daemon-watchdog
# activation du "chien de garde" (daemon-watchdog) toutes les 18'
*/18 * * * * root $DIR_DEST_BIN/alcasar-daemon.sh > /dev/null 2>&1
EOF
# suppression des crons usagers
        rm -f /var/spool/cron/*
} # End cron

##################################################################
##                      Fonction Fail2Ban                       ##
##- Modification de la configuration de fail2ban                ##
##- Sécurisation DDOS, SSH-Brute-Force, Intercept.php ...      ##
##################################################################
fail2ban()
{
        $DIR_CONF/fail2ban.sh
#Autorise la lecture seule 2 des 3 fichiers de log concernés, havp est traité dans le script d'init de havp
        [ -e /var/log/fail2ban.log ] || touch /var/log/fail2ban.log
        [ -e /var/Save/logs/security/watchdog.log ] || touch /var/Save/logs/security/watchdog.log
        chmod 644 /var/log/fail2ban.log
        chmod 644 /var/Save/logs/security/watchdog.log
} #Fin de fail2ban_install()

##################################################################
##                      Fonction post_install                   ##
## - Modification des bannières (locales et ssh) et des prompts ##
## - Installation de la structure de chiffrement pour root      ##
## - Mise en place du sudoers et de la sécurité sur les fichiers##
## - Mise en place du la rotation des logs                      ##
## - Configuration dans le cas d'une mise à jour               ##
##################################################################
post_install()
{
# adaptation du script "chien de garde" (watchdog)
        $SED "s?^EXTIF=.*?EXTIF=\"$EXTIF\"?g" $DIR_DEST_BIN/alcasar-watchdog.sh
        $SED "s?^INTIF=.*?INTIF=\"$INTIF\"?g" $DIR_DEST_BIN/alcasar-watchdog.sh
# création de la bannière locale
        [ -e /etc/mageia-release.default ]  || cp /etc/mageia-release /etc/mageia-release.default
        cp -f $DIR_CONF/banner /etc/mageia-release
        echo " V$VERSION" >> /etc/mageia-release
# création de la bannière SSH
        cp /etc/mageia-release /etc/ssh/alcasar-banner-ssh
        chmod 644 /etc/ssh/alcasar-banner-ssh ; chown root:root /etc/ssh/alcasar-banner-ssh
        [ -e /etc/ssh/sshd_config.default ] || cp /etc/ssh/sshd_config /etc/ssh/sshd_config.default
        $SED "s?^Banner.*?Banner /etc/ssh/alcasar-banner-ssh?g" /etc/ssh/sshd_config
        $SED "s?^#Banner.*?Banner /etc/ssh/alcasar-banner-ssh?g" /etc/ssh/sshd_config
# postfix banner anonymisation
        $SED "s?^smtpd_banner =.*?smtpd_banner = $myhostname ESMTP?g" /etc/postfix/main.cf
# sshd écoute côté LAN et WAN
        $SED "s?^#ListenAddress 0\.0\.0\.0?ListenAddress $PRIVATE_IP?g" /etc/ssh/sshd_config
        $SED "/^ListenAddress $PRIVATE_IP/a\ListenAddress $PUBLIC_IP" /etc/ssh/sshd_config 
        # Put the default value in conf file (sshd, QOS and protocols/dns/ are off)(web antivirus is on)
        echo "SSH=off" >> $CONF_FILE
        echo 'SSH_ADMIN_FROM=0.0.0.0/0.0.0.0' >> $CONF_FILE
        echo "QOS=off" >> $CONF_FILE
        echo "LDAP=off" >> $CONF_FILE
        echo "LDAP_IP=0.0.0.0/0.0.0.0" >> $CONF_FILE
        echo "WEB_ANTIVIRUS=on" >> $CONF_FILE
        echo "PROTOCOLS_FILTERING=off" >> $CONF_FILE
        echo "DNS_FILTERING=off" >> $CONF_FILE
        echo "YOUTUBE_ID=ABCD1234567890abcdef" >> $CONF_FILE
        echo "MULTIWAN=off" >> $CONF_FILE
        echo "FAILOVER=30" >> $CONF_FILE
        echo "## WANx=active,@IPx/mask,GWx,Weight,MTUx" >> $CONF_FILE
        echo "#WAN1=\"1,eth0:1,192.168.2.20/24,192.168.2.6,1,1500\"" >> $CONF_FILE
        echo "#WAN2=\"1,eth0:2,192.168.3.20/24,192.168.3.1,2,1500\"" >> $CONF_FILE
# Coloration des prompts
        [ -e /etc/bashrc.default ]  || cp /etc/bashrc /etc/bashrc.default
        cp -f $DIR_CONF/bashrc /etc/. ; chmod 644 /etc/bashrc ; chown root:root /etc/bashrc
        $SED "s?^ORGANISME.*?ORGANISME=$ORGANISME?g" /etc/bashrc
# Droits d'exécution pour utilisateur apache et sysadmin
        [ -e /etc/sudoers.default ]  || cp /etc/sudoers /etc/sudoers.default
        cp -f $DIR_CONF/sudoers /etc/. ; chmod 440 /etc/sudoers ; chown root:root /etc/sudoers
        $SED "s?^Host_Alias.*?Host_Alias        LAN_ORG=$PRIVATE_NETWORK/$PRIVATE_NETMASK,localhost             #réseau de l'organisme?g" /etc/sudoers
# prise en compte de la rotation des logs sur 1 an (concerne mysql, httpd, dansguardian, squid, radiusd, ulogd)
        cp -f $DIR_CONF/logrotate.d/* /etc/logrotate.d/
        chmod 644 /etc/logrotate.d/*
# rectification sur versions précédentes de la compression des logs
        $SED "s?^delaycompress.*?#&?g" /etc/logrotate.conf
# actualisation des fichiers logs compressés
        for dir in firewall squid dansguardian httpd
        do
              find /var/log/$dir -type f -name *.log-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] -exec gzip {} \;
        done
# export des logs en 'retard' dans /var/Save/logs
        /usr/local/bin/alcasar-log.sh --export
# processus lancés par défaut au démarrage
        for i in ntpd iptables ulogd dnsmasq squid chilli httpd radiusd netfs mysqld dansguardian havp freshclam nfsen
        do
                /sbin/chkconfig --add $i
        done

cat << EOF > /lib/systemd/system/alcasar-load_balancing.service
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

# This unit lauches alcasar-load-balancing.sh script.
[Unit]
Description=alcasar-load_balancing.sh execution
After=network.target iptables.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/alcasar-load_balancing.sh start
ExecStop=/usr/local/sbin/alcasar-load_balancing.sh stop
TimeoutSec=0
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
EOF
systemctl enable alcasar-load_balancing.service

# On applique les préconisations ANSSI
# Apply French Security Agency rules
# ignorer les broadcast ICMP. (attaque smurf) 
sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1
# ignorer les erreurs ICMP bogus
sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1
# désactiver l'envoi et la réponse aux ICMP redirects
sysctl -w net.ipv4.conf.all.accept_redirects=0
accept_redirect=`grep accept_redirect /etc/sysctl.conf|wc -l`
        if [ "$accept_redirect" == "0" ]
        then
                echo "net.ipv4.conf.all.accept_redirects = 0" >> /etc/sysctl.conf
        else
                $SED "s?accept_redirects.*?accept_redirects = 0?g" /etc/sysctl.conf
        fi
sysctl -w net.ipv4.conf.all.send_redirects=0
send_redirect=`grep send_redirect /etc/sysctl.conf|wc -l`
        if [ "$send_redirect" == "0" ]
        then
                echo "net.ipv4.conf.all.send_redirects = 0" >> /etc/sysctl.conf
        else
                $SED "s?send_redirects.*?send_redirects = 0?g" /etc/sysctl.conf
        fi
# activer les SYN Cookies (attaque syn flood)
sysctl -w net.ipv4.tcp_syncookies=1
tcp_syncookies=`grep tcp_syncookies /etc/sysctl.conf|wc -l`
        if [ "$tcp_syncookies" == "0" ]
        then
                echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
        else
                $SED "s?tcp_syncookies.*?tcp_syncookies = 1?g" /etc/sysctl.conf
        fi
# activer l'antispoofing niveau Noyau
sysctl -w net.ipv4.conf.all.rp_filter=1
# ignorer le source routing
sysctl -w net.ipv4.conf.all.accept_source_route=0
accept_source_route=`grep accept_source_route /etc/sysctl.conf|wc -l`
        if [ "$accept_source_route" == "0" ]
        then
                echo "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
        else
                $SED "s?accept_source_route.*?accept_source_route = 0?g" /etc/sysctl.conf
        fi
# réglage du timer de maintien de suivi de session à 1h (3600s) au lieu de 5 semaines
sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=3600
timeout_established=`grep timeout_established /etc/sysctl.conf|wc -l`
        if [ "$timeout_established" == "0" ]
        then
                echo "net.netfilter.nf_conntrack_tcp_timeout_established = 3600" >> /etc/sysctl.conf
        else
                $SED "s?timeout_established.*?timeout_established = 3600?g" /etc/sysctl.conf
        fi
# disable log_martians (ALCASAR is often installed between two private network addresses) 
sysctl -w net.ipv4.conf.all.log_martians=0
# On supprime la gestion du <CTRL>+<ALT>+<SUPPR> et des Magic SysReq Keys
# ???   $SED "s?^ALLOW_REBOOT=.*?ALLOW_REBOOT=no?g" /etc/security/msec/level.fileserver
# modification /etc/inittab
        [ -e /etc/inittab.default ] || cp /etc/inittab /etc/inittab.default
# We keep only 3 TTYs
        $SED "s?^4.*?#&?g" /etc/inittab
        $SED "s?^5.*?#&?g" /etc/inittab
        $SED "s?^6.*?#&?g" /etc/inittab
# switch to multi-users runlevel (instead of x11)
ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
$SED "s?^id.*?id:3:initdefault:?g" /etc/inittab
#       GRUB modifications
# limit wait time to 3s
# create an alcasar entry instead of linux-nonfb
# change display to 1024*768 (vga791)
$SED "s?^timeout.*?timeout 3?g" /boot/grub/menu.lst
$SED "s?^title linux?title ALCASAR?g" /boot/grub/menu.lst
$SED "/^kernel/s/splash quiet //" /boot/grub/menu.lst
$SED "/^kernel/s/vga=.*/vga=791 nomodeset/" /boot/grub/menu.lst
$SED "/^kernel/s/BOOT_IMAGE=linux /BOOT_IMAGE=linux-nonfb /" /boot/grub/menu.lst
$SED "/^gfxmenu/d" /boot/grub/menu.lst

# Remove unused services and users
for old_svc in alsa sound dm
do
        /sbin/chkconfig --del $old_svc
done
for svc in snmpd.service sshd.service
do
        /bin/systemctl disable $svc
done
for rm_users in avahi-autoipd avahi icapd
do
        user=`cat /etc/passwd|grep $rm_users|cut -d":" -f1`
        if [ "$user" == "$rm_users" ]
        then
                /usr/sbin/userdel -f $rm_users
        fi
done
# Load and apply the previous conf file
if [ "$mode" = "update" ]
then
        $DIR_DEST_BIN/alcasar-conf.sh --load
        PARENT_SCRIPT=`basename $0`
        export PARENT_SCRIPT # to avoid stop&start process during the installation process
        $DIR_DEST_BIN/alcasar-conf.sh --apply
        $SED "s?^INSTALL_DATE=.*?INSTALL_DATE=$DATE?g" $CONF_FILE
        $SED "s?^VERSION=.*?VERSION=$VERSION?g" $CONF_FILE
fi
rm -f /tmp/alcasar-conf*
chown -R root:apache $DIR_DEST_ETC/*
chmod -R 660 $DIR_DEST_ETC/*
chmod ug+x $DIR_DEST_ETC/digest

# Apply and save the firewall rules
        sh $DIR_DEST_BIN/alcasar-iptables.sh
        sleep 2
        cd $DIR_INSTALL
        echo ""
        echo "#############################################################################"
        if [ $Lang == "fr" ]
                then
                echo "#                        Fin d'installation d'ALCASAR                       #"
                echo "#                                                                           #"
                echo "#         Application Libre pour le Contrôle Authentifié et Sécurisé        #"
                echo "#                     des Accès au Réseau ( ALCASAR )                       #"
                echo "#                                                                           #"
                echo "#############################################################################"
                echo
                echo "- ALCASAR sera fonctionnel après redémarrage du système"
                echo
                echo "- Lisez attentivement la documentation d'exploitation"
                echo
                echo "- Le centre de controle d'ALCASAR (ACC) est à l'adresse http://alcasar"
                echo
                echo "                   Appuyez sur 'Entrée' pour continuer"
        else    
                echo "#                        Enf of ALCASAR install process                     #"
                echo "#                                                                           #"
                echo "#         Application Libre pour le Contrôle Authentifié et Sécurisé        #"
                echo "#                     des Accès au Réseau ( ALCASAR )                       #"
                echo "#                                                                           #"
                echo "#############################################################################"
                echo
                echo "- The system will be rebooted in order to operate ALCASAR"
                echo
                echo "- Read the exploitation documentation"
                echo
                echo "- The ALCASAR Control Center (ACC) is at http://alcasar"
                echo
                echo "                   Hit 'Enter' to continue"
        fi
        sleep 2
        if [ "$mode" != "update" ]
        then
                read a
        fi
        clear

        reboot
} # End post_install ()

#################################
#       Main Install loop       #
#################################
dir_exec=`dirname "$0"`
if [ $dir_exec != "." ]
then
        echo "Lancez ce programme depuis le répertoire de l'archive d'ALCASAR"
        echo "Launch this program from the ALCASAR archive directory"
        exit 0
fi
VERSION=`cat $DIR_INSTALL/VERSION`
usage="Usage: alcasar.sh {-i or --install} | {-u or --uninstall}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
        nb_args=1
        args="-h"
fi
chmod -R u+x $DIR_SCRIPTS/*
case $args in
        -\? | -h* | --h*)
                echo "$usage"
                exit 0
                ;;
        -i | --install)
                license
                header_install
                testing
# Test if ALCASAR is already installed
                if [ -e $DIR_WEB/VERSION ]
                then
                        actual_version=`cat $DIR_WEB/VERSION`
                        if [ $Lang == "fr" ]
                                then echo -n "La version "; echo -n $actual_version ; echo " d'ALCASAR est déjà installée";
                                else echo -n "ALCASAR Version "; echo -n $actual_version ; echo " is already installed";
                        fi
                        response=0
                        PTN='^[oOnNyY]$'
                        until [[ $(expr $response : $PTN) -gt 0 ]]
                        do
                                if [ $Lang == "fr" ]
                                        then echo -n "Voulez-vous effectuer une mise à jour (O/n)? ";
                                        else echo -n "Do you want to update (Y/n)?";
                                 fi
                                read response
                        done
                        if [ "$response" = "n" ] || [ "$response" = "N" ] 
                        then
                                rm -f /tmp/alcasar-conf*
                        else
# Create a backup of running version importants files
                                $DIR_SCRIPTS/alcasar-conf.sh --create
                                mode="update"
                        fi
                fi
# RPMs install
                $DIR_SCRIPTS/alcasar-urpmi.sh
                echo "Mise à jour des modules noyau installés"                
                if [ "$?" != "0" ]
                then
                        exit 0
                fi
                if [ -e $DIR_WEB/VERSION ]
                then
# Uninstall the running version
                        $DIR_SCRIPTS/sbin/alcasar-uninstall.sh
                fi
# Test if manual update 
                if [ -e /tmp/alcasar-conf*.tar.gz ] && [ "$mode" != "update" ]
                then
                        header_install
                        if [ $Lang == "fr" ]
                                then echo "Le fichier de configuration d'une ancienne version a été trouvé";
                                else echo "The configuration file of an old version has been found";
                        fi
                        response=0
                        PTN='^[oOnNyY]$'
                        until [[ $(expr $response : $PTN) -gt 0 ]]
                        do
                                if [ $Lang == "fr" ]
                                        then echo -n "Voulez-vous l'utiliser (O/n)? ";
                                        else echo -n "Do you want to use it (Y/n)?";
                                 fi
                                read response
                                if [ "$response" = "n" ] || [ "$response" = "N" ] 
                                then rm -f /tmp/alcasar-conf*
                                fi
                        done
                fi
# Test if update
                if [ -e /tmp/alcasar-conf* ] 
                then
                        if [ $Lang == "fr" ]
                                then echo "#### Installation avec mise à jour ####";
                                else echo "#### Installation with update     ####";
                        fi
# Extract the central configuration file
                        tar -xf /tmp/alcasar-conf* conf/etc/alcasar.conf 
                        ORGANISME=`grep ORGANISM conf/etc/alcasar.conf|cut -d"=" -f2`
                        PREVIOUS_VERSION=`grep VERSION conf/etc/alcasar.conf|cut -d"=" -f2`
                        MAJ_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f1`
                        MIN_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f2|cut -c1`
                        UPD_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f3`
                        mode="update"
                else
                        mode="install"
                fi
                for func in init network gestion AC init_db param_radius param_web_radius param_chilli param_squid param_dansguardian antivirus param_ulogd param_nfsen param_dnsmasq BL cron fail2ban post_install
                do
                        $func
# echo "*** 'debug' : end of function $func ***"; read a
                done
                ;;
        -u | --uninstall)
                if [ ! -e $DIR_DEST_SBIN/alcasar-uninstall.sh ]
                then
                        if [ $Lang == "fr" ]
                                then echo "ALCASAR n'est pas installé!";
                                else echo "ALCASAR isn't installed!";
                        fi
                        exit 0
                fi
                response=0
                PTN='^[oOnN]$'
                until [[ $(expr $response : $PTN) -gt 0 ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Voulez-vous créer le fichier de configuration de la version actuelle (0/n)? ";
                                else echo -n "Do you want to create the running version configuration file (Y/n)? ";
                        fi
                        read response
                done
                if [ "$response" = "o" ] || [ "$response" = "O" ] || [ "$response" = "Y" ] || [ "$response" = "y" ]
                then
                        $DIR_SCRIPTS/alcasar-conf.sh --create
                else    
                        rm -f /tmp/alcasar-conf*
                fi
# Uninstall the running version
                $DIR_SCRIPTS/sbin/alcasar-uninstall.sh
                ;;
        *)
                echo "Argument inconnu :$1";
                echo "Unknown argument :$1";
                echo "$usage"
                exit 1
                ;;
esac
# end of script