Subversion Repositories ALCASAR

Compare Revisions

No changes between revisions

Ignore whitespace Rev 1 → Rev HEAD

/scripts/alcasar-uninstall.sh
0,0 → 1,418
#!/bin/bash
# $Id$
 
# alcasar-uninstall.sh
# by Franck BOUIJOUX, Pascal LEVANT and Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# Désinstallation ou mise à jour d'ALCASAR
# Uninstall or update ALCASAR
 
SED="/bin/sed -i"
 
[ -z $DEBUG_ALCASAR ] && DEBUG_ALCASAR='off'
 
init ()
{
echo -en "(3) : "
rm -f /root/ALCASAR* && echo -n "1, " # The files in /usr/local/ will be removed at the end (still usefull here)
[ -e /boot/grub2/user.cfg ] && rm -f /boot/grub2/user.cfg && echo -n "2, "
[ -e /root/grub.default ] && mv -f /root/grub.default /etc/grub.d/10_linux && echo -n "3"
}
 
ACC ()
{
echo -en "(11) : "
[ -d /var/www/html ] && rm -rf /var/www/html && echo -n "1, "
[ -d /etc/freeradius-web ] && rm -rf /etc/freeradius-web && echo -n "2, "
[ -e /etc/php.d/05_date.ini.default ] && mv -f /etc/php.d/05_date.ini.default /etc/php.d/05_date.ini && echo -n "3, "
[ -e /etc/php.ini.default ] && mv -f /etc/php.ini.default /etc/php.ini && echo -n "4, "
[ -e /etc/lighttpd/lighttpd.conf.default ] && mv -f /etc/lighttpd/lighttpd.conf.default /etc/lighttpd/lighttpd.conf && echo -n "5, "
[ -e /etc/lighttpd/modules.conf.default ] && mv -f /etc/lighttpd/modules.conf.default /etc/lighttpd/modules.conf && echo -n "6, "
[ -e /etc/lighttpd/conf.d/fastcgi.conf.default ] && mv -f /etc/lighttpd/conf.d/fastcgi.conf.default /etc/lighttpd/conf.d/fastcgi.conf && echo -n "7, "
[ -e /etc/php-fpm.conf.default ] && mv -f /etc/php-fpm.conf.default /etc/php-fpm.conf && echo -n "8, "
[ -d /etc/lighttpd/vhosts.d ] && rm -rf /etc/lighttpd/vhosts.d && echo -n "9, "
[ -d /usr/local/etc/digest ] && rm -rf /usr/local/etc/digest && echo -n "10, "
[ -e /etc/systemd/system/lighttpd.service ] && rm -f /etc/systemd/system/lighttpd.service && echo -n "11"
}
 
CA ()
{
echo -en "(5) : "
[ -e /etc/pki/CA/alcasar-ca.crt ] && rm -f /etc/pki/CA/alcasar-ca.crt && echo -n "1, "
[ -e /etc/pki/CA/private/alcasar-ca.key ] && rm -f /etc/pki/CA/private/alcasar-ca.key && echo -n "2, "
[ -e /etc/pki/tls/certs/alcasar.crt ] && rm -f /etc/pki/tls/certs/alcasar.crt && echo -n "3, "
[ -e /etc/pki/tls/private/alcasar.key ] && rm -f /etc/pki/tls/private/alcasar.key && echo -n "4, "
[ -e /etc/pki/tls/private/alcasar.pem ] && rm -f /etc/pki/tls/private/alcasar.pem && echo -n "5"
}
 
time_server ()
{
echo -en "(1) : "
[ -e /etc/ntp.conf.default ] && mv /etc/ntp.conf.default /etc/ntp.conf && echo -n "1"
}
 
init_db ()
{
echo -en "(2) : "
[ -e /etc/my.cnf.default ] && mv -f /etc/my.cnf.default /etc/my.cnf && echo -n "1, "
if [ -e /etc/systemd/system/mysqld.service ]
then
rm /etc/systemd/system/mysqld.service
echo -n "2"
fi
/usr/bin/systemctl daemon-reload
rm -rf /var/lib/mysql
}
 
freeradius ()
{
echo -en "(22) : "
[ -e /etc/raddb/empty-radiusd-db.sql ] && rm /etc/raddb/empty-radiusd-db.sql && echo -n "1, "
[ -e /etc/raddb/radiusd.conf.default ] && mv /etc/raddb/radiusd.conf.default /etc/raddb/radiusd.conf && echo -n "2, "
[ -e /etc/raddb/dictionary.default ] && mv /etc/raddb/dictionary.default /etc/raddb/dictionary && echo -n "3, "
[ -e /etc/raddb/dictionary.alcasar ] && rm /etc/raddb/dictionary.alcasar && echo -n "4, "
[ -e /etc/raddb/dictionary.coovachilli ] && rm /etc/raddb/dictionary.coovachilli && echo -n "5, "
[ -e /etc/raddb/clients.conf.default ] && mv /etc/raddb/clients.conf.default /etc/raddb/clients.conf && echo -n "6, "
[ -e /etc/raddb/sites-enabled/alcasar ] && rm /etc/raddb/sites-enabled/alcasar && echo -n "7, "
[ -e /etc/raddb/sites-available/alcasar ] && rm /etc/raddb/sites-available/alcasar && echo -n "8, "
[ -e /etc/raddb/sites-available/alcasar-with-ldap ] && rm /etc/raddb/sites-available/alcasar-with-ldap && echo -n "9, "
[ -e /etc/raddb/mods-available/ldap-alcasar ] && rm /etc/raddb/mods-available/ldap-alcasar && echo -n "10, "
i=10
for mods in sql sqlcounter attr_filter expiration logintime pap expr always
do
i=`expr $i + 1`
[ -e /etc/raddb/mods-enabled/$mods ] && rm /etc/raddb/mods-enabled/$mods && echo -n "$i, "
done
[ -e /etc/raddb/mods-available/sql.default ] && mv /etc/raddb/mods-available/sql.default /etc/raddb/mods-available/sql && echo -n "19, "
[ -e /etc/raddb/mods-config/sql/main/mysql/queries.conf.default ] && mv /etc/raddb/mods-config/sql/main/mysql/queries.conf.default /etc/raddb/mods-config/sql/main/mysql/queries.conf && echo -n "20, "
[ -e /etc/raddb/mods-available/sqlcounter.default ] && mv /etc/raddb/mods-available/sqlcounter.default /etc/raddb/mods-available/sqlcounter && echo -n "21, "
if [ -e /etc/systemd/system/radiusd.service ]; then
rm -f /etc/systemd/system/radiusd.service
echo -n "22"
fi
}
 
chilli ()
{
echo -en "(4) : "
[ -e /etc/init.d/chilli.default ] && mv /etc/init.d/chilli.default /etc/init.d/chilli && echo -n "1, "
[ -e /usr/libexec/chilli ] && rm /usr/libexec/chilli && echo -n "2, "
[ -e /etc/chilli.conf.default ] && mv /etc/chilli.conf.default /etc/chilli.conf && echo -n "3, "
[ -e /etc/systemd/system/chilli.service ] && rm /etc/systemd/system/chilli.service && echo -n "4"
}
 
e2guardian ()
{
echo -en "(8) : "
[ -d /var/e2guardian ] && rm -rf /var/e2guardian
[ -d /var/dansguardian ] && rm -rf /var/dansguardian
if [ -e /etc/systemd/system/e2guardian.service ]; then
rm -f /etc/systemd/system/e2guardian.service
echo -n "1, "
fi
[ -e /etc/e2guardian/e2guardian.conf.default ] && mv /etc/e2guardian/e2guardian.conf.default /etc/e2guardian/e2guardian.conf && echo -n "2, "
[ -e /usr/share/e2guardian/languages/french/alcasar-e2g.html ] && rm /usr/share/e2guardian/languages/french/alcasar-e2g.html && echo -n "3, "
[ -e /usr/share/e2guardian/languages/ukenglish/alcasar-e2g.html ] && rm /usr/share/e2guardian/languages/ukenglish/alcasar-e2g.html && echo -n "4, "
[ -e /etc/e2guardian/e2guardianf1.conf.default ] && mv /etc/e2guardian/e2guardianf1.conf.default /etc/e2guardian/e2guardianf1.conf && echo -n "5, "
[ -d /etc/e2guardian/lists/group1 ] && rm -rf /etc/e2guardian/lists/group1 && echo -n "6, "
[ -e /etc/e2guardian/lists/common/exceptioniplist.default ] && mv /etc/e2guardian/lists/common/exceptioniplist.default /etc/e2guardian/lists/common/exceptioniplist && echo -n "7, "
[ -e /etc/e2guardian/e2guardianf2.conf ] && rm -f /etc/e2guardian/e2guardianf2.conf && echo -n "8."
}
 
antivirus ()
{
echo -en "(4) : "
if [ -e /etc/systemd/system/clamav-daemon.service ]; then
rm -f /etc/systemd/system/clamav-daemon.service
echo -n "1, "
fi
if [ -e /etc/systemd/system/clamav-daemon.socket ]; then
rm -f /etc/systemd/system/clamav-daemon.socket
echo -n "2, "
fi
[ -e /etc/clamd.conf.default ] && mv /etc/clamd.conf.default /etc/clamd.conf && echo -n "3, "
[ -e /etc/freshclam.conf.default ] && mv /etc/freshclam.conf.default /etc/freshclam.conf && echo -n "4"
}
 
ulogd ()
{
echo -en "(6) : "
i=0
for log_type in traceability ssh ext-access
do
i=`expr $i + 1`
[ -e /etc/ulogd-$log_type.conf ] && rm -f /etc/ulogd-$log_type.conf && echo -n "$i, "
i=`expr $i + 1`
[ -e /etc/systemd/system/ulogd-$log_type.service ] && rm -f /etc/systemd/system/ulogd-$log_type.service && echo -n "$i, "
done
}
 
nfsen ()
{
# we don't remove user "nfcapd" & nfcapd folders in order to keep data when updating
echo -en "(1) : "
[ -e /etc/systemd/system/nfcapd.service ] && rm -f /etc/systemd/system/nfcapd.service && echo -n "1"
}
 
vnstat ()
{
echo -en "(2) : "
[ -e /etc/vnstat.conf.default ] && mv /etc/vnstat.conf.default /etc/vnstat.conf && echo -n "1, "
if [ -e /etc/systemd/system/vnstat.service ]; then
rm -f /etc/systemd/system/vnstat.service
echo -n "2"
fi
}
 
unbound ()
{
echo -en "(9) : "
[ -e /etc/unbound/unbound.conf.default ] && mv /etc/unbound/unbound.conf.default /etc/unbound/unbound.conf && echo -n "1, "
[ -e /etc/unbound/unbound-blacklist.conf ] && rm -f /etc/unbound/unbound-blacklist.conf && echo -n "2, "
[ -e /etc/unbound/unbound-whitelist.conf ] && rm -f /etc/unbound/unbound-whitelist.conf && echo -n "3, "
[ -e /etc/unbound/unbound-blackhole.conf ] && rm -f /etc/unbound/unbound-blackhole.conf && echo -n "4, "
[ -e /etc/unbound/conf.d ] && rm -rf /etc/unbound/conf.d && echo -n "5, "
i=6
for list in blacklist blackhole whitelist
do
if [ -e /etc/systemd/system/unbound-$list.service ]
then
rm -f /etc/systemd/system/unbound-$list.service
echo -n "$i, "
fi
i=`expr $i + 1`
done
if [ -e /etc/systemd/system/unbound.service ]; then
rm -f /etc/systemd/system/unbound.service
echo -n "9"
fi
}
 
dhcpd ()
{
echo -en "(1) : "
[ -e /etc/dhcpd.conf.default ] && mv /etc/dhcpd.conf.default /etc/dhcpd.conf && echo -n "1"
}
 
cron ()
{
# /etc/cron.d/alcasar-daemon-watchdog is removed at the beginning of this script
echo -en "(12) : "
i=1
for cron in `ls /etc/cron.d/alcasar-* 2>/dev/null`
do
rm $cron && echo -n "$i, "
i=`expr $i + 1`
done
[ -e /etc/crontab.default ] && mv /etc/crontab.default /etc/crontab && echo -n "11, "
[ -e /etc/anacrontab.default ] && mv /etc/anacrontab.default /etc/anacrontab && echo -n "12"
}
 
fail2ban ()
{
echo -en "(11) : "
[ -e /etc/fail2ban/jail.conf.default ] && mv /etc/fail2ban/jail.conf.default /etc/fail2ban/jail.conf && echo -n "1, "
[ -e /etc/fail2ban/action.d/iptables-allports.conf.default ] && mv /etc/fail2ban/action.d/iptables-allports.conf.default /etc/fail2ban/action.d/iptables-allports.conf # only for ALCASAR version <= V3.5.1
i=2
for filter in `ls /etc/fail2ban/filter.d/alcasar_* 2>/dev/null`
do
i=`expr $i + 1`
rm $filter && echo -n "$i, "
done
for jail in `ls /etc/fail2ban/jail.d/*alcasar_* 2>/dev/null`
do
i=`expr $i + 1`
rm $jail && echo -n "$i, "
done
if [ -e /etc/systemd/system/fail2ban.service ]; then
rm -f /etc/systemd/system/fail2ban.service
echo -n "11"
fi
}
 
gammu_smsd ()
{
echo -en "(4) : "
[ -e /etc/gammu_smsd_conf ] && rm -f /etc/gammu_smsd_conf && echo -n "1, "
[ -e /etc/systemd/system/gammu-smsd.service ] && rm -f /etc/systemd/system/gammu-smsd.service && echo -n "2, "
[ -e /var/log/gammu-smsd ] && rm -rf /var/log/gammu-smsd && echo -n "3, "
userdel -r gammu_smsd 2>/dev/null && echo -n "4"
#[ -e /lib/udev/rules.d/66-huawei.rules ] && rm -f /lib/udev/rules.d/66-huawei.rules && echo -n "4"
}
 
msec ()
{
echo -en "(2) : "
if [ -e /etc/security/msec/security.conf ]; then
[ -e /etc/security/msec/security.conf.default ] && mv /etc/security/msec/security.conf.default /etc/security/msec/security.conf && echo -n "1, "
[ -e /etc/security/msec/perm.local ] && rm -f /etc/security/msec/perm.local && echo -n "2"
else
echo -n "uninstalled"
fi
}
 
letsencrypt ()
{
echo -en "(3) : "
[ -e /usr/local/etc/letsencrypt ] && rm -rf /usr/local/etc/letsencrypt && echo -n "1, "
[ -e /opt/acme.sh/acme.sh ] && /opt/acme.sh/acme.sh --uninstall --nocron 1>/dev/null && echo -n "2, "
[ -e /opt/acme.sh ] && rm -rf /opt/acme.sh && echo -n "3"
}
 
mail_service()
{
echo -en "(1) : "
[ -e /etc/postfix/main.cf.orig ] && mv /etc/postfix/main.cf.orig /etc/postfix/main.cf && echo -n "1"
}
 
post_install ()
{
echo -en "(7) : "
[ -e /etc/mageia-release.default ] && mv -f /etc/mageia-release.default /etc/mageia-release && echo -n "1, "
[ -e /etc/ssh/alcasar-banner-ssh ] && rm -f /etc/ssh/alcasar-banner-ssh && echo -n "2, "
[ -e /etc/ssh/sshd_config.default ] && mv -f /etc/ssh/sshd_config.default /etc/ssh/sshd_config && echo -n "3, "
[ -e /etc/bashrc.default ] && mv -f /etc/bashrc.default /etc/bashrc && echo -n "4, "
[ -e /etc/sudoers.default ] && mv -f /etc/sudoers.default /etc/sudoers && echo -n "5, "
[ -e /etc/security/limits.conf.default ] && mv -f /etc/security/limits.conf.default /etc/security/limits.conf && echo -n "6, "
[ -e /etc/default/grub.default ] && mv -f /etc/default/grub.default /etc/default/grub && echo -n "7"
}
 
usage="Usage: alcasar-uninstall.sh {-update or --update} | {-full or --full}"
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]; then
nb_args=1
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--update | -update)
mode="update"
;;
--full | -full)
mode="full"
;;
*)
echo "Argument inconnu :$1";
echo "$usage"
exit 1
;;
esac
clear
if [ $mode == "full" ]; then
echo "----------------------------------------------------------------------------"
echo "** Uninstall/Désinstallation d'ALCASAR **"
echo "----------------------------------------------------------------------------"
services="vnstat clamav-daemon clamav-freshclam ntpd php-fpm lighttpd radiusd mysqld unbound unbound-blacklist unbound-whitelist unbound-blackhole nfcapd fail2ban iptables ulogd-ext-access ulogd-ssh ulogd-traceability e2guardian sshd chilli"
/usr/local/bin/alcasar-logout.sh all # logout everybody
else
echo "--------------------------------------------------------------------------"
echo "** update/mise à jour d'ALCASAR **"
echo "--------------------------------------------------------------------------"
# unbound, iptables & sshd should stay on to allow remote update
services="vnstat clamav-daemon clamav-freshclam ntpd php-fpm lighttpd radiusd mysqld unbound-blacklist unbound-whitelist unbound-blackhole nfcapd fail2ban ulogd-ext-access ulogd-ssh ulogd-traceability e2guardian chilli"
/usr/local/bin/alcasar-bypass.sh -on # to allow remote update + users stay connected during the update
fi
 
echo "Stopping services : "
# remove daemon watchdog in order to not restart alcasar daemons during the uninstall process
[ -e /etc/cron.d/alcasar-daemon-watchdog ] && rm -f /etc/cron.d/alcasar-daemon-watchdog
/usr/local/bin/alcasar-sms.sh --stop
for i in $services
do
service_exist=`systemctl list-unit-files | grep ^$i.service | wc -l`
if [ $service_exist -eq 1 ]; then
/usr/bin/systemctl disable $i.service
/usr/bin/systemctl stop $i.service 1>/dev/null
sleep 1
else
echo "The service $i.service doesn't exist !"
fi
done
echo "Check the service clearing"
for i in $services
do
if [ `systemctl is-active $i.service` == "active" ]; then
echo "The service '$i' need to be killed"
/usr/bin/systemctl stop $i.service
killall $i
fi
done
 
[ $mode == "update" ] && /usr/bin/systemctl reload sshd # reload sshd in case of remote update
 
echo "Reset ALCASAR main functions : "
for func in init ACC CA time_server init_db freeradius chilli e2guardian antivirus ulogd nfsen vnstat unbound dhcpd cron fail2ban gammu_smsd msec letsencrypt mail_service post_install
do
echo -en "\n- $func "
$func
if [ $DEBUG_ALCASAR == "on" ]; then
echo -n " *** 'debug' : end removing function '$func' *** "
read a
fi
done
if [ $mode == "full" ]; then
echo -en "\n- network(10) : "
hostnamectl set-hostname localhost.localdomain
chmod a-x /etc/sysconfig/network-scripts/default-*
i=0
for nic in `ls /etc/sysconfig/network-scripts/default-*|cut -d'-' -f4`
do
i=`expr $i + 1`
/sbin/ifdown $nic
[ -e /etc/sysconfig/network-scripts/default-ifcfg-$nic ] && mv -f /etc/sysconfig/network-scripts/default-ifcfg-$nic /etc/sysconfig/network-scripts/ifcfg-$nic && echo -n "$i ($nic), "
done
[ -e /etc/sysconfig/network.default ] && mv -f /etc/sysconfig/network.default /etc/sysconfig/network && echo -n "3, "
[ -e /etc/hosts.default ] && mv -f /etc/hosts.default /etc/hosts && echo -n "4, "
[ -e /etc/hosts.allow.default ] && mv -f /etc/hosts.allow.default /etc/hosts.allow && echo -n "5, "
[ -e /etc/hosts.deny.default ] && mv -f /etc/hosts.deny.default /etc/hosts.deny && echo -n "6, "
[ -e /etc/modprobe.preload.default ] && mv -f /etc/modprobe.preload.default /etc/modprobe.preload && echo -n "7, "
if [ -e /etc/systemd/system/alcasar-network.service ]; then
rm -f /etc/systemd/system/alcasar-network.service
echo -n "8, "
fi
if [ -e /etc/systemd/system/iptables.service ]; then
rm -f /etc/systemd/system/iptables.service
echo -n "9, "
fi
[ -e /usr/libexec/iptables.init.default ] && mv -f /usr/libexec/iptables.init.default /usr/libexec/iptables.init && echo -n "10"
/usr/bin/systemctl restart network
sleep 1
fi
 
# Reset "skip.list" (we keep "kernel" in order not to download kernel we don't want to have)
echo "/^kernel/" > /etc/urpmi/skip.list
if [ `grep -E '^exclude=' /etc/dnf/dnf.conf |wc -l` -eq "1" ]; then
$SED "s?^exclude=.*?exclude=kernel\*?g" /etc/dnf/dnf.conf
else
echo "exclude=kernel*" >> /etc/dnf/dnf.conf
fi
# Cleaning (remove all "old" alcasar scripts)
echo -en "\n- End of cleaning ...\n"
for rm_fic in /usr/local/bin /usr/local/etc /usr/local/sbin
do
rm -rf $rm_fic/alcasar*
done
/usr/bin/update-grub2
 
if [ $mode == "full" ]; then
echo -n "Waiting for Network to be up again : "
i=0
while [ $i -lt 10 ] # We wait 10 seconds max
do
echo -n "."
DNS1=`grep ^nameserver /etc/resolv.conf|awk -F" " '{print $2}'|head -n 1`
if [ "$DNS1" != "" ] && [ "$DNS1" != "127.0.0.1" ]; then
i=9
echo -n "ok"
fi
i=`expr $i + 1`
sleep 1
done
fi
echo
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-bl.sh
0,0 → 1,378
#!/bin/bash
 
# $Id$
 
# alcasar-bl.sh
# by Franck BOUIJOUX and Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# Gestion de la BL pour le filtrage de domaine (via unbound) et d'URL (via E2guardian)
# Manage the BL for domain filtering (with unbound) and URL filtering (with E2guardian)
 
DIR_CONF="/usr/local/etc"
CONF_FILE="$DIR_CONF/alcasar.conf"
private_ip_mask=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
private_ip_mask=${private_ip_mask:=192.168.182.1/24}
DIR_tmp="/tmp/blacklists"
FILE_tmp="/tmp/filesfilter.txt"
FILE_ip_tmp="/tmp/filesipfilter.txt"
DIR_DG="/etc/e2guardian/lists"
DIR_DG_BL="$DIR_DG/blacklists"
DIR_DG_GROUP1="$DIR_DG/group1"
GLOBAL_USAGE="$DIR_CONF/alcasar-global-usage" # file containing the description of the lists
BL_CATEGORIES="$DIR_CONF/alcasar-bl-categories" # list of names of the BL categories
WL_CATEGORIES="$DIR_CONF/alcasar-wl-categories" # ' ' WL categories
BL_CATEGORIES_ENABLED="$DIR_CONF/alcasar-bl-categories-enabled" # ' ' BL enabled categories
WL_CATEGORIES_ENABLED="$DIR_CONF/alcasar-wl-categories-enabled" # ' ' WL enabled categories
DIR_SHARE="/usr/local/share"
DIR_DNS_BL="$DIR_SHARE/unbound-bl" # all the BL in the Unbound format
DIR_DNS_WL="$DIR_SHARE/unbound-wl" # all the WL ' ' '
DIR_IP_BL="$DIR_SHARE/iptables-bl" # all the IP addresses of the BL
DIR_IP_WL="$DIR_SHARE/iptables-wl" # IP ossi disabled WL
DIR_DNS_BL_ENABLED="$DIR_SHARE/unbound-bl-enabled" # symbolic link to the domains BL (only enabled categories)
DIR_DNS_WL_ENABLED="$DIR_SHARE/unbound-wl-enabled" # ' ' ' WL ' '
DIR_IP_BL_ENABLED="$DIR_SHARE/iptables-bl-enabled" # ' ' ip BL (only enabled categories)
DIR_IP_WL_ENABLED="$DIR_SHARE/iptables-wl-enabled" # ' ' ip WL (ossi and ossi-* imported from ACC)
REHABILITATED_DNS_FILE="/etc/unbound/conf.d/blacklist/rehabilitated.conf"
BL_SERVER="dsi.ut-capitole.fr"
SED="/bin/sed -i"
 
# enable/disable the BL & WL categories
function cat_choice (){
mkdir -p $DIR_tmp
for LIST in $DIR_IP_BL_ENABLED $DIR_DNS_BL_ENABLED $DIR_IP_WL_ENABLED $DIR_DNS_WL_ENABLED
do
if [ ! -e $LIST ] # only on install stage
then
mkdir $LIST
else
rm -rf ${LIST:?}/*
fi
chown root:apache $LIST
chmod 770 $LIST
done
# update categories with rsync
if [ ! -e $DIR_CONF/update_cat.conf ]
then
touch $DIR_CONF/update_cat.conf
chown root:apache $DIR_CONF/update_cat.conf
chmod 660 $DIR_CONF/update_cat.conf
fi
$SED "/\.Include/d" $DIR_DG_GROUP1/bannedurllist # cleaning E2G url blacklisted
# $SED "/\.Include/d" $DIR_DG_GROUP1/bannedsitelist # cleaning E2G domain blacklisted (now managed by unbound)
$SED "s?^[^#]?#&?g" $BL_CATEGORIES $WL_CATEGORIES # cleaning BL & WL categories file (comment all lines)
 
# process the file $BL_CATEGORIES with the choice of categories
for ENABLE_CATEGORIE in `cat $BL_CATEGORIES_ENABLED`
do
$SED "/\/$ENABLE_CATEGORIE$/d" $BL_CATEGORIES
$SED "1i\/etc\/e2guardian\/lists\/blacklists\/$ENABLE_CATEGORIE" $BL_CATEGORIES
ln -sf $DIR_DNS_BL/$ENABLE_CATEGORIE.conf $DIR_DNS_BL_ENABLED/$ENABLE_CATEGORIE
ln -sf $DIR_IP_BL/$ENABLE_CATEGORIE $DIR_IP_BL_ENABLED/$ENABLE_CATEGORIE
# echo ".Include<$DIR_DG_BL/$ENABLE_CATEGORIE/domains>" >> $DIR_DG_GROUP1/bannedsitelist # Blacklisted domains are managed by unbound
echo ".Include<$DIR_DG_BL/$ENABLE_CATEGORIE/urls>" >> $DIR_DG_GROUP1/bannedurllist
done
sort +0.0 -0.2 $BL_CATEGORIES -o $FILE_tmp
mv $FILE_tmp $BL_CATEGORIES
sort +0.0 -0.2 $BL_CATEGORIES_ENABLED -o $FILE_tmp
mv $FILE_tmp $BL_CATEGORIES_ENABLED
chown root:apache $BL_CATEGORIES $BL_CATEGORIES_ENABLED
chmod 660 $BL_CATEGORIES $BL_CATEGORIES_ENABLED
 
# process the file $WL_CATEGORIES with the choice of categories
for ENABLE_CATEGORIE in `cat $WL_CATEGORIES_ENABLED`
do
$SED "/\/$ENABLE_CATEGORIE$/d" $WL_CATEGORIES
$SED "1i\/etc\/e2guardian\/lists\/blacklists\/$ENABLE_CATEGORIE" $WL_CATEGORIES
ln -sf $DIR_DNS_WL/$ENABLE_CATEGORIE.conf $DIR_DNS_WL_ENABLED/$ENABLE_CATEGORIE
done
sort +0.0 -0.2 $WL_CATEGORIES -o $FILE_tmp
mv $FILE_tmp $WL_CATEGORIES
sort +0.0 -0.2 $WL_CATEGORIES_ENABLED -o $FILE_tmp
mv $FILE_tmp $WL_CATEGORIES_ENABLED
chown root:apache $WL_CATEGORIES $WL_CATEGORIES_ENABLED
chmod 660 $WL_CATEGORIES $WL_CATEGORIES_ENABLED
}
 
# cleaning file and split it ("domains" in $FILE_tmp & "IP" in $FILE_ip_tmp)
function clean_split (){
$SED '/^[.#]/d' $FILE_tmp # remove commented lines and lines beginning with a dot
$SED '/^\s*$/d' $FILE_tmp # remove empty lines
$SED '/[äâëêïîöôüû@,]/d' $FILE_tmp # remove line with "chelou" characters
# extract ip addresses and ip networks for iptables.
awk '/^([0-9]{1,3}\.){3}[0-9]{1,3}$/{print "add bl_ip_blocked " $0}' $FILE_tmp > $FILE_ip_tmp
awk '/^([0-9]{1,3}\.){3}[0-9]{1,3}\/[0-9]{1,2}$/{print "add bl_ip_blocked " $0}' $FILE_tmp >> $FILE_ip_tmp
# extract domain names for unbound.
$SED -n '/^\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/!p' $FILE_tmp
# Retrieve max Top Level Domain for domain name synthax
#MAX_TLD=$(curl http://data.iana.org/TLD/tlds-alpha-by-domain.txt | grep -v '-' | grep -v '#' | wc -L)
#if [ $(echo $MAX_TLD | wc -c) -eq 0 ];then
# MAX_TLD=18
#fi
# search for correction grep -E "([a-zA-Z0-9_-.]+\.){1,2}[a-zA-Z]{2,$MAX_TLD}" $ossi_custom_dir/domains > $FILE_tmp
}
 
usage="Usage: alcasar-bl.sh { -cat_choice or --cat_choice } | { -download or --download } | { -adapt or --adapt } | { -reload or --reload }"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
# Retrieve Toulouse University BL
-download | --download)
rm -rf /tmp/con_ok.html
`/usr/bin/curl $BL_SERVER -# -o /tmp/con_ok.html`
if [ ! -e /tmp/con_ok.html ]
then
echo "Erreur : le serveur de blacklist ($BL_SERVER) n'est pas joignable"
else
rm -rf /tmp/con_ok.html $DIR_tmp
mkdir $DIR_tmp
wget -P $DIR_tmp http://$BL_SERVER/blacklists/download/blacklists.tar.gz
md5sum $DIR_tmp/blacklists.tar.gz | cut -d" " -f1 > $DIR_tmp/md5sum
chown -R apache:apache $DIR_tmp
fi
;;
# enable/disable categories (used only during the alcasar install process)
-cat_choice | --cat_choice)
cat_choice
;;
# Adapt Toulouse University BL to ALCASAR architecture (unbound + DG + iptables)
-adapt | --adapt)
echo -n "Adaptation process of Toulouse University blackList. Please wait : "
if [ -f $DIR_tmp/blacklists.tar.gz ] # when downloading the last version of the BL
then
# keep custom files (ossi)
for x in $(ls -1 $DIR_DG_BL | grep "^ossi-*")
do
mv $DIR_DG_BL/$x $DIR_tmp
done
rm -rf $DIR_DG_BL $DIR_IP_BL
mkdir $DIR_DG_BL $DIR_IP_BL
tar zxf $DIR_tmp/blacklists.tar.gz --directory=$DIR_DG/
# replace the global_usage file of the archive
cp -f $GLOBAL_USAGE $DIR_DG_BL/global_usage
chown -R e2guardian:apache $DIR_DG
chmod -R 770 $DIR_DG
# Add the two local categories (ossi-bl & ossi-wl) to the usage file
# Add the custom categories (ossi-tor_nodes) to the usage file
cat <<EOF >> $DIR_DG_BL/global_usage
 
NAME: ossi-bl
DEFAULT_TYPE: black
SOURCE: ALCASAR Team
DESC FR: sites blacklistés ajoutés localement
DESC EN: blacklisted sites add locally
NAME FR: ossi-bl
NAME EN: ossi-bl
 
NAME: ossi-wl
DEFAULT_TYPE: white
SOURCE: ALCASAR Team
DESC FR: sites autorisés ajoutés localement
DESC EN: whitelisted sites add locally
NAME FR: ossi-wl
NAME EN: ossi-wl
 
NAME: ossi-bl-tor_nodes
DEFAULT_TYPE: black
SOURCE: ALCASAR Team
DESC FR: Adresses IP des noeuds (routeurs) d'entrée du réseau TOR
DESC EN: IP addresses of input TOR nodes (routers)
NAME FR: Noeuds TOR
NAME EN: TOR nodes
 
NAME: ossi-bl-ultrasurf
DEFAULT_TYPE: black
SOURCE: ALCASAR Team
DESC FR: Adresses IP des point de sortie ULTRASURF
DESC EN: IP addresses of output points of ULTRASURF
NAME FR: Points de sortie ULTRASURF
NAME EN: ULTRASURF output points
 
NAME: ossi-bl-candc
DEFAULT_TYPE: black
SOURCE: Bambenek Consulting: https://osint.bambenekconsulting.com
DESC FR: liste des URLs et IPs des serveurs command & control
DESC EN: list of URLs and IPs of command & control servers
NAME FR: Serveurs Command & Control
NAME EN: Command & Control Server
 
EOF
# Retrieve custom files (ossi)
for x in $(ls -1 $DIR_tmp | grep "^ossi-*")
do
mv $DIR_tmp/$x $DIR_DG_BL
done
fi
rm -f $BL_CATEGORIES $WL_CATEGORIES $WL_CATEGORIES_ENABLED
rm -rf $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
rm -rf $DIR_DNS_BL_ENABLED $DIR_DNS_WL_ENABLED $DIR_IP_BL_ENABLED $DIR_IP_WL_ENABLED
touch $BL_CATEGORIES $WL_CATEGORIES
mkdir $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
mkdir $DIR_DNS_BL_ENABLED $DIR_DNS_WL_ENABLED $DIR_IP_BL_ENABLED $DIR_IP_WL_ENABLED
find $DIR_DG_BL/ -type f -name domains > $FILE_tmp # retrieve directory name where a domain file exist
$SED "s?\/domains??g" $FILE_tmp # remove "/domains" suffix
for dir_categorie in `cat $FILE_tmp` # create the blacklist and the whitelist files
do
categorie=`echo $dir_categorie|cut -d "/" -f6`
categorie_type=`grep -A1 ^NAME:[$' '$'\t']*$categorie\$ $DIR_DG_BL/global_usage | grep ^DEFAULT_TYPE | cut -d":" -f2 | tr -d " \t"`
if [ "$categorie_type" == "white" ]
then
echo "$categorie" >> $WL_CATEGORIES_ENABLED
fi
echo "$dir_categorie" >> $BL_CATEGORIES
echo "$dir_categorie" >> $WL_CATEGORIES
done
rm -f $FILE_tmp
# Verify that the enabled categories are effectively in the BL (need after an update of the BL)
for ENABLE_CATEGORIE in `cat $BL_CATEGORIES_ENABLED`
do
ok=`grep /$ENABLE_CATEGORIE$ $BL_CATEGORIES|wc -l`
if [ $ok != "1" ]
then
$SED "/^$ENABLE_CATEGORIE$/d" $BL_CATEGORIES_ENABLED
fi
done
# Verify that the enabled categories are effectively in the WL (need after an update of the WL)
for ENABLE_CATEGORIE in `cat $WL_CATEGORIES_ENABLED`
do
ok=`grep /$ENABLE_CATEGORIE$ $WL_CATEGORIES|wc -l`
if [ $ok != "1" ]
then
$SED "/^$ENABLE_CATEGORIE$/d" $WL_CATEGORIES_ENABLED
fi
done
 
# Creation of Unbound and Iptables BL and WL
for LIST in $BL_CATEGORIES $WL_CATEGORIES # for each list (bl and wl)
do
for PATH_FILE in `cat $LIST` # for each category
do
DOMAIN=`basename $PATH_FILE`
echo -n "$DOMAIN, "
if [ ! -f $PATH_FILE/urls ] # create 'urls' file if it doesn't exist
then
touch $PATH_FILE/urls
chown e2guardian:apache $PATH_FILE/urls
fi
cp $PATH_FILE/domains $FILE_tmp
clean_split # clean ossi custom files & split them for unbound and for iptables
if [ "$LIST" == "$BL_CATEGORIES" ]
then
# adapt to the unbound syntax for the blacklist
$SED "s?.*?local-zone: & typetransparent\nlocal-zone-tag: & blacklist?g" $FILE_tmp
mv $FILE_tmp $DIR_DNS_BL/$DOMAIN.conf
mv $FILE_ip_tmp $DIR_IP_BL/$DOMAIN
else
# adapt to the unbound syntax for the whitelist
$SED "s?.*?local-zone: & transparent?g" $FILE_tmp
$SED "p; s? transparent? ipset?g" $FILE_tmp # duplicate lines to enable ipset module
mv $FILE_tmp $DIR_DNS_WL/$DOMAIN.conf
fi
done
done
echo
chown -R root:apache $BL_CATEGORIES $WL_CATEGORIES $BL_CATEGORIES_ENABLED $WL_CATEGORIES_ENABLED $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
chmod 770 $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
chmod -f 660 $BL_CATEGORIES $WL_CATEGORIES $BL_CATEGORIES_ENABLED $WL_CATEGORIES_ENABLED $DIR_DNS_BL/* $DIR_DNS_WL/* $DIR_IP_BL/* $DIR_IP_WL/*
rm -f $FILE_tmp $FILE_ip_tmp
rm -rf $DIR_tmp
;;
# reload when selected categories are changed or when ossi change his custom files
-reload | --reload)
# for E2Gardian
cat_choice
# for unbound (rehabilitated domain names)
rm -f $REHABILITATED_DNS_FILE
if [ "$(wc -w $DIR_DG_GROUP1/exceptionsitelist | cut -d " " -f1)" != "0" ]
then
touch $REHABILITATED_DNS_FILE
while read -r domain; do
[ -z "$domain" ] && continue
echo "local-zone: $domain typetransparent" >> $REHABILITATED_DNS_FILE
echo "local-zone-tag: $domain \"\"" >> $REHABILITATED_DNS_FILE
done < $DIR_DG_GROUP1/exceptionsitelist
fi
# adapt OSSI BL & WL custom files
for dir in $DIR_DNS_BL_ENABLED $DIR_DNS_WL_ENABLED $DIR_IP_BL_ENABLED $DIR_IP_WL_ENABLED $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
do
rm -f $dir/ossi*
done
find $DIR_DG_BL/ -type f -name domains | grep ossi- > $FILE_tmp # retrieve ossi directories name where a domain file exist
$SED "s?\/domains??g" $FILE_tmp # remove "/domains" suffix
for ossi_custom_dir in `cat $FILE_tmp` # create the blacklist and the whitelist files
do
chown -R root:apache $ossi_custom_dir
chmod 770 $ossi_custom_dir
ossi_categorie=`echo $ossi_custom_dir|cut -d "/" -f6`
short_categorie=`echo "$ossi_categorie" | cut -d"-" -f2`
if [ $short_categorie == "bl" ]
then
categorie_type="black"
else
categorie_type="white"
fi
$SED "s/\r//" $ossi_custom_dir/domains $ossi_custom_dir/urls # remove Windows <CR> from custom file
cp $ossi_custom_dir/domains $FILE_tmp
clean_split # clean ossi custom files & split them for unbound and for iptables
if [ $categorie_type == "white" ]
then
# adapt the file to the unbound syntax and enable it if needed
# for the WL
$SED "s?.*?local-zone: & transparent?g" $FILE_tmp
$SED "p; s? transparent? ipset?g" $FILE_tmp # duplicate lines to enable ipset module
mv $FILE_tmp $DIR_DNS_WL/$ossi_categorie.conf
mv $FILE_ip_tmp $DIR_IP_WL/$ossi_categorie
enabled=`grep ^$ossi_categorie$ $WL_CATEGORIES_ENABLED | wc -l`
if [ $enabled == "1" ]
then
$SED "/\/$ossi_categorie$/d" $WL_CATEGORIES
$SED "1i\/etc\/e2guardian\/lists\/blacklists\/$ossi_categorie" $WL_CATEGORIES
ln -sf $DIR_DNS_WL/$ossi_categorie.conf $DIR_DNS_WL_ENABLED/$ossi_categorie
ln -sf $DIR_IP_WL/$ossi_categorie $DIR_IP_WL_ENABLED/$ossi_categorie
fi
else
# for the BL
$SED "s?.*?local-zone: & typetransparent\nlocal-zone-tag: & blacklist?g" $FILE_tmp
mv $FILE_tmp $DIR_DNS_BL/$ossi_categorie.conf
mv $FILE_ip_tmp $DIR_IP_BL/$ossi_categorie
enabled=`grep ^$ossi_categorie$ $BL_CATEGORIES_ENABLED | wc -l`
if [ $enabled == "1" ]
then
$SED "/\/$ossi_categorie$/d" $BL_CATEGORIES
$SED "1i\/etc\/e2guardian\/lists\/blacklists\/$ossi_categorie" $BL_CATEGORIES
ln -sf $DIR_DNS_BL/$ossi_categorie.conf $DIR_DNS_BL_ENABLED/$ossi_categorie
ln -sf $DIR_IP_BL/$ossi_categorie $DIR_IP_BL_ENABLED/$ossi_categorie
fi
fi
done
for file in $BL_CATEGORIES $BL_CATEGORIES_ENABLED $WL_CATEGORIES $WL_CATEGORIES_ENABLED
do
sort +0.0 -0.2 $file -o $FILE_tmp
mv $FILE_tmp $file
chown root:apache $file
chmod 660 $file
done
chown -R root:apache $DIR_DNS_BL $DIR_DNS_WL $DIR_IP_BL $DIR_IP_WL
chmod 660 $DIR_DNS_BL/* $DIR_DNS_WL/* $DIR_IP_BL/* $DIR_IP_WL/*
if [ "$PARENT_SCRIPT" != "alcasar-conf.sh" ] # don't launch on install stage
then
/usr/bin/systemctl restart unbound-blacklist
/usr/bin/systemctl restart unbound-whitelist
/usr/bin/systemctl restart e2guardian
/usr/local/bin/alcasar-iptables.sh
fi
;;
*)
echo "Argument inconnu :$1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-conf.sh
0,0 → 1,524
#!/bin/bash
# $Id$
 
# alcasar-conf.sh
# by REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Ce script permet la mise à jour d'un ALCASAR
# - (alcasar-conf.sh -create) : création de l'archive des fichiers de configuration (/var/tmp/alcasar-conf.tar.gz)
# - (alcasar-conf.sh -load) : chargement de l'archive des fichiers de configuration. Le cas échéant, c'est ici qu'on met à jour les fichiers entre versions
# - (alcasar-conf.sh -apply) : application des directives du fichier de conf central "/usr/local/etc/alcasar.conf". Peut aussi être exploité à chaud après avoir changé des valeurs du fichier de conf.
# This script allows ALCASAR update
# - (alcasar-conf.sh -create) : create the configuration files backup (/var/tmp/alcasar-conf.tar.gz)
# - (alcasar-conf.sh -load) : load the backup of configuration files. If needed, it's here we update files between versions
# - (alcasar-conf.sh -load) : apply ALCASAR central configuration file "/usr/local/etc/alcasar.conf". Can be use after changes of conf file values.
 
DIR_UPDATE="/var/tmp/conf" # répertoire de stockage des fichier de conf pour une mise à jour
DIR_WEB="/var/www/html" # répertoire du centre de gestion
DIR_BIN="/usr/local/bin" # scripts directory
DIR_ETC="/usr/local/etc" # conf directory
DIR_E2G="/etc/e2guardian/lists" # Toulouse BL directory
DIR_BLACKLIST="$DIR_E2G/blacklists" # Toulouse BL directory
CONF_FILE="$DIR_ETC/alcasar.conf" # main alcasar conf file
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_USER=$(grep '^db_user=' $PASSWD_FILE | cut -d'=' -f 2-)
DB_PASS=$(grep '^db_password=' $PASSWD_FILE | cut -d'=' -f 2-)
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2` # EXTernal InterFace
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2` # INTernal InterFace
MTU=`grep ^PUBLIC_MTU= $CONF_FILE|cut -d"=" -f2`
DHCP_mode=`grep ^DHCP= $CONF_FILE|cut -d"=" -f2`
INT_DNS_mode=`grep ^INT_DNS_ACTIVE= $CONF_FILE|cut -d"=" -f2`
HOSTNAME=`grep ^HOSTNAME= $CONF_FILE|cut -d"=" -f2`
DOMAIN=`grep ^DOMAIN= $CONF_FILE|cut -d"=" -f2`
DOMAIN=${DOMAIN:=localdomain}
DNS1=`grep ^DNS1= $CONF_FILE | cut -d'=' -f2` # To configure WL domain names
HTTPS_LOGIN=`grep ^HTTPS_LOGIN= $CONF_FILE | cut -d'=' -f2`
SED="/bin/sed -i"
 
private_network_calc ()
{
PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP $PRIVATE_NETMASK |cut -d"=" -f2` # prefixe du réseau (ex. 24)
PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP $PRIVATE_NETMASK| cut -d"=" -f2` # @ réseau de consultation (ex.: 192.168.182.0)
PRIVATE_NETWORK_MASK=$PRIVATE_NETWORK/$PRIVATE_PREFIX # @ + masque du réseau de consult (192.168.182.0/24)
classe=$((PRIVATE_PREFIX/8)); classe_sup=`expr $classe + 1`; # classes de réseau (ex.: 2=classe B, 3=classe C)
PRIVATE_NETWORK_SHORT=`echo $PRIVATE_NETWORK | cut -d"." -f1-$classe`. # @ compatible hosts.allow et hosts.deny (ex.: 192.168.182.)
PRIVATE_BROADCAST=`/bin/ipcalc -b $PRIVATE_NETWORK_MASK | cut -d"=" -f2` # private network broadcast (ie.: 192.168.182.255)
private_broadcast_ending=`echo $PRIVATE_BROADCAST | cut -d"." -f$classe_sup` # last octet of LAN broadcast
private_ip_ending=`echo $PRIVATE_IP | cut -d"." -f4` # last octet of LAN address
PRIVATE_SECOND_IP=`echo $PRIVATE_IP | cut -d"." -f1-3`"."`expr $private_ip_ending + 1` # 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| sed 's/:/-/g'| awk '{print toupper($0)}'` # MAC address of INTIF
}
 
usage="Usage: alcasar-conf.sh {--create or -create} | {--load or -load} | {--apply or -apply}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
###################################################
## Create an archive conf file ##
###################################################
--create|-create)
[ -d $DIR_UPDATE ] && rm -rf $DIR_UPDATE
mkdir $DIR_UPDATE
# backup the users database (test to delete in future version)
$DIR_BIN/alcasar-mysql.sh --dump
cp /var/Save/base/"$(ls -1t /var/Save/base|head -1)" $DIR_UPDATE
# backup organism logo
cp -f $DIR_WEB/images/organisme.png $DIR_UPDATE
# backup E2D BL/WL custom files
mkdir $DIR_UPDATE/custom_bl
for i in urlregexplist exceptionsitelist bannedurllist
do
cp $DIR_E2G/group1/$i $DIR_UPDATE/custom_bl/
done
cp $DIR_E2G/common/exceptioniplist $DIR_UPDATE/custom_bl/
cp -rf $DIR_BLACKLIST/ossi-* $DIR_UPDATE/custom_bl/ 2>/dev/null
# backup conf files (main conf file, filtering, digest, etc.)
mkdir $DIR_UPDATE/etc/
cp -rf $DIR_ETC/* $DIR_UPDATE/etc/
cp -f /etc/hosts $DIR_UPDATE/etc/
# backup of the security certificates (server & CA)
cp -f /etc/pki/tls/certs/alcasar.crt* $DIR_UPDATE
cp -f /etc/pki/tls/private/alcasar.key* $DIR_UPDATE
[ -e /etc/pki/tls/private/alcasar.pem ] && cp -f /etc/pki/tls/private/alcasar.pem $DIR_UPDATE # since V3.3
cp -f /etc/pki/CA/alcasar-ca.crt $DIR_UPDATE
cp -f /etc/pki/CA/private/alcasar-ca.key $DIR_UPDATE
if [ -e /etc/pki/tls/certs/server-chain.pem ]; then
cp -f /etc/pki/tls/certs/server-chain.pem $DIR_UPDATE # autosigned and official if exist
else
cp -f /etc/pki/tls/certs/alcasar.crt $DIR_UPDATE/server-chain.pem
fi
# backup gammu conf file (if necessary)
SMS=`grep ^SMS= $CONF_FILE|cut -d"=" -f2`
if [ "$SMS" == "on" ]
then
cp -f /etc/gammurc $DIR_UPDATE
cp -f /etc/gammu_smsd_conf $DIR_UPDATE
fi
# archive file creation
cd /var/tmp || { echo "Unable to find /var/tmp directory"; }
tar -cf alcasar-conf.tar conf/
gzip -f alcasar-conf.tar
cp alcasar-conf.tar.gz /var/www/html/acc/backup/alcasar-conf.tar.gz
chown apache:apache /var/www/html/acc/backup/alcasar-conf.tar.gz
rm -rf $DIR_UPDATE
;;
 
###################################################
## Load an archive conf file ##
###################################################
--load|-load)
if [ ! -f /var/tmp/alcasar-conf.tar.gz ]; then
echo "Conf file not found (/var/tmp/alcasar-conf.tar.gz) !"
return 1
fi
CURRENT_DIR=`pwd` # install folder
cd /var/tmp
tar -xf alcasar-conf.tar.gz
# update alcasar.conf parameters
PREVIOUS_VERSION=`grep ^VERSION= $DIR_UPDATE/etc/alcasar.conf|cut -d"=" -f2`
MAJ_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f1`
MIN_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f2`
UPD_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f3|cut -c1`
for line in `cat $DIR_UPDATE/etc/alcasar.conf | grep "=" | grep -Ev "^#| |VERSION|INSTALL_DATE|PUBLIC|GW|EXTIF|INTIF"`
do
key=`echo $line | cut -d"=" -f1`
key=$key=
value=`echo $line|cut -d"=" -f2-`
if [ "$value" != "" ]
then
sed -i "s?^$key.*?$key$value?g" /usr/local/etc/alcasar.conf
fi
done
# lighttpd need a .pem certificate (aggregation with private key & server crt)
[ ! -f $DIR_UPDATE/alcasar.pem ] && (cat $DIR_UPDATE/alcasar.key; echo; cat $DIR_UPDATE/alcasar.crt) > $DIR_UPDATE/alcasar.pem
# Retrieve organism logo
[ -e $DIR_UPDATE/organisme.png ] && cp -f $DIR_UPDATE/organisme.png $DIR_WEB/images/
chown apache:apache $DIR_WEB/images/organisme.png $DIR_WEB/intercept.php
# Retrieve the security certificates (CA and server)
cp -f $DIR_UPDATE/alcasar-ca.crt /etc/pki/CA/
cp -f $DIR_UPDATE/alcasar-ca.key /etc/pki/CA/private/
cp -f $DIR_UPDATE/alcasar.crt /etc/pki/tls/certs/
cp -f $DIR_UPDATE/alcasar.key /etc/pki/tls/private/
cp -f $DIR_UPDATE/alcasar.pem /etc/pki/tls/private/
[ -e $DIR_UPDATE/server-chain.pem ] && cp -f $DIR_UPDATE/server-chain.pem /etc/pki/tls/certs/ # autosigned and official if exist
chmod 755 /etc/pki/
chown root:apache /etc/pki/CA; chmod 750 /etc/pki/CA
chown root:apache /etc/pki/CA/alcasar-ca.crt; chmod 640 /etc/pki/CA/alcasar-ca.crt
chown root:root /etc/pki/CA/private; chmod 700 /etc/pki/CA/private
chmod 600 /etc/pki/CA/private/*
chown -R root:apache /etc/pki/tls/private; chmod 750 /etc/pki/tls/private
chmod 640 /etc/pki/tls/private/*
chmod 644 /etc/pki/tls/certs/*
# Import of the users database
$DIR_BIN/alcasar-mysql.sh --import "$(ls $DIR_UPDATE/alcasar-users-database*)"
# Retrieve local parameters
[ -d $DIR_UPDATE/etc/digest ] && cp -rf $DIR_UPDATE/etc/digest $DIR_ETC/ # ACC accounts
[ -e $DIR_UPDATE/etc/alcasar-iptables-local.sh ] && cp -f $DIR_UPDATE/etc/alcasar-iptables-local.sh $DIR_ETC/ # local FW rules
[ -e $DIR_UPDATE/etc/alcasar-iptables-local-mac-filtered ] && cp -f $DIR_UPDATE/etc/alcasar-iptables-local-mac-filtered $DIR_ETC/ # blocked MAC addresses
[ -e $DIR_UPDATE/etc/alcasar-services ] && cp -f $DIR_UPDATE/etc/alcasar-services $DIR_ETC/ # protocols filtering for users (profil 3 : customized with ACC)
[ -e $DIR_UPDATE/etc/alcasar-uamdomain ] && cp -f $DIR_UPDATE/etc/alcasar-uamdomain $DIR_ETC/ # exception domain names
[ -e $DIR_UPDATE/etc/alcasar-uamallowed ] && cp -f $DIR_UPDATE/etc/alcasar-uamallowed $DIR_ETC/ # exception IP_addresses or network_IP_addresses
[ -e $DIR_UPDATE/etc/alcasar-ethers ] && cp -f $DIR_UPDATE/etc/alcasar-ethers $DIR_ETC/ # DHCP static hosts
[ -e $DIR_UPDATE/etc/alcasar-ethers-info ] && cp -f $DIR_UPDATE/etc/alcasar-ethers-info $DIR_ETC/ # DHCP static hosts information
[ -e $DIR_UPDATE/etc/hosts ] && cp -f $DIR_UPDATE/etc/hosts /etc/ # local host name resolution
[ -e $DIR_UPDATE/etc/alcasar-letsencrypt ] && cp -f $DIR_UPDATE/etc/alcasar-letsencrypt $DIR_ETC/ # Letsencrypt local conf
[ -d $DIR_UPDATE/etc/letsencrypt ] && cp -rf $DIR_UPDATE/etc/letsencrypt $DIR_ETC/ # Letsencrypt local conf files
[ -e $DIR_UPDATE/gammurc ] && cp -f $DIR_UPDATE/gammurc /etc/ # Gammu conf file
[ -e $DIR_UPDATE/gammu_smsd_conf ] && cp -f $DIR_UPDATE/gammu_smsd_conf /etc/ # Gammu_smsd conf file
# Retrieve BL/WL custom files
cp -f $DIR_UPDATE/custom_bl/exceptioniplist $DIR_E2G/common/
cp -f $DIR_UPDATE/custom_bl/exceptionsitelist $DIR_E2G/group1/
cp -f $DIR_UPDATE/custom_bl/urlregexplist $DIR_E2G/
cp -f $DIR_UPDATE/custom_bl/bannedurllist $DIR_E2G/group1/
cp -rf $DIR_UPDATE/custom_bl/ossi-* $DIR_BLACKLIST/ 2>/dev/null
chown -R e2guardian:apache $DIR_E2G
chmod -R g+rw $DIR_E2G
# Adapt DNS/URL filtering
PARENT_SCRIPT=`basename $0`
export PARENT_SCRIPT
$DIR_BIN/alcasar-bl.sh -cat_choice
$DIR_BIN/alcasar-bl.sh -reload
# admin profile update (admin + manager + backup)
$DIR_BIN/alcasar-profil.sh --list
# Apply changes between versions
## V5.5 --> V6.0
## remove dnsmasq service
[ -e /etc/dnsmasq-whitelist.conf ] && rm -f /etc/dnsmasq*
[ -e /etc/systemd/system/dnsmasq-whitelist.service ] && rm -f /etc/systemd/system/dnsmasq* && urpme dnsmasq
# Remove the update folder
rm -rf $DIR_UPDATE
;;
 
####################################################
## Configure ALCASAR according to alcasar.conf ##
####################################################
--apply|-apply)
PTN="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([012]?[0-9]|3[0-2])\b"
PRIVATE_IP_MASK=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
if ! echo $PRIVATE_IP_MASK | grep -q -E $PTN
then
echo "Syntax error for PRIVATE_IP_MASK ($PRIVATE_IP_MASK)"
exit 0
fi
PUBLIC_IP_MASK=`grep ^PUBLIC_IP= $CONF_FILE|cut -d"=" -f2`
PTN="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if [[ "$PUBLIC_IP_MASK" == "dhcp" ]]
then
PUBLIC_GATEWAY="dhcp"
DHCP_DNS_servers=`cat /var/lib/dhclient/dhclient--$EXTIF.lease |grep domain-name-servers|sed -n "1 p"| rev|cut -d" " -f1|rev|tr -d ';'`
DNS1=`echo $DHCP_DNS_servers | cut -d"," -f1`
DNS2=`echo $DHCP_DNS_servers | cut -d"," -f2`
else
if ! echo $PUBLIC_IP_MASK | grep -q -E $PTN
then
echo "Syntax error for PUBLIC_IP_MASK ($PUBLIC_IP_MASK)"
exit 0
fi
PUBLIC_IP=`echo $PUBLIC_IP_MASK | cut -d"/" -f1`
PUBLIC_NETMASK=`/bin/ipcalc -m $PUBLIC_IP_MASK | cut -d"=" -f2`
PUBLIC_GATEWAY=`grep ^GW= $CONF_FILE|cut -d"=" -f2`
if ! echo $PUBLIC_GATEWAY | grep -q -E $PTN
then
echo "Syntax error for the Gateway IP ($PUBLIC_GATEWAY)"
exit 0
fi
DNS1=`grep ^DNS1= $CONF_FILE|cut -d"=" -f2`
if ! echo $DNS1 | grep -q -E $PTN
then
echo "Syntax error for the IP address of the first DNS server ($DNS1)"
exit 0
fi
DNS2=`grep ^DNS2= $CONF_FILE|cut -d"=" -f2`
if ! echo $DNS2 | grep -q -E $PTN
then
echo "Syntax error for the IP address of the second DNS server ($DNS2)"
exit 0
fi
fi
PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`
PRIVATE_NETMASK=`/bin/ipcalc -m $PRIVATE_IP_MASK | cut -d"=" -f2`
private_network_calc
INSTALL_DATE=`grep ^INSTALL_DATE= $CONF_FILE|cut -d"=" -f2`
ORGANISME=`grep ^ORGANISM= $CONF_FILE|cut -d"=" -f2-`
BL_SAFESEARCH=`grep ^BL_SAFESEARCH= $CONF_FILE|cut -d"=" -f2`
WL_SAFESEARCH=`grep ^WL_SAFESEARCH= $CONF_FILE|cut -d"=" -f2`
BL_PUREIP=`grep ^BL_PUREIP= $CONF_FILE|cut -d"=" -f2`
DHCP_mode=`grep ^DHCP= $CONF_FILE|cut -d"=" -f2`
if [ "$PARENT_SCRIPT" != "alcasar.sh" ] # don't launch on install stage
then
if [ "$DHCP_mode" = "off" ] || [ "$DHCP_mode" = "Off" ] || [ "$DHCP_mode" = "OFF" ]
then
$DIR_BIN/alcasar-dhcp.sh --off
else
$DIR_BIN/alcasar-dhcp.sh --on
fi
# Set the local DNS (or not)
if [ "$INT_DNS_mode" = "on" ] || [ "$INT_DNS_mode" = "On" ] || [ "$INT_DNS_mode" = "ON" ]
then
$DIR_BIN/alcasar-dns-local.sh --on-without-restart
else
$DIR_BIN/alcasar-dns-local.sh --off-without-restart
fi
# Set the pure ip option (or not)
if [ "$BL_PUREIP" = "off" ] || [ "$BL_PUREIP" = "Off" ] || [ "$BL_PUREIP" = "OFF" ]
then
bl_filter_param+="--pureip_off"
else
bl_filter_param+="--pureip_on"
fi
# Set the safesearch options (or not)
bl_filter_param=""
if [ "$BL_SAFESEARCH" = "on" ] || [ "$BL_SAFESEARCH" = "On" ] || [ "$BL_SAFESEARCH" = "ON" ]
then
bl_filter_param+="--safesearch_on "
else
bl_filter_param+="--safesearch_off "
fi
$DIR_BIN/alcasar-url_filter_bl.sh $bl_filter_param
if [ "$WL_SAFESEARCH" = "on" ] || [ "$WL_SAFESEARCH" = "On" ] || [ "$WL_SAFESEARCH" = "ON" ]
then
$DIR_BIN/alcasar-url_filter_wl.sh --safesearch_on
else
$DIR_BIN/alcasar-url_filter_wl.sh --safesearch_off
fi
# Reload the local dns configuration
$DIR_BIN/alcasar-dns-local.sh --reload
# Logout everybody
$DIR_BIN/alcasar-logout.sh all
# Services stop
echo -n "Stop services : "
for i in ntpd e2guardian unbound unbound-whitelist unbound-blacklist unbound-blackhole chilli network lighttpd
do
/usr/bin/systemctl stop $i && echo -n "$i, "
done
echo
fi
# EXTIF config
if [ $PUBLIC_IP_MASK == "dhcp" ]
then
cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=dhcp
DNS1=127.0.0.1
PEERDNS=no
RESOLV_MODS=yes
ONBOOT=yes
METRIC=10
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
NOZEROCONF=yes
EOF
else # set the static configuration for EXTIF in multi-gw mode
$DIR_BIN/alcasar-network.sh --apply
fi
# INTIF config (for bypass mode only)
$SED "s?^IPADDR=.*?IPADDR=$PRIVATE_IP?" /etc/sysconfig/network-scripts/bypass-ifcfg-$INTIF
$SED "s?^NETMASK=.*?NETMASK=$PRIVATE_NETMASK?" /etc/sysconfig/network-scripts/bypass-ifcfg-$INTIF
# NTP server
$SED "/127.0.0.1/!s?^restrict.*?restrict $PRIVATE_NETWORK mask $PRIVATE_NETMASK nomodify notrap?g" /etc/ntp.conf
# host.allow
cat <<EOF > /etc/hosts.allow
ALL: LOCAL, 127.0.0.1, localhost, $PRIVATE_IP
sshd: ALL
ntpd: $PRIVATE_NETWORK_SHORT
EOF
# Set hostname
hostnamectl set-hostname $HOSTNAME.$DOMAIN
# /etc/hosts (retriving local hostnames)
cp /etc/hosts /tmp/hosts
echo "127.0.0.1 localhost" > /etc/hosts
echo "$PRIVATE_IP $HOSTNAME $HOSTNAME.$DOMAIN" >> /etc/hosts
while read -r line
do
if ! echo $line | grep -E -q "^([0-9\.\t ]+alcasar( |$)|127\.0\.0)"
then
echo $line >> /etc/hosts
fi
done < /tmp/hosts
rm -f /tmp/hosts
# MOTD
$SED "s@'https://\(.\+\)/acc'@'https://$HOSTNAME.$DOMAIN/acc'@" /etc/mageia-release
# Lighttpd
$SED "s?^server\.bind.*?server\.bind = \"$PRIVATE_IP\"?g" /etc/lighttpd/lighttpd.conf
$SED 's/^$SERVER\["socket"\] == ".*:443.*/$SERVER\["socket"\] == "'"$PRIVATE_IP"':443" {/g' /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf
$SED "s/^\([\t ]*\)var.server_name.*/\1var.server_name = \"$PRIVATE_IP\"/g" /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf
# FreeRADIUS
$SED "s?^nas1_name:.*?nas1_name: alcasar-$ORGANISME?g" /etc/freeradius-web/naslist.conf
$SED "s?^nas1_ip:.*?nas1_ip: $PRIVATE_IP?g" /etc/freeradius-web/naslist.conf
# CoovaChilli
$SED "s/^uamallowed.*/uamallowed\t$HOSTNAME,$HOSTNAME.$DOMAIN/g" /etc/chilli.conf
$SED "s/^locationname.*/locationname\t$HOSTNAME.$DOMAIN/g" /etc/chilli.conf
$SED "s/^domain.*/domain\t\t$DOMAIN/g" /etc/chilli.conf
[ "`grep ^HTTPS_LOGIN= $CONF_FILE | cut -d'=' -f2`" == "on" ] && chilli_login_protocol="https" || chilli_login_protocol="http"
$SED "s/^uamserver.*/uamserver\t$chilli_login_protocol:\/\/$HOSTNAME.$DOMAIN\/intercept.php/" /etc/chilli.conf
$SED "s/^radiusnasid.*/radiusnasid\t$HOSTNAME.$DOMAIN/g" /etc/chilli.conf
$SED "s?^net.*?net\t\t$PRIVATE_NETWORK_MASK?g" /etc/chilli.conf
$SED "s?^dns1.*?dns1\t\t$PRIVATE_IP?g" /etc/chilli.conf
$SED "s?^dns2.*?dns2\t\t$PRIVATE_IP?g" /etc/chilli.conf
$SED "s?^uamlisten.*?uamlisten\t$PRIVATE_IP?g" /etc/chilli.conf
PRIVATE_IP_HEXA=$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f1)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f2)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f3)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f4)")
$SED "s?^dhcpopt.*?dhcpopt\t\t2a04$PRIVATE_IP_HEXA?g" /etc/chilli.conf
# modify the DHCP static ip file. Reserve the second IP address for INTIF (the first one is for tun0). Keep previous entries
$SED "s?^$PRIVATE_MAC.*?$PRIVATE_MAC $PRIVATE_SECOND_IP?" $DIR_ETC/alcasar-ethers $DIR_ETC/alcasar-ethers-info
# unbound
# removing unbound configuration files
rm -f /etc/unbound/conf.d/{forward,blacklist,whitelist,blackhole}/iface.*
rm -f /etc/unbound/conf.d/common/forward-zone.conf
# Configuration file for the dns servers forward-zone
cat << EOF > /etc/unbound/conf.d/common/forward-zone.conf
forward-zone:
name: "."
forward-addr: $DNS1
forward-addr: $DNS2
EOF
# Configuration file for lo of forward
cat << EOF > /etc/unbound/conf.d/forward/iface.lo.conf
server:
interface: 127.0.0.1@53
access-control-view: 127.0.0.1/8 lo
view:
name: "lo"
local-data: "$HOSTNAME A 127.0.0.1"
local-data: "$HOSTNAME.$DOMAIN A 127.0.0.1"
local-data-ptr: "127.0.0.1 $HOSTNAME.$DOMAIN"
view-first: yes
EOF
# Configuration file for $INTIF of forward
cat << EOF > /etc/unbound/conf.d/forward/iface.${INTIF}.conf
server:
interface: ${PRIVATE_IP}@53
access-control-view: $PRIVATE_NETWORK_MASK $INTIF
view:
name: "$INTIF"
view-first: yes
EOF
# Configuration file for $INTIF of blacklist
cat << EOF > /etc/unbound/conf.d/blacklist/iface.${INTIF}.conf
server:
interface: ${PRIVATE_IP}@54
access-control: $PRIVATE_IP_MASK allow
access-control-tag: $PRIVATE_IP_MASK "blacklist"
access-control-tag-action: $PRIVATE_IP_MASK "blacklist" redirect
access-control-tag-data: $PRIVATE_IP_MASK "blacklist" "A $PRIVATE_IP"
EOF
# Configuration file for $INTIF of whitelist
cat << EOF > /etc/unbound/conf.d/whitelist/iface.${INTIF}.conf
server:
interface: ${PRIVATE_IP}@55
access-control: $PRIVATE_IP_MASK allow
access-control-tag: $PRIVATE_IP_MASK "whitelist"
access-control-tag-action: $PRIVATE_IP_MASK "whitelist" redirect
access-control-tag-data: $PRIVATE_IP_MASK "whitelist" "A $PRIVATE_IP"
EOF
# Configuration file for $INTIF of blackhole unbound
cat << EOF > /etc/unbound/conf.d/blackhole/iface.${INTIF}.conf
server:
interface: ${PRIVATE_IP}@56
access-control-view: $PRIVATE_NETWORK_MASK $INTIF
view:
name: "$INTIF"
local-zone: "." redirect
local-data: ". A $PRIVATE_IP"
EOF
 
# dhcpd
cat <<EOF > /etc/dhcpd.conf
ddns-update-style none;
subnet $PRIVATE_NETWORK netmask $PRIVATE_NETMASK {
option routers $PRIVATE_IP;
option subnet-mask $PRIVATE_NETMASK;
option domain-name-servers $PRIVATE_IP;
range dynamic-bootp $PRIVATE_SECOND_IP $PRIVATE_LAST_IP;
default-lease-time 21600;
max-lease-time 43200;
}
EOF
$DIR_BIN/alcasar-dns-local.sh -hosts_to_unbound # add local name resolution to unbound (forward & blackhole)
# E2guardian
$SED "s?^filterip.*?filterip = $PRIVATE_IP?g" /etc/e2guardian/e2guardian.conf
$SED "s?\/\/[a-z.]*\/?\/\/$HOSTNAME.$DOMAIN\/?g" /usr/share/e2guardian/languages/french/alcasar-e2g.html
$SED "s?\/\/[a-z.]*\/?\/\/$HOSTNAME.$DOMAIN\/?g" /usr/share/e2guardian/languages/ukenglish/alcasar-e2g.html
# Prompts
$SED "s?^ORGANISME.*?ORGANISME=$ORGANISME?g" /etc/bashrc
# sudoers
$SED "s?^Host_Alias.*?Host_Alias LAN_ORG=$PRIVATE_NETWORK/$PRIVATE_NETMASK,localhost #réseau de l'organisme?g" /etc/sudoers
# gammu-smsd
$SED "s?^user =.*?user = $DB_USER?g" /etc/gammu_smsd_conf
$SED "s?^password =.*?password = $DB_PASS?g" /etc/gammu_smsd_conf
# HTTPS login (Y/n)
if [ "$HTTPS_LOGIN" = "on" ] || [ "$HTTPS_LOGIN" = "On" ] || [ "$HTTPS_LOGIN" = "ON" ]
then
$SED "s?^HTTPS_LOGIN=.*?HTTPS_LOGIN=on?" $CONF_FILE
$SED "s?^HTTPS_CHILLI=.*?HTTPS_CHILLI=on?" $CONF_FILE
$SED "s?^uamserver.*?uamserver\thttps://$HOSTNAME.$DOMAIN/intercept.php?" /etc/chilli.conf
$SED "s?^#redirssl.*?redirssl?" /etc/chilli.conf
$SED "s?^#uamuissl.*?uamuissl?" /etc/chilli.conf
rm -f /etc/lighttpd/vhosts.d/alcasar.conf
ln -s /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar.conf
else
$SED "s?^HTTPS_LOGIN=.*?HTTPS_LOGIN=off?" $CONF_FILE
$SED "s?^HTTPS_CHILLI=.*?HTTPS_CHILLI=off?" $CONF_FILE
$SED "s?^uamserver.*?uamserver\thttp://$HOSTNAME.$DOMAIN/intercept.php?" /etc/chilli.conf
$SED "s?^redirssl.*?#&?" /etc/chilli.conf
$SED "s?^uamuissl.*?#&?" /etc/chilli.conf
rm -f /etc/lighttpd/vhosts.d/alcasar.conf
ln -s /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf /etc/lighttpd/vhosts.d/alcasar.conf
fi
# Services start
if [ "$PARENT_SCRIPT" != "alcasar.sh" ] # don't launch on install stage
then
/usr/bin/systemctl start network && echo -n "Start service : network" && sleep 1
$DIR_BIN/alcasar-dhcp.sh -$DHCP_mode && echo -n ", chilli" # apply DHCP mode and start CoovaChilli
for i in unbound unbound-blackhole ntpd
do
sleep 1
/usr/bin/systemctl start $i && echo -n ", $i"
done
$DIR_BIN/alcasar-bl.sh -reload && echo -n ", unbound-blacklist, unbound-whitelist, e2guardian, iptables"
/usr/bin/systemctl restart lighttpd && echo -n ", lighttpd"
fi
# Email user registration
$DIR_BIN/alcasar-mail-install.sh
# Start / Stop LDAP authentification
if [ "$PARENT_SCRIPT" != "alcasar.sh" ] # don't launch on install stage
then
LDAP_mode=`grep ^LDAP= $CONF_FILE|cut -d"=" -f2`
if [ $LDAP_mode = "on" ]
then
$DIR_BIN/alcasar-ldap.sh --on
else
$DIR_BIN/alcasar-ldap.sh --off
fi
fi
# Start / Stop Gammu-smsd (SMS)
if [ "$PARENT_SCRIPT" != "alcasar.sh" ] # don't launch on install stage
then
SMS_mode=`grep ^SMS= $CONF_FILE|cut -d"=" -f2`
if [ $SMS_mode = "on" ]
then
$DIR_BIN/alcasar-sms.sh --start
fi
fi
echo
;;
*)
echo "Argument inconnu : $1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-iptables.sh
0,0 → 1,588
#!/bin/bash
# $Id$
# Script de mise en place des regles du parefeu d'Alcasar (mode normal)
# This script writes the netfilter rules for ALCASAR
# Rexy - 3abtux - CPN
#
# Reminders
# There are four channels for log :
# 1 tracability of the consultation equipment with The 'Netflow' kernel module (iptables target = NETFLOW);
# 2 protection of ALCASAR with the Ulog group 1 (default group)
# 3 SSH on ALCASAR with the Ulog group 2;
# 4 extern access attempts on ALCASAR with the Ulog group 3.
# The bootps/dhcp (67) port is always open on tun0/INTIF by coova
CONF_FILE="/usr/local/etc/alcasar.conf"
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2` # EXTernal InterFace
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2` # INTernal InterFace
TUNIF="tun0" # listen device for chilli daemon
private_ip_mask=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
private_ip_mask=${private_ip_mask:=192.168.182.1/24}
PRIVATE_IP=`echo $private_ip_mask | cut -d"/" -f1` # ALCASAR LAN IP address
private_network=`/bin/ipcalc -n $private_ip_mask|cut -d"=" -f2` # LAN IP address (ie.: 192.168.182.0)
private_prefix=`/bin/ipcalc -p $private_ip_mask|cut -d"=" -f2` # LAN prefix (ie. 24)
PRIVATE_NETWORK_MASK=$private_network/$private_prefix # LAN IP address + prefix (192.168.182.0/24)
public_ip_mask=`grep ^PUBLIC_IP= $CONF_FILE|cut -d"=" -f2` # ALCASAR WAN IP address
dhcp_on_extif="off"
if [[ "$public_ip_mask" == "dhcp" ]]
then
dhcp_on_extif="on"
PTN="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([012]?[0-9]|3[0-2])\b"
public_ip_mask=`ip addr show $EXTIF | grep -o -E $PTN`
fi
PUBLIC_IP=`echo $public_ip_mask | cut -d"/" -f1`
dns1=`grep ^DNS1= $CONF_FILE|cut -d"=" -f2`
dns2=`grep ^DNS2= $CONF_FILE|cut -d"=" -f2`
dns1=${dns1:=208.67.220.220}
dns2=${dns2:=208.67.222.222}
DNSSERVERS="$dns1,$dns2" # first and second public DNS servers
INT_DNS_IP=`grep INT_DNS_IP $CONF_FILE|cut -d"=" -f2` # Adresse du serveur DNS interne
INT_DNS_ACTIVE=`grep INT_DNS_ACTIVE $CONF_FILE|cut -d"=" -f2` # Activation de la redirection DNS interne
BL_IP_CAT="/usr/local/share/iptables-bl-enabled" # categories files of the BlackListed IP
WL_IP_CAT="/usr/local/share/iptables-wl-enabled" # categories files of the WhiteListed IP
TMP_users_set_save="/tmp/users_set_save" # tmp file for backup users set
TMP_set_save="/tmp/ipset_save" # tmp file for blacklist and whitelist creation
TMP_ip_gw_save="/tmp/ipset_ip_gw_save" # tmp file for already connected ips
SSH_LAN=`grep ^SSH_LAN= $CONF_FILE|cut -d"=" -f2` # SSH LAN port
SSH_LAN=${SSH_LAN:=0}
SSH_WAN=`grep ^SSH_WAN= $CONF_FILE|cut -d"=" -f2` # SSH WAN port
SSH_WAN=${SSH_WAN:=0}
SSH_WAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f2`
SSH_WAN_ADMIN_FROM=${SSH_WAN_ADMIN_FROM:="0.0.0.0"}
SSH_WAN_ADMIN_FROM=$([ "$SSH_WAN_ADMIN_FROM" == "0.0.0.0" ] && echo "0.0.0.0/0" || echo "$SSH_WAN_ADMIN_FROM" )
SSH_LAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f1`
SSH_LAN_ADMIN_FROM=${SSH_LAN_ADMIN_FROM:="0.0.0.0"}
SSH_LAN_ADMIN_FROM=$([ "$SSH_LAN_ADMIN_FROM" == "0.0.0.0" ] && echo "$PRIVATE_NETWORK_MASK" || echo "$SSH_LAN_ADMIN_FROM" )
IPTABLES="/sbin/iptables"
REHABILITED_IP="/etc/e2guardian/lists/common/exceptioniplist"
ALLOWED_SITES="/usr/local/etc/alcasar-site-direct" # WEB Sites allowed for all (no av and no filtering for av_bl users)
MULTIWAN=`grep ^MULTIWAN $CONF_FILE|cut -d"=" -f2`
PROXY=`grep ^PROXY= $CONF_FILE|cut -d"=" -f2`
PROXY_IP=`grep ^PROXY_IP= $CONF_FILE|cut -d"=" -f2`
nb_gw=`grep ^WAN $CONF_FILE|wc -l`
interlan=`grep ^INTERLAN= $CONF_FILE|cut -d"=" -f2`
interlan=${interlan:=off}
 
# Allow requests to internal DNS if activated
if [ "$INT_DNS_ACTIVE" = "on" ]
then
DNSSERVERS="$DNSSERVERS,$INT_DNS_IP"
fi
 
#ipset name list for load_balancing
gw_list="gw0"
if [ "$MULTIWAN" == "on" ] || [ "$MULTIWAN" == "On" ]; then
for ((i=1 ; i<=$nb_gw ; i++)); do
gw_list="${gw_list} gw$i"
done
fi
 
# Sauvegarde des SET des utilisateurs connectés si ils existent
# Saving SET of connected users if it exists
ipset list not_filtered 1>/dev/null 2>&1
if [ $? -eq 0 ];
then
ipset save not_filtered > $TMP_users_set_save
ipset save av >> $TMP_users_set_save
ipset save av_bl >> $TMP_users_set_save
ipset save av_wl >> $TMP_users_set_save
ipset save proto_0 >> $TMP_users_set_save
ipset save proto_1 >> $TMP_users_set_save
ipset save proto_2 >> $TMP_users_set_save
ipset save proto_3 >> $TMP_users_set_save
fi
 
# Sauvegarde de la liste de toutes les IP déjà connectées pour les réintégrer dans le load balancing
# Saving all of the already connected IP in order to put them back in the load balancing after
if [ ! -f $TMP_ip_gw_save ];then
# Save only if alcasar-network.sh --save has not been executed before
for i in $gw_list;do
ipset list $i 1>/dev/null 2>&1
if [ $? -eq 0 ]
then
# the cut -d":" -f5 deletes all the lines with a :, i.e all the lines execpt the members
ipset list $i | cut -d":" -f5 | sed '/^[[:space:]]*$/d' >> $TMP_ip_gw_save
fi
done
fi
 
# Chargement de la sonde NetFlow (module noyau ipt_NETFLOW)
# loading of NetFlow probe (ipt_NETFLOW kernel module)
modprobe ipt_NETFLOW destination=127.0.0.1:2055
 
# Effacement des règles existantes
# Flush all existing rules
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F
$IPTABLES -F INPUT
$IPTABLES -F FORWARD
$IPTABLES -F OUTPUT
 
# Suppression des chaines utilisateurs sur les tables filter et nat
# Flush non default rules on filter and nat tables
$IPTABLES -X
$IPTABLES -t nat -X
 
# Stratégies par défaut
# Default policies
$IPTABLES -P INPUT DROP
$IPTABLES -P FORWARD DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -t nat -P PREROUTING ACCEPT
$IPTABLES -t nat -P POSTROUTING ACCEPT
$IPTABLES -t nat -P OUTPUT ACCEPT
 
#############################
# IPSET #
#############################
# destruction de tous les SET
# destroy all SET
ipset flush
ipset destroy
 
###### BL set ###########
# Calcul de la taille / Compute the length
bl_set_length=$(wc -l $BL_IP_CAT/* | awk '{print $1}' | tail -n 1)
# Chargement / loading
echo "create bl_ip_blocked hash:net family inet hashsize 1024 maxelem $bl_set_length" > $TMP_set_save
for category in `ls -1 $BL_IP_CAT | cut -d '@' -f1`
do
cat $BL_IP_CAT/$category >> $TMP_set_save
done
ipset -! restore < $TMP_set_save
rm -f $TMP_set_save
# Suppression des ip réhabilitées / Removing of rehabilitated ip
for ip in $(cat $REHABILITED_IP)
do
ipset -q del bl_ip_blocked $ip
done
 
# ipset for exception web sites (usefull for filtered users = av_bl)
ipset create site_direct hash:net hashsize 1024
for site in $(cat $ALLOWED_SITES)
do
ipset add site_direct $site
done
 
###### WL set ###########
# taille fixe, car peuplé par unbound / fixe length due to unbound dynamic loading
wl_set_length=65536
# Chargement Loading
echo "create wl_ip_allowed hash:net family inet hashsize 1024 maxelem $wl_set_length" > $TMP_set_save
#get ip-wl files from ACC
for category in `ls -1 $WL_IP_CAT |cut -d '@' -f1`
do
cat $WL_IP_CAT/$category >> $TMP_set_save
done
ipset -! restore < $TMP_set_save
rm -f $TMP_set_save
 
# Restoration des SET des utilisateurs connectés si ils existent sinon création des SET
# Restoring the connected users SETs if available, otherwise creating SETs
if [ -e $TMP_users_set_save ];
then
ipset -! restore < $TMP_users_set_save
rm -f $TMP_users_set_save
else
ipset create not_filtered hash:ip hashsize 1024
ipset create av hash:ip hashsize 1024
ipset create av_bl hash:ip hashsize 1024
ipset create av_wl hash:ip hashsize 1024
# pour les filtrages de protocole par utilisateur / For network protocols filtering by user
ipset create proto_0 hash:ip hashsize 1024
ipset create proto_1 hash:ip hashsize 1024
ipset create proto_2 hash:ip hashsize 1024
ipset create proto_3 hash:ip hashsize 1024
fi
 
#ipsets for load balancing
for i in $gw_list; do
ipset create $i hash:ip
done
cat $TMP_ip_gw_save | while read ip; do
gw_min="gw0"
weight=`grep ^PUBLIC_WEIGHT= $CONF_FILE | cut -d"=" -f2`
already=`ipset list $gw_min | grep Number\ of\ entries: | cut -d":" -f2`
#The *1000 is here to avoid working on floats in bash
gw_min_value=$((1000 * $already / $weight))
i=1
for gw in $gw_list;do
if [ "$gw" != "gw0" ]; then
weight=`grep ^WAN$i= $CONF_FILE | awk -F'"' '{ print $2 }' | awk -F ',' '{ print $2 }'`
already=`ipset list $gw | grep Number\ of\ entries: | cut -d":" -f2`
value=$((1000 * $already / $weight))
if [ $value -lt $gw_min_value ]
then
gw_min_value=$value
gw_min=$gw
fi
i=$(($i+1))
fi
done
ipset add $gw_min $ip
done
rm -f $TMP_ip_gw_save
 
#############################
# PREROUTING #
#############################
# Marquage (et journalisation) des paquets qui tentent d'accéder directement aux ports d'écoute du proxy HTTP/HTTPS (E2Guardian) pour pouvoir les rejeter en INPUT
# Mark (and log) the direct attempts to E2guardian listen ports in order to REJECT them in INPUT rules
# 8080 = ipset av_bl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8080 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8080 -j MARK --set-mark 1
# 8081 = ipset av_wl + av (to be redefine)
$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8081 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8081 -j MARK --set-mark 2
# 8443 = tranparent HTTPS for ipsets av_bl + av_wl + av (future version)
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8443 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
#$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8443 -j MARK --set-mark 6
 
# Marquage des paquets qui tentent d'accéder directement aux ports d'écoute DNS (UNBOUND) pour pouvoir les rejeter en INPUT
# Mark the direct attempts to DNS ports (UNBOUND) in order to REJECT them in INPUT rules
# 54 = ipset av_bl
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 54 -j MARK --set-mark 3
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 54 -j MARK --set-mark 3
# 55 = ipset av_wl
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 55 -j MARK --set-mark 4
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 55 -j MARK --set-mark 4
# 56 = blackall
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 56 -j MARK --set-mark 5
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 56 -j MARK --set-mark 5
 
# redirection DNS des usagers
# users DNS redirection
# 54 = ipset av_bl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -p udp --dport domain -j REDIRECT --to-port 54
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -p tcp --dport domain -j REDIRECT --to-port 54
# 55 = ipset av_wl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -p udp --dport domain -j REDIRECT --to-port 55
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -p tcp --dport domain -j REDIRECT --to-port 55
# 53 = all other users
$IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p udp --dport domain -j REDIRECT --to-port 53
$IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p tcp --dport domain -j REDIRECT --to-port 53
 
# Redirection HTTP des usagers 'av_bl' cherchant à joindre les IP de la blacklist vers ALCASAR (page 'accès interdit')
# Redirect HTTP of 'av_bl' users who want blacklist IP to ALCASAR ('access denied' page)
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p tcp --dport http -j REDIRECT --to-port 80
 
# Redirection HTTP des usagers 'av_wl' cherchant à joindre les IP qui ne sont pas dans la WL vers ALCASAR (page 'accès interdit')
# Redirect HTTP of 'av_wl' users who want IP not in the WL to ALCASAR ('access denied' page)
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -m set ! --match-set wl_ip_allowed dst -p tcp --dport http -j REDIRECT --to-port 80
 
# Journalisation des usagers "av_bl + av_wl + av" (paquets SYN uniquement). Les autres protocoles sont journalisés en FORWARD par netflow.
# accounting of "av_bl + av_wl + av" users (only syn packets). Other protocols are logged in FORWARD by netflow
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "
 
# Redirection des requêtes HTTP des usagers "av_bl + av_wl + av" vers E2guardian
# Redirect outbound "av_bl + av_wl +av" users HTTP requests to E2guardian
# 8080 = ipset av_bl
#$IPTABLES -A PREROUTING -t mangle -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP -p tcp --dport http -j MARK --set-mark 200
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP -p tcp --dport http -j REDIRECT --to-port 8080
# 8081 = ipset av_wl & av
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src ! -d $PRIVATE_IP -p tcp --dport http -j REDIRECT --to-port 8081
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src ! -d $PRIVATE_IP -p tcp --dport http -j REDIRECT --to-port 8081
 
# Redirection des requêtes HTTPS sortantes des usagers av_bl + av_wl + av vers E2Guardian (in a future version - don't forget to set E2guardian as a tranparent HTTPS proxy)
# Redirect outbound HTTPS requests of av_bl + av_wl + av users to E2Guardian
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP -p tcp --dport https -j REDIRECT --to-port 8443
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP -p tcp --dport https -j REDIRECT --to-port 8443
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP -p tcp --dport https -j REDIRECT --to-port 8443
 
# Redirection des requêtes NTP vers le serveur NTP local
# Redirect NTP request in local NTP server
$IPTABLES -A PREROUTING -t nat -i $TUNIF -s $PRIVATE_NETWORK_MASK ! -d $PRIVATE_IP -p udp --dport ntp -j REDIRECT --to-port 123
 
#Récupération de la marque associée à une gw pour chaque connection
$IPTABLES -A PREROUTING -t mangle -j CONNMARK --restore-mark
 
if [ "$PROXY" == "on" ] || [ "$PROXY" == "On" ];then
$IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p tcp -m multiport --dports http,https -j DNAT --to-destination $PROXY_IP
fi
 
#Marquage pour le load balancing
if [ "$MULTIWAN" == "on" ] || [ "$MULTIWAN" == "On" ]; then
temp_index=200
for i in $gw_list; do
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -m set --match-set $i src -j MARK --set-mark $temp_index
temp_index=$(($temp_index+1))
done
fi
 
#############################
# INPUT #
#############################
# Tout passe sur loopback
# accept all on loopback
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A OUTPUT -o lo -j ACCEPT
 
# Rejet des demandes de connexions non conformes (FIN-URG-PUSH, XMAS, NullScan, SYN-RST et NEW not SYN)
# Drop non standard connexions (FIN-URG-PUSH, XMAS, NullScan, SYN-RST and NEW not SYN)
$IPTABLES -A INPUT -p tcp --tcp-flags FIN,URG,PSH FIN,URG,PSH -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
$IPTABLES -A INPUT -p tcp -m tcp ! --syn -m conntrack --ctstate NEW -j DROP
 
# Si configuré, on autorise les réponses DHCP sur EXTIF
# If configured, DHCP responses are allowed on EXTIF
if [[ "$dhcp_on_extif" == "on" ]]
then
$IPTABLES -A INPUT -i $EXTIF -p tcp --dport 68 -j ACCEPT
$IPTABLES -A INPUT -i $EXTIF -p udp --dport 68 -j ACCEPT
fi
 
# On rejette les trame en broadcast et en multicast sur EXTIF (évite leur journalisation)
# Drop broadcast & multicast on EXTIF to avoid log
$IPTABLES -A INPUT -m addrtype --dst-type BROADCAST,MULTICAST -j DROP
 
# On autorise les retours de connexions légitimes par INPUT
# Conntrack on INPUT
$IPTABLES -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
 
# On interdit les connexions directes aux ports d'écoute d'E2Guardian. Les packets concernés ont été marqués et loggués dans la table mangle (PREROUTING)
# Deny direct connections on E2Guardian listen ports. The concerned paquets have been marked and logged in mangle table (PREROUTING)
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8080 -m mark --mark 1 -j REJECT --reject-with tcp-reset # av_bl
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8081 -m mark --mark 2 -j REJECT --reject-with tcp-reset # av_wl + av
#$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8443 -m mark --mark 6 -j REJECT --reject-with tcp-reset # av_bl + av_wl + av (future version)
 
# On autorise les connexions HTTP/HTTPS légitimes vers E2Guardian
# Allow HTTP connections to E2Guardian
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8080 -m conntrack --ctstate NEW --syn -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8081 -m conntrack --ctstate NEW --syn -j ACCEPT
#$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8443 -m conntrack --ctstate NEW --syn -j ACCEPT # (future version)
 
# On interdit les connexions directes aux ports d'écoupe DNS (UNBOUND). Les packets concernés ont été marqués dans la table mangle (PREROUTING)
# Deny direct connections to DNS ports (UNBOUND). The concerned paquets are marked in mangle table (PREROUTING)
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 54 -m mark --mark 3 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 54 -m mark --mark 3 -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 55 -m mark --mark 4 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 55 -m mark --mark 4 -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 56 -m mark --mark 5 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 56 -m mark --mark 5 -j REJECT --reject-with tcp-reset
 
# On autorise les connexion DNS légitime
# Allow DNS connections
# ipset = av_bl
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 54 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 54 -j ACCEPT
# ipset = av_wl
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 55 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 55 -j ACCEPT
# blackall
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 56 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 56 -j ACCEPT
 
# On accepte l'accès aux services internes
# Internal services access
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport domain -j ACCEPT # DNS
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport domain -j ACCEPT # DNS
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 8 -j ACCEPT # Réponse ping # ping responce
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 0 -j ACCEPT # Requête ping # ping request
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport https -j ACCEPT # Pages d'authentification et MCC # authentication pages and MCC
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport http -j ACCEPT # Page d'avertissement filtrage # Filtering warning pages
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 3990:3991 -j ACCEPT # Requêtes de deconnexion usagers # Users logout requests
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport ntp -j ACCEPT # Serveur local de temps # local time server
 
# Accès au serveur SSHD si activé en LAN et WAN
# SSHD server access in LAN and WAN if enabled
if [ $SSH_LAN -gt 0 ]
then
$IPTABLES -A INPUT -i $TUNIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -m conntrack --ctstate NEW -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-LAN -- ACCEPT"
$IPTABLES -A INPUT -i $TUNIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -j ACCEPT
fi
if [ $SSH_WAN -gt 0 ]
then
$IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -m conntrack --ctstate NEW --syn -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-WAN -- ACCEPT"
$IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -j ACCEPT
fi
 
# Insertion de règles locales
# Here, we add local rules (i.e. VPN from Internet)
if [ -f /usr/local/etc/alcasar-iptables-local.sh ]; then
. /usr/local/etc/alcasar-iptables-local.sh
fi
 
# Journalisation et rejet des connexions (autres que celles autorisées) effectuées depuis le LAN
# Deny and log on INPUT from the LAN
$IPTABLES -A INPUT -i $TUNIF -m conntrack --ctstate NEW -j NFLOG --nflog-group 3 --nflog-prefix "RULE rej-int -- REJECT "
$IPTABLES -A INPUT -i $TUNIF -p tcp -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp -j REJECT --reject-with icmp-port-unreachable
 
# Interdiction d'accès à INTIF (n'est utile que lorsque chilli est arrêté).
# Reject INTIF access (only when chilli is down)
$IPTABLES -A INPUT -i $INTIF -j NFLOG --nflog-group 3 --nflog-prefix "RULE Protect1 -- REJECT "
$IPTABLES -A INPUT -i $INTIF -j REJECT
 
# Journalisation et rejet des connexions initiées depuis le réseau extérieur (test des effets du paramètre --limit en cours)
# On EXTIF, the access attempts are log in channel 2 (we should test --limit option to avoid deny of service)
$IPTABLES -A INPUT -i $EXTIF -m conntrack --ctstate NEW -j NFLOG --nflog-group 3 --nflog-threshold 10 --nflog-prefix "RULE rej-ext -- DROP"
 
#############################
# FORWARD #
#############################
 
# Blocage des IPs du SET bl_ip_blocked pour le SET av_bl
# Deny IPs of the SET bl_ip_blocked for the set av_bl
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p icmp -j REJECT --reject-with icmp-host-prohibited
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p udp -j REJECT --reject-with icmp-host-prohibited
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p tcp -j REJECT --reject-with tcp-reset
 
# Active le suivi de session
# Allow Conntrack
$IPTABLES -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
 
# Compute uamallowed IP (ie : IP address of equipments connected between ALCASAR and router like DMZ, own servers, etc.)
nb_uamallowed=`wc -l /usr/local/etc/alcasar-uamallowed | cut -d" " -f1`
if [ $nb_uamallowed != "0" ]
then
while read ip_allowed_line
do
ip_allowed=`echo $ip_allowed_line|cut -d"\"" -f2`
$IPTABLES -A FORWARD -i $TUNIF -d $ip_allowed -m conntrack --ctstate NEW -j NETFLOW
$IPTABLES -A FORWARD -i $TUNIF -d $ip_allowed -m conntrack --ctstate NEW -j ACCEPT
done < /usr/local/etc/alcasar-uamallowed
fi
 
# filtrage protocole par utilisateur (profile 1 : http, https)
# protocols filtering for users (profil 1 : http, https)
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_1 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports http,https -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_1 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports http,https -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable
 
# filtrage protocole par utilisateur (profile 2 : http https smtp pop3 pop3s imap imaps ftp sftp ssh)
# protocols filtering for users (profil 2 : http https smtp pop3 pop3s imap imaps ftp sftp ssh)
 
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_2 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports smtp,http,https,pop3,pop3s,imap,imaps,ftp,ftp-data,sftp,ssh -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_2 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports smtp,http,https,pop3,pop3s,imap,imaps,ftp,ftp-data,sftp,ssh -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable
 
# filtrage protocole par utilisateur (profile 3 : personnalisable via l'ACC)
# protocols filtering for users (profil 3 : customized with ACC)
custom_tcp_protocols_list='';custom_udp_protocols_list=''
while read svc_line
do
svc_on=`echo $svc_line|cut -b1`
if [ $svc_on != "#" ]
then
svc_name=`echo $svc_line|cut -d" " -f1`
svc_port=`echo $svc_line|cut -d" " -f2`
if [ $svc_name = "icmp" ]
then
svc_icmp="on"
else
if [ "$custom_tcp_protocols_list" == "" ]
then
custom_tcp_protocols_list=$svc_port
else
custom_tcp_protocols_list=`echo $custom_tcp_protocols_list","$svc_port`
fi
udp_svc=`grep -E "[[:space:]]$svc_port/udp" /etc/services|wc -l`
if [ $udp_svc = "1" ] # udp service exist
then
if [ "$custom_udp_protocols_list" == "" ]
then
custom_udp_protocols_list=$svc_port
else
custom_udp_protocols_list=`echo $custom_udp_protocols_list","$svc_port`
fi
fi
fi
fi
done < /usr/local/etc/alcasar-services
if [ "$custom_tcp_protocols_list" == "" ]
then
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -j REJECT
else
if [ "$svc_icmp" != "on" ]
then
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p icmp -j REJECT --reject-with icmp-proto-unreachable
fi
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports $custom_tcp_protocols_list -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports $custom_udp_protocols_list -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable
fi
 
# On autorise (ou pas) les utilisateurs à accéder au réseau situé entre ALCASAR et le routeur Internet
# Users are allowed (or not allowed) to access the network between ALCASAR and the Internet router
if [ "$interlan" != "on" ]
then
$IPTABLES -A FORWARD -i $TUNIF -d $public_ip_mask -j DROP
fi
 
# Blocage des usagers 'av_wl' cherchant à joindre les IP qui ne sont pas dans la WL
# Block 'av_wl' users who want IP not in the WL
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_wl src -m set ! --match-set wl_ip_allowed dst -j DROP
 
# journalisation et autorisation des connections sortant du LAN
# Allow forward connections with log
$IPTABLES -A FORWARD -i $TUNIF -s $PRIVATE_NETWORK_MASK -m conntrack --ctstate NEW -j NETFLOW
$IPTABLES -A FORWARD -i $TUNIF -s $PRIVATE_NETWORK_MASK -m conntrack --ctstate NEW -j ACCEPT
 
#############################
# OUTPUT #
#############################
# On laisse tout sortir sur la carte interne (voir les règles suivantes pour la carte externe)
# We let everything out on INTIF (see following rules for the EXTIF)
$IPTABLES -A OUTPUT ! -o $EXTIF -j ACCEPT
 
# Si configuré, on autorise les requêtes DHCP sur EXTIF
# Allow DHCP requests on EXTIF if configured
if [[ "$dhcp_on_extif" == "on" ]]
then
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport 67 -j ACCEPT
$IPTABLES -A OUTPUT -o $EXTIF -p udp --dport 67 -j ACCEPT
fi
 
# On autorise les requêtes DNS vers les serveurs DNS identifiés
# Allow DNS requests to identified DNS servers
$IPTABLES -A OUTPUT -o $EXTIF -d $DNSSERVERS -p udp --dport domain -m conntrack --ctstate NEW -j ACCEPT
 
# On autorise les requêtes HTTP et HTTPS avec log Netflow (en provenance de E2guardian)
# HTTP & HTTPS requests are allowed with netflow log (from E2guardian)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport http -j NETFLOW
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport http -j ACCEPT
#$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport https -j NETFLOW # When E2guardian will be in HTTPS transparent proxy)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport https -j ACCEPT
 
# On autorise les requêtes RSYNC sortantes (maj BL de Toulouse)
# RSYNC requests are allowed (update of Toulouse BL)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport rsync -j ACCEPT
 
# On autorise les requêtes FTP
# FTP requests are allowed
# modprobe nf_conntrack_ftp # no more needed with kernel > 5.15.85
# $IPTABLES -t raw -A OUTPUT -p tcp --dport ftp -j CT --helper ftp # no more needed with kernel > 5.15.85
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport ftp -j ACCEPT
$IPTABLES -A OUTPUT -o $EXTIF -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
 
# On autorise les requêtes NTP
# NTP requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p udp --dport ntp -j ACCEPT
 
# On autorise les requêtes ICMP (ping)
# ICMP (ping) requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p icmp --icmp-type 8 -j ACCEPT
 
# On autorise les requêtes LDAP
# LDAP requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p tcp -m multiport --dports ldap,ldaps -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
$IPTABLES -A OUTPUT -o $EXTIF -p udp -m multiport --dports ldap,ldaps -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
 
#############################
# POSTROUTING #
#############################
# Traduction dynamique d'adresse en sortie
# Dynamic NAT on EXTIF
$IPTABLES -A POSTROUTING -t nat -o $EXTIF -j MASQUERADE
 
#Sauvegarde de la marque associée à la connexion pour le load balancing
$IPTABLES -A POSTROUTING -t mangle -j CONNMARK --save-mark
 
#############################
# FAIL2BAN #
#############################
# Reload Fail2Ban
if systemctl -q is-active fail2ban; then
/usr/bin/fail2ban-client ping &>/dev/null && /usr/bin/fail2ban-client -q reload &>/dev/null
fi
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-url_filter_bl.sh
0,0 → 1,126
#!/bin/bash
 
# Id: $Id$
 
# alcasar-url_filter.sh
# by REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Active / désactive : safesearch des moteurs de recherche
# Enable / disable : search engines safesearch
# Active / désactive : le filtrage des url contenant une adresse ip à la place d'un nom de domaine
# Enable / disable : filter of urls containing ip address instead of domain name
 
CONF_FILE="/usr/local/etc/alcasar.conf"
DIR_DG_GROUP1="/etc/e2guardian/lists/group1"
UNBOUND_BL_DOMAIN_FILTER_CONF="/etc/unbound/conf.d/blacklist/domainfilter.conf"
SED="/bin/sed -i"
safesearch="Off"
pureip="Off"
usage="Usage: alcasar-url_filter_bl.sh { -safesearch_on or -safesearch_off } & { -pureip_on or -pureip_off }"
 
nb_args=$#
 
googledomains="google.com. google.ad. google.ae. google.com.af. google.com.ag. google.com.ai. google.al. google.am. google.co.ao. google.com.ar. google.as. google.at. google.com.au. google.az. google.ba. google.com.bd. google.be. google.bf. google.bg. google.com.bh. google.bi. google.bj. google.com.bn. google.com.bo. google.com.br. google.bs. google.bt. google.co.bw. google.by. google.com.bz. google.ca. google.cd. google.cf. google.cg. google.ch. google.ci. google.co.ck. google.cl. google.cm. google.cn. google.com.co. google.co.cr. google.com.cu. google.cv. google.com.cy. google.cz. google.de. google.dj. google.dk. google.dm. google.com.do. google.dz. google.com.ec. google.ee. google.com.eg. google.es. google.com.et. google.fi. google.com.fj. google.fm. google.fr. google.ga. google.ge. google.gg. google.com.gh. google.com.gi. google.gl. google.gm. google.gp. google.gr. google.com.gt. google.gy. google.com.hk. google.hn. google.hr. google.ht. google.hu. google.co.id. google.ie. google.co.il. google.im. google.co.in. google.iq. google.is. google.it. google.je. google.com.jm. google.jo. google.co.jp. google.co.ke. google.com.kh. google.ki. google.kg. google.co.kr. google.com.kw. google.kz. google.la. google.com.lb. google.li. google.lk. google.co.ls. google.lt. google.lu. google.lv. google.com.ly. google.co.ma. google.md. google.me. google.mg. google.mk. google.ml. google.com.mm. google.mn. google.ms. google.com.mt. google.mu. google.mv. google.mw. google.com.mx. google.com.my. google.co.mz. google.com.na. google.com.nf. google.com.ng. google.com.ni. google.ne. google.nl. google.no. google.com.np. google.nr. google.nu. google.co.nz. google.com.om. google.com.pa. google.com.pe. google.com.pg. google.com.ph. google.com.pk. google.pl. google.pn. google.com.pr. google.ps. google.pt. google.com.py. google.com.qa. google.ro. google.ru. google.rw. google.com.sa. google.com.sb. google.sc. google.se. google.com.sg. google.sh. google.si. google.sk. google.com.sl. google.sn. google.so. google.sm. google.sr. google.st. google.com.sv. google.td. google.tg. google.co.th. google.com.tj. google.tk. google.tl. google.tm. google.tn. google.to. google.com.tr. google.tt. google.com.tw. google.co.tz. google.com.ua. google.co.ug. google.co.uk. google.com.uy. google.co.uz. google.com.vc. google.co.ve. google.vg. google.co.vi. google.com.vn. google.vu. google.ws. google.rs. google.co.za. google.co.zm. google.co.zw. google.cat."
 
youtubedomains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
 
safesearch=""
pureip=""
 
if [ $nb_args -lt 1 ]
then
echo "$usage"
exit 1
fi
 
while [ $nb_args -ge 1 ]
do
arg=${!nb_args}
case $arg in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
# Safe search activation
-safesearch_on | --safesearch_on)
safesearch="On"
;;
# Safe search deactivation
-safesearch_off | --safesearch_off)
safesearch="Off"
;;
# pure_ip activation
-pureip_on | --pureip_on)
pureip="On"
;;
# pureip deactivation
-pureip_off | --pureip_off)
pureip="Off"
;;
*)
echo "Argument inconnu :$arg";
echo "$usage"
exit 1
;;
esac
nb_args=$(expr $nb_args - 1)
done
 
if [ "$safesearch" == "On" ]
then
$SED "s?^#\"?\"?g" $DIR_DG_GROUP1/urlregexplist # on décommente les lignes de regles
# add 'SafeSearch' redirection for google searching
google_safe_server=`host -ta forcesafesearch.google.com | grep "address" | cut -d" " -f4` # retrieve google forcesafesearch ip
 
# config file header
echo "server:" > $UNBOUND_BL_DOMAIN_FILTER_CONF
 
for domain in $googledomains
do
echo -e "\tlocal-zone: \"$domain\" redirect" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"$domain A $google_safe_server\"" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
done
 
# add 'SafeSearch' redirection for youtube searching
youtube_safe_server=`host -ta restrict.youtube.com | grep "address" | cut -d" " -f4` # retrieve youtube restrict ip
for domain in $youtubedomains
do
echo -e "\tlocal-zone: \"$domain\" redirect" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"$domain A $youtube_safe_server\"" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
done
 
# add 'SafeSearch' redirection for bing searching
bing_safe_server=`host -ta strict.bing.com | grep "address" | cut -d" " -f4` # retrieve bing strict ip
echo -e "\tlocal-zone: \"www.bing.com\" redirect" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"www.bing.com A $bing_safe_server\"" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
 
# add 'SafeSearch' redirection for qwant searching
qwant_safe_server=`host -ta safeapi.qwant.com | grep "address" | cut -d" " -f4` # retrieve qwant strict ip
echo -e "\tlocal-zone: \"api.qwant.com\" redirect" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"api.qwant.com A $qwant_safe_server\"" >> $UNBOUND_BL_DOMAIN_FILTER_CONF
 
$SED 's/^BL_SAFESEARCH=.*/BL_SAFESEARCH=on/g' $CONF_FILE
elif [ "$safesearch" == "Off" ]
then
$SED "s?^[^#]?#&?g" $DIR_DG_GROUP1/urlregexplist
[ -e $UNBOUND_BL_DOMAIN_FILTER_CONF ] && rm -f $UNBOUND_BL_DOMAIN_FILTER_CONF
 
$SED 's/^BL_SAFESEARCH=.*/BL_SAFESEARCH=off/g' $CONF_FILE
fi
 
if [ "$pureip" == "On" ]
then
$SED "s/^\#\*ip$/*ip/g" $DIR_DG_GROUP1/bannedsitelist
$SED "s/^\#\*ips$/*ips/g" $DIR_DG_GROUP1/bannedsitelist
 
$SED 's/^BL_PUREIP=.*/BL_PUREIP=on/g' $CONF_FILE
elif [ "$pureip" == "Off" ]
then
$SED "s/^\*ip$/#*ip/g" $DIR_DG_GROUP1/bannedsitelist
$SED "s/^\*ips$/#*ips/g" $DIR_DG_GROUP1/bannedsitelist
 
$SED 's/^BL_PUREIP=.*/BL_PUREIP=off/g' $CONF_FILE
fi
systemctl restart e2guardian
systemctl restart unbound-blacklist
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-rpm.sh
0,0 → 1,292
#!/bin/bash
 
# alcasar-rpm.sh
# by 3abtux and Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# script de mise en place des dépots RPM + installation des RPM complémentaires
# configure the RPM repository + complementary RPM installation
 
Lang=`echo $LANG|cut -c 1-2`
SED="/bin/sed -i"
VERSION="9"
ARCH="x86_64"
# The kernel version we compile netflow for
KERNEL="kernel-server-6.6.22-1.mga9"
# ****** Alcasar needed RPMS - paquetages nécessaires au fonctionnement d'Alcasar ******
# (old) perl-Socket6 : needed by nfsen
# "fonts-dejavu-common" & "fonts-ttf-dejavu" : fonts needed by wkhtmltopdf
# "lsscsi" & nvme-cli" & "php-dom" : needed by phpsysinfo
# "socat" : avoid a warning when run the install script of letsencrypt ("acme.sh")
# "sudo" : needed after a reinstallation (to be investigated)
# "postfix" + "cyrus-sasl" + "lib64sasl2-plug-plain" : email registration method
# "nmap" : "/usr/share/nmap/nmap-mac-prefixes" is used to display MAC manufacturers in ACC
 
PACKAGES="vim-enhanced freeradius freeradius-mysql freeradius-ldap lighttpd lighttpd-mod_auth php-fpm php-gd php-ldap php-mysqli php-mbstring php-sockets php-curl php-pdo_sqlite php-cli php-dom php-filter unbound e2guardian postfix mariadb ntpsec bind-utils openssh-server rng-utils rsync fail2ban gnupg2 ulogd ipset usb_modeswitch vnstat dos2unix p7zip msec kernel-userspace-headers kernel-firmware kernel-firmware-nonfree dhcp-server tcpdump fonts-dejavu-common fonts-ttf-dejavu lsscsi nvme-cli sudo socat postfix cyrus-sasl lib64sasl2-plug-plain iftop"
 
rpm_repository_sync ()
{
cat <<EOF > /etc/urpmi/urpmi.cfg
{
downloader: wget
}
EOF
echo ${!MIRRORLIST}
urpmi.addmedia core --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/core/release
urpmi.addmedia core-updates --update --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/core/updates
urpmi.addmedia nonfree --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/nonfree/release
urpmi.addmedia nonfree-updates --update --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/nonfree/updates
}
 
rpm_error ()
{
# restore previous rpm conf file & removed RPMs
[ -e /etc/urpmi/urpmi.cfg.old ] && mv /etc/urpmi/urpmi.cfg.old /etc/urpmi/urpmi.cfg
urpmi --no-verify-rpm --auto rpms/$ARCH/wkhtmltopdf*.rpm
echo
if [ $Lang == "fr" ]
then
echo "Relancez l'installation ultérieurement."
echo "Si vous rencontrez à nouveau ce problème, modifier les variables MIRRORLIST[1&2] du fichier 'scripts/alcasar-rpm.sh'"
else
echo "Try an other install later."
echo "If this problem occurs again, change the MIRRORLIST[1&2] variables in the file 'scripts/alcasar-rpm.sh'"
fi
}
 
# We prefer wget than curl
urpmi --no-verify-rpm --auto rpms/$ARCH/wget*.rpm
 
# Set the RPM repository (if not already set)
cp /etc/urpmi/urpmi.cfg /etc/urpmi/urpmi.cfg.old
ACTIVE_REPO=`cat /etc/urpmi/urpmi.cfg|grep "mageia.org"|wc -l`
MIRROR_NBR=3
# For French
MIRRORLIST1="http://ftp.free.fr/mirrors/mageia.org/distrib/$VERSION/$ARCH"
# For Europeans
MIRRORLIST2="https://www.mirrorservice.org/pub/mageia/distrib/$VERSION/$ARCH"
# For everybody
MIRRORLIST3="https://mirrors.mageia.org/api/mageia.$VERSION.$ARCH.list"
try_nb="0"; nb_repository="0"
while [ "$nb_repository" != "4" ]
do
try_nb=`expr $try_nb + 1`
MIRRORLIST="MIRRORLIST$try_nb"
rpm_repository_sync
nb_repository=`cat /etc/urpmi/urpmi.cfg|grep mirrorlist|wc -l`
if [ "$nb_repository" != "4" ]
then
if [ $Lang == "fr" ]
then
echo "Une erreur a été détectée lors de la synchronisation avec le dépot N°$try_nb."
else
echo "An error occurs when synchronising the repositories N°$try_nb"
fi
if [ $(expr $try_nb) -eq $MIRROR_NBR ]
then
rpm_error
exit 1
fi
if [ $Lang == "fr" ]
then
echo "Voulez-vous tenter une synchronisation avec un autre dépôt ? (O/n)"
else
echo "Do you want to try a synchronisation with an other repository? (Y/n)"
fi
response=0
PTN='^[oOnNyY]?$'
until [[ "$response" =~ $PTN ]]
do
read response
done
if [ "$response" = "n" ] || [ "$response" = "N" ]
then
[ -e /etc/urpmi/urpmi.cfg.old ] && mv /etc/urpmi/urpmi.cfg.old /etc/urpmi/urpmi.cfg # restore previous rpm conf file
exit 1
fi
fi
done
 
# At this time, we only skip Kernel update
echo "/^kernel/" > /etc/urpmi/skip.list
if [ `grep -E '^exclude=' /etc/dnf/dnf.conf |wc -l` -eq "1" ]; then
$SED "s?^exclude=.*?exclude=kernel\*?g" /etc/dnf/dnf.conf
else
echo "exclude=kernel*" >> /etc/dnf/dnf.conf
fi
 
# download the kernel used by ALCASAR
if [ $Lang == "fr" ]
then
echo "Récupération du noyau Linux exploité par ALCASAR. Veuillez patienter ..."
else
echo "Download the Linux kernel used by ALCASAR. Please wait ..."
fi
urpmi --auto --quiet $KERNEL
 
# download updated RPM in cache
if [ $Lang == "fr" ]
then
echo "Récupération des paquetages de mise à jour. Veuillez patienter ..."
echo "Il est temps d'aller prendre un café (ou une bonne bière) ;-)"
else
echo "Updated RPM download. Please wait ..."
echo "You should now take a coffe (or a good beer) ;-)"
fi
urpmi --auto --auto-update --quiet --test --retry 2
if [ "$?" != "0" ]
then
echo
if [ $Lang == "fr" ]
then
echo "Une erreur a été détectée lors de la récupération des paquetages."
else
echo "An error occurs when downloading RPMS"
fi
rpm_error
exit 1
fi
 
# update with cached RPM
urpmi --auto --auto-update
if [ "$?" != "0" ]
then
echo
if [ $Lang == "fr" ]
then
echo "Une erreur a été détectée lors de la mise à jour des paquetages."
else
echo "An error occurs when updating packages"
fi
rpm_error
exit 1
fi
# Clean the RPM cache
urpmi --clean
 
# Download of ALCASAR specifics RPM in cache (and test)
if [ $Lang == "fr" ]
then
echo "Récupération des paquetages complémentaires. Veuillez patienter ..."
else
echo "Download of complementary packages. Please wait ..."
fi
urpmi --auto --no-recommends $PACKAGES --quiet --test --retry 2
if [ "$?" != "0" ]
then
echo
if [ $Lang == "fr" ]
then
echo "Une erreur a été détectée lors de la récupération des paquetages complémentaires."
else
echo "An error occurs when downloading complementary packages"
fi
rpm_error
exit 1
fi
 
# update with cached RPM
urpmi --auto --no-recommends $PACKAGES
if [ "$?" != "0" ]
then
echo
if [ $Lang == "fr" ]
then
echo "Une erreur a été détectée lors de l'installation des paquetages complémentaires."
else
echo "An error occurs when installing complementary packages"
fi
rpm_error
exit 1
fi
 
# Keep only the kernel version we compil netflow with, and remove all others
kernelVersion=$(rpm -qa | grep -e ^kernel-server -e ^kernel-desktop)
for i in $kernelVersion
do
if [ $i != $KERNEL ];then
urpme --auto $i
fi
done
 
# delete unused RPMs
if [ $Lang == "fr" ]
then
echo "Cleaning the system : "
else
echo "Nettoyage du système : "
fi
unused_rpm="shorewall mandi plymouth squid polkit pm-utils dnsmasq clamav clamd clamav-db"
/usr/sbin/urpme --auto -a $unused_rpm
for rpm in `rpm -qa|grep mga7`; do urpme --auto $rpm; done
/usr/sbin/urpme --auto --auto-orphans
 
# Save chilli launch script (erase with new rpm one)
[ -e /etc/chilli.conf ] && cp /etc/chilli.conf /tmp/
# Install home made RPMs
for pkg in `ls rpms/$ARCH/*.rpm`
do
urpmi --no-verify --auto $pkg
done
# restore chilli launch script
[ -e /tmp/chilli.conf ] && mv /tmp/chilli.conf /etc/
 
# Clean the RPM cache
urpmi --clean
# the ipt-netflow RPM add the kernel module ipt_NETFLOW (the modules dependance tree need to be updated). "2>/dev/null" in order not to display a error (the running kernel is not the ALCASAR one during the installation process)
/sbin/depmod -a 2>/dev/null
# test if all needed rpms are correctly installed
count_pkg=0; nb_pkg=0;
for pkg in $PACKAGES
do
nb_pkg=`expr $nb_pkg + 1`
if rpm -q --quiet $pkg ; then
count_pkg=`expr $count_pkg + 1`
else
echo "error installing $pkg"
fi
done
if [ $count_pkg -ne $nb_pkg ]
then
exit 1
fi
 
# test if all custom rpms are correctly installed
count_pkg=0; nb_pkg=0;
for pkg in `ls rpms/$ARCH/|sed 's/.x86_64.rpm//'`
do
nb_pkg=`expr $nb_pkg + 1`
if rpm -q --quiet $pkg ; then
count_pkg=`expr $count_pkg + 1`
else
echo "error installing $pkg"
fi
done
if [ $count_pkg -ne $nb_pkg ]
then
exit 1
fi
 
# .rpmnew handling (unused with ALCASAR)
[ -e /etc/shadow.rpmnew ] && rm -f /etc/shadow.rpmnew
[ -e /etc/sysconfig/system.rpmnew ] && rm -f /etc/sysconfig/system.rpmnew
[ -e /etc/rpm/macros.rpmnew ] && rm -f /etc/rpm/macros.rpmnew
[ -e /etc/fstab.rpmnew ] && rm -f /etc/fstab.rpmnew
[ -e /etc/shells.rpmnew ] && rm -f /etc/shells.rpmnew
[ -e /etc/hosts.rpmnew ] && rm -f /etc/hosts.rpmnew
[ -e /etc/systemd/journald.conf.rpmnew ] && rm -f /etc/systemd/journald.conf.rpmnew
[ -e /etc/raddb/certs/dh.rpmnew ] && rm -f /etc/raddb/certs/dh.rpmnew
 
# .rpmnew handling (used with ALCASAR)
[ -e /etc/php.ini.rpmnew ] && mv -f /etc/php.ini.rpmnew /etc/php.ini.default
[ -e /etc/lighttpd/lighttpd.conf.rpmnew ] && mv -f /etc/lighttpd/lighttpd.conf.rpmnew /etc/lighttpd/lighttpd.conf.default
[ -e /etc/lighttpd/modules.conf.rpmnew ] && mv -f /etc/lighttpd/modules.conf.rpmnew /etc/lighttpd/modules.conf.default
[ -e /etc/e2guardian/e2guardian.conf.rpmnew ] && mv -f /etc/e2guardian/e2guardian.conf.rpmnew /etc/e2guardian/e2guardian.conf.default
[ -e /etc/e2guardian/e2guardianf1.conf.rpmnew ] && mv -f /etc/e2guardian/e2guardianf1.conf.rpmnew /etc/e2guardian/e2guardianf1.conf.default
[ -e /etc/e2guardian/lists/urlregexplist.rpmnew ] && mv -f /etc/e2guardian/lists/urlregexplist.rpmnew /etc/e2guardian/lists/urlregexplist.default
[ -e /etc/e2guardian/lists/bannedregexpurllist.rpmnew ] && mv -f /etc/e2guardian/lists/bannedregexpurllist.rpmnew /etc/e2guardian/lists/bannedregexpurllist.default
[ -e /etc/vnstat.conf.rpmnew ] && mv -f /etc/vnstat.conf.rpmnew /etc/vnstat.conf.default
[ -e /etc/fail2ban/jail.conf.rpmnew ] && mv -f /etc/fail2ban/jail.conf.rpmnew /etc/fail2ban/jail.conf.default
[ -e /etc/ssh/sshd_config.rpmnew ] && mv -f /etc/ssh/sshd_config.rpmnew /etc/ssh/sshd_config.default
 
exit 0
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-bl-autoupdate.sh
0,0 → 1,130
#!/bin/bash
 
# $Id: alcasar-bl.sh 2688 2019-01-18 23:15:49Z lucas.echard $
 
# alcasar-autoupdate.sh
# by Sven RATH and Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# Gestion de la BL pour le filtrage de domaine (via unbound) et d'URL (via E2guardian)
# Manage the BL for DnsBlackHole (unbound) and URL filtering (E2guardian)
 
FILE_tmp="/tmp/filesfilter.txt"
FILE_ip_tmp="/tmp/filesipfilter.txt"
DIR_DG="/etc/e2guardian/lists"
DIR_DG_BL="$DIR_DG/blacklists"
DIR_SHARE="/usr/local/share"
DIR_DNS_BL="$DIR_SHARE/unbound-bl" # all the BL in the Unbound format
DIR_DNS_WL="$DIR_SHARE/unbound-wl" # all the WL ' ' '
DIR_IP_BL="$DIR_SHARE/iptables-bl" # all the IP addresses of the BL
DIR_IP_WL="$DIR_SHARE/iptables-wl" # IP ossi disabled WL
CNC_BL_NAME="ossi-bl-candc"
CNC_URL="https://osint.bambenekconsulting.com/feeds/"
CNC_DNS=${CNC_URL}c2-dommasterlist-high.txt
CNC_IP=${CNC_URL}c2-ipmasterlist-high.txt
SED="/bin/sed -i"
CURL="/usr/bin/curl"
 
# cleaning file and split it ("domains" in $FILE_tmp & "IP" in $FILE_ip_tmp)
function clean_split (){
$SED '/^#.*/d' $FILE_tmp # remove commented lines
$SED '/^\s*$/d' $FILE_tmp # remove empty lines
$SED '/[äâëêïîöôüû@,]/d' $FILE_tmp # remove line with "chelou" characters
# extract ip addresses for iptables.
awk '/^([0-9]{1,3}\.){3}[0-9]{1,3}$/{print "add bl_ip_blocked " $0}' $FILE_tmp > $FILE_ip_tmp
# extract domain names for unbound.
$SED -n '/^\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/!p' $FILE_tmp
# Retrieve max Top Level Domain for domain name synthax
#MAX_TLD=$(curl http://data.iana.org/TLD/tlds-alpha-by-domain.txt | grep -v '-' | grep -v '#' | wc -L)
#if [ $(echo $MAX_TLD | wc -c) -eq 0 ];then
# MAX_TLD=18
#fi
# search for correction grep -E "([a-zA-Z0-9_-.]+\.){1,2}[a-zA-Z]{2,$MAX_TLD}" $ossi_custom_dir/domains > $FILE_tmp
}
 
usage="Usage: alcasar-bl-autoupdate.sh { -update_cat or --update_cat | -update_ossi-bl-candc or --update_ossi-bl-candc }"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
# Update the categories of Toulouse BL listed in "/usr/local/etc/update_cat.conf" (via rsync). Cron runs this function every 12h
-update_cat | --update_cat)
if [ $(cat /usr/local/etc/update_cat.conf | wc -l) -ne 0 ]
then
echo -n "Updating categories in /usr/local/etc/update_cat.conf ..."
cat /usr/local/etc/update_cat.conf | while read LIGNE_RSYNC
do
CATEGORIE=$(echo $LIGNE_RSYNC | cut -d' ' -f1)
URL=$(echo $LIGNE_RSYNC | cut -d' ' -f2)
PATH_FILE=$(find $DIR_DG_BL/ -type d -name $CATEGORIE) # retrieve directory name of the category
rsync -rv $URL $(dirname $PATH_FILE ) #rsync inside of the blacklist directory
# Creation of unbound and Iptables BL and WL
DOMAIN=$(basename $PATH_FILE)
cp $PATH_FILE/domains $FILE_tmp
clean_split # clean ossi custom files & split them for unbound and for iptables
black=`grep black $PATH_FILE/usage |wc -l`
if [ $black == "1" ]
then
# adapt to the unbound syntax for the blacklist
$SED "s?.*?local-zone: & typetransparent\nlocal-zone-tag: & blacklist?g" $FILE_tmp
mv $FILE_tmp $DIR_DNS_BL/$DOMAIN.conf
mv $FILE_ip_tmp $DIR_IP_BL/$DOMAIN
else
# adapt to the unbound syntax for the whitelist
$SED "s?.*?local-zone: & transparent?g" $FILE_tmp
$SED "p; s? transparent? ipset?g" $FILE_tmp # duplicate lines to enable ipset module
mv $FILE_tmp $DIR_DNS_WL/$DOMAIN.conf
mv $FILE_ip_tmp $DIR_IP_WL/$DOMAIN
fi
rm -f $FILE_tmp $FILE_ip_tmp
done
/usr/local/bin/alcasar-bl.sh --reload
else
echo -n "/usr/local/etc/update_cat.conf is empty ..."
fi
echo
;;
# Update C&C-Server Blacklist (TODO : check that there is a difference between two downloads)
-update_ossi-bl-candc | --update_ossi-bl-candc)
# check availability of the lists
echo "Downloading blacklists from ${CNC_URL}..."
STATUS_DNS_BL=$(${CURL} --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${CNC_DNS})
STATUS_IP_BL=$(${CURL} --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${CNC_IP})
# if downloaded successfully
if [ $STATUS_DNS_BL = 200 ] && [ $STATUS_IP_BL = 200 ]; then
## parse domain names and ips from feed (cut first 19 lines (comments) and extract first column)
CNC_DOMAINS=$($CURL $CNC_DNS | tail -n +19 | awk -F, '{print $1}')
CNC_IPS=$($CURL $CNC_IP | tail -n +19 | awk -F, '{print $1}')
## create files and adapt downloaded data to alcasar structure (add newlines after each ip/domain)
BL_DIR=${DIR_DG_BL}/${CNC_BL_NAME}
rm -rf ${BL_DIR}
mkdir $BL_DIR
echo $CNC_DOMAINS | tr " " "\n" > ${BL_DIR}/urls
echo $CNC_IPS | tr " " "\n" > ${BL_DIR}/domains
## reload ossi-blacklists to add the created blacklist to ALCASAR
echo "Download successfull."
/usr/local/bin/alcasar-bl.sh --reload
exit 0
# if server responded with a code different than 200
else
## 000 means that curl failed
if [ $STATUS_DNS_BL = 000 ] || [ $STATUS_IP_BL = 000 ]; then
echo "ERROR: curl could not access the internet to download blacklists."
echo "This appears to be an error on your side: please check the connection to the internet."
else
echo "ERROR: could not donwload blacklists: Server returned non-200 codes:"
echo "${CNC_DNS} returned ${STATUS_DNS_BL}"
echo "${CNC_IP} returned ${STATUS_IP_BL}"
echo "Check the availability of the sites. Maybe the server removed its content or changed its address."
fi
exit 1
fi
;;
esac
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-daemon.sh
0,0 → 1,92
#!/bin/bash
# $Id$
 
# alcasar-daemon.sh
# by Franck BOUIJOUX & Rexy
# This script is distributed under the Gnu General Public License (GPL)
# Watchdog of Services
# With the option "-after-update" checks if services or system need to be restarted after a RPM update
# See /etc/cron.d/alcasar-daemon-watchdog for config the time
 
conf_file="/usr/local/etc/alcasar.conf"
SMS=`grep ^SMS= $conf_file|cut -d"=" -f2` # SMS active (on/off)
SMS=${SMS:=off}
LDAP=`grep ^LDAP= $conf_file|cut -d"=" -f2` # ldap active (on/off)
LDAP=${LDAP:=off}
INTIF=`grep ^INTIF= $conf_file|cut -d"=" -f2` # INTIF name
EXTIF=`grep ^EXTIF= $conf_file|cut -d"=" -f2` # EXTIF name
SERVICES="mysqld lighttpd php-fpm ntpd unbound unbound-blacklist unbound-whitelist unbound-blackhole radiusd nfcapd e2guardian ulogd-ssh ulogd-traceability ulogd-ext-access chilli fail2ban sshd vnstat gammu-smsd"
nb_available_srv=`echo $SERVICES|wc -w`
 
function ServiceTest () {
service=$1
if [ $(/usr/bin/systemctl is-active $service) != "active" ]; then
logger -t alcasar-daemon -i "$service is inactive. Activation attempt"
echo "the $service service is disabled! trying to start it..."
if [ $service == 'gammu-smsd' ]; then
/usr/local/bin/alcasar-sms.sh --start
fi
if [ $service == 'sshd' ]; then
[ -s /etc/ssh/ssh_host_rsa_key ] || rm -f /etc/ssh/ssh_host_* # sometimes sshd doesn't initialise its keys
fi
/usr/bin/systemctl start $service.service
else
nb_srv=$((nb_srv+1))
fi
}
 
usage="Usage: alcasar-daemon.sh {-after-update}"
case $1 in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
-after-update)
# TODO : check precisely which processes should be restarted (reboot the system or restart alcasar processes)
# extract processes name : for i in `dnf needs-restarting|cut -d " " -f3|sort -u|tr -d ":"|rev|cut -d"/" -f1|rev`;do;echo $i;done
# system_processes=`dnf needs-restarting|grep -E 'dbus|python|systemd|agetty'|wc -l` # processes to be restarted after glibc update
nb_processes=`dnf needs-restarting|wc -l`
if [ $nb_processes -ne 0 ]; then
reboot
fi
;;
*)
for NIC in $EXTIF $INTIF
do
if [ `/usr/sbin/ip a show $NIC|grep DOWN|wc -l` -eq "1" ]; then
echo "The network interface card '$NIC' is down! Try to enable it"
/usr/sbin/ifup $NIC
fi
done
nb_srv=0
for service in $SERVICES; do
if [ $service == 'gammu-smsd' ]; then
if [ $SMS != "ON" ] && [ $SMS != "on" ] && [ $SMS != "On" ]; then
nb_available_srv=$((nb_available_srv-1))
continue
fi
fi
ServiceTest $service
done
if [ $nb_available_srv -ne $nb_srv ]; then
echo "Restart this script to know if all is ok"
else
echo "$nb_srv services needed by ALCASAR are started."
fi
if [ `cat /proc/modules|grep -c ^ipt_NETFLOW` == 0 ]; then
logger -t alcasar-daemon -i "ipt_netflow is inactive."
echo "The Log system is disabled! try to know why (modprobe ipt_NETFLOW)"
else
echo "The Log system is active"
fi
if [ ! -e /etc/raddb/mods-enabled/ldap ]; then
if [ $LDAP == "ON" ] || [ $LDAP == "on" ] || [ $LDAP == "On" ]; then
echo "Enabling LDAP..."
/usr/local/bin/alcasar-ldap.sh -on
fi
fi
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-iptables-bypass.sh
0,0 → 1,157
#!/bin/bash
# $Id$
 
# alcasar-iptables-bypass.sh
# by Rexy - 3abtux
# This script is distributed under the Gnu General Public License (GPL)
 
# Applique les regles du parefeu en mode ByPass
# Set the firewall rules in 'ByPass' mode
 
CONF_FILE="/usr/local/etc/alcasar.conf"
private_ip_mask=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
private_ip_mask=${private_ip_mask:=192.168.182.1/24}
private_network=`/bin/ipcalc -n $private_ip_mask|cut -d"=" -f2` # LAN IP address (ie.: 192.168.182.0)
private_prefix=`/bin/ipcalc -p $private_ip_mask|cut -d"=" -f2` # LAN prefix (ie. 24)
IPTABLES="/sbin/iptables"
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2` # EXTernal InterFace
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2` # INTernal InterFace
TUNIF="tun0" # listen device for chilli daemon
PRIVATE_NETWORK_MASK=$private_network/$private_prefix # Lan IP address + prefix (192.168.182.0/24)
PRIVATE_IP=`echo $private_ip_mask | cut -d"/" -f1` # ALCASAR LAN IP address
public_ip_mask=`grep ^PUBLIC_IP= $CONF_FILE|cut -d"=" -f2` # ALCASAR WAN IP address
if [[ "$public_ip_mask" == "dhcp" ]]
then
PTN="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([012]?[0-9]|3[0-2])\b"
public_ip_mask=`ip addr show $EXTIF | grep -o -E $PTN`
fi
PUBLIC_IP=`echo $public_ip_mask | cut -d"/" -f1`
SSH_LAN=`grep ^SSH_LAN= $CONF_FILE|cut -d"=" -f2` # SSH LAN port
SSH_LAN=${SSH_LAN:=0}
SSH_WAN=`grep ^SSH_WAN= $CONF_FILE|cut -d"=" -f2` # SSH WAN port
SSH_WAN=${SSH_WAN:=0}
SSH_WAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f2`
SSH_WAN_ADMIN_FROM=${SSH_WAN_ADMIN_FROM:="0.0.0.0"}
SSH_WAN_ADMIN_FROM=$([ "$SSH_WAN_ADMIN_FROM" == "0.0.0.0" ] && echo "0.0.0.0/0" || echo "$SSH_WAN_ADMIN_FROM" )
SSH_LAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f1`
SSH_LAN_ADMIN_FROM=${SSH_LAN_ADMIN_FROM:="0.0.0.0"}
SSH_LAN_ADMIN_FROM=$([ "$SSH_LAN_ADMIN_FROM" == "0.0.0.0" ] && echo "$PRIVATE_NETWORK_MASK" || echo "$SSH_LAN_ADMIN_FROM" )
interlan=`grep ^INTERLAN= $CONF_FILE|cut -d"=" -f2`
interlan=${interlan:=off}
 
# On vide (flush) toutes les règles existantes
# Flush all existing rules
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -F INPUT
$IPTABLES -F FORWARD
$IPTABLES -F OUTPUT
 
# On indique les politiques par défaut
# Default policies
$IPTABLES -P INPUT DROP
$IPTABLES -P FORWARD DROP
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -t nat -P PREROUTING ACCEPT
$IPTABLES -t nat -P POSTROUTING ACCEPT
$IPTABLES -t nat -P OUTPUT ACCEPT
 
# On efface toutes les chaînes qui ne sont pas par défaut dans les tables filter et nat
# Flush non default rules on filter and nat tables
$IPTABLES -X
$IPTABLES -t nat -X
 
# On autorise tout sur loopback
# accept all on loopback
$IPTABLES -A OUTPUT -o lo -j ACCEPT
$IPTABLES -A INPUT -i lo -j ACCEPT
 
#############################
# INPUT #
#############################
# SSHD rules if activate
if [ $SSH_LAN -gt 0 ]
then
$IPTABLES -A INPUT -i $INTIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -m conntrack --ctstate NEW -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-LAN -- ACCEPT"
$IPTABLES -A INPUT -i $INTIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -j ACCEPT
fi
if [ $SSH_WAN -gt 0 ]
then
$IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -m conntrack --ctstate NEW --syn -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-WAN -- ACCEPT"
$IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -j ACCEPT
fi
 
# Insertion de règles locales
# Here, we add local rules (i.e. VPN from Internet)
if [ -f /usr/local/etc/alcasar-iptables-local.sh ]; then
. /usr/local/etc/alcasar-iptables-local.sh
fi
 
# on autorise les requêtes dhcp
# accept dhcp
$IPTABLES -A INPUT -i $INTIF -p udp -m udp --sport bootpc --dport bootps -j ACCEPT
 
# On drop le broadcast et le multicast sur les interfaces (sans Log)
# Drop broadcast & multicast
$IPTABLES -A INPUT -m addrtype --dst-type BROADCAST,MULTICAST -j DROP
 
# On autorise l'accès aux services internes
# Allow Internal access
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport domain -j ACCEPT # DNS
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport domain -j ACCEPT # DNS
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 8 -j ACCEPT # Réponse ping # ping responce
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 0 -j ACCEPT # Requête ping # ping request
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport https -j ACCEPT # ACC
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport http -j ACCEPT # ACC
$IPTABLES -A INPUT -i $INTIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport ntp -j ACCEPT # Serveur local de temps # local time server
 
# On autorise le retour des connexions entrante déjà acceptées
$IPTABLES -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
 
# On interdit et on log le reste sur les 2 interfaces d'accès
$IPTABLES -A INPUT -i $INTIF -j NFLOG --nflog-group 1 --nflog-prefix "RULE rej-int -- REJECT "
$IPTABLES -A INPUT -i $EXTIF -j NFLOG --nflog-group 1 --nflog-prefix "RULE rej-ext -- REJECT "
$IPTABLES -A INPUT -p tcp -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
 
#############################
# FORWARD #
#############################
# On autorise les retours de connexions légitimes par FORWARD
# Conntrack on forward
$IPTABLES -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
 
# On autorise (ou pas) les utilisateurs à accéder au réseau situé entre ALCASAR et le routeur Internet
# Users are allowed (or not allowed) to access the network between ALCASAR and the Internet router
if [ "$interlan" != "on" ]
then
$IPTABLES -A FORWARD -i $TUNIF -d $public_ip_mask -j DROP
fi
 
# Insertion de règles de blocage
# Here, we add block rules
if [ -s /usr/local/etc/alcasar-ip-blocked ]; then
while read ip_line
do
ip_on=`echo $ip_line|cut -b1`
if [ $ip_on != "#" ]
then
ip_blocked=`echo $ip_line|cut -d" " -f1`
$IPTABLES -A FORWARD -d $ip_blocked -j NFLOG --nflog-group 1 --nflog-prefix "RULE IP-blocked -- REJECT "
$IPTABLES -A FORWARD -d $ip_blocked -j REJECT
fi
done < /usr/local/etc/alcasar-ip-blocked
fi
 
# On autorise les demandes de connexions sortantes
$IPTABLES -A FORWARD -i $INTIF -m state --state NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE Transfert -- ACCEPT "
$IPTABLES -A FORWARD -i $INTIF -m state --state NEW -j ACCEPT
 
#############################
# POSTROUTING #
#############################
# On active le masquage d'adresse par translation (NAT)
$IPTABLES -A POSTROUTING -t nat -o $EXTIF -j MASQUERADE
 
# on ne sauvegarde pas les règles. En cas de reboot, on repasse ainsi automatiquement en mode normal (bypass -off)
# Fin du script des regles du parefeu
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-watchdog.sh
0,0 → 1,180
#!/bin/bash
# $Id$
 
# alcasar-watchdog.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
# - Ce script prévient les usagers de l'indisponibilité de l'accès Internet
# - Il déconnecte les usagers dont les équipements réseau ne répondent plus (leur onglet 'status.php' a été fermé)
# - Il deconnecte les usagers dont les adresses MAC sont usurpées
#
# - This script tells users that Internet access is down
# - It logs out users whose PCs are quiet (their status tab is closed)
# - It logs out users whose MAC address is used by other systems (usurped)
 
CONF_FILE="/usr/local/etc/alcasar.conf"
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2` # EXTernal InterFace
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2` # INTernal InterFace
private_ip_mask=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
private_ip_mask=${private_ip_mask:=192.168.182.1/24}
PRIVATE_IP=`echo $private_ip_mask |cut -d"/" -f1`
PRIVATE_IP=${PRIVATE_IP:=192.168.182.1}
MULTIWAN=`grep ^MULTIWAN= $CONF_FILE|cut -d"=" -f2`
current_users_file="/tmp/current_users.txt" # file containing active users with their "status.php" tab open
DIR_WEB="/var/www/html"
Index_Page="$DIR_WEB/index.php"
IPTABLES="/sbin/iptables"
TUNIF="tun0" # listen device for chilli daemon
OLDIFS=$IFS
IFS=$'\n'
 
function lan_down_alert ()
# users are redirected on ALCASAR IP address if a LAN problem is detected
{
case $LAN_DOWN in
"1")
logger -t alcasar-watchdog "$EXTIF (WAN card) link down"
echo "$EXTIF (WAN card) link down"
/bin/sed -i "s?diagnostic =.*?diagnostic = \"$EXTIF (WAN card) link down\";?g" $Index_Page
;;
"2")
logger -t alcasar-watchdog "can't contact the default router"
echo "can't contact the default router"
/bin/sed -i "s?diagnostic =.*?diagnostic = \"can't contact the default router\";?g" $Index_Page
;;
"3")
logger -t alcasar-watchdog "can't resolv DNS queries"
echo "can't resolv DNS queries"
/bin/sed -i "s?diagnostic =.*?diagnostic = \"can't resolv DNS queries\";?g" $Index_Page
;;
esac
net_pb=`grep "network_pb = true;" $Index_Page|wc -l`
if [ $net_pb = "0" ] # if previously up
then
/bin/sed -i "s?^\$network_pb.*?\$network_pb = true;?g" $Index_Page
$IPTABLES -I PREROUTING -t nat -i $TUNIF -p udp --dport domain -j REDIRECT --to-port 56
fi
}
 
function lan_test ()
# LAN connectiivity testing
{
watchdog_process=`ps -C alcasar-watchdog.sh|wc -l`
if [[ $(expr $watchdog_process) -gt 3 ]]
then
echo "ALCASAR watchdog is already running"
exit 0
fi
# EXTIF testing
LAN_DOWN="0"
if [ `/sbin/ip link | grep $EXTIF|grep "NO-CARRIER" | wc -l` -eq "1" ]
then
LAN_DOWN="1"
fi
# Default GW testing
if [ $LAN_DOWN -eq "0" ]
then
GW_EXIST=`/sbin/ip route list|grep ^default|wc -l`
if [ $GW_EXIST -eq "0" ] # no GW defined !
then
systemctl restart network
else
if [ "$MULTIWAN" == "off" ] || [ "$MULTIWAN" == "Off" ]
then
IP_GW=`/sbin/ip route list|grep ^default|cut -d" " -f3`
arp_reply=`LANG=en_US.UTF-8 /usr/sbin/arping -I$EXTIF -c1 $IP_GW|grep response|cut -d" " -f2`
if [ $arp_reply -eq "0" ]
then
LAN_DOWN="2"
fi
fi
fi
fi
# DNS request testing (twice)
if [ $LAN_DOWN -eq "0" ]
then
dns_reply=`/usr/bin/host -W1 www.free.fr|grep SERVFAIL|wc -l`
if [ $dns_reply -eq "1" ]
then
dns_reply=`/usr/bin/host -W1 www.startpage.com|grep SERVFAIL|wc -l`
if [ $dns_reply -eq "1" ]
then LAN_DOWN="3"
fi
fi
fi
# if LAN pb detected, users are warned
if [ $LAN_DOWN != "0" ]
then
lan_down_alert
# else switch in normal mode
else
echo "Internet access is OK for now"
net_pb=`grep "network_pb = true;" $Index_Page|wc -l`
if [ $net_pb != "0" ] # if already down
then
/bin/sed -i "s?^\$network_pb.*?\$network_pb = false;?g" $Index_Page
$IPTABLES -D PREROUTING -t nat -i $TUNIF -p udp --dport domain -j REDIRECT --to-port 56
fi
fi
}
 
usage="Usage: alcasar-watchdog.sh {-lt --lan_test | --disconnect-permanent-users}"
case $1 in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
-lt | --lan_test)
lan_test
exit 0
;;
--disconnect-permanent-users)
/bin/sed -i '/PERM/d' $current_users_file
exit 0
;;
*)
lan_test
# We disconnect inactive users (its means that their 'status.php' tab has been closed --> their ip address isn't in $current_users_file)
# process each equipment known by chilli
for system in `/usr/sbin/chilli_query list | grep -v "0\.0\.0\.0"`
do
active_ip=`echo $system |cut -d" " -f2`
active_session=`echo $system |cut -d" " -f5`
active_mac=`echo $system | cut -d" " -f1`
active_user=`echo $system |cut -d" " -f6`
# We check if the user isn't an auth @MAC and if he is still connected
if [ "$active_user" != "$active_mac" ] && [ $(expr $active_session) -eq 1 ]; then
if [ -e $current_users_file ]; then
# We check if user @IP is in 'current_users.txt'
cmp_user_ok=$(cat $current_users_file | awk -F':' "\$1 == \"$active_ip\" {print \$2}")
# If not we disconnect this user.
if [ -z "$cmp_user_ok" ]; then
logger -t alcasar-watchdog "$active_ip ($active_mac) doesn't contact ALCASAR any more. We disconnects the user ($active_user)."
/usr/sbin/chilli_query logout $active_mac
elif [ "$cmp_user_ok" == "TEMP" ]; then
# Remove the user's IP from 'current_users.txt'. Every user status page need to insert their @IP everytime to prove their connectivity.
# We don't disconnect when $cmp_user_ok == "PERM" (status page not needed)
sed -i "/^$active_ip:$cmp_user_ok\$/d" $current_users_file
fi
else # "current_user.txt" does not exists. We disconnect every users.
logger -t alcasar-watchdog "The file /tmp/current_users.txt doesn't' exist. We disconnects the user $active_user"
/usr/sbin/chilli_query logout $active_mac
fi
fi
# IP usurpation test : process only equipment with an authenticated user
if [[ $(expr $active_session) -eq 1 ]]
then
arp_reply=`LANG=en_US.UTF-8 /usr/sbin/arping -b -I$INTIF -s$PRIVATE_IP -c1 -w4 $active_ip|grep -c "Unicast reply"`
# disconnect users whose equipement is usurped. For example, if there are 2 same @MAC it will make 2 lines in output.
if [[ $(expr $arp_reply) -gt 1 ]]
then
echo "[$(date +"%Y-%m-%d %H:%M:%S")] : alcasar-watchdog : $active_ip is usurped ($active_mac). Alcasar disconnect the user ($active_user)." >> /var/Save/security/watchdog.log
logger -t alcasar-watchdog "$active_ip is usurped ($active_mac). Alcasar disconnect the user ($active_user)."
/usr/sbin/chilli_query logout $active_mac
chmod 644 /var/Save/security/watchdog.log
fi
fi
done
;;
esac
IFS=$OLDIFS
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-letsencrypt.sh
0,0 → 1,284
#!/bin/bash
#
# $Id$
#
# alcasar-letsencrypt.sh
# by Tom HOUDAYER & Rexy
#
# This script is distributed under the Gnu General Public License (GPL)
#
# Manage Let's Encrypt for ALCASAR integration
 
CONF_FILE="/usr/local/etc/alcasar-letsencrypt"
ACCOUNT_EMAIL=""
DOMAIN=""
DNS_API=""
DEBUG=false
STAGING_SERVER=""
FORCE=""
OPT_PARAMS=""
ACMESH_HOME="/usr/local/etc/letsencrypt"
ACMESH_BIN="/opt/acme.sh/acme.sh"
LE_SERVER="letsencrypt"
 
usage="Usage: alcasar-letsencrypt.sh
--issue -d alcasar.domain.tld --email alcasar@domain.tld [--dns-api dns_registrar] [--force] [--staging]
--renew [-d alcasar.domain.tld] [--force] [--staging]"
 
################################################################################
# ISSUE #
################################################################################
issue() {
if [ ! -f $ACMESH_BIN ]; then
echo "The client does not seem to be installed."
return 1
fi
TMP_OUTPUT=$(mktemp --suffix=_ALCASAR-LE)
if [ ! -z $ACCOUNT_EMAIL ]; then
emailField=" --accountemail $ACCOUNT_EMAIL"
sed -i "s/^email=.*/email=$ACCOUNT_EMAIL/" $CONF_FILE
else
emailField=""
fi
rm -rf $ACMESH_HOME/certs/*
$DEBUG && debugOpt=" --debug" || debugOpt=""
[ ! -z "$DNS_API" ] && dnsApiOpt="$DNS_API" || dnsApiOpt="--yes-I-know-dns-manual-mode-enough-go-ahead-please"
$ACMESH_BIN --config-home $ACMESH_HOME/data \
$STAGING_SERVER $FORCE $debugOpt \
$emailField \
--issue --dns $dnsApiOpt -d $DOMAIN \
$OPT_PARAMS \
--server $LE_SERVER \
> $TMP_OUTPUT 2>&1
exitCode=$?
$DEBUG && cat $TMP_OUTPUT && echo -e "\n\n"
sed -i "s/^domainRequest=.*/domainRequest=$DOMAIN/" $CONF_FILE
sed -i "s/^dateIssueRequest=.*/dateIssueRequest=$(date +%s)/" $CONF_FILE
sed -i "s/^dnsapi=.*/dnsapi=${DNS_API:="dns"}/" $CONF_FILE
if ! _handle_client_response $TMP_OUTPUT; then
if [ $exitCode -ne 0 ]; then
echo -e "Error!\n"
cat $TMP_OUTPUT
rm -f $TMP_OUTPUT
return 1
else
echo -e "Unknown state\n"
cat $TMP_OUTPUT
fi
fi
rm -f $TMP_OUTPUT
}
 
################################################################################
# RENEW #
################################################################################
renew() {
if [ ! -f $ACMESH_BIN ]; then
echo "The client does not seem to be installed."
return 1
fi
TMP_OUTPUT=$(mktemp --suffix=_ALCASAR-LE)
$DEBUG && debugOpt=" --debug" || debugOpt=""
[ ! -z "$DNS_API" ] && dnsApiOpt="" || dnsApiOpt="--yes-I-know-dns-manual-mode-enough-go-ahead-please"
$ACMESH_BIN --config-home $ACMESH_HOME/data \
$STAGING_SERVER $FORCE $debugOpt \
--renew -d $DOMAIN $dnsApiOpt \
$OPT_PARAMS \
--server $LE_SERVER \
> $TMP_OUTPUT 2>&1
exitCode=$?
$DEBUG && cat $TMP_OUTPUT && echo -e "\n\n"
if ! _handle_client_response $TMP_OUTPUT; then
if [ $exitCode -ne 0 ]; then
echo -e "Error!\n"
cat $TMP_OUTPUT
rm -f $TMP_OUTPUT
return 1
else
echo -e "Unknown state\n"
cat $TMP_OUTPUT
fi
fi
rm -f $TMP_OUTPUT
}
 
################################################################################
# CRON TASK #
################################################################################
cron_task() {
if [ $(grep '^dateNextRenewal=' $CONF_FILE | cut -d'=' -f2) -le $(date +%s) ]; then
logger -t alcasar-letsencrypt "Launch CRON task."
renew
fi
}
 
################################################################################
# HANDLE CLIENT RESPONSE #
################################################################################
_handle_client_response() {
[ $# -lt 1 ] && return 1
responseFile=$1
 
# issue / renew
if [ $(cat $responseFile | grep "Add the following TXT record:" -c) -ne 0 ]; then
challenge=$(cat $responseFile | grep -E "TXT value: '[0-9a-zA-Z_-]+'" -o | cut -d"'" -f2)
sed -i "s/^challenge=.*/challenge=$challenge/" $CONF_FILE
echo "Add the following TXT record:"
echo "Domain: '_acme-challenge.$DOMAIN'"
echo "TXT value: '$challenge'"
elif [ $(cat $responseFile | grep "Cert success." -c) -ne 0 ]; then
sed -i "s/^challenge=.*/challenge=/" $CONF_FILE
sed -i "s/^dateIssued=.*/dateIssued=$(date +%s)/" $CONF_FILE
sed -i "s/^dateNextRenewal=.*/dateNextRenewal=$(date +%s -d '2 months - 3 days')/" $CONF_FILE
install_cert
logger -t alcasar-letsencrypt "Certificate \"$DOMAIN\" imported."
echo "Certificate imported."
[ -z $DNS_API ] && echo "Note: you can delete the TXT record."
elif [ $(cat $responseFile | grep "Domains not changed." -c) -ne 0 ]; then
echo "Domain not changed"
elif [ $(cat $responseFile | grep "$DOMAIN is already verified, skip dns-01." -c) -ne 0 ]; then
echo "Domain already verified"
elif [ $(cat $responseFile | grep "Error add txt for domain:_acme-challenge.$DOMAIN" -c) -ne 0 ]; then
echo "Error add txt for domain:_acme-challenge.$DOMAIN"
elif [ $(cat $responseFile | grep "Please add the TXT records to the domains, and retry again." -c) -ne 0 ]; then
echo "Dns record not added yet, you need to add it manually and retry again."
elif [ $(cat $responseFile | grep 'new-authz error: {"type":"urn:acme:error:malformed","detail":"Error creating new authz :: \(.*\)","status": 400}' -c) -ne 0 ]; then
errorMsg=$(cat $responseFile | grep 'new-authz error: {"type":"urn:acme:error:malformed","detail":"Error creating new authz :: \(.*\)","status": 400}' | sed 's/.*new-authz error: {"type":"urn:acme:error:malformed","detail":"Error creating new authz :: \(.*\)","status": 400}.*/\1/')
echo "Incorrect domain name"
echo "$errorMsg"
elif [ $(cat $responseFile | grep "'$DOMAIN' is not a issued domain, skip." -c) -ne 0 ]; then
echo "'$DOMAIN' is not a issued domain"
 
# renew
elif [ $(cat $responseFile | grep "Skip, Next renewal time is: " -c) -ne 0 ]; then
nextRenewal=$(cat $responseFile | grep 'Skip, Next renewal time is: ' | sed 's/.*Skip, Next renewal time is: \(.*\)/\1/')
echo "Skip, Next renewal time is: $nextRenewal"
echo "Add '--force' to force to renew."
elif [ $(cat $responseFile | grep "$DOMAIN:Verify error:Correct value not found for DNS challenge" -c) -ne 0 ]; then
echo "Correct value not found for DNS challenge"
elif [ $(cat $responseFile | grep "Unable to update challenge :: The challenge is not pending." -c) -ne 0 ]; then
echo "The challenge is not pending. You need to issue."
else
return 2
fi
return 0
}
 
################################################################################
# INSTALL CERTIFICATE #
################################################################################
install_cert() {
echo "Importing certificate to ALCASAR..."
LE_cert_folder="$( echo "$ACMESH_HOME/certs/$DOMAIN"*"")"
if [ ! -f $LE_cert_folder"/"$DOMAIN.cer ]; then
echo "Certificate not found."
return 1
fi
/usr/local/bin/alcasar-importcert.sh \
-i $LE_cert_folder"/"$DOMAIN.cer \
-k $LE_cert_folder"/"$DOMAIN.key \
-c $LE_cert_folder/fullchain.cer \
> /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Error."
return 1
fi
}
 
################################################################################
# MAIN #
################################################################################
 
if [ $# -eq 0 ]; then
echo "$usage"
exit 1
fi
cmd=""
while [ $# -gt 0 ]; do
case $1 in
-\? | -h | --help)
echo "$usage"
exit 0
;;
--issue)
cmd="issue"
shift 1
;;
--renew)
cmd="renew"
shift 1
;;
--cron)
cmd="cron"
shift 1
;;
--install-cert)
cmd="install-cert"
shift 1
;;
--email)
ACCOUNT_EMAIL="$2"
shift 2
;;
--domain | -d)
DOMAIN="$2"
shift 2
;;
--dns-api)
DNS_API="$2"
shift 2
;;
--force)
FORCE="--force"
shift 1
;;
--staging)
STAGING_SERVER="--staging"
shift 1
;;
--debug)
DEBUG=true
shift 1
;;
*)
found=false
for param in "--dnssleep"; do
if [ $1 == $param ]; then
OPT_PARAMS="$OPT_PARAMS $1 $2"
shift 2
found=true
break
fi
done
if ! $found; then
echo "Unknown argument: $1"
echo "$usage"
exit 1
fi
;;
esac
done
 
if [ -z $DOMAIN ]; then
if [ $(grep '^domainRequest=' $CONF_FILE | cut -d'=' -f2 | wc --chars) -gt 1 ]; then
DOMAIN="$(grep '^domainRequest=' $CONF_FILE | cut -d'=' -f2)"
else
DOMAIN="$(grep '^HOSTNAME=' /usr/local/etc/alcasar.conf | cut -d'=' -f2).$(grep '^DOMAIN=' /usr/local/etc/alcasar.conf | cut -d'=' -f2)"
fi
fi
 
case $cmd in
issue)
issue
;;
renew)
renew
;;
cron)
cron_task
;;
install-cert)
install_cert
;;
*) exit 1 ;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-rpm-download.sh
0,0 → 1,156
#!/bin/bash
# $Id$
 
# alcasar-rpm-download.sh
# by Franck BOUIJOUX and Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# récupération des RPM nécessaires dans un fichier tarball
# retrieve needed RPM in a tarball file
 
VERSION="8"
ARCH="x86_64"
# The kernel version we compile netflow for
KERNEL="kernel-server-5.15.126-1.mga8-1-1.mga8"
# ****** Alcasar needed RPMS - paquetages nécessaires au fonctionnement d'Alcasar ******
# (old) perl-Socket6 : needed by nfsen
# "fonts-dejavu-common" & "fonts-ttf-dejavu" : fonts needed by wkhtmltopdf
# "lsscsi" & nvme-cli" : needed by phpsysinfo
# "socat" : avoid a warning when run the install script of letsencrypt ("acme.sh")
# "sudo" : needed after a reinstallation (to be investigated)
# "clamav" + "clamav-db" : needed because of a lack of mutual dependance
# "postfix" + "cyrus-sasl" + "lib64sasl2-plug-plain" : email registration method
PACKAGES="vim-enhanced freeradius freeradius-mysql freeradius-ldap lighttpd lighttpd-mod_auth php-fpm php-gd php-ldap php-mysqli php-mbstring php-sockets php-curl php-pdo_sqlite php-cli php-filter unbound e2guardian postfix mariadb ntp bind-utils openssh-server rng-utils rsync clamav clamav-db clamd fail2ban gnupg2 ulogd ipset usb_modeswitch vnstat dos2unix p7zip msec kernel-userspace-headers kernel-firmware-nonfree dhcp-server tcpdump fonts-dejavu-common fonts-ttf-dejavu lsscsi nvme-cli sudo socat postfix cyrus-sasl lib64sasl2-plug-plain iftop"
 
rpm_repository_sync ()
{
cat <<EOF > /etc/urpmi/urpmi.cfg
{
downloader: wget
}
EOF
urpmi.addmedia core --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/core/release
urpmi.addmedia core-updates --update --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/core/updates
urpmi.addmedia nonfree --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/nonfree/release
urpmi.addmedia nonfree-updates --update --probe-synthesis --mirrorlist ${!MIRRORLIST} /media/nonfree/updates
}
 
rpm_error ()
{
echo
echo "Relancez l'installation ultérieurement."
echo "Si vous rencontrez à nouveau ce problème, modifier les variables MIRRORLIST[1&2] du fichier 'scripts/alcasar-rpm.sh'"
echo "Try an other install later."
echo "If this problem occurs again, change the MIRRORLIST[1&2] variables in the file 'scripts/alcasar-rpm.sh'"
}
 
# extract the current architecture (i586 ou X64)
fic=`cat /etc/product.id`
old="$IFS"
IFS=","
set $fic
for i in $*
do
if [ "`echo $i|grep arch|cut -d'=' -f1`" == "arch" ]
then
ARCH=`echo $i|cut -d"=" -f2`
fi
done
IFS="$old"
# We prefer wget than curl
wget_exist=`rpm -qa|grep wget|wc -l`
if [ "$wget_exist" -eq "0" ]
then
urpmi --no-verify-rpm --auto ../rpms/$ARCH/wget*.rpm
fi
# Set the RPM repository
MIRROR_NBR=2
# For french ALCASARistes
MIRRORLIST1="http://www.mirrorservice.org/sites/mageia.org/pub/mageia/distrib/$VERSION/$ARCH"
# For International install
MIRRORLIST2="http://mirrors.mageia.org/api/mageia.$VERSION.$ARCH.list"
try_nb="0"; nb_repository="0"
while [ "$nb_repository" != "4" ]
do
try_nb=`expr $try_nb + 1`
MIRRORLIST="MIRRORLIST$try_nb"
rpm_repository_sync
nb_repository=`cat /etc/urpmi/urpmi.cfg|grep mirrorlist|wc -l`
if [ "$nb_repository" != "4" ]
then
echo "Une erreur a été détectée lors de la synchronisation avec le dépot N°$try_nb."
echo "An error occurs when synchronising the repositories N°$try_nb"
if [ $(expr $try_nb) -eq $MIRROR_NBR ]
then
rpm_error
exit 1
fi
echo "Voulez-vous tenter une synchronisation avec un autre dépôt (O/n)?"
echo "Do you want to try a synchronisation with an other repository (Y/n)?"
response=0
PTN='^[oOnNyY]?$'
until [[ "$response" =~ $PTN ]]
do
read response
done
if [ "$response" = "n" ] || [ "$response" = "N" ]
then
exit 1
fi
fi
done
# delete unused RPMs
echo "Cleaning the system : "
for rm_rpm in shorewall dhcp-server cyrus-sasl distcache-server avahi mandi radeontool mondo mindi
do
/usr/sbin/urpme --auto $rm_rpm --auto-orphans 2>/dev/null
echo -n "."
done
urpmi --clean
# download RPM in cache
echo "Récupération des paquetages de mise à jour. Veuillez patienter ..."
echo "Updated RPM download. Please wait ..."
echo "Il est temps d'aller prendre un café :-) "
echo "You should now take a Beer ;-) "
urpmi --auto --auto-update --quiet --test --retry 2
if [ "$?" != "0" ]
then
echo
echo "Une erreur a été détectée lors de la récupération des paquetages."
echo "An error occurs when downloading RPMS"
rpm_error
exit 1
fi
# update with cached RPM
urpmi --auto --auto-update --noclean
if [ "$?" != "0" ]
then
echo
echo "Une erreur a été détectée lors de la mise à jour des paquetages."
echo "An error occurs when updating packages"
rpm_error
exit 1
fi
 
# Download of ALCASAR specifics RPM in cache (and test)
echo "Récupération des paquetages complémentaires. Veuillez patienter ..."
echo "Download of complementary packages. Please wait ..."
urpmi --auto $KERNEL --quiet --test --retry 2
urpmi --auto $PACKAGES --quiet --test --retry 2
if [ "$?" != "0" ]
then
echo
echo "Une erreur a été détectée lors de la récupération des paquetages complémentaires."
echo "An error occurs when downloading complementary packages"
rpm_error
exit 1
fi
echo "archive creation. Please wait..."
cd /var/cache/urpmi
tar -czf rpms-$ARCH.tar.gz rpms/
# Clean the RPM cache
urpmi --clean
mv rpms-$ARCH.tar.gz /root/
cd
echo "Your RPM archive file is /root/rpms-$ARCH.tar.gz"
exit 0
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-certificates.sh
0,0 → 1,119
#!/bin/sh
 
# Id: $Id$
 
# alcasar-certificates.sh
# by Franck BOUIJOUX and REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Script permettant
# - d'exporter les certificats d'un serveur pour les transposer sur un autre.
 
# This script allows
# - export certificates server to move them.
 
 
DIR_EXPORT="/root/Certificats"
DIR_PKI="/etc/pki"
DIR_SAVE="/root/PKI_SAVE"
DIR_IMPORT="/root/Certificats"
 
 
usage="Usage: alcasar-certificates.sh {--export or -x} | {--import or -i <FileOfCertificate.tar.gz>} "
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
 
 
NOW="$(date +%G%m%d-%Hh%M)" # date et heure du moment
FILE="certificates-$NOW"
DIR_SAVE=$DIR_SAVE-$NOW
 
# Function of export
function certs_export() {
# Export of CA Certificate
cd /root
tar cvf $FILE.tar $DIR_PKI/CA/{alcasar-ca.crt,private/alcasar-ca.key}
 
# Export of server Certificate
tar rvf $FILE.tar $DIR_PKI/tls/{certs/alcasar.crt,private/alcasar.key,certs/server-chain.pem}
gzip $FILE.tar
echo "Le fichier des certificats exportés est : $FILE.tar.gz"
} # end function export
 
 
function archive() {
# Sauvegarde de la pki actuelle
[ -d $DIR_SAVE ] || mkdir $DIR_SAVE
 
# Save of CA Certificate
cd $DIR_PKI/CA/
cp alcasar-ca.crt $DIR_SAVE/.
cp private/alcasar-ca.key $DIR_SAVE/.
 
# Save of server Certificate
cd $DIR_PKI/tls
cp certs/alcasar.crt $DIR_SAVE/.
cp private/alcasar.key $DIR_SAVE/.
cp certs/server-chain.pem $DIR_SAVE/.
} # end function archive
 
function import() {
echo "Would you like to Import New Certificates in ALCASAR ?"
read response
if [ $response = "y" ] || [ $response = "o" ] || [ $response = "Y" ] || [ $response = "O" ]
then
[ -d $DIR_IMPORT ] || mkdir $DIR_IMPORT
rm -rf $DIR_IMPORT/*
 
# Import of CA Certificate
tar xzvf $1 --directory=$DIR_IMPORT
 
(cat $DIR_PKI/tls/private/alcasar.key; echo; cat $DIR_PKI/tls/certs/alcasar.crt) > $DIR_PKI/tls/private/alcasar.pem
 
echo "Import new certificates in ALCASAR !!!"
cp -r $DIR_IMPORT/* /.
chown root:apache $DIR_PKI/CA/{alcasar-ca.crt,private/alcasar-ca.key}
chown root:apache $DIR_PKI/tls/{certs/alcasar.crt,private/alcasar.key,private/alcasar.pem,certs/server-chain.pem}
 
chmod 750 $DIR_PKI/CA/{alcasar-ca.crt,private/alcasar-ca.key}
chmod 750 $DIR_PKI/tls/{certs/alcasar.crt,private/alcasar.key,private/alcasar.pem,certs/server-chain.pem}
 
service lighttpd restart
else
echo "You are not import new certificates !!!"
exit 0
fi
} # end import
 
# Core script
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--export | -x)
archive
certs_export
;;
--import | -i)
nb_args=$#
if [ $nb_args -eq 1 ]
then
echo "Il faut passer un fichier de certificat en paramètre !!!"
exit 0
fi
import $2
;;
*)
echo "Unknown argument :$1";
echo "$usage"
exit 1
;;
esac
exit 0
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-ssh.sh
0,0 → 1,168
 
#!/bin/bash
 
# alcasar-ssh.sh
# by Alexandre Vezin
 
# enable/disable SSH on external card
# activation/désactivation de SSH sur la carte réseau externe
 
SED="/bin/sed -i"
CAT="/bin/cat"
GREP="/bin/grep"
SYSTEMCTL="/bin/systemctl"
ALCASAR_CONF="/usr/local/etc/alcasar.conf"
SSH_CONF="/etc/ssh/sshd_config"
 
usage="Usage: alcasar-ssh.sh {--off | -off} | {--on | -on} [-p port] [-i allowed ip] {-l lan} | {-w wan}" # | {--all | -all} à add pour off all?
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
echo "$usage"
exit 1
fi
 
while getopts ":p:i:wl" portarg; do
case "${portarg}" in
p)
SSH_PORT=${OPTARG}
NUM_REGEX='^[0-9]+$'
if ! [[ $SSH_PORT =~ $NUM_REGEX ]];
then
echo "The port $SSH_PORT is invalid"
exit 1
fi
if [ $SSH_PORT -lt 0 ] || [ $SSH_PORT -gt 65535 ]
then
echo "The port $SSH_PORT is invalid"
exit 1
fi
;;
i)
IP_FROM=${OPTARG}
ipcalc -c $IP_FROM
if [ $? -ne 0 ]
then
exit 1;
fi
;;
w)
NETWORK="wan"
;;
l)
NETWORK="lan"
;;
esac
done
 
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--off | -off)
NETWORK=${NETWORK:="none"}
if [ $NETWORK == "wan" ]
then
# Editing Alcasar configuration - Deleting the port
$SED "s/^SSH_WAN=.*/SSH_WAN=0/g" $ALCASAR_CONF
# Editing SSH configuration - Deleting any port other than 22
$SED "/^.*Port\s[0-9]*/{/\s22$/!d}" $SSH_CONF
# Applying iptables
/usr/local/bin/alcasar-iptables.sh
elif [ $NETWORK == "lan" ]
then
# Editing Alcasar configuration
$SED "s/^SSH_LAN=.*/SSH_LAN=0/g" $ALCASAR_CONF
# Applying iptables
/usr/local/bin/alcasar-iptables.sh
else
echo "$usage"
exit 0
fi
$SYSTEMCTL restart sshd
exit 0
;;
--on | -on)
NETWORK=${NETWORK:="none"}
if [ $NETWORK == "wan" ]
then
# Getting LAN IP
LAN_IP=`$GREP "^SSH_ADMIN_FROM=" $ALCASAR_CONF |cut -d"=" -f2|cut -d"/" -f1`
# Setting accepted IP in Alcasar configuration
IP_FROM=${IP_FROM:="0.0.0.0"}
$SED "s ^SSH_ADMIN_FROM=.* SSH_ADMIN_FROM=$LAN_IP/$IP_FROM g" $ALCASAR_CONF
# Setting SSH port in Alcasar configuration
SSH_PORT=${SSH_PORT:=22}
$SED "s/^SSH_WAN=.*/SSH_WAN=$SSH_PORT/g" $ALCASAR_CONF
LAN_PORT=`$GREP "^SSH_LAN=" $ALCASAR_CONF | cut -d"=" -f2`
LAN_PORT=${LAN_PORT:=0}
# Checking if there is already a port other than the LAN port set
if [ `grep -E "^.*Port\s[0-9]*" /etc/ssh/sshd_config| grep -vEc "\s$LAN_PORT$"` -gt 0 ]
then
if [ $SSH_PORT -ne $LAN_PORT ]
then
# Editing SSH configuration - Changing any port other than the LAN port
$SED "/\s$LAN_PORT$/! s/^.*Port\s[0-9]*/Port $SSH_PORT/" $SSH_CONF
else
# Editing SSH configuration - Deleting any port other than the LAN port
$SED "/^.*Port\s[0-9]*/{/\s$LAN_PORT$/!d}" $SSH_CONF
fi
else
if [ $SSH_PORT -ne $LAN_PORT ]
then
# Adding the new SSH port in the config
echo "Port $SSH_PORT" >> $SSH_CONF
fi
fi
# Applying iptables
/usr/local/bin/alcasar-iptables.sh
elif [ $NETWORK == "lan" ]
then
# Getting WAN IP
WAN_IP=`$GREP "^SSH_ADMIN_FROM=" $ALCASAR_CONF |cut -d"=" -f2|cut -d"/" -f2`
# Setting accepted IP in Alcasar configuration
IP_FROM=${IP_FROM:="0.0.0.0"}
$SED "s ^SSH_ADMIN_FROM=.* SSH_ADMIN_FROM=$IP_FROM/$WAN_IP g" $ALCASAR_CONF
# Editing Alcasar configuration
$SED "s/^SSH_LAN=.*/SSH_LAN=$SSH_PORT/g" $ALCASAR_CONF
# Setting SSH port in Alcasar configuration
SSH_PORT=${SSH_PORT:=22}
$SED "s/^SSH_LAN=.*/SSH_LAN=$SSH_PORT/g" $ALCASAR_CONF
WAN_PORT=`$GREP "^SSH_WAN=" $ALCASAR_CONF | cut -d"=" -f2`
WAN_PORT=${WAN_PORT:=0}
# Checking if there is already a port other than the WAN port set
if [ `grep -E "^.*Port\s[0-9]*" /etc/ssh/sshd_config| grep -vEc "\s$WAN_PORT$"` -gt 0 ]
then
if [ $SSH_PORT -ne $WAN_PORT ]
then
# Editing SSH configuration - Changing any port other than the WAN port
$SED "/\s$WAN_PORT$/! s/^.*Port\s[0-9]*/Port $SSH_PORT/" $SSH_CONF
else
# Editing SSH configuration - Deleting any port other than the WAN port
$SED "/^.*Port\s[0-9]*/{/\s$WAN_PORT$/!d}" $SSH_CONF
fi
else
if [ $SSH_PORT -ne $WAN_PORT ]
then
# Adding the new SSH port in the config
echo "Port $SSH_PORT" >> $SSH_CONF
fi
fi
# Applying iptables
/usr/local/bin/alcasar-iptables.sh
else
echo "$usage"
exit 0
fi
$SYSTEMCTL restart sshd
exit 0
;;
*)
echo "Argument inconnu : $1"
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-activity_report.sh
0,0 → 1,715
#!/bin/bash
# $Id$
#
# Create an activity report for ALCASAR every week (sunday at 5.35 pm --> see cron.d).
# We read configuration files and logs to create cool charts.
# Written by Raphaël PION, Rexy & Tom HOUDAYER
 
CONF_FILE='/usr/local/etc/alcasar.conf'
# files
DIR_TMP="/var/tmp"
TMP_AV="$DIR_TMP/av_count.txt"
TMP_BL="$DIR_TMP/bl_count.txt"
TMP_BL_WEEK="$DIR_TMP/bl_count_week.txt"
TMP_BL_WEEK_CAT="$DIR_TMP/bl_count_week_cat.txt"
 
# Model loaded to create charts
DIR_BUILD="/var/www/html/acc/manager/activity_report/"
MODEL_CHARTJS="$DIR_BUILD/models/Chart.report.js"
MODEL_TABINFO="$DIR_BUILD/models/tabinfo.html"
 
# Where the report will be created.
HTML_REPORT="$DIR_BUILD/alcasar-report-$(date +%F).html"
 
# TIME VALUE
C_TS=$(date +"%s") #current timestamp
MAX_DAY_AGO=7
SECS_AGO=$(date --date="$MAX_DAY_AGO days ago" +"%s") #timestamp ago
STEP_TS=$((C_TS-$SECS_AGO)) #timestamp between current timestamp and SECS_AGO
 
# PRIVATE IP OF ALCASAR
PRIVATE_IP=$(grep ^PRIVATE_IP= $CONF_FILE | cut -d'=' -f2 | cut -d'/' -f1)
 
# COLOR for charts
COLOR="'#ff0000','#3333cc','#009933','#993300','#1720EE','#D30229','#8D726D','#41C4E4','#8574F4','#A0BC1A','#BFDC1F','#5ADDC3','#B05744','#CD9319','#8CA39B','#D4AA1C','#A76752','#B03088','#445E87','#70424D','#D118C3','#46ABEF','#E9F197','#AEC0D4','#755C79','#94BBD7','#E2E9DC','#8B68D0','#F7EC7C','#1F16B8','#F4DA0A','#2EC17A','#E06483','#48B342','#F510CD','#9B2662','#180E98','#988FC1','#209E4E','#034240','#FDB142','#36B445','#CDD5C9','#6FA0DE','#EE2206','#204E19','#15FC93','#161ECE','#83D33B','#11A44A','#B7BF6C','#87274C','#B52C4F','#AD2805','#427E6C','#91341A','#191315','#FCB290','#13D3CD','#90F0E6','#C870C9','#AD2C14','#201D2A','#E4DB79','#90A919','#FE17FE','#09B35C','#88D950','#3440FC','#A9D42F','#E2DFAC','#DA69EC','#67430A','#43E94E','#5F7349','#22CF16','#CF038F','#0F6427','#F7AD0F','#C5E382','#DB49B6','#F760BF','#0BE701','#EF88D8','#79E6D7','#8A2D3D','#435A30','#A3C8AC','#99B118','#A929FF','#08A36D','#0A1654','#6F8283','#E1CA3E','#3E8577','#580FB6','#DB0E16','#386CBE','#FA0C43','#B713C9'"
 
# Values to create new htdigest user to consult statistique of ACC
DIR_KEY="/usr/local/etc/digest"
tmp_account="tmp_activityreport"
realm="ALCASAR Control Center (ACC)"
password=$(openssl rand -base64 32) #random password (length : 32)
SED="/usr/bin/sed -i "
TMP_STATS="$DIR_TMP/stats.html"
TMP_STATS_2="$DIR_TMP/stats2.html"
 
# if empty logs, replace charts by text.
ENABLE_BL=0
ENABLE_BL_WEEK=0
ENABLE_AV=0
 
if [ -e $TMP_AV ]
then
rm $TMP_AV
fi
 
if [ -e $TMP_BL ]
then
rm $TMP_BL
fi
 
if [ -e $TMP_BL_WEEK ]
then
rm $TMP_BL_WEEK
fi
 
if [ -e $TMP_BL_WEEK_CAT ]
then
rm $TMP_BL_WEEK_CAT
fi
 
if [ -e $HTML_REPORT ]
then
rm $HTML_REPORT
fi
 
echo "<!doctype html>" >> $HTML_REPORT
echo "<html>" >> $HTML_REPORT
echo "<head>" >> $HTML_REPORT
echo "<meta charset=\"utf-8\">" >> $HTML_REPORT
echo "<title>ALCASAR report</title>" >> $HTML_REPORT
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../css/bootstrap.min.css\">" >> $HTML_REPORT
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../css/report.css\">" >> $HTML_REPORT
echo "<script src=\"../../../js/Chart.bundle.min.js\"></script>" >> $HTML_REPORT
echo "<script src=\"../../../js/jquery.min.js\"></script>" >> $HTML_REPORT
echo "</head>" >> $HTML_REPORT
echo "<body>" >> $HTML_REPORT
echo "<h1><center>Rapport d'activité de l'ALCASAR-$(grep ^ORGANISM= $CONF_FILE | cut -d'=' -f2-)</center></h1>" >> $HTML_REPORT
echo "<i><p style=\"text-align: right;\">Date de création $(date +%F)</p></i>" >> $HTML_REPORT
echo "<font size=\"1\">" >> $HTML_REPORT
 
######################TABINFO######################
echo "Create information about system and ALCASAR"
#contain every information about ALCASAR configuration, system and last update
 
cat $MODEL_TABINFO | while read LINE_HTML
do
if [ "$(echo $LINE_HTML | grep 'XXORGXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^ORGANISM= $CONF_FILE | cut -d'=' -f2-)
echo ${LINE_HTML/XXORGXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXINSTALLXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^INSTALL_DATE= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXINSTALLXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXAVERSIONXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^VERSION= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXAVERSIONXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXIP_PUBLICXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^PUBLIC_IP= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXIP_PUBLICXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXIP_PRIVEXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^PRIVATE_IP= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXIP_PRIVEXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXGWXX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^GW= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXGWXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXDNS1XX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^DNS1= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXDNS1XX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXDNS2XX' | wc -l)" -eq 1 ]
then
VALUE=$(grep ^DNS2= $CONF_FILE | cut -d'=' -f2)
echo ${LINE_HTML/XXDNS2XX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXHOSTXX' | wc -l)" -eq 1 ]
then
VALUE=$(hostname)
echo ${LINE_HTML/XXHOSTXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXOS_VERSIONXX' | wc -l)" -eq 1 ]
then
VALUE=$(echo "$(uname -r) [ $(uname -m) ]")
echo ${LINE_HTML/XXOS_VERSIONXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXREBOOTXX' | wc -l)" -eq 1 ]
then
VALUE=$(who -b | cut -d' ' -f12-)
echo ${LINE_HTML/XXREBOOTXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXMAJCLAMAVXX' | wc -l)" -eq 1 ]
then
VALUE=$(date -d "@$(rpm -qa --queryformat "%{installtime} %{name}\n" | grep -E "clamav-db" | cut -d' ' -f1 )" "+%Y-%m-%d %H:%M:%S")
echo ${LINE_HTML/XXMAJCLAMAVXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXMAJBLXX' | wc -l)" -eq 1 ]
then
VALUE=$(cat /etc/e2guardian/lists/blacklists/README | grep 'Last version' | cut -d' ' -f4-6)
echo ${LINE_HTML/XXMAJBLXX/$VALUE} >> $HTML_REPORT
 
elif [ "$(echo $LINE_HTML | grep 'XXRPMXX' | wc -l)" -eq 1 ]
then
#show every ALCASAR RPM updated since X day ago
#get timestamp of X day ago. Then we get every packets chich have been updated since this date.
if [ "$(rpm -qa --queryformat '%{installtime} %{name} %{version}\n' | awk -v seuil="$SECS_AGO" '$1 > seuil' | sort -n | grep -E "$PACKAGE" | wc -l)" -gt 1 ]
then
PACKAGE='php|lighttpd|iptables|unbound|radius|nfdump|e2guardian|clamav|ulogd|chilli|fail2ban|openssh|ipt-netflow|wget|mariadb|gnupg|openssl'
rpm -qa --queryformat '%{installtime} %{name} %{version}\n' | awk -v seuil="$SECS_AGO" '$1 > seuil' | sort -n | grep -E "$PACKAGE" | while read RPM_ALCASAR
do
RPM_TIMESTAMP=$(echo $RPM_ALCASAR | cut -d' ' -f1)
RPM_DATE=$(date -d "@$(echo $RPM_TIMESTAMP)" "+%Y-%m-%d %H:%M:%S")
RPM_NAME=$(echo $RPM_ALCASAR | cut -d' ' -f2)
RPM_VERSION=$(echo $RPM_ALCASAR | cut -d' ' -f3)
 
echo "<tr>" >> $HTML_REPORT
echo "<td>$RPM_NAME</td>" >> $HTML_REPORT
echo "<td>$RPM_DATE</td>" >> $HTML_REPORT
echo "<td>$RPM_VERSION</td>" >> $HTML_REPORT
echo "</tr>" >> $HTML_REPORT
done
else
echo "<tr><td colspan=\"3\">Pas de RPM mis à jour cette semaine</td></tr>" >> $HTML_REPORT
fi
else
echo $LINE_HTML >> $HTML_REPORT
fi
done
 
######################BL WEBSITE SINCE INSTALLATION######################
echo "Create BL website since the installation of ALCASAR"
#find data
 
#decompress every logs
if [ "$(ls -1 /var/log/unbound/unbound-blacklist.log.*.gz 2>/dev/null | wc -l)" -ge 1 ]
then
gunzip -d unbound-blacklist.log.*.gz
fi
 
#convert logs date in timestamp and find categories of blacklisted website
tmp_log=$(mktemp)
for FILE in /var/log/unbound/unbound-blacklist.log*
do
grep -E "info: [^ ]+ typetransparent $PRIVATE_IP" /var/log/unbound/unbound-blacklist.log > $tmp_log
while read LOG_BL
do
# find the current blacklisted category
website_bl=$(echo $LOG_BL | cut -d' ' -f4)
website_bl=${website_bl%?} # remove the last character
 
#we convert www.test.co.uk => test.co.uk to find the category of this website
if [ "$(grep -o '\.' <<< "$website_bl" | wc -l)" -ge "2" ]
then
website_bl=$(echo $website_bl | cut -d'.' -f2-)
fi
 
#get BL category
categorie_bl=$(grep -Rl "$website_bl" /usr/local/share/unbound-bl-enabled/ | cut -d'/' -f6 | head -1)
 
CURRENT_TS=$(echo $LOG_BL | cut -d '[' -f2 | cut -d ']' -f1)
echo "$CURRENT_TS:$categorie_bl:" >> $TMP_BL
done < $tmp_log
done
rm $tmp_log
 
#if data exists, create this section in html document
if [ -e $TMP_BL ]
then
ENABLE_BL=1
#count every BL website consulted since installation (maximum 1 year)
DATE_END=$(cat $TMP_BL | cut -d':' -f1 | sort -n | head -1 )
 
 
for TS in $(seq $C_TS -$STEP_TS $DATE_END)
do
DATE_1=$TS
DATE_2=$((TS-$STEP_TS))
COUNT_BL_INSTALLATION=0
 
for LINE in $(cat $TMP_BL)
do
TS_FILE=$(echo $LINE | cut -d':' -f1)
 
if [ "$TS_FILE" -le "$DATE_1" ] && [ "$TS_FILE" -ge "$DATE_2" ]
then
COUNT_BL_INSTALLATION=$((COUNT_BL_INSTALLATION+1))
fi
done
 
VALUE_BL_INSTALLATION_LABEL="'$(date -d @$DATE_2 "+%Y-%m-%d" )', $VALUE_BL_INSTALLATION_LABEL"
VALUE_BL_INSTALLATION_DATA="$COUNT_BL_INSTALLATION, $VALUE_BL_INSTALLATION_DATA"
done
 
#create Antivirus section in html document
NAME_BL_INSTALLATION='chart_bl_installation'
CONF_BL_INSTALLATION='config_bl_installation'
echo "<center>" >> $HTML_REPORT
echo "<canvas id='$NAME_BL_INSTALLATION' width='450' height='450'></canvas>" >> $HTML_REPORT
echo "</center>" >> $HTML_REPORT
 
#create chart bar in html file with javascript (chartjs.com)
echo "<script>" >> $HTML_REPORT
cat $MODEL_CHARTJS | while read LINE_JS
do
#name of variable
if [ "$(echo $LINE_JS | grep 'XXCONFXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCONFXX/$CONF_BL_INSTALLATION} >> $HTML_REPORT
#chart type
elif [ "$(echo $LINE_JS | grep 'XXTYPEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTYPEXX/bar} >> $HTML_REPORT
#chart title
elif [ "$(echo $LINE_JS | grep 'XXTITLEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTITLEXX/"Sites bloqués au total"} >> $HTML_REPORT
#chart data
elif [ "$(echo $LINE_JS | grep 'XXDATAXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXDATAXX/$VALUE_BL_INSTALLATION_DATA} >> $HTML_REPORT
#color
elif [ "$(echo $LINE_JS | grep 'XXCOLORXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCOLORXX/$COLOR} >> $HTML_REPORT
#labels
elif [ "$(echo $LINE_JS | grep 'XXLABELSXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLABELSXX/$VALUE_BL_INSTALLATION_LABEL} >> $HTML_REPORT
elif [ "$(echo $LINE_JS | grep 'XXLEGENDXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLEGENDXX/false} >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-BEGINXX' | wc -l)" -eq 1 ]
then
echo "" >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-ENDXX' | wc -l)" -eq 1 ]
then
echo "" >> $HTML_REPORT
elif [ "$(echo $LINE_JS | grep 'XXYLABELXX' | wc -l)" -eq 1 ]
then
echo "\"Nombre de site bloqué par la blacklist\"" >> $HTML_REPORT
else
echo $LINE_JS >> $HTML_REPORT
fi
done
echo "</script>" >> $HTML_REPORT
else
echo "<h2>Aucune activité de la Blacklist depuis l'installation.</h2>" >> $HTML_REPORT
fi
 
 
 
######################Unbound BLACKLIST######################
echo "Create BL website since $MAX_DAY_AGO days"
 
#if data exists, create BL section in html document
if [ -e $TMP_BL ]
then
ENABLE_BL_WEEK=1
#find data
#count every BL website consulted since DAYS_AGO
DATE_1=$C_TS
DATE_2=$((DATE_1-$STEP_TS))
 
touch $TMP_BL_WEEK
 
for LINE in $(cat $TMP_BL)
do
TS_FILE=$(echo $LINE | cut -d':' -f1)
#select only elements between DATE_1 and DATE_2
if [ "$TS_FILE" -le "$DATE_1" ] && [ "$TS_FILE" -ge "$DATE_2" ]
then
echo $LINE >> $TMP_BL_WEEK
fi
done
 
#then we count every occurence for each category in TMP_BL_WEEK
for CAT in $(ls /usr/local/share/unbound-bl/ -1 | cut -d'.' -f1)
do
echo "$CAT:$(grep -o ":$CAT:" <<< "$(cat $TMP_BL_WEEK)" | wc -l):" >> $TMP_BL_WEEK_CAT
done
 
#we sort by number of occurence and we take the top 10 BL categories
for LINE in $(sort -t':' -k2 -rn $TMP_BL_WEEK_CAT | head -n 10)
do
 
DATA=$(echo $LINE | cut -d':' -f2)
LABEL=$(echo $LINE | cut -d':' -f1)
if [ $DATA -ne 0 ]
then
VALUE_BL_DATA="$VALUE_BL_DATA $DATA, "
VALUE_BL_LABEL="$VALUE_BL_LABEL '$LABEL ($DATA)',"
fi
done
 
#get other categories (sum them all)
if [ "$(cat $TMP_BL_WEEK_CAT | cut -d':' -f2 | sort -k1 -rn | tail -n+$(($(echo $VALUE_BL_DATA | wc -w)+1)) | paste -sd+ | bc)" -gt 0 ]
then
VALUE_BL_DATA="$VALUE_BL_DATA $(cat $TMP_BL_WEEK_CAT | cut -d':' -f2 | sort -k1 -rn | tail -n+$(($(echo $VALUE_BL_DATA | wc -w)+1)) | paste -sd+ | bc)"
VALUE_BL_LABEL="$VALUE_BL_LABEL 'autre ($(cat $TMP_BL_WEEK_CAT | cut -d':' -f2 | sort -k1 -rn | tail -n+$(($(echo $VALUE_BL_DATA | wc -w)+1)) | paste -sd+ | bc))'"
fi
 
#create chart pie in html file with javascript (chartjs.com)
NAME_BL='chart_bl'
CONF_BL='config_bl'
echo "<center>" >> $HTML_REPORT
echo "<canvas id='$NAME_BL' width='450' height='450' ></canvas>" >> $HTML_REPORT
echo "</center>" >> $HTML_REPORT
echo "<script>" >> $HTML_REPORT
 
cat $MODEL_CHARTJS | while read LINE_JS
do
#variable name
if [ "$(echo $LINE_JS | grep 'XXCONFXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCONFXX/$CONF_BL} >> $HTML_REPORT
#chart type
elif [ "$(echo $LINE_JS | grep 'XXTYPEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTYPEXX/pie} >> $HTML_REPORT
#graph title
elif [ "$(echo $LINE_JS | grep 'XXTITLEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTITLEXX/"Sites bloqués cette semaine"} >> $HTML_REPORT
#chart data
elif [ "$(echo $LINE_JS | grep 'XXDATAXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXDATAXX/$VALUE_BL_DATA} >> $HTML_REPORT
#color
elif [ "$(echo $LINE_JS | grep 'XXCOLORXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCOLORXX/$COLOR} >> $HTML_REPORT
#labels
elif [ "$(echo $LINE_JS | grep 'XXLABELSXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLABELSXX/$VALUE_BL_LABEL} >> $HTML_REPORT
#display legend, only useful for chart pie
elif [ "$(echo $LINE_JS | grep 'XXLEGENDXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLEGENDXX/true} >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-BEGINXX' | wc -l)" -eq 1 ]
then
echo "/*" >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-ENDXX' | wc -l)" -eq 1 ]
then
echo "*/" >> $HTML_REPORT
else
echo $LINE_JS >> $HTML_REPORT
fi
done
echo "</script>" >> $HTML_REPORT
else
echo "<h2>Aucune activité de la Blacklist cette semaine.</h2>" >> $HTML_REPORT
fi
 
######################VIRUS THREAT######################
echo "Create AV logs since the installation of ALCASAR"
 
#decompress every logs, if they exist
if [ "$(ls -1 /var/log/clamav/clamd.log.*.gz 2>/dev/null | wc -l)" -ge 1 ]
then
gunzip -d clamd.log.*.gz
fi
 
for FILE in /var/log/clamav/clamd.log*
do
while read LINE_AV
do
if [ "`echo $LINE_AV|grep -c FOUND`" == 1 ]
then
Y=$(echo $LINE_AV | cut -d' ' -f5)
M=$(echo $LINE_AV | cut -d' ' -f2)
D=$(echo $LINE_AV | cut -d' ' -f3)
H=$(echo $LINE_AV | cut -d' ' -f4)
CURRENT_TS=$(date -d "$M $D $Y $H" +"%s")
echo $CURRENT_TS >> $TMP_AV
fi
done < $FILE
done
 
if [ -e $TMP_AV ]
then
ENABLE_AV=1
DATE_END=$(cat $TMP_AV | sort -n | head -1)
for TS in $(seq $C_TS -$STEP_TS $DATE_END)
do
DATE_1=$TS
DATE_2=$((TS-$STEP_TS))
COUNT_AV=0
 
for TS_FILE in $(cat $TMP_AV)
do
if [ "$TS_FILE" -le "$DATE_1" ] && [ "$TS_FILE" -ge "$DATE_2" ]
then
COUNT_AV=$((COUNT_AV+1))
fi
done
 
VALUE_AV_LABEL="'$(date -d @$DATE_2 "+%Y-%m-%d" )', $VALUE_AV_LABEL"
VALUE_AV_DATA="$COUNT_AV, $VALUE_AV_DATA"
done
 
#create Antivirus section in html document
NAME_AV='chart_av'
CONF_AV='config_av'
echo "<center>" >> $HTML_REPORT
echo "<canvas id='$NAME_AV' width='450' height='450' ></canvas>" >> $HTML_REPORT
echo "</center>" >> $HTML_REPORT
 
 
#create chart bar in html file with javascript (chartjs.com)
echo "<script>" >> $HTML_REPORT
cat $MODEL_CHARTJS | while read LINE_JS
do
#name of variable
if [ "$(echo $LINE_JS | grep 'XXCONFXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCONFXX/$CONF_AV} >> $HTML_REPORT
#chart type
elif [ "$(echo $LINE_JS | grep 'XXTYPEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTYPEXX/bar} >> $HTML_REPORT
#graph title
elif [ "$(echo $LINE_JS | grep 'XXTITLEXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXTITLEXX/"Menaces bloqués par l\'antivirus"} >> $HTML_REPORT
#chart data
elif [ "$(echo $LINE_JS | grep 'XXDATAXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXDATAXX/$VALUE_AV_DATA} >> $HTML_REPORT
#color
elif [ "$(echo $LINE_JS | grep 'XXCOLORXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXCOLORXX/$COLOR} >> $HTML_REPORT
#labels
elif [ "$(echo $LINE_JS | grep 'XXLABELSXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLABELSXX/$VALUE_AV_LABEL} >> $HTML_REPORT
elif [ "$(echo $LINE_JS | grep 'XXLEGENDXX' | wc -l)" -eq 1 ]
then
echo ${LINE_JS/XXLEGENDXX/false} >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-BEGINXX' | wc -l)" -eq 1 ]
then
echo "" >> $HTML_REPORT
#display value of Y axis, only useful for chart bar
elif [ "$(echo $LINE_JS | grep 'XXCOMMENT-ENDXX' | wc -l)" -eq 1 ]
then
echo "" >> $HTML_REPORT
elif [ "$(echo $LINE_JS | grep 'XXYLABELXX' | wc -l)" -eq 1 ]
then
echo "\"Nombre de menaces virales bloqués par l'antivirus\"" >> $HTML_REPORT
else
echo $LINE_JS >> $HTML_REPORT
fi
done
echo "</script>" >> $HTML_REPORT
else
echo "<h2>Aucune menace virale.</h2>" >> $HTML_REPORT
fi
 
 
######################ALCASAR : DAILY USE######################
echo "Get daily use connection of the week"
#create html document
echo "<h2>Statistiques volumétrie connexions</h2>" >> $HTML_REPORT
 
#create new htdigest user to consult statistique of ACC
#if user does not exist, we create him
if [ "$(grep "$tmp_account:" $DIR_KEY/key_only_manager | wc -l)" -lt 1 ]
then
(echo -n "$tmp_account:$realm:" && echo -n "$tmp_account:$realm:$password" | md5sum | awk '{print $1}' ) >> $DIR_KEY/key_only_manager
(echo -n "$tmp_account:$realm:" && echo -n "$tmp_account:$realm:$password" | md5sum | awk '{print $1}' ) >> $DIR_KEY/key_manager
(echo -n "$tmp_account:$realm:" && echo -n "$tmp_account:$realm:$password" | md5sum | awk '{print $1}' ) >> $DIR_KEY/key_all
chown -R root:apache $DIR_KEY
chmod 640 $DIR_KEY/key_*
fi
 
#get stats.php from ACC
wget -q -nv --user $tmp_account --password $password https://alcasar/acc/manager/htdocs/stats.php -O $TMP_STATS --no-check-certificate
 
#clean this file to include it in html report.
DELIM_1="<td colspan=10 height=20><img src=\"images\/pixel.gif\"><\/td>"
DELIM_2="<\/td><\/tr> <\/table> <\/td><\/tr> <\/table> <\/td><\/tr> <\/table> <p>"
cat $TMP_STATS | sed -n "/$DELIM_1/,/$DELIM_2/p" | tail -n+3 | head -n-2 >> $TMP_STATS_2
cat $TMP_STATS_2 | sed -e 's:images/pixel.gif:../../manager/htdocs/images/pixel.gif:g' >> $HTML_REPORT
 
#we delete our user if he still exists
if [ "$(grep "$tmp_account:" $DIR_KEY/key_only_manager | wc -l)" -ge 1 ]
then
$SED "/^$tmp_account:/d" $DIR_KEY/key_only_manager
$SED "/^$tmp_account:/d" $DIR_KEY/key_manager
$SED "/^$tmp_account:/d" $DIR_KEY/key_all
fi
 
 
###################### ALCASAR : LOG ACCESS ######################
echo "Get ACC log access of the week"
 
ROWS=""
while read -r access ; do
access_datas=(${access//|/ })
 
accces_date_intl=$(echo "${access_datas[0]} ${access_datas[1]}" | sed -E 's@^([0-9]{2})+/+([0-9]{2})+/+([0-9]{4})+@\3-\2-\1@') # Convert date format DD/MM/YYYY to YYYY-MM-DD
access_date=$(date -d "$accces_date_intl" +%s)
access_user=${access_datas[2]}
access_ip=${access_datas[3]}
access_agent=$(echo "$access" | cut -d'|' -f4)
if [ $access_date -lt $SECS_AGO ]; then
break
fi
 
access_date_formatted=$(date -d @$access_date +"%x %X")
 
ROWS="$ROWS<tr><td>$access_date_formatted</td><td>$access_user</td><td>$access_ip</td><td>$access_agent</td></tr>"
done < <(cat /var/Save/security/acc_access.log | sort -r)
# TODO: Read archives if necessary
 
if [ -z "$ROWS" ]; then
ROWS="<tr><td colspan=\"4\" style=\"text-align: center;\">Aucune connexion</td></tr>"
fi
 
# Create HTML document
echo "<h2>Connexion à l'ALCASAR Control Center (ACC)</h2>" >> $HTML_REPORT
echo "<table class=\"table table-striped\">" >> $HTML_REPORT
echo "<thead><tr><th>Date</th><th>Utilisateur</th><th>Adresse IP</th><th>Agent</th></tr></thead><tbody>" >> $HTML_REPORT
echo "$ROWS" >> $HTML_REPORT
echo "</tbody></table>" >> $HTML_REPORT
 
 
###################### ALCASAR : GLOBAL TRAFFIC ######################
echo "Get Global traffic of the last 30 days"
 
ROWS=""
EXTIF=$(grep ^EXTIF= $CONF_FILE | cut -d'=' -f2)
for day in $(vnstat --exportdb -i $EXTIF | grep '^d;' | sort -t";" -k3 -r); do
day_datas=(${day//;/ })
day_date=${day_datas[2]}
day_rxMio=${day_datas[3]}
day_txMio=${day_datas[4]}
day_rxKio=${day_datas[5]}
day_txKio=${day_datas[6]}
day_act=${day_datas[7]}
 
if [ $day_act -ne 1 ]; then
continue
fi
 
if [ $day_date -lt $SECS_AGO ]; then
break
fi
 
day_date_formatted=$(date -d @$day_date +%x)
day_rx=$(($day_rxMio * 1048576 + $day_rxKio * 1024))
day_tx=$(($day_txMio * 1048576 + $day_txKio * 1024))
day_total=$(($day_rx + $day_tx))
day_rx_formatted=$(numfmt --from=iec --to=iec --suffix=B $day_rx)
day_tx_formatted=$(numfmt --from=iec --to=iec --suffix=B $day_tx)
day_total_formatted=$(numfmt --from=iec --to=iec --suffix=B $day_total)
 
ROWS="$ROWS<tr><td>$day_date_formatted</td><td>$day_rx_formatted</td><td>$day_tx_formatted</td><td>$day_total_formatted</td></tr>"
done
 
if [ -z "$ROWS" ]; then
ROWS="<tr><td colspan=\"4\" style=\"text-align: center;\">Aucun jour capturé</td></tr>"
fi
 
# Create html document
echo "<h2>Trafic global</h2>" >> $HTML_REPORT
echo "<table class=\"table table-striped\">" >> $HTML_REPORT
echo "<thead><tr><th>Date</th><th>Entrant</th><th>Sortant</th><th>Total</th></tr></thead><tbody>" >> $HTML_REPORT
echo "$ROWS" >> $HTML_REPORT
echo "</tbody></table>" >> $HTML_REPORT
 
 
###################### ALCASAR : FAIL2BAN ######################
echo "Get fail2ban log of the week"
 
ROWS=""
dateDaysAgo_formatted=$(date --date="$MAX_DAY_AGO days ago" +'%Y-%m-%d %H:%M:%S,%N' | rev | cut -c 7- | rev)
while read -r log ; do
log_datas=($log)
log_date="${log_datas[0]} ${log_datas[1]}"
log_type=${log_datas[4]:1:-1}
log_ip=${log_datas[6]}
log_date_formatted=$(date -d "$log_date" +"%x %X")
 
ROWS="$ROWS<tr><td>$log_date_formatted</td><td>$log_ip</td><td>$log_type</td></tr>"
done < <(grep " Ban " /var/log/fail2ban.log | sort -r | awk -v dateDaysAgo="$dateDaysAgo_formatted" '($1 " " $2) >= dateDaysAgo')
 
if [ -z "$ROWS" ]; then
ROWS="<tr><td colspan=\"3\" style=\"text-align: center;\">Aucune adresse IP bloquée</td></tr>"
fi
 
# Create html document
echo "<h2>Adresse(s) IP bloquée(s) (Fail2Ban)</h2>" >> $HTML_REPORT
echo "<table class=\"table table-striped\">" >> $HTML_REPORT
echo "<thead><tr><th>Date</th><th>Adresse IP</th><th>Règle</th></tr></thead><tbody>" >> $HTML_REPORT
echo $ROWS >> $HTML_REPORT
echo "</tbody></table>" >> $HTML_REPORT
 
 
######################FIN HTML######################
 
#Execute our javascript function to print charts
echo "<script>window.onload = function() {" >> $HTML_REPORT
#BL SINCE INSTALLATION
if [ $ENABLE_BL -eq "1" ]
then
echo "var ctx_$NAME_BL_INSTALLATION = document.getElementById('$NAME_BL_INSTALLATION').getContext('2d');" >> $HTML_REPORT
echo "var $NAME_BL_INSTALLATION = new Chart(ctx_$NAME_BL_INSTALLATION, $CONF_BL_INSTALLATION);" >> $HTML_REPORT
fi
#BL WEEK
if [ $ENABLE_BL_WEEK -eq "1" ]
then
echo "var ctx_$NAME_BL = document.getElementById('$NAME_BL').getContext('2d');" >> $HTML_REPORT
echo "var $NAME_BL = new Chart(ctx_$NAME_BL, $CONF_BL);" >> $HTML_REPORT
fi
#VIRUS THREAT
if [ $ENABLE_AV -eq "1" ]
then
echo "var ctx_$NAME_AV = document.getElementById('$NAME_AV').getContext('2d');" >> $HTML_REPORT
echo "var $NAME_AV = new Chart(ctx_$NAME_AV, $CONF_AV);" >> $HTML_REPORT
fi
echo "};</script>" >> $HTML_REPORT
echo "</body>" >> $HTML_REPORT
echo "</html>" >> $HTML_REPORT
 
#convert html document to PDF
/usr/bin/wkhtmltopdf $HTML_REPORT "$(echo $HTML_REPORT | cut -d'.' -f1).pdf"
chown apache:apache "$(echo $HTML_REPORT | cut -d'.' -f1).pdf"
chmod 644 "$(echo $HTML_REPORT | cut -d'.' -f1).pdf"
mv "$(echo $HTML_REPORT | cut -d'.' -f1).pdf" /var/Save/activity_report/
 
#compress every logs, if they exist
if [ "$(ls -1 /var/log/clamav/clamd.log.* 2>/dev/null | wc -l)" -ge 1 ]
then
gzip /var/log/clamav/clamd.log.*
fi
 
#compress every logs
if [ "$(ls -1 /var/log/unbound/unbound-blacklist.log.* 2>/dev/null | wc -l)" -ge 1 ]
then
gzip /var/log/unbound/unbound-blacklist.log.*
fi
 
#remove our files
rm -f $TMP_BL
rm -f $TMP_BL_WEEK
rm -f $TMP_BL_WEEK_CAT
rm -f $TMP_STATS
rm -f $TMP_STATS_2
rm -f $HTML_REPORT
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-dns-local.sh
0,0 → 1,141
#!/bin/bash
# $Id$
 
# alcasar-dns-local.sh
# by Rexy - 3abtux
# This script is distributed under the Gnu General Public License (GPL)
 
# active ou desactive la redirection du service DNS sur le réseau de consultation
# enable or disable the redirector of internal DNS service on consultation LAN
 
SED="/bin/sed -i"
 
ALCASAR_CONF_FILE="/usr/local/etc/alcasar.conf"
LOCAL_DOMAIN_CONF_FILE="/etc/unbound/conf.d/common/local-forward/dns-redirector.conf"
LOCAL_HOSTNAME_FILE="/etc/hosts"
 
# define DNS parameters (LAN side)
INT_DNS_DOMAIN=`grep ^DOMAIN $ALCASAR_CONF_FILE|cut -d"=" -f2`
INT_DNS_HOST=`grep ^HOSTNAME $ALCASAR_CONF_FILE|cut -d"=" -f2`
INT_DNS_IP_MASK=`grep ^PRIVATE_IP $ALCASAR_CONF_FILE|cut -d"=" -f2`
INT_DNS_IP=`grep ^PRIVATE_IP $ALCASAR_CONF_FILE|cut -d"=" -f2|cut -d"/" -f1`
INTIF=`grep ^INTIF $ALCASAR_CONF_FILE|cut -d"=" -f2`
INT_DNS_ACTIVE=`grep INT_DNS_ACTIVE $ALCASAR_CONF_FILE|cut -d"=" -f2`
LOCAL_DNS_FILE="/etc/unbound/conf.d/common/local-dns/$INTIF.conf"
 
usage="Usage: alcasar-dns-local.sh {--on | -on} | {--off | -off} | {--add | -add} ip domain | {--del | -del} ip domain | {--reload | -reload}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
echo "$usage"
exit 1
fi
 
function restart_dns(){
for dns in unbound unbound-blacklist unbound-whitelist unbound-blackhole
do
echo "Restarting $dns. Please wait..."
systemctl restart $dns
done
}
 
function hosts_to_unbound(){ # configure the unbound conf file with local host names resolution
cat << EOF > $LOCAL_DNS_FILE
server:
local-data: "$INT_DNS_HOST.$INT_DNS_DOMAIN IN A $INT_DNS_IP"
local-data-ptr: "$INT_DNS_IP $INT_DNS_HOST.$INT_DNS_DOMAIN"
EOF
while read -r line
do
ip_address=$(echo $line | awk '{ print $1 }')
domain=$(echo $line | awk '{ print $2 }')
if ! echo $line | grep -E -q "^([0-9\.\t ]+alcasar( |$)|127\.0\.0)"
then
echo -e "\tlocal-data: \"$domain.$INT_DNS_DOMAIN IN A $ip_address\"" >> $LOCAL_DNS_FILE
echo -e "\tlocal-data-ptr: \"$ip_address $domain.$INT_DNS_DOMAIN\"" >> $LOCAL_DNS_FILE
fi
done < $LOCAL_HOSTNAME_FILE
if [ $INT_DNS_DOMAIN == "localdomain" ]
then
echo -e "\tlocal-zone: \"$INT_DNS_DOMAIN\" static" >> $LOCAL_DNS_FILE # Don't forward this local zone
fi
}
 
case $args in
-\? | -h | --h)
echo "$usage"
exit 0
;;
--add|-add) # add a local host resolution
if [ $nb_args -ne 3 ]
then
echo "$usage"
exit 1
else
# removing if already exists
$SED "/^$2[ \t]*$3/d" $LOCAL_HOSTNAME_FILE
# adding to the hosts file
echo -e "$2\t$3" >> $LOCAL_HOSTNAME_FILE
hosts_to_unbound
restart_dns
fi
;;
--del|-del) # remove a local host resolution
if [ $nb_args -ne 3 ]
then
echo "$usage"
exit 1
else
$SED "/^$2[ \t]*$3/d" $LOCAL_HOSTNAME_FILE
hosts_to_unbound
restart_dns
fi
;;
--reload|-reload)
hosts_to_unbound
restart_dns
;;
--hosts_to_unbound|-hosts_to_unbound)
hosts_to_unbound
;;
--off|-off) # disable DNS redirector
rm -f $LOCAL_DOMAIN_CONF_FILE
$SED "s?^INT_DNS_ACTIVE.*?INT_DNS_ACTIVE=off?g" $ALCASAR_CONF_FILE
restart_dns
/usr/local/bin/alcasar-iptables.sh
;;
--off-without-restart|-off-without-restart) # disable DNS redirector
rm -f $LOCAL_DOMAIN_CONF_FILE
$SED "s?^INT_DNS_ACTIVE.*?INT_DNS_ACTIVE=off?g" $ALCASAR_CONF_FILE
/usr/local/bin/alcasar-iptables.sh
;;
--on|-on) # enable DNS redirector
cat > $LOCAL_DOMAIN_CONF_FILE << EOF
server:
local-zone: "$INT_DNS_DOMAIN." transparent
forward-zone:
name: "$INT_DNS_DOMAIN."
forward-addr: $INT_DNS_IP
EOF
$SED "s?^INT_DNS_ACTIVE.*?INT_DNS_ACTIVE=on?g" $ALCASAR_CONF_FILE
restart_dns
/usr/local/bin/alcasar-iptables.sh
;;
--on-without-restart|-on-without-restart) # enable DNS redirector
cat > $LOCAL_DOMAIN_CONF_FILE << EOF
server:
local-zone: "$INT_DNS_DOMAIN." transparent
forward-zone:
name: "$INT_DNS_DOMAIN."
forward-addr: $INT_DNS_IP
EOF
$SED "s?^INT_DNS_ACTIVE.*?INT_DNS_ACTIVE=on?g" $ALCASAR_CONF_FILE
/usr/local/bin/alcasar-iptables.sh
;;
*)
echo "Argument inconnu : $1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-sms.sh
0,0 → 1,498
#!/bin/bash
# $Id$
 
# alcasar-sms.sh
# by Nicolas Aubry & Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# This script manages the 'gammu-smsd' service when a GSM adapter is detected
# Ce script gère le service 'gammu-smsd' quand un adaptateur GSM est détecté
 
CONF_FILE='/usr/local/etc/alcasar.conf'
 
####### VARIABLES ########
nb_essais=3
time_account=1
time_ban=2
####### IDs DB ##########################
PASSWD_FILE="/root/ALCASAR-passwords.txt"
u_db=$(grep '^db_user=' $PASSWD_FILE | cut -d'=' -f2-)
p_db=$(grep '^db_password=' $PASSWD_FILE | cut -d'=' -f2-)
#########################################
 
rad="radcheck"
radgp="radusergroup"
radgpck="radgroupcheck"
radinf="userinfo"
sms_p="SMS_ban_perm"
sms_t="SMS_ban_temp"
inb="inbox"
SMS_c="SMS_country"
config="/etc/gammu_smsd_conf"
config2="/etc/gammurc"
logfile="/var/log/gammu-smsd/gammu-smsd.log"
script="/usr/local/bin/alcasar-sms.sh"
separator="########## START ##########"
end="%%%%%%%%%% STOP %%%%%%%%%%"
 
usage="Usage: alcasar-gammu.sh
Start Gammu-smsd : --start
Stop Gammu-smsd : --stop
Process on new sms : --new_sms"
 
nb_args=$#
args=$1
 
# Functions
function mode_huawei() {
couple=$(lsusb | grep -i huawei | cut -d ' ' -f6)
vendor=$(echo $couple | cut -d ':' -f1)
product=$(echo $couple | cut -d ':' -f2)
echo "******** Modeswitch *************" >> $logfile
echo $vendor >> $logfile
echo $product >> $logfile
/usr/sbin/usb_modeswitch -I -H -v 0x$vendor -p 0x$product -V 0x$vendor -P 0x$product -W -n >> $logfile
} # end function mode_huawei
 
function start_gammu() {
# Truncate phones table (informations signal/IMEI/battery/sent et reveived sms)
mysql --user=$u_db --password=$p_db --database=gammu -Bs -e 'TRUNCATE phones;'
# Verify the sms group is created
if [ $(mysql --user=$u_db --password=$p_db --database=radius -Bs -e "SELECT COUNT(*) FROM $radgp WHERE username='sms' AND groupname='sms';") -eq 0 ]; then
sql_add_gp="INSERT INTO $radgp (username,groupname) VALUES ('sms','sms'); INSERT INTO $radgpck (groupname,attribute,op,value) VALUES ('sms','Simultaneous-Use',':=',1);"
mysql --user=$u_db --password=$p_db --database=radius -Bs -e "$sql_add_gp"
fi
# Start gammu
echo $separator >> $logfile
/usr/bin/systemctl -q start gammu-smsd.service
/usr/bin/systemctl -q enable gammu-smsd.service
} # end function start_gammu
 
function stop_gammu() {
/usr/bin/systemctl -q stop gammu-smsd.service
/usr/bin/systemctl -q disable gammu-smsd.service
echo $end >> $logfile
} # end function stop_gammu
 
function unlock() {
# Remove phone number in SMS_ban_perm table
sql_remove_ban_perm="connect gammu; DELETE FROM $sms_p"
mysql --user=$u_db --password=$p_db -B -se "$sql_remove_ban_perm WHERE SenderNumber=$1;"
# Add sms group
sql_remove_gp="connect radius; DELETE FROM $radgp WHERE username='$1';"
mysql --user=$u_db --password=$p_db -B -se "$sql_remove_gp"
# Remove account in Radcheck table
sql_remove_compte="connect radius; DELETE FROM $rad WHERE username='$1';"
mysql --user=$u_db --password=$p_db -B -se "$sql_remove_compte"
} # end function unlock
 
function change_country() {
sql_status_country="connect gammu; SELECT status FROM SMS_country WHERE name='$1'"
stat=$(mysql --user=$u_db --password=$p_db -B -se "$sql_status_country")
if [ $stat -eq 0 ]
then
sql_change_country="connect gammu; UPDATE $SMS_c SET status=1 WHERE name='$1'"
mysql --user=$u_db --password=$p_db -B -se "$sql_change_country"
else
sql_change_country="connect gammu; UPDATE $SMS_c SET status=0 WHERE name='$1'"
mysql --user=$u_db --password=$p_db -B -se "$sql_change_country"
fi
} # end change_country
 
function supp_acc_rad() {
# Remove account in Radcheck table
sql_del_compte="connect radius; DELETE FROM $rad WHERE username='$1';"
mysql --user=$u_db --password=$p_db -B -se "$sql_del_compte"
} # end function supp_acc_rad()
 
function add_acc_rad() {
# Add accoubt in RadCheck table
sql_add_pass="connect radius; INSERT INTO $rad (username,attribute,op,value) VALUES ('$1','Crypt-Password',':=','$2');"
sql_add_expe="connect radius; INSERT INTO $rad (username,attribute,op,value) VALUES ('$1','Expiration',':=','$3');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_pass"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_expe"
# Add this account to sms group
sql_add_gp="connect radius; INSERT INTO $radgp (username,groupname) VALUES ('$1','sms');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_gp"
} # end function add_acc_rad()
 
function supp_num_temp() {
# Remove phone number in SMS_ban_temp table
sql_remove_ban_temp="connect gammu; DELETE FROM $sms_t"
mysql --user=$u_db --password=$p_db -B -se "$sql_remove_ban_temp WHERE SenderNumber=$1;"
} # end function supp_num_temp()
 
function add_num_perm() {
# Add phone number in SMS_ban_perm table
sql_add_ban_perm="connect gammu; INSERT INTO $sms_p (SenderNumber,Perm,Expiration) VALUES ('$1',0,'$2');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_ban_perm"
} # end function add_num_perm()
 
function supp_num_perm() {
# Remove phone number in SMS_ban_perm table
sql_remove_ban_perm="connect gammu; DELETE FROM $sms_p"
mysql --user=$u_db --password=$p_db -B -se "$sql_remove_ban_perm WHERE SenderNumber=$1;"
} # end function add_num_perm()
 
function new_sms() {
# Check Inbox table, manage Ban temp and perm, create account
export salt='$5$passwd$'
sql_select_inbox="connect gammu; SELECT ID, SenderNumber, TextDecoded FROM $inb;"
sql_delete_inbox="connect gammu; DELETE FROM $inb"
mysql --user=$u_db --password=$p_db -B -se "$sql_select_inbox" | while read result;
do
# Retrieve the number of words (result)
nb=$(echo $result | wc -w)
# Retrive the ID
id=$(echo $result | cut -d ' ' -f1)
numero=$(echo $result | cut -d ' ' -f2)
if [[ $numero =~ ^\+ ]]
then
# Check if country is blocked
sql_select_countries="connect gammu; SELECT id FROM $SMS_c WHERE status=1"
mysql --user=$u_db --password=$p_db -B -se "$sql_select_countries" | while read result_c;
do
if [[ $numero =~ ^"$result_c" ]]
then
numero=$(echo $numero | cut -d '+' -f2)
# Check if GSM number is nabbed
sql_ban_perm="connect gammu; SELECT * FROM $sms_p WHERE SenderNumber=$numero"
result_bp=$(mysql --user=$u_db --password=$p_db -B -se "$sql_ban_perm")
if test -z "$result_bp"
then
# Test the number of word (result)
if [ $nb -eq 2 ] # if only 2 words : lack of password
then
# Add "1" in bans_temp table // NO PASSWORD
sql_add_temp="connect gammu; INSERT INTO $sms_t(SenderNumber) VALUES ('$numero');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_temp"
elif [ $nb -eq 3 ] # if 3 words (id + password + phone numbere)
then
export pass=$(echo $result | cut -d ' ' -f3)
pass_salt=$(perl -e'print crypt($ARGV[0],$ARGV[1])' $pass $salt)
export LC_TIME="en_US.UTF-8"
expir=$(date '+%d %B %Y' -d "$time_account days")
supp_acc_rad "$numero"
add_acc_rad "$numero" "$pass_salt" "$expir"
supp_num_temp "$numero"
add_num_perm "$numero" "$expir"
else # more then 3 words --> Add "1" in ban_temp table
sql_add_temp="connect gammu; INSERT INTO $sms_t(SenderNumber) VALUES ('$numero');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_temp"
fi
# manage ban perm
sql_select_temp="connect gammu; SELECT ID FROM $sms_t WHERE SenderNumber='$numero'"
r_select_temp=$(mysql --user=$u_db --password=$p_db -B -se "$sql_select_temp")
nb_ban_t=$(echo $r_select_temp| wc -w)
if [ $nb_ban_t -ge $nb_essais ]
then
supp_num_temp "$numero"
export LC_TIME="en_US.UTF-8"
expir_f=$(date '+%d %B %Y' -d "$time_ban days")
# Add "1" in SMS_ban_perm table : flood
sql_add_ban_perm="connect gammu; INSERT INTO $sms_p (SenderNumber,Perm,Expiration) VALUES ('$numero',1,'$expir_f');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_ban_perm"
fi
else
date_expiration=$(echo $result_bp | cut -d ' ' -f2,3,4)
perm=$(echo $result_bp | cut -d ' ' -f5)
export LC_TIME="en_US.UTF-8"
date_script=$(date '+%d %B %Y' -d "now")
# convert in seconds in order to be able to compare
d_exp=$(date --date "$date_expiration" +%s)
d_scr=$(date --date "$date_script" +%s)
if test $d_scr -ge $d_exp # Si le ban à expiré
then
# Test the number of words (result)
if [ $nb -eq 2 ] # Si 2 mots : le mot de passe est manquant
then
# Add "1" in ban temp table
sql_add_temp="connect gammu; INSERT INTO $sms_t(SenderNumber) VALUES ('$numero');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_temp"
elif [ $nb -eq 3 ] # Si 3 mots : id + mot de passe + numero
then
date_expiration=$(echo $result_bp | cut -d ' ' -f2,3,4)
perm=$(echo $result_bp | cut -d ' ' -f5)
date_script=$(date '+%d %B %Y' -d "now")
# convert in seconds in order to be able to compare
d_exp=$(date --date "$date_expiration" +%s)
d_scr=$(date --date "$date_script" +%s)
export pass=$(echo $result | cut -d ' ' -f3)
pass_salt=$(perl -e'print crypt($ARGV[0],$ARGV[1])' $pass $salt)
export LC_TIME="en_US.UTF-8"
expir=$(date '+%d %B %Y' -d "$time_account days")
supp_acc_rad "$numero"
add_acc_rad "$numero" "$pass_salt" "$expir"
supp_num_temp "$numero"
supp_num_perm "$numero"
add_num_perm "$numero" "$expir"
else
# number of words to big (> 3)
# Add "1" in bans temp table
sql_add_temp="connect gammu; INSERT INTO $sms_t(SenderNumber) VALUES ('$numero');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_temp"
echo "Mot de passe incorrect, ajout du numero en ban temporaire"
fi
# manage bans_temp & ban_perm
sql_select_temp="connect gammu; SELECT ID FROM $sms_t WHERE SenderNumber='$numero'"
r_select_temp=$(mysql --user=$u_db --password=$p_db -B -se "$sql_select_temp")
nb_ban_t=$(echo $r_select_temp| wc -w)
if [ $nb_ban_t -ge $nb_essais ]
then
supp_num_perm "$numero"
supp_num_temp "$numero"
export LC_TIME="en_US.UTF-8"
expir_f=$(date '+%d %B %Y' -d "$time_ban days")
# Add phne number in ban_perm : flood
sql_add_ban_perm="connect gammu; INSERT INTO $sms_p (SenderNumber,Perm,Expiration) VALUES ('$numero',1,'$expir_f');"
mysql --user=$u_db --password=$p_db -B -se "$sql_add_ban_perm"
fi
else
echo "Le ban de $numero est encore valide"
fi
break
fi
#else
#echo "Pays bloqué"
fi
done
else
echo "Numero non autorisé (ex: 36665)"
fi
# On supprime la ligne d'ID=$id dans inbox
mysql --user=$u_db --password=$p_db -B -e "$sql_delete_inbox WHERE ID=$id;"
done
} # end function new_sms
 
 
# CORE
case $args in
-h | --help)
echo "$usage"
exit 0
;;
--start)
failed="0"
comports=`ls -l /dev/ttyUSB* 2>/dev/null | wc -l`
if [ $comports == "0" ]
then
echo "No GSM modem found."
failed="1"
fi
if [ -z "$(grep '^SMS_NUM=' $CONF_FILE | cut -d'=' -f2-)" ]; then
echo 'The phone number is not set.'
failed="1"
fi
if [ $failed == "1" ]
then
sed -i "s/^SMS=.*/SMS=off/" $CONF_FILE
exit 0
fi
gammu_pid=`/usr/bin/pidof gammu-smsd|wc -l`
if [ $gammu_pid != "0" ]
then
echo "Gammu is already started"
else
start_gammu
sleep 1
is_active=`systemctl is-active gammu-smsd`
if [ $is_active == "active" ]
then
sed -i "s/^SMS=.*/SMS=on/" $CONF_FILE
else
sed -i "s/^SMS=.*/SMS=off/" $CONF_FILE
fi
fi
exit 0
;;
--stop)
gammu_pid=`/usr/bin/pidof gammu-smsd|wc -l`
if [ $gammu_pid != "0" ]
then
stop_gammu
else
echo "Gammu is already stopped"
fi
sed -i "s/^SMS=.*/SMS=off/" $CONF_FILE
exit 0
;;
--pidof)
/usr/bin/pidof gammu-smsd
;;
--last_nosim)
# Récupère la dernière ligne où NOSIM est présent (error)
cat $logfile | grep -n "NOSIM" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_start)
# Récupère la dernière ligne où ########## est présent (séparateur)
cat $logfile | grep -n "##########" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_stop)
# Récupère la dernière ligne où %%%%%%%%%% est présent (séparateur)
cat $logfile | grep -n "%%%%%%%%%%" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_writeerror)
#Récupère la dernière ligne où DEVICEWRITEERROR est présent (error)
cat $logfile | grep -n "DEVICEWRITEERROR" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_timeout)
# Récupère la dernière ligne où TIMEOUT est présent (error)
cat $logfile | grep -n "TIMEOUT" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_secu)
# Récupère la dernière ligne où SECURITYERROR est présent (error)
cat $logfile | grep -n "SECURITYERROR" | cut -d ':' -f1 | tail -n 1
exit 0
;;
--last_puk)
# Récupère la dernière ligne où PUK est présent (error)
cat $logfile | grep -n "UNKNOWN" | cut -d ':' -f1 | tail -n 1
exit 0
;;
#--log)
# # Récupère le nom du fichier de log
# cat $config | grep logfile | cut -d ' ' -f3
# exit 0
# ;;
--connect)
# display the com port speed
cat $config | grep connection | cut -d ' ' -f3
exit 0
;;
--replace_port)
# modify the com port
echo $2
sed -i "s?^port = .*?port = $2?g" $config
sed -i "0,/^device =/ s?device =.*?device = $2?" $config2
exit 0
;;
--replace_speed)
# modufy the com port speed
sed -i "s/^connection = at.*/connection = at$2/g" $config
sed -i "0,/^connection =/ s/connection =.*/connection = $2/" $config2
exit 0
;;
--pin)
# Récupère le code PIN (file de conf)
cat $config | grep PIN | cut -d ' ' -f3
exit 0
;;
--replace_pin)
# Edition du code PIN
sed -i "s/^PIN =.*/PIN = $2/g" $config
exit 0
;;
--try_ban)
# Récupère le nombre d'essais avant le ban perm
grep nb_essais= $script | head -n 1 | cut -d '=' -f2
exit 0
;;
--replace_try_ban)
# Edition le nombre d'essais avant le ban perm
sed -i "s/^nb_essais=.*/nb_essais=$2/g" $script
exit 0
;;
--time_account)
# Récupère la durée en jours de la session créée
grep time_account= $script | head -n 1 | cut -d '=' -f2
exit 0
;;
--replace_time_account)
# Edition de la durée de la session créée
sed -i "s/^time_account=.*/time_account=$2/g" $script
exit 0
;;
--time_perm)
# Récupère la durée un jours d'un ban perm (après flood par exemple)
grep time_ban= $script | head -n 1 | cut -d '=' -f2
exit 0
;;
--replace_time_perm)
# Edition de la durée d'un ban perm
sed -i "s/^time_ban=.*/time_ban=$2/g" $script
exit 0
;;
--unlock_num)
# Appel de la fonction unlock : deban un numero $2
unlock "$2"
exit 0
;;
--change_country)
# Permet de changer l'état de blocage d'un pays
a=""
for i in "$@"
do
a=$(echo "$a $i")
done
a=$(echo $a | cut -d ' ' -f2-$#)
change_country "$a"
exit
;;
--change_country_ena_all)
# Active l'ensemble des pays
sql_change_country="connect gammu; UPDATE $SMS_c SET status=1"
mysql --user=$u_db --password=$p_db -B -se "$sql_change_country"
exit
;;
--change_country_dis_all)
# Desactive l'ensemble des pays
sql_change_country="connect gammu; UPDATE $SMS_c SET status=0"
mysql --user=$u_db --password=$p_db -B -se "$sql_change_country"
exit
;;
--change_country_filter)
# Change la valeur du filtrage (FR, UE, all, perso)
sql_change_country="connect gammu; UPDATE $SMS_c SET id='$2' WHERE name='FILTRAGE'"
mysql --user=$u_db --password=$p_db -B -se "$sql_change_country"
break
;;
--new_sms)
# Appel de la fonction new_sms : filtrage du password, creation du compte et ban
new_sms
exit 0
;;
--imei_device)
# Recuperation de l'imei du device
sql_imei_phones="connect gammu; SELECT \`IMEI\` FROM phones;"
mysql --user=$u_db --password=$p_db -B -se "$sql_imei_phones"
exit 0
;;
--signal_device)
# Recuperation du signal du device
sql_signal_phones="connect gammu; SELECT \`Signal\` FROM phones;"
mysql --user=$u_db --password=$p_db -B -se "$sql_signal_phones"
exit 0
;;
--sms_received)
# Recuperation du nombre de sms reçu. Depuis la dernière activation.
sql_sms_received="connect gammu; SELECT \`Received\` FROM phones;"
mysql --user=$u_db --password=$p_db -B -se "$sql_sms_received"
exit 0
;;
--numero_alcasar)
# Récupère le numero de la clé 3g (téléphone)
grep '^SMS_NUM=' $CONF_FILE | cut -d'=' -f2-
exit 0
;;
--replace_numero_alcasar)
# Edition du numero de la clé 3g (téléphone)
sed -i "s/^SMS_NUM=.*/SMS_NUM=$2/" $CONF_FILE
exit 0
;;
--mode)
# Mode huawei
mode_huawei
exit 0
;;
*)
# Default
echo "$usage"
exit 0
;;
esac
exit 0
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-mail-install.sh
0,0 → 1,202
#!/bin/bash
 
###########################################################################################
## ALCASAR MAIL SERVICE CONFIGURATION
##
## Script by K@M3L & T3RRY (LaPlateforme.io), joss_p & Rexy
## This script configure PostFix
## 0 : no email autoregistration
## 1 : PostFix is the SMTP server
## 2 : PostFix relay to an other SMTP server
## 3 : PostFix use an external email address (with Cyrus-SASL)
###########################################################################################
 
######################################################
## Email configuration examples (mode = 3)
## common parameters : smtp_use_tls = yes, smtp_tls_security_level = encrypt, smtp_sasl_auth_enable = yes
## common rules : 'myhostname' parameter should be the domain name of the sasl_email account
########## smtp.free.fr:465 (expose mechanisms : PLAIN LOGIN CRAM-MD5 DIGEST-MD5)
## smtp_sasl_security_option = noanonymous, relayhost = [smtp.free.fr]:465, smtp_tls_wrappermode = yes
########## smtp.free.fr:587 (expose mechanismes
## smtp_sasl_security_option = noanonymous, relayhost = [smtp.free.fr]:587, smtp_tls_wrappermode = no, smtputf8_enable = no
########## smtp.orange.fr:465 (expose mechanisms : LOGIN PLAIN)
## smtp_sasl_security_option = noanonymous, relayhost = [smtp.orange.fr]:465, smtp_tls_wrappermode = yes, smtputf8_enable = no
########## smtp.sfr.fr:465 (expose mechanisms : LOGIN PLAIN)
## smtp_sasl_security_option = noanonymous, relayhost = [smtp.sfr.fr]:465, smtp_tls_wrappermode = yes
########## smtp.laposte.net:465 (expose mechanisms : LOGIN PLAIN)
## smtp_sasl_security_option = noanonymous, relayhost = [laposte.net]:465, smtp_tls_wrappermode = yes
########## smtp.bbox.net:465 (expose mechanisms : LOGIN PLAIN)
## smtp_sasl_security_option = noanonymous, relayhost = [laposte.net]:465, smtp_tls_wrappermode = yes
########## smtp.gmail.com:587 (expose mechanisms : LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH)
## smtp_sasl_security_option = noanonymous, relayhost = [gmail.com]:587, smtp_tls_wrappermode = no
## In this case (gmail) the password must be an "application password" created via the gmail account manager (security tab)
 
# ****** Paths *******
SED="/bin/sed -i"
CONF_FILE="/usr/local/etc/alcasar.conf"
POSTFIX_CONF_FILE="/etc/postfix/main.cf"
LOCAL_IPTABLE_FILE="/usr/local/etc/alcasar-iptables-local.sh"
SASLPATH="/etc/postfix/sasl"
smtpIP="0.0.0.0/0"
hostName=`grep ^HOSTNAME= $CONF_FILE|cut -d"=" -f2`
domainName=`grep ^DOMAIN= $CONF_FILE|cut -d"=" -f2`
usage="Usage: alcasar-mail_install.sh -h|-0|-1|-2|-3"
 
nb_args=$#
if [ $nb_args -eq 0 ]; then # apply alcasar.conf
mail=`grep ^MAIL= $CONF_FILE|cut -d"=" -f2`
if [ "$mail" = "off" ]; then
TYPE_MAIL=0
else
TYPE_MAIL=`grep ^MAIL_TYPE= $CONF_FILE|cut -d"=" -f2`
smtpPort=`grep ^MAIL_SMTP_PORT= $CONF_FILE|cut -d"=" -f2`
smtpIP=`grep ^MAIL_SMTP_IP= $CONF_FILE|cut -d"=" -f2`
mailAddr=`grep ^MAIL_ADDR= $CONF_FILE|cut -d"=" -f2`
[ -e ${SASLPATH}/sasl_passwd ] && mailMdp=`cat $SASLPATH/sasl_passwd|cut -d":" -f3`
adminMail=`grep ^MAIL_ADMIN= $CONF_FILE|cut -d"=" -f2`
whiteDomain=`grep ^MAIL_WHITEDOMAIN= $CONF_FILE|cut -d"=" -f2`
fi
else # apply args
if [ "$1" = "-h" ] || [ "$1" = "--h" ]; then
echo $usage
exit 0
fi
while getopts ":h:s:p:m:o:a:w:0123" option
do
case $option in
0)
TYPE_MAIL=0
;;
1)
TYPE_MAIL=1
;;
2)
TYPE_MAIL=2
;;
3)
TYPE_MAIL=3
;;
p)
smtpPort=$OPTARG
;;
s)
smtpIP=$OPTARG
;;
m)
mailAddr=$OPTARG
;;
o)
mailMdp=$OPTARG
;;
a)
adminMail=$OPTARG
;;
w)
whiteDomain=$OPTARG
;;
:)
echo "L'option $OPTARG requiert un argument"
exit 1
;;
\?)
echo "$OPTARG : option invalide"
exit 1
;;
esac
done
fi
if [[ $TYPE_MAIL -eq 0 ]]; then # disable mail service
$SED "s/^MAIL=.*/MAIL=off/" $CONF_FILE
$SED "s/^MAIL_TYPE=.*/MAIL_TYPE=/" $CONF_FILE
$SED "s/^MAIL_SMTP_IP=.*/MAIL_SMTP_IP=/" $CONF_FILE
$SED "s/^MAIL_SMTP_PORT=.*/MAIL_SMTP_PORT=/" $CONF_FILE
$SED "s/^MAIL_ADDR=.*/MAIL_ADDR=/" $CONF_FILE
$SED "s/^MAIL_WHITEDOMAIN=.*/MAIL_WHITEDOMAIN=/" $CONF_FILE
$SED "s/^MAIL_ADMIN=.*/MAIL_ADMIN=/" $CONF_FILE
$SED "/^SMTP_IP=/ s/^/#/" $LOCAL_IPTABLE_FILE
$SED "/^SMTP_PORT=/ s/^/#/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/#\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -d \$SMTP_IP -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/#\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -s \$SMTP_IP -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^relayhost =.*/relayhost =/" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_security_level =.*/smtp_tls_security_level = may/g" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_wrappermode =.*/smtp_tls_wrappermode = no/g" $POSTFIX_CONF_FILE
$SED "s/^myhostname =.*/myhostname = $hostName.$domainName/g" $POSTFIX_CONF_FILE
[ -e ${SASLPATH}/sasl_passwd ] && rm -f ${SASLPATH}/*
elif [[ $TYPE_MAIL -eq 1 ]]; then # Enable mail service (act as smtp server)
$SED "s/^MAIL=.*/MAIL=on/" $CONF_FILE
$SED "s/^MAIL_TYPE=.*/MAIL_TYPE=1/" $CONF_FILE
$SED "s/^MAIL_SMTP_IP=.*/MAIL_SMTP_IP=/" $CONF_FILE
$SED "s/^MAIL_SMTP_PORT=.*/MAIL_SMTP_PORT=$smtpPort/" $CONF_FILE
$SED "s/^MAIL_ADDR=.*/MAIL_ADDR=/" $CONF_FILE
$SED "s/^MAIL_WHITEDOMAIN=.*/MAIL_WHITEDOMAIN=$whiteDomain/" $CONF_FILE
$SED "s/^MAIL_ADMIN=.*/MAIL_ADMIN=$adminMail/" $CONF_FILE
$SED "/^SMTP_IP=/ s/^/#/" $LOCAL_IPTABLE_FILE
$SED "s/^SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^relayhost =.*/relayhost =/" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_security_level =.*/smtp_tls_security_level = may/g" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_wrappermode =.*/smtp_tls_wrappermode = no/g" $POSTFIX_CONF_FILE
$SED "s/^myhostname =.*/myhostname = $hostName.$domainName/g" $POSTFIX_CONF_FILE
[ -e ${SASLPATH}/sasl_passwd ] && rm -f ${SASLPATH}/*
elif [[ $TYPE_MAIL -eq 2 ]]; then # Enable mail service (relaying to an extern mail server)
$SED "s/^MAIL=.*/MAIL=on/" $CONF_FILE
$SED "s/^MAIL_TYPE=.*/MAIL_TYPE=2/" $CONF_FILE
$SED "s/^MAIL_SMTP_IP=.*/MAIL_SMTP_IP=$smtpIP/" $CONF_FILE
$SED "s/^MAIL_SMTP_PORT=.*/MAIL_SMTP_PORT=$smtpPort/" $CONF_FILE
$SED "s/^MAIL_ADDR=.*/MAIL_ADDR=/" $CONF_FILE
$SED "s/^MAIL_WHITEDOMAIN=.*/MAIL_WHITEDOMAIN=$whiteDomain/" $CONF_FILE
$SED "s/^MAIL_ADMIN=.*/MAIL_ADMIN=$adminMail/" $CONF_FILE
$SED "s/^SMTP_IP=.*/SMTP_IP=$smtpIP/" $LOCAL_IPTABLE_FILE
$SED "s/^SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -d \$SMTP_IP -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -s \$SMTP_IP -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#SMTP_IP=.*/SMTP_IP=$smtpIP/" $LOCAL_IPTABLE_FILE
$SED "s/^#SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -d \$SMTP_IP -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -s \$SMTP_IP -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^relayhost =.*/relayhost = [$smtpIP]:$smtpPort/g" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_security_level =.*/smtp_tls_security_level = may/g" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_wrappermode =.*/smtp_tls_wrappermode = no/g" $POSTFIX_CONF_FILE
$SED "s/^myhostname =.*/myhostname = $hostName.$domainName/g" $POSTFIX_CONF_FILE
[ -e ${SASLPATH}/sasl_passwd ] && rm -f ${SASLPATH}/*
elif [[ $TYPE_MAIL -eq 3 ]]; then # Enable mail service (using an email address)
$SED "s/^MAIL=.*/MAIL=on/" $CONF_FILE
$SED "s/^MAIL_TYPE=.*/MAIL_TYPE=3/" $CONF_FILE
$SED "s/^MAIL_SMTP_IP=.*/MAIL_SMTP_IP=$smtpIP/" $CONF_FILE
$SED "s/^MAIL_SMTP_PORT=.*/MAIL_SMTP_PORT=$smtpPort/" $CONF_FILE
$SED "s/^MAIL_ADDR=.*/MAIL_ADDR=$mailAddr/" $CONF_FILE
$SED "s/^MAIL_WHITEDOMAIN=.*/MAIL_WHITEDOMAIN=$whiteDomain/" $CONF_FILE
$SED "s/^MAIL_ADMIN=.*/MAIL_ADMIN=$adminMail/" $CONF_FILE
$SED "s/^SMTP_IP=.*/SMTP_IP=$smtpIP/" $LOCAL_IPTABLE_FILE
$SED "s/^SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#SMTP_IP=.*/SMTP_IP=$smtpIP/" $LOCAL_IPTABLE_FILE
$SED "s/^#SMTP_PORT=.*/SMTP_PORT=$smtpPort/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT.*/\$IPTABLES -A OUTPUT -p tcp --dport \$SMTP_PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^#\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT.*/\$IPTABLES -A INPUT -p tcp --sport \$SMTP_PORT -m conntrack --ctstate ESTABLISHED -j ACCEPT/" $LOCAL_IPTABLE_FILE
$SED "s/^relayhost =.*/relayhost = [$smtpIP]:$smtpPort/g" $POSTFIX_CONF_FILE
$SED "s/^smtp_tls_security_level =.*/smtp_tls_security_level = encrypt/g" $POSTFIX_CONF_FILE
if [ "$smtpPort" = "465" ]; then # wrappermode is madatory only if port = 465
$SED "s/^smtp_tls_wrappermode =.*/smtp_tls_wrappermode = yes/g" $POSTFIX_CONF_FILE
else
$SED "s/^smtp_tls_wrappermode =.*/smtp_tls_wrappermode = no/g" $POSTFIX_CONF_FILE
fi
$SED "s/^myhostname =.*/myhostname = alcasar.net/g" $POSTFIX_CONF_FILE # use the alcasar domain name to avoid extern smtp servers reject
[ -d ${SASLPATH} ] || mkdir ${SASLPATH}
echo "[${smtpIP}]:${smtpPort} ${mailAddr}:${mailMdp}" > ${SASLPATH}/sasl_passwd
postmap ${SASLPATH}/sasl_passwd
chmod -R 644 ${SASLPATH}
chown root:root ${SASLPATH}/sasl_passwd*
chmod 0600 ${SASLPATH}/sasl_passwd*
else
echo "Erreur ! Aucun type de messagerie sélectionné !"
exit 0
fi
/usr/local/bin/alcasar-iptables.sh
systemctl restart postfix.service
exit 0
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-mysql.sh
0,0 → 1,144
#!/bin/bash
# $Id$
 
# alcasar-mysql.sh
# by Franck BOUIJOUX, Pascal LEVANT and Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# Gestion (sauvegarde / import / RAZ) de la base MySQL 'radius'. Fermeture des sessions de comptabilité ouvertes
# Management of mysql 'radius' database (save / import / RAZ). Close the accounting open sessions
 
rep_tr="/var/Save/base"
DIR_BIN="/usr/local/bin"
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_RADIUS="radius"
DB_USER=$(grep '^db_user=' $PASSWD_FILE | cut -d'=' -f 2-)
DB_PASS=$(grep '^db_password=' $PASSWD_FILE | cut -d'=' -f 2-)
new="$(date +%G%m%d-%Hh%M)" # date & hour of files
fichier="alcasar-users-database-$new.sql"
 
 
stop_acct ()
{
date_now=`date "+%F %X"`
echo "UPDATE radacct SET acctstoptime = '$date_now', acctterminatecause = 'Admin-Reset' WHERE acctstoptime IS NULL" | mysql -u$DB_USER -p$DB_PASS $DB_RADIUS
}
check ()
{
echo "check (and repair if needed) the database :"
mysqlcheck --databases $DB_RADIUS -u $DB_USER -p$DB_PASS --auto-repair
}
 
expire_user () # remove users whom expiration date has passed to 7 days
{
del_date=`date +%F`
MYSQL_USER=""
MYSQL_USER=`/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS -ss --execute "SELECT username FROM radcheck WHERE ( DATE_SUB(CURDATE(),INTERVAL 7 DAY) > STR_TO_DATE(value,'%d %M %Y')) AND attribute='Expiration';"`
for u in $MYSQL_USER
do
/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS --execute "DELETE FROM radusergroup WHERE username = '$u'; DELETE FROM radreply WHERE username = '$u'; DELETE FROM userinfo WHERE UserName = '$u'; DELETE FROM radcheck WHERE username = '$u';"
if [ $? = 0 ]
then
echo "User $u was deleted $del_date" >> /var/log/mysqld/delete_user.log
else
echo "Delete User $u : Error $del_date" >> /var/log/mysqld/delete_user.log
fi
done
}
 
expire_group () # remove users of group whom expiration date has passed to 7 days
{
del_date=`date +%F`
MYSQL_GROUP=""
MYSQL_GROUP=`/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS -ss --execute "SELECT groupname FROM radgroupcheck WHERE ( DATE_SUB(CURDATE(),INTERVAL 7 DAY) > STR_TO_DATE(value,'%d %M %Y')) AND attribute='Expiration';"`
for g in $MYSQL_GROUP
do
MYSQL_USERGROUP=""
MYSQL_USERGROUP=`/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS -ss --execute "SELECT username FROM radusergroup WHERE groupname = '$g';"`
for u in $MYSQL_USERGROUP
do
/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS --execute "DELETE FROM radusergroup WHERE username = '$u'; DELETE FROM radreply WHERE username = '$u'; DELETE FROM userinfo WHERE UserName = '$u'; DELETE FROM radcheck WHERE username = '$u';"
if [ $? = 0 ]
then
echo "User $u was deleted $del_date" >> /var/log/mysqld/delete_user.log
else
echo "Delete User $u : Error $del_date" >> /var/log/mysqld/delete_user.log
fi
done
/usr/bin/mysql -u$DB_USER -p$DB_PASS $DB_RADIUS --execute "DELETE FROM radgroupreply WHERE groupname = '$g'; DELETE FROM radgroupcheck WHERE groupname = '$g';"
if [ $? = 0 ]
then
echo "Group $g was deleted $del_date" >> /var/log/mysqld/delete_group.log
else
echo "Delete Group $g : Error $del_date" >> /var/log/mysqld/delete_group.log
fi
done
}
 
usage="Usage: alcasar-mysql.sh { -d or --dump } | { -c or --check } | { -i or --import } | { -r or --raz } | { -a or --acct_stop } | [ -e or --expire_user ]"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
-d | --dump | -dump)
[ -d $rep_tr ] || mkdir -p $rep_tr
if [ -e $fichier ];
then rm -f $fichier
fi
check
echo "Export the database in file : $fichier.gz"
mysqldump -u $DB_USER -p$DB_PASS --opt -BcQC $DB_RADIUS > $rep_tr/$fichier
gzip -f $rep_tr/$fichier
echo "End of export $( date "+%Hh %Mmn" )"
;;
-c | --check | -check)
check
;;
-i | --import | -import)
if [ $nb_args -ne 2 ]
then
echo "Enter a SQL file name ('.sql' or '.sql.gz')"
exit 0
else
case $2 in
*.sql.gz )
gunzip -f < $2 | mysql -u $DB_USER -p$DB_PASS
stop_acct
;;
*.sql )
mysql -u $DB_USER -p$DB_PASS < $2
stop_acct
;;
esac
migrationsPath="$DIR_BIN/alcasar-db-migrations"
"$migrationsPath/alcasar-migration-3.2.0_dbStructure.sh"
"$migrationsPath/alcasar-migration-3.3.0_dbRadiusAttrs.sh"
"$migrationsPath/alcasar-migration-3.3.1_dbRadiusAttrs.sh"
fi
;;
-r | --raz | -raz)
mysqldump -u $DB_USER -p$DB_PASS --opt -BcQC $DB_RADIUS > $rep_tr/$fichier
gzip -f $rep_tr/$fichier
mysql -u$DB_USER -p$DB_PASS $DB_RADIUS < /etc/raddb/empty-radiusd-db.sql
;;
-a | --acct_stop | -acct_stop)
stop_acct
;;
-e | --expire_user)
expire_user
expire_group
;;
*)
echo "Unknown argument :$1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/test-create-delete-multiple_MAC-sh
0,0 → 1,19
#!/bin/bash
PASSWD_FILE="/root/ALCASAR-passwords.txt"
USER_NAME="test"
DB_USER=`cat $PASSWD_FILE|grep ^db_user=|cut -d'=' -f2`
DB_PASSWORD=`cat $PASSWD_FILE|grep ^db_password=|cut -d'=' -f2`
MAC_ADDRESSES="00:11:22:33:44:50 00:11:22:33:44:51 00:11:22:33:44:52" # write here @MAC or user_names (delimiter=space)
 
for MAC in $MAC_ADDRESSES
do
salt=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c8`
export algo_salt='$5$'$salt
export pass='PASSWORD'
pass_salt=$(perl -e'print crypt($ARGV[0],$ARGV[1])' $pass $algo_salt)
db_query1="INSERT INTO radcheck (username,attribute,op,value) VALUES ('$MAC', 'Crypt-Password', ':=', '$pass_salt'); INSERT INTO userinfo (username) VALUES ('$MAC');"
db_query2="DELETE FROM radcheck WHERE username = '$MAC'; DELETE FROM userinfo WHERE username = '$MAC';"
db_radcheck_insert_res=$(mysql -u $DB_USER -p$DB_PASSWORD -D radius -e "$db_query2" -Ns) # choose here db_query1 or 2
echo -n "$MAC "
done
echo
/scripts/alcasar-network.sh
0,0 → 1,131
#!/bin/bash
 
# alcasar-network.sh
# by Pierre RIVAULT and Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# Met à jour la configuration réseau conformément au fichier de configuration (alcasar.conf)
# update network configuration according to alcasar.conf
 
CONF_FILE="/usr/local/etc/alcasar.conf"
TMP_ip_gw_save="/tmp/ipset_ip_gw_save"
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2`
PUBLIC_IP=`grep ^PUBLIC_IP= $CONF_FILE|cut -d"=" -f2`
if [ $PUBLIC_IP != "dhcp" ]; then
GW1=`grep ^GW= $CONF_FILE|cut -d"=" -f2`
MTU=`grep ^PUBLIC_MTU= $CONF_FILE|cut -d"=" -f2`
MULTIWAN=`grep ^MULTIWAN= $CONF_FILE|cut -d"=" -f2`
MULTIWAN=${MULTIWAN:=off}
NET="`ipcalc -n $PUBLIC_IP | cut -d"=" -f2`/`ipcalc -p $PUBLIC_IP | cut -d"=" -f2`"
IP=`echo $PUBLIC_IP | cut -d"/" -f1`
PRIVATE_IP_MASK=`grep ^PRIVATE_IP $CONF_FILE | cut -d"=" -f2`
PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`
PRIVATE_NETMASK=`echo $PRIVATE_IP_MASK | cut -d"/" -f2`
PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP $PRIVATE_NETMASK |cut -d"=" -f2` # prefixe du réseau (ex. 24)
PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP $PRIVATE_NETMASK| cut -d"=" -f2` # @ réseau de consultation (ex.: 192.168.182.0)
PRIVATE_NETWORK_MASK=$PRIVATE_NETWORK/$PRIVATE_PREFIX # @ + masque du réseau de consult (192.168.182.0/24)
nb_gw=`grep ^WAN $CONF_FILE | wc -l`
fi
routecmd="ip route replace default scope global"
 
if [ $(whoami) != "root" ]; then
echo "You must be root to run this!" ; echo ; exit 1
fi
 
if [ $# -eq 0 ]; then
args="--apply"
else
args=$1
fi
 
case $args in
--save) # save all the IP before changing the configuration
rm -f $TMP_ip_gw_save
gw_list="gw0" # ipset name list for load_balancing
for ((i=1 ; i<=$nb_gw ; i++)); do
gw_list="${gw_list} gw$i"
done
# Saving all of the already connected IP in order to put them back in the load balancing after
for i in $gw_list;do
ipset list $i 1>/dev/null 2>&1
if [ $? -eq 0 ]
then
# the cut -d":" -f5 deletes all the lines with a :, i.e all the lines except the members
ipset list $i | grep -v ":" >> $TMP_ip_gw_save
fi
done
exit 0
;;
--apply)
[ -e /etc/sysconfig/network-scripts/ifcfg-$EXTIF ] && ifdown $EXTIF
# set the new configuration for EXTIF
if [ $PUBLIC_IP == "dhcp" ]; then
cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=dhcp
DNS1=127.0.0.1
PEERDNS=no
RESOLV_MODS=yes
ONBOOT=yes
NOZEROCONF=yes
METRIC=10
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
EOF
ifup $EXTIF
else
cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=static
IPADDR=$IP
NETMASK=`ipcalc -m $PUBLIC_IP | cut -d= -f2`
NETWORK=`ipcalc -n $PUBLIC_IP | cut -d= -f2`
GATEWAY=$GW1
DNS1=127.0.0.1
RESOLV_MODS=yes
ONBOOT=yes
METRIC=10
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
NOZEROCONF=yes
EOF
ifup $EXTIF
ip route flush ${NET} # Remove the previous route for the network of EXTIF
ip route delete default scope global # Remove the previous default route
ip route add ${NET} dev ${EXTIF} src ${IP} # Set the new route for EXTIF network
ip route add ${NET} dev ${EXTIF} src ${IP} table 200 # Set the new default route. If no multiwan, these lines are equivalent to `ip route add default via ${GW1}`
ip route add default via ${GW1} table 200
routecmd="${routecmd} nexthop via ${GW1} dev ${EXTIF}"
ip rule flush # Remove the previous routing rules
ip rule add from all lookup main pref 32766 # Set back the main rules
ip rule add from all lookup default pref 32767 # Set back the default rules
ip rule add from ${PRIVATE_NETWORK_MASK} fwmark 200 lookup 200 # Add the rule for the first gateway
if [ "$MULTIWAN" == "on" ] || [ "$MULTIWAN" == "On" ]; then
nb_gw_supp=`grep ^WAN $CONF_FILE|wc -l`
for ((i=0 ; $i < $nb_gw_supp ; i++)); do
table=$(($i + 201)) # This number is used to mark the paquets in order to route them to the choosen GW
GW=`grep ^WAN$(($i + 1))= $CONF_FILE|awk -F'"' '{ print $2 }' | awk -F, '{print $1}'`
ip route add ${NET} dev ${EXTIF} src ${IP} table $table # Add the others route in their respective tables
ip route add default via ${GW} table $table
ip rule add from ${PRIVATE_NETWORK_MASK} fwmark $table lookup $table # Add the rule for each rule depending of the mark set by the firewall
routecmd="${routecmd} nexthop via ${GW} dev ${EXTIF}" # add the added gateway into the default gateway
done
fi
${routecmd} # define the default gateway for outgoing traffic
ip route flush cache
fi
/usr/local/bin/alcasar-iptables.sh
exit 0
;;
*)
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-list-ip_gw.sh
0,0 → 1,19
#!/bin/sh
#
# alcasar-list-ip_gw.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# This script displays authenticated systems (users & @MAC) with their gw
# Ce script affiche les systèmes authentifiés (utilisateurs et @MAC) avec leur routeur
 
CONF_FILE="/usr/local/etc/alcasar.conf"
 
nb_gw=`grep ^WAN $CONF_FILE | wc -l`
for (( i = 0 ; i <= $nb_gw ; i++ ));do
gw="gw$i"; gw_order=`expr $i + 1`
ip_list=`ipset l $gw|grep -v :`
for ip in $ip_list;do
echo "$ip $gw_order"
done
done
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/test-retrieve-users-attributes-sh
0,0 → 1,69
#! /bin/bash
# script test&debug.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# This script tests the following behaviour :
# - Retreive 3 special attributes of a user ('test' by default). It Retrieves theses attributes from default group, then from user's group, then from its account
# - test if the attribute "Alcasar-Status-Page-Must-Stay-Open" is set to "2", then retrieve the "expiration" attribute
# - (todo) if the "expiration" attribute exists then create a new user (login = user's @MAC) and duplicates all user's attributes
 
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
USER_NAME="test"
DB_USER=`cat $PASSWD_FILE|grep ^db_user=|cut -d'=' -f2`
DB_PASSWORD=`cat $PASSWD_FILE|grep ^db_password=|cut -d'=' -f2`
 
# Retrieve 3 ALCASAR special radius attributes (search order : default group, then user's group, then user)
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radreply WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ) UNION \
( SELECT attribute, value FROM radgroupreply gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupreply WHERE groupname = 'default' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ) \
) attrs GROUP BY attribute;"
db_radreply_res=$(mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns)
 
filter=$(echo "$db_radreply_res" | awk '$1 == "Alcasar-Filter" { print $2 }')
filterProto=$(echo "$db_radreply_res" | awk '$1 == "Alcasar-Protocols-Filter" { print $2 }')
statusOpenRequired=$(echo "$db_radreply_res" | awk '$1 == "Alcasar-Status-Page-Must-Stay-Open" { print $2 }')
echo "USER_NAME = $USER_NAME; filter = $filter; filterproto = $filterProto; statusOpenRequired = $statusOpenRequired";
 
# If status page isn't required :
if [ "$statusOpenRequired" == '2' ]; then # Status page is not required
echo ""
# Retrieve "expiration" attribute from radcheck
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radcheck WHERE username = '$USER_NAME' AND attribute = 'Expiration' ) UNION \
( SELECT attribute, value FROM radgroupcheck gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' AND attribute = 'Expiration' ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupcheck WHERE groupname = 'default' AND attribute = 'Expiration' ) \
) attrs GROUP BY attribute;"
db_radcheck_expiration_res=$(mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns)
# if a expiration date exists we retrieve all radreply attributes
if [ `echo $db_radcheck_expiration_res|wc -l` == '1' ]; then
echo "###########################"
echo "## Radreply attributes"
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radreply WHERE username = '$USER_NAME' ) UNION \
( SELECT attribute, value FROM radgroupreply gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupreply WHERE groupname = 'default' ) \
) attrs GROUP BY attribute;"
mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns | while IFS= read -r loop
do
attr=`echo $loop|cut -d" " -f1`
attr_value=`echo $loop|cut -d" " -f2-`
echo "$attr = $attr_value"
done
# if a expiration date exists we retrieve all radcheck attributes
echo "## Radcheck attributes"
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radcheck WHERE username = '$USER_NAME' ) UNION \
( SELECT attribute, value FROM radgroupcheck gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupcheck WHERE groupname = 'default' ) \
) attrs GROUP BY attribute;"
mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns | while IFS= read -r loop
do
attr=`echo $loop|cut -d" " -f1`
attr_value=`echo $loop|cut -d" " -f2-`
echo "$attr = $attr_value"
done
fi
fi
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-condown.sh
0,0 → 1,91
#!/bin/sh
#
# $Id$
#
# alcasar-condown.sh
# by Rexy & Pierre RIVAULT
# This script is distributed under the Gnu General Public License (GPL)
 
# This script is started by coova after each logout
# Ce script est lancé par coova à chaque déconnexion d'usager
 
CONF_FILE="/usr/local/etc/alcasar.conf"
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_USER=`cat $PASSWD_FILE|grep ^db_user=|cut -d'=' -f2`
DB_PASSWORD=`cat $PASSWD_FILE|grep ^db_password=|cut -d'=' -f2`
 
if [ -z $FRAMED_IP_ADDRESS ]; then
exit 1
fi
 
# Retrieve 2 alcasar special radius attributes (search order : default group, then user's group, then user)
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radreply WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter')) ) UNION \
( SELECT attribute, value FROM radgroupreply gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter')) ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupreply WHERE groupname = 'default' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter')) ) \
) attrs GROUP BY attribute;"
db_res=$(mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns)
 
filter=$(echo "$db_res" | awk '$1 == "Alcasar-Filter" { print $2 }')
filterProto=$(echo "$db_res" | awk '$1 == "Alcasar-Protocols-Filter" { print $2 }')
 
if [ "$filter" == '4' ]; then # AV_WL
set_filter="av_wl"
elif [ "$filter" == '3' ]; then # AV_BL
set_filter="av_bl"
elif [ "$filter" == '2' ]; then # AV
set_filter="av"
else # NOT_FILTERED
set_filter="not_filtered"
fi
 
if [ "$filterProto" == '4' ]; then # PROFILE 3 (Custom)
set_filterProto="proto_3";
elif [ "$filterProto" == '3' ]; then # PROFILE 2 (WEB + Mail + Remote access)
set_filterProto="proto_2";
elif [ "$filterProto" == '2' ]; then # PROFILE 1 (WEB)
set_filterProto="proto_1";
else # PROFILE 0 (Not filtered)
set_filterProto="proto_0";
fi
 
# Remove user from his IPSET
ipset del $set_filter $FRAMED_IP_ADDRESS
ipset del $set_filterProto $FRAMED_IP_ADDRESS
 
# Remove IP address from active users list
current_users_file="/tmp/current_users.txt"
[ -e $current_users_file ] && sed -i "/^$FRAMED_IP_ADDRESS:/d" $current_users_file
 
# Remove user_IP from ipset of load balancing
nb_gw=`grep ^WAN $CONF_FILE | wc -l`
for (( i = 0 ; i <= $nb_gw ; i++ ));do
gw="gw$i"
ipset test $gw $FRAMED_IP_ADDRESS 1>/dev/null 2>&1
if [ $? -eq 0 ];then
ipset del $gw $FRAMED_IP_ADDRESS
break
fi
done
 
#############################
## Debug : show all the coova parse variables (+ ALCASAR-Filter + ALCASAR-Protocols-Filter).
## see "/src/chilli.c" for the complete list of parse variables
#debug_file="/tmp/debug-condown.txt"
#echo "-----------------------------------------------" >> $debug_file
#echo `date` >> $debug_file
#for i in DEV NET MASK ADDR USER_NAME NAS_IP_ADDRESS SERVICE_TYPE FRAMED_IP_ADDRESS FILTER_ID STATE CLASS CUI SESSION_TIMEOUT IDLE_TIMEOUT CALLING_STATION_ID CALLED_STATION_ID NAS_ID NAS_PORT_TYPE ACCT_SESSION_ID ACCT_INTERIM_INTERVAL WISPR_LOCATION_ID WISPR_LOCATION_NAME WISPR_BANDWIDTH_MAX_UP WISPR_BANDWIDTH_MAX_DOWN COOVACHILLI_MAX_INPUT_OCTETS COOVACHILLI_MAX_OUTPUT_OCTETS COOVACHILLI_MAX_TOTAL_OCTETS INPUT_OCTETS OUTPUT_OCTETS INPUT_PACKETS OUTPUT_PACKETS SESSION_TIME IDLE_TIME LOCATION OLD_LOCATION TERMINATE_CAUSE
#do
# echo -n "$i=" >> $debug_file
# if [[ -v $i ]];
# then
# echo -n "${!i}; " >> $debug_file
# else
# echo -n "not defined; " >> $debug_file
# fi
#done
#echo >> $debug_file
#echo "ALCASAR-Filter : $set_filter" >> $debug_file
#echo "ALCASAR-Protocols-Filter : $set_filterProto" >> $debug_file
## END Debug
#################################
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-conup.sh
0,0 → 1,112
#!/bin/sh
#
# $Id$
#
# alcasar-conup.sh
# by Rexy & Pierre RIVAULT
# This script is distributed under the Gnu General Public License (GPL)
 
# This script is started by coova after each successfull login
# Ce script est démarré par coova à chaque connexion d'usager (authentification réussi)
 
CONF_FILE="/usr/local/etc/alcasar.conf"
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_USER=`cat $PASSWD_FILE|grep ^db_user=|cut -d'=' -f2`
DB_PASSWORD=`cat $PASSWD_FILE|grep ^db_password=|cut -d'=' -f2`
 
if [ -z $FRAMED_IP_ADDRESS ]; then
exit 1
fi
 
# Retrieve 3 alcasar special radius attributes (search order : default group, then user's group, then user)
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radreply WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ) UNION \
( SELECT attribute, value FROM radgroupreply gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ORDER BY ug.priority ) UNION \
( SELECT attribute, value FROM radgroupreply WHERE groupname = 'default' AND (attribute IN ('Alcasar-Filter', 'Alcasar-Protocols-Filter', 'Alcasar-Status-Page-Must-Stay-Open')) ) \
) attrs GROUP BY attribute;"
db_res=$(mysql -u$DB_USER -p$DB_PASSWORD -D radius -e "$db_query" -Ns)
 
filter=$(echo "$db_res" | awk '$1 == "Alcasar-Filter" { print $2 }')
filterProto=$(echo "$db_res" | awk '$1 == "Alcasar-Protocols-Filter" { print $2 }')
statusPageRequired=$(echo "$db_res" | awk '$1 == "Alcasar-Status-Page-Must-Stay-Open" { print $2 }')
 
 
# Add user to his IPSET
if [ "$filter" == '4' ]; then # AV_WL
set_filter="av_wl"
elif [ "$filter" == '3' ]; then # AV_BL
set_filter="av_bl"
elif [ "$filter" == '2' ]; then # AV
set_filter="av"
else # NOT_FILTERED
set_filter="not_filtered"
fi
 
if [ "$filterProto" == '4' ]; then # PROFILE 3 (Custom)
set_filterProto="proto_3";
elif [ "$filterProto" == '3' ]; then # PROFILE 2 (WEB + Mail + Remote access)
set_filterProto="proto_2";
elif [ "$filterProto" == '2' ]; then # PROFILE 1 (WEB)
set_filterProto="proto_1";
else # PROFILE 0 (Not filtered)
set_filterProto="proto_0";
fi
 
# Add user to his IPSET
ipset add $set_filter $FRAMED_IP_ADDRESS
ipset add $set_filterProto $FRAMED_IP_ADDRESS
 
# If status page isn't required :
# -add user_IP with flag PERM in /tmp/current_users.txt (watchdog remove these @IP at midnight)
# if the user has the "Expiration" attribute, add its @MAC as an authenticated user (with the same user's attributes)
if [ "$statusPageRequired" == '2' ]; then # Status page is not required
current_users_file="/tmp/current_users.txt"
if [ ! -e $current_users_file ]; then
touch $current_users_file && chown root:apache $current_users_file && chmod 660 $current_users_file
fi
echo "$FRAMED_IP_ADDRESS:PERM" >> $current_users_file
fi
 
# set the user_ip to an gw_ipset for load-balancing
gw_min="gw0"
weight=`grep ^PUBLIC_WEIGHT= $CONF_FILE | cut -d"=" -f2`
already=`ipset list $gw_min | grep Number\ of\ entries: | cut -d":" -f2`
#The *1000 is here to avoid working on floats in bash
gw_min_value=$((1000 * $already / $weight))
 
nb_gw=`grep ^WAN $CONF_FILE | wc -l`
for (( i = 1 ; i <= $nb_gw ; i++ ));do
gw="gw${i}"
weight=`grep ^WAN$i= $CONF_FILE | awk -F'"' '{ print $2 }' | awk -F ',' '{ print $2 }'`
already=`ipset list $gw | grep Number\ of\ entries: | cut -d":" -f2`
value=$((1000 * $already / $weight))
if [ $value -lt $gw_min_value ]
then
gw_min_value=$value
gw_min=$gw
fi
done
ipset add $gw_min $FRAMED_IP_ADDRESS
 
#############################
## Debug : show all the coova parse variables (+ ALCASAR-Filter + ALCASAR-Protocols-Filter + Alcasar-Status-Page-Must-Stay-Open).
## see "/src/chilli.c" for the complete list of parse variables
#debug_file="/tmp/debug-conup.txt"
#echo "-----------------------------------------------" >> $debug_file
#echo `date` >> $debug_file
#for i in DEV NET MASK ADDR USER_NAME NAS_IP_ADDRESS SERVICE_TYPE FRAMED_IP_ADDRESS FILTER_ID STATE CLASS CUI SESSION_TIMEOUT IDLE_TIMEOUT CALLING_STATION_ID CALLED_STATION_ID NAS_ID NAS_PORT_TYPE ACCT_SESSION_ID ACCT_INTERIM_INTERVAL WISPR_LOCATION_ID WISPR_LOCATION_NAME WISPR_BANDWIDTH_MAX_UP WISPR_BANDWIDTH_MAX_DOWN COOVACHILLI_MAX_INPUT_OCTETS COOVACHILLI_MAX_OUTPUT_OCTETS COOVACHILLI_MAX_TOTAL_OCTETS INPUT_OCTETS OUTPUT_OCTETS INPUT_PACKETS OUTPUT_PACKETS SESSION_TIME IDLE_TIME LOCATION OLD_LOCATION TERMINATE_CAUSE
#do
# echo -n "$i=" >> $debug_file
# if [[ -v $i ]];
# then
# echo -n "${!i}; " >> $debug_file
# else
# echo -n "not defined; " >> $debug_file
# fi
#done
#echo >> $debug_file
#echo "ALCASAR-Filter : $set_filter" >> $debug_file
#echo "ALCASAR-Protocols-Filter : $set_filterProto" >> $debug_file
#echo "Alcasar-Status-Page-Must-Stay-Open : $statusPageRequired" >> $debug_file
## END DEBUG
#################################
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-wifi4eu.sh
0,0 → 1,48
#!/bin/bash
 
# alcasar-wifi4eu.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# active ou désactive l'affichage du logo WIFI4EU (+ intégration de leur échantillon de code)
# enable or disable the display of WIFI4EU logo (+ integration of their snippet)
 
SED="/bin/sed -i"
CONF_FILE="/usr/local/etc/alcasar.conf"
TRUST_SITES_FILE='/usr/local/etc/alcasar-uamdomain'
TRUST_DOMAIN='collection.wifi4eu.ec.europa.eu' # the web site where the snippet connects to
HOSTNAME=$(grep ^HOSTNAME= $CONF_FILE | cut -d'=' -f2)
DOMAIN=$(grep ^DOMAIN= $CONF_FILE | cut -d'=' -f2)
 
usage="Usage: alcasar-wifi4eu.sh {--on | -on} | {--off | -off}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
echo "$usage"
exit 1
fi
 
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--off | -off)
$SED "s?^WIFI4EU=.*?WIFI4EU=off?" $CONF_FILE
$SED "/$TRUST_DOMAIN/d" $TRUST_SITES_FILE
/usr/local/bin/alcasar-file-clean.sh # Clean & sort conf files.
/usr/bin/systemctl restart chilli
;;
--on | -on)
$SED "s?^WIFI4EU=.*?WIFI4EU=on?" $CONF_FILE
echo "uamdomain=\"$TRUST_DOMAIN\"" >> $TRUST_SITES_FILE
/usr/local/bin/alcasar-file-clean.sh # Clean & sort conf files.
/usr/bin/systemctl restart chilli
;;
*)
echo "Argument inconnu : $1"
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-CA.sh
0,0 → 1,191
#!/bin/sh
# $Id$
 
# alcasar-CA.sh
# by Franck BOUIJOUX (3abtux), Pascal LEVANT and Richard REY (Rexy)
# This script is distributed under the Gnu General Public License (GPL)
#
# Some ideas from "nessus-mkcert" script written by Renaud Deraison <deraison@cvs.nessus.org>
# and Michel Arboi <arboi@alussinan.org>
#
DIR_TMP=${TMPDIR-/tmp}/alcasar-mkcert.$$
DIR_PKI=/etc/pki
DIR_CERT=$DIR_PKI/tls
DIR_WEB=/var/www/html
CACERT=$DIR_PKI/CA/alcasar-ca.crt
CAKEY=$DIR_PKI/CA/private/alcasar-ca.key
SRVREQ=$DIR_CERT/alcasar.req
SRVKEY=$DIR_CERT/private/alcasar.key
SRVCERT=$DIR_CERT/certs/alcasar.crt
SRVPEM=$DIR_CERT/private/alcasar.pem
SRVCHAIN=$DIR_CERT/certs/server-chain.pem
CONF_FILE="/usr/local/etc/alcasar.conf"
hostname=`grep ^HOSTNAME= $CONF_FILE|cut -d"=" -f2`
domain=`grep ^DOMAIN= $CONF_FILE|cut -d"=" -f2`
domain=${domain:=localdomain}
fqdn_hostname="$hostname.$domain"
# The value for organizationalUnitName must be 64 chars or less;
# thus, hostname must be 36 chars or less. If it's too big,
# try removing domain (merci REXY ;-) ).
hostname_len=`echo $fqdn_hostname| wc -c`
if [ $hostname_len -gt 36 ];
then
fqdn_hostname=$hostname
fi
private_ip=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f1`
 
CACERT_LIFETIME="1460"
SRVCERT_LIFETIME="1460"
COUNTRY="FR"
PROVINCE="none"
LOCATION="Paris"
ORGANIZATION="ALCASAR-Team"
 
mkdir $DIR_TMP || exit 1
[ -d $DIR_PKI/CA/private ] || mkdir -p $DIR_PKI/CA/private ; chown -R root:root $DIR_PKI/CA ; chmod -R 750 $DIR_PKI/CA
# dynamic conf file for openssl
cat <<EOF >$DIR_TMP/ssl.conf
RANDFILE = $HOME/.rnd
#
[ca]
default_ca = AlcasarCA
 
[AlcasarCA]
dir = $DIR_TMP # Where everything is kept
certs = \$dir # Where the issued certs are kept
crl_dir = \$dir # Where the issued crl are kept
database = \$dir/index.txt # database index file.
new_certs_dir = \$dir # default place for new certs.
certificate = $CACERT # The CA certificate
serial = \$dir/serial # The current serial number
crl = \$dir/crl.pem # The current CRL
private_key = $CAKEY # The private key
x509_extensions = usr_cert # The extentions to add to the cert
crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sha256 # which message digest to use.
preserve = no # keep passed DN ordering
policy = policy_anything
 
[policy_anything]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
 
[req]
default_bits = 2048
distinguished_name = req_distinguished_name
# attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
 
[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = critical,CA:true
keyUsage = cRLSign, keyCertSign
nsCertType = sslCA
 
[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = FR
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
localityName_default = Lyon
0.organizationName = Organization Name (eg, company)
0.organizationName_default = your organization name
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (eg, your name or your server\'s hostname)
commonName_max = 255
emailAddress = Email Address
emailAddress_max = 255
 
[usr_cert]
nsCertType = server
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
issuerAltName = issuer:copy
subjectAltName = @alt_names
 
[alt_names]
DNS.1 = $fqdn_hostname
IP.1 = $private_ip
EOF
 
CAMAIL=
SRVMAIL=
echo 01 > $DIR_TMP/serial
touch $DIR_TMP/index.txt
 
# CA key
rm -f $CAKEY
echo "*********CAKEY*********" > $DIR_TMP/openssl-log
openssl genrsa -out $CAKEY 2048 2>> $DIR_TMP/openssl-log
 
# CA certificate
rm -f $CACERT
echo >> $DIR_TMP/openssl-log
echo "*********CACERT*********" >> $DIR_TMP/openssl-log
echo "$COUNTRY
$PROVINCE
$LOCATION
$ORGANIZATION
Certification Authority for $fqdn_hostname
$fqdn_hostname-local-CA
$CAMAIL" |
openssl req -config $DIR_TMP/ssl.conf -new -x509 -sha256 -days $CACERT_LIFETIME -key $CAKEY -out $CACERT 2>> $DIR_TMP/openssl-log
 
# Server key
rm -f $SRVKEY
echo >> $DIR_TMP/openssl-log
echo "*********SRVKEY*********" >> $DIR_TMP/openssl-log
openssl genrsa -out $SRVKEY 2048 2>> $DIR_TMP/openssl-log
 
# Server certificate "request"
echo >> $DIR_TMP/openssl-log
echo "*********SRVRQST*********" >> $DIR_TMP/openssl-log
echo "$COUNTRY
$PROVINCE
$LOCATION
$ORGANIZATION
Server certificate for $fqdn_hostname
$fqdn_hostname
$SRVMAIL" |
openssl req -config $DIR_TMP/ssl.conf -new -key $SRVKEY -out $SRVREQ 2>> $DIR_TMP/openssl-log
 
# Sign the server certificate "request" to create server certificate
rm -f $SRVCERT
echo >> $DIR_TMP/openssl-log
echo "*********SRVCERT*********" >> $DIR_TMP/openssl-log
openssl ca -config $DIR_TMP/ssl.conf -name AlcasarCA -batch -days $SRVCERT_LIFETIME -in $SRVREQ -out $SRVCERT 2>> $DIR_TMP/openssl-log
rm -f $SRVREQ
 
(cat $SRVKEY; echo; cat $SRVCERT) > $SRVPEM
cp -f $CACERT $SRVCHAIN
 
# Limit rights
chown -R root:root $SRVKEY $CAKEY
chmod -R 0600 $SRVKEY $CAKEY
 
# Link certs in ALCASAR Control Center
if [ -s "$CACERT" -a -s "$CAKEY" -a -s "$SRVCERT" -a -s "$SRVKEY" ];
then
[ -d $DIR_WEB/certs ] || mkdir -p $DIR_WEB/certs
rm -f $DIR_WEB/certs/*
ln -s $CACERT $DIR_WEB/certs/certificat_alcasar_ca.crt
ln -s $SRVCERT $DIR_WEB/certs/certificat_alcasar.crt
rm -rf $DIR_TMP
exit 0
else
echo "An error occured when generating security certificates (see : $DIR_TMP/openssl-log)"
exit 1
fi
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-https.sh
0,0 → 1,58
#!/bin/bash
# $Id$
 
# alcasar-dhcp.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# active ou désactive le chiffrement sur les flux d'authentification
# enable or disable encryption on authentication flows
 
SED="/bin/sed -i"
CONF_FILE="/usr/local/etc/alcasar.conf"
CHILLI_CONF_FILE="/etc/chilli.conf"
HOSTNAME=$(grep ^HOSTNAME= $CONF_FILE | cut -d'=' -f2)
DOMAIN=$(grep ^DOMAIN= $CONF_FILE | cut -d'=' -f2)
 
usage="Usage: alcasar-https.sh {--on | -on} | {--off | -off}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
echo "$usage"
exit 1
fi
 
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--off | -off) # Chilli : disable HTTPS (it will listen only on 3990 port) + lighttpd : switch with an HTTP conf file
$SED "s?^HTTPS_LOGIN=.*?HTTPS_LOGIN=off?" $CONF_FILE
$SED "s?^HTTPS_CHILLI=.*?HTTPS_CHILLI=off?" $CONF_FILE
$SED "s?^uamserver.*?uamserver\thttp://$HOSTNAME.$DOMAIN/intercept.php?" $CHILLI_CONF_FILE
$SED "s?^redirssl.*?#&?" $CHILLI_CONF_FILE
$SED "s?^uamuissl.*?#&?" $CHILLI_CONF_FILE
/usr/bin/systemctl restart chilli
rm -f /etc/lighttpd/vhosts.d/alcasar.conf
ln -s /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf /etc/lighttpd/vhosts.d/alcasar.conf
/usr/bin/systemctl restart lighttpd
;;
--on | -on) # Chilli : enable HTTPS (it will listen on ports 3990 (http) and 3991 (https) + lighttpd : switch with an HTTPS conf file
$SED "s?^HTTPS_LOGIN=.*?HTTPS_LOGIN=on?" $CONF_FILE
$SED "s?^HTTPS_CHILLI=.*?HTTPS_CHILLI=on?" $CONF_FILE
$SED "s?^uamserver.*?uamserver\thttps://$HOSTNAME.$DOMAIN/intercept.php?" $CHILLI_CONF_FILE
$SED "s?^#redirssl.*?redirssl?" $CHILLI_CONF_FILE
$SED "s?^#uamuissl.*?uamuissl?" $CHILLI_CONF_FILE
/usr/bin/systemctl restart chilli
rm -f /etc/lighttpd/vhosts.d/alcasar.conf
ln -s /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar.conf
/usr/bin/systemctl restart lighttpd
;;
*)
echo "Argument inconnu : $1"
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-iot_capture.sh
0,0 → 1,62
#!/bin/bash
 
# alcasar-iot_capture.sh
# by Guillaume Gellusseau, Dorian Lemoine & REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Ce script lance une capture de flux réseau en fonction d'une adresse IP source ($1)
# This script performs a network flow capture based on source ip address ($1)
 
CONF_FILE="/usr/local/etc/alcasar.conf"
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2`
PRIVATE_IP=$(grep ^PRIVATE_IP= $CONF_FILE | cut -d'=' -f2 | cut -d'/' -f1)
 
function info
{
_PID=$(ps -ef | grep tcpdump | grep $1 | awk {'print $2'})
if [[ -n $_PID ]]
then
echo "CaptureON"
else
echo "CaptureOFF"
fi
}
 
function kill
{
_PID=$(ps -ef | grep tcpdump | grep $1 | awk {'print $2'})
sudo kill -2 $_PID
}
 
function launch
{
# capture only one @MAC, on $INTIF, max filesize=10M, without flows to PRIVATE_IP except DNS
sudo tcpdump "ether host $1 and (host not $PRIVATE_IP or port 53)" -i $INTIF -n -C 10 -W 1 -w /var/Save/iot_captures/$1.pcap
}
 
function flush
{
sudo rm /var/Save/iot_captures/$1.pcap -f
}
 
 
while getopts "l k i f" option; do
 
case "${option}" in
 
l)
launch $2
;;
k)
kill $2
;;
i)
info $2
;;
f)
flush $2
;;
esac
done
 
#End
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-importcert.sh
0,0 → 1,173
#!/bin/bash
#
# $Id$
#
# alcasar-importcert.sh
# by Raphaël, Hugo, Clément, Bettyna & rexy
#
# This script is distributed under the Gnu General Public License (GPL)
#
# Script permettant
# - d'importer des certificats sur Alcasar
# - de revenir au certificat par default
#
# This script allows
# - to import a certificate in Alcasar
# - to go back to the default certificate
 
SED="/bin/sed -ri"
DIR_CERT="/etc/pki/tls"
CONF_FILE="/usr/local/etc/alcasar.conf"
PRIVATE_IP_MASK=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`
 
usage="Usage: alcasar-importcert.sh -i /path/to/certificate.crt -k /path/to/privatekey.key [-c /path/to/serverchain.crt]\n alcasar-importcert.sh -d (restore default certificate)"
nb_args=$#
arg1=$1
 
function defaultCert()
{
mv -f $DIR_CERT/certs/alcasar.crt.old $DIR_CERT/certs/alcasar.crt
mv -f $DIR_CERT/private/alcasar.key.old $DIR_CERT/private/alcasar.key
if [ -f $DIR_CERT/certs/server-chain.pem.old ]
then
mv $DIR_CERT/certs/server-chain.pem.old $DIR_CERT/certs/server-chain.pem
fi
(cat $DIR_CERT/private/alcasar.key; echo; cat $DIR_CERT/certs/alcasar.crt) > $DIR_CERT/private/alcasar.pem
chown root:apache $DIR_CERT/private/alcasar.pem
chmod 750 $DIR_CERT/private/alcasar.pem
}
 
function domainName() # change the domain name in the conf files
{
fqdn=$(openssl x509 -noout -subject -nameopt multiline -in $DIR_CERT/certs/alcasar.crt | grep commonName|cut -d"=" -f2|tr -d ' ')
#check if there is a wildcard in $fqdn
if [[ $fqdn == *"*"* ]];
then
hostname="alcasar"
fqdn=${fqdn/"*"/$hostname}
else
hostname=$(echo $fqdn | cut -d'.' -f1)
fi
domain=$(echo $fqdn | cut -d'.' -f2-)
echo "fqdn=$fqdn hostname=$hostname domain=$domain"
#check fqdn format
if [[ "$fqdn" != "" && "$domain" != "" ]]; then
$SED "s/^HOSTNAME=.*/HOSTNAME=$hostname/g" /usr/local/etc/alcasar.conf
$SED "s/^DOMAIN=.*/DOMAIN=$domain/g" /usr/local/etc/alcasar.conf
/usr/local/bin/alcasar-conf.sh --apply
fi
}
 
function certImport()
{
if [ ! -f "$DIR_CERT/certs/alcasar.crt.old" ]
then
echo "Backup of old cert (alcasar.crt)"
mv $DIR_CERT/certs/alcasar.crt $DIR_CERT/certs/alcasar.crt.old
fi
if [ ! -f "$DIR_CERT/private/alcasar.key.old" ]
then
echo "Backup of old private key (alcasar.key)"
mv $DIR_CERT/private/alcasar.key $DIR_CERT/private/alcasar.key.old
fi
cp $cert $DIR_CERT/certs/alcasar.crt
cp $key $DIR_CERT/private/alcasar.key
(cat $DIR_CERT/private/alcasar.key; echo; cat $DIR_CERT/certs/alcasar.crt) > $DIR_CERT/private/alcasar.pem
chown root:apache $DIR_CERT/certs/alcasar.crt
chown root:apache $DIR_CERT/private/alcasar.key
chown root:apache $DIR_CERT/private/alcasar.pem
chmod 750 $DIR_CERT/certs/alcasar.crt
chmod 750 $DIR_CERT/private/alcasar.key
chmod 750 $DIR_CERT/private/alcasar.pem
if [ "$sc" != "" ]
then
echo "cert-chain exists"
if [ ! -f "$DIR_CERT/certs/server-chain.pem.old" ]
then
echo "Backup of old cert-chain (server-chain.pem)"
mv $DIR_CERT/certs/server-chain.pem $DIR_CERT/certs/server-chain.pem.old
fi
cp $sc $DIR_CERT/certs/server-chain.pem
chown root:apache $DIR_CERT/certs/server-chain.pem
chmod 750 $DIR_CERT/certs/server-chain.pem
fi
}
 
 
if [ $nb_args -eq 0 ]
then
echo -e "$usage"
exit 1
fi
 
case $arg1 in
-\? | -h* | --h*)
echo -e "$usage"
exit 0
;;
-i)
arg3=$3
arg5=$5
cert=$2
key=$4
sc=$6
 
if [ "$cert" == "" ] || [ "$key" == "" ]
then
echo -e "$usage"
exit 1
fi
 
if [ ! -f "$cert" ] || [ ! -f "$key" ]
then
echo "Certificate and/or private key not found"
exit 1
fi
 
if [ ${cert: -4} != ".crt" ] && [ ${cert: -4} != ".cer" ]
then
echo "Invalid certificate file"
exit 1
fi
 
if [ ${key: -4} != ".key" ]
then
echo "Invalid private key"
exit 1
fi
 
if [ "$arg5" != "-c" ] || [ -z "$sc" ]
then
echo "No server-chain given"
echo "Importing certificate $cert with private key $key"
sc=""
else
if [ ! -f "$sc" ]
then
echo "Server-chain certificate not found"
exit 1
fi
if [ ${sc: -4} != ".crt" ] && [ ${sc: -4} != ".cer" ] && [ ${sc: -4} != ".pem" ]
then
echo "Invalid server-chain certificate file"
exit 1
fi
echo "Importing certificate $cert with private key $key and server-chain $sc"
fi
certImport
domainName
;;
-d)
if [ -f "/etc/pki/tls/certs/alcasar.crt.old" -a -f "/etc/pki/tls/private/alcasar.key.old" ]
then
echo "Restoring default certificate"
defaultCert
domainName
else echo "No default cert found"
fi
;;
*)
echo -e "$usage"
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-flush_ipset_wl.sh
0,0 → 1,11
#!/bin/sh
#by Raphaël Pion
#Permet de vider l'ipset wl_ip_allowed lorsque tous les utilisateurs de la whitelist sont déconnectés
#Clean wl_ip_allowed ipset when WL users are gone.
 
PTN="(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
NB_USERS=$(ipset list av_wl | grep -E $PTN | wc -l)
if [ $NB_USERS -eq '0' ]
then
/sbin/ipset flush wl_ip_allowed
fi
/scripts/alcasar-db-migrations/alcasar-migration-3.2.0_dbStructure.sh
0,0 → 1,81
#!/bin/bash
#
# $Id$
#
# alcasar-migration-3.2.0_dbStructure.sh
# by Tom HOUDAYER & Richard REY (Rexy)
#
# This script is distributed under the Gnu General Public License (GPL)
#
# Migrate database structure to ALCASAR 3.2.0
# Changes:
# - Set database engine of radius tables to InnoDB
# - Set column names in lowercase in radius tables
# - Set index names in lowercase in radius tables
# - Set RADIUS attribute length to 64 characters
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_PASS=$(cat $PASSWD_FILE | grep ^db_root= | cut -d'=' -f2-)
 
DRY_RUN=false
 
if [ $# -eq 1 ] && [ "$1" == "--simulation" ]; then
DRY_RUN=true
fi
 
db_query () {
if $DRY_RUN && [[ ! "$1" =~ ^'SELECT ' ]]; then
echo "[SQL] request: \"$1\""
else
mysql -u root -p"$DB_PASS" -D radius -e "$1" -Ns
[ $? -ne 0 ] && echo "[SQL] ERROR (\"$1\")"
fi
}
 
 
# Set database engine of radius tables to InnoDB
db_res=$(db_query "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'radius' AND ENGINE != 'InnoDB';")
if [ -n "$db_res" ]; then
while read -r tableName; do
db_query "ALTER TABLE $tableName ENGINE = InnoDB;"
done <<< "$db_res"
fi
 
# Set column names in lowercase in radius tables
db_res=$(db_query "SELECT COLUMN_NAME, TABLE_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'radius' AND TABLE_NAME IN ('mtotacct', 'totacct', 'userinfo') AND BINARY COLUMN_NAME REGEXP BINARY '[A-Z]';")
if [ -n "$db_res" ]; then
while read -r line; do
columnName=$(echo "$line" | cut -f1)
tableName=$(echo "$line" | cut -f2)
columnType=$(echo "$line" | cut -f3)
columnNameLower=${columnName,,}
db_query "ALTER TABLE $tableName CHANGE $columnName $columnNameLower $columnType;"
done <<< "$db_res"
fi
 
# Set index names in lowercase in radius tables
db_res=$(db_query "SELECT INDEX_NAME, TABLE_NAME, GROUP_CONCAT(COLUMN_NAME SEPARATOR ',') FROM ( SELECT INDEX_NAME, TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = 'radius' AND TABLE_NAME IN ('mtotacct', 'totacct', 'userinfo') AND INDEX_NAME != 'PRIMARY' AND BINARY INDEX_NAME REGEXP BINARY '[A-Z]' ORDER BY SEQ_IN_INDEX ) AS indexes GROUP BY TABLE_NAME, INDEX_NAME;")
if [ -n "$db_res" ]; then
while read -r line; do
indexName=$(echo "$line" | cut -f1)
tableName=$(echo "$line" | cut -f2)
indexColumns=$(echo "$line" | cut -f3)
indexNameLower=${indexName,,}
db_query "ALTER TABLE $tableName DROP INDEX $indexName, ADD INDEX $indexNameLower ($indexColumns);"
done <<< "$db_res"
fi
 
# Set RADIUS attribute length to 64 characters
db_query "ALTER TABLE radacct MODIFY COLUMN acctuniqueid varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '';"
db_query "ALTER TABLE radcheck MODIFY COLUMN attribute varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '';"
db_query "ALTER TABLE radreply MODIFY COLUMN attribute varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '';"
db_query "ALTER TABLE radgroupcheck MODIFY COLUMN attribute varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '';"
db_query "ALTER TABLE radgroupreply MODIFY COLUMN attribute varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '';"
 
# Fix potential bugs
db_query "UPDATE radreply SET attribute = 'Alcasar-Status-Page-Must-Stay-Open' WHERE attribute = 'Alcasar-Status-Page-Must-Stay-Op';"
db_query "UPDATE radgroupreply SET attribute = 'Alcasar-Status-Page-Must-Stay-Open' WHERE attribute = 'Alcasar-Status-Page-Must-Stay-Op';"
db_query "ALTER TABLE mtotacct DROP COLUMN mtotacctid;"
db_query "ALTER TABLE mtotacct ADD COLUMN mtotacctid bigint(21) AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST;"
db_query "ALTER TABLE totacct DROP COLUMN totacctid;"
db_query "ALTER TABLE totacct ADD COLUMN totacctid bigint(21) AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST;"
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-db-migrations/alcasar-migration-3.3.0_dbRadiusAttrs.sh
0,0 → 1,103
#!/bin/bash
#
# $Id$
#
# alcasar-migration-3.3.0_dbRadiusAttrs.sh
# by Tom HOUDAYER
#
# This script is distributed under the Gnu General Public License (GPL)
#
# Migrate user database to ALCASAR 3.3.0
# Changes:
# - Explode "Filter-Id" RADIUS attribute into "Alcasar-Filter", "Alcasar-Protocols-Filter", "Alcasar-Status-Page-Must-Stay-Open" and "Alcasar-Imputability-Warning"
# - Rename "ChilliSpot-*" RADIUS attribute to "CoovaChilli-*"
# - Rename "Max-All-Session" RADIUS attribute to "Alcasar-Expire-After"
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_PASS=$(cat $PASSWD_FILE | grep ^db_root= | cut -d'=' -f2-)
 
DRY_RUN=false
 
if [ $# -eq 1 ] && [ "$1" == "--simulation" ]; then
DRY_RUN=true
fi
 
db_query () {
if $DRY_RUN && [[ ! "$1" =~ ^'SELECT ' ]]; then
echo "[SQL] request: \"$1\""
else
mysql -u root -p"$DB_PASS" -D radius -e "$1" -Ns
[ $? -ne 0 ] && echo "[SQL] ERROR (\"$1\")"
fi
}
 
for step in $(seq 1 2); do
if [ $step -eq 1 ]; then
tableNameCheck='radcheck'
tableNameReply='radreply'
loginName='username'
else
tableNameCheck='radgroupcheck'
tableNameReply='radgroupreply'
loginName='groupname'
fi
 
# Explode "Filter-Id" RADIUS attribute into "Alcasar-Filter", "Alcasar-Protocols-Filter", "Alcasar-Status-Page-Must-Stay-Open" and "Alcasar-Imputability-Warning"
db_res=$(db_query "SELECT $loginName, value FROM $tableNameReply WHERE attribute = 'Filter-Id';")
if [ -n "$db_res" ]; then
echo "$(echo "$db_res" | wc -l) \"Filter-Id\" found in table \"$tableNameReply\"."
while read -r line; do
login=$(echo "$line" | cut -f1)
filterId=$(echo "$line" | cut -f2)
echo " $login ($filterId)..."
 
if [ ${filterId:5:1} == '1' ]; then # Filter: HAVP_WL
filter='4'
elif [ ${filterId:6:1} == '1' ]; then # Filter: HAVP_BL
filter='3'
elif [ ${filterId:7:1} == '1' ]; then # Filter: HAVP
filter='2'
else # Filter: NOT_FILTERED
filter=''
fi
[ ! -z "$filter" ] && db_query "INSERT INTO $tableNameReply ($loginName, attribute, value, op) VALUES ('$login','Alcasar-Filter','$filter', '=');"
 
if [ ${filterId:2:1} == '1' ]; then # FilterProto: PROFILE 3 (Custom)
filterProto='4';
elif [ ${filterId:1:1} == '1' ]; then # FilterProto: PROFILE 2 (WEB + Mail + Remote access)
filterProto='3';
elif [ ${filterId:0:1} == '1' ]; then # FilterProto: PROFILE 1 (WEB)
filterProto='2';
else # FilterProto: PROFILE 0 (Not filtered)
filterProto='';
fi
[ ! -z "$filterProto" ] && db_query "INSERT INTO $tableNameReply ($loginName, attribute, value, op) VALUES ('$login','Alcasar-Protocols-Filter','$filterProto', '=');"
 
if [ ${filterId:4:1} == '1' ]; then # status_open_required
statusOpenRequired='2';
else
statusOpenRequired='';
fi
[ ! -z "$statusOpenRequired" ] && db_query "INSERT INTO $tableNameReply ($loginName, attribute, value, op) VALUES ('$login','Alcasar-Status-Page-Must-Stay-Open','$statusOpenRequired', '=');"
 
if [ ${filterId:3:1} == '1' ]; then # imputability warning
imputabilityWarning='1';
else
imputabilityWarning='';
fi
[ ! -z "$imputabilityWarning" ] && db_query "INSERT INTO $tableNameReply ($loginName, attribute, value, op) VALUES ('$login','Alcasar-Imputability-Warning','$imputabilityWarning', '=');"
 
db_query "DELETE FROM $tableNameReply WHERE attribute = 'Filter-Id' AND $loginName = '$login';"
done <<< "$db_res"
fi
 
# Rename "ChilliSpot-*" RADIUS attribute to "CoovaChilli-*"
db_query "UPDATE $tableNameReply SET attribute = 'CoovaChilli-Max-Input-Octets' WHERE attribute = 'ChilliSpot-Max-Input-Octets';"
db_query "UPDATE $tableNameReply SET attribute = 'CoovaChilli-Max-Output-Octets' WHERE attribute = 'ChilliSpot-Max-Output-Octets';"
db_query "UPDATE $tableNameReply SET attribute = 'CoovaChilli-Max-Total-Octets' WHERE attribute = 'ChilliSpot-Max-Total-Octets';"
db_query "UPDATE $tableNameReply SET attribute = 'CoovaChilli-Bandwidth-Max-Up' WHERE attribute = 'ChilliSpot-Bandwidth-Max-Up';"
db_query "UPDATE $tableNameReply SET attribute = 'CoovaChilli-Bandwidth-Max-Down' WHERE attribute = 'ChilliSpot-Bandwidth-Max-Down';"
 
# Rename "Max-All-Session" RADIUS attribute to "Alcasar-Expire-After"
db_query "UPDATE $tableNameCheck SET attribute = 'Alcasar-Expire-After' WHERE attribute = 'Max-All-Session';"
done
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-db-migrations/alcasar-migration-3.3.1_dbRadiusAttrs.sh
0,0 → 1,62
#!/bin/bash
#
# $Id$
#
# alcasar-migration-3.3.1_dbRadiusAttrs.sh
# by Tom HOUDAYER
#
# This script is distributed under the Gnu General Public License (GPL)
#
# Migrate user database to ALCASAR 3.3.1
# Changes:
# - Move "CoovaChilli-Max-Total-Octets" RADIUS attribute from radreply to radcheck
# - Delete "CoovaChilli-Max-Input-Octets" and "CoovaChilli-Max-Output-Octets" RADIUS attributes
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_PASS=$(grep ^db_root= $PASSWD_FILE | cut -d'=' -f2-)
 
DRY_RUN=false
 
if [ $# -eq 1 ] && [ "$1" == "--simulation" ]; then
DRY_RUN=true
fi
 
db_query () {
if $DRY_RUN && [[ ! "$1" =~ ^'SELECT ' ]]; then
echo "[SQL] request: \"$1\""
else
mysql -u root -p"$DB_PASS" -D radius -e "$1" -Bs
[ $? -ne 0 ] && echo "[SQL] ERROR (\"$1\")"
fi
}
 
for step in $(seq 1 2); do
if [ $step -eq 1 ]; then
tableNameCheck='radcheck'
tableNameReply='radreply'
loginName='username'
else
tableNameCheck='radgroupcheck'
tableNameReply='radgroupreply'
loginName='groupname'
fi
 
# Move "CoovaChilli-Max-Total-Octets" RADIUS attribute from radreply to radcheck
db_res=$(db_query "SELECT $loginName, value FROM $tableNameReply WHERE attribute = 'CoovaChilli-Max-Total-Octets';")
if [ -n "$db_res" ]; then
echo "$(echo "$db_res" | wc -l) \"CoovaChilli-Max-Total-Octets\" found in table \"$tableNameReply\"."
while read -r line; do
login=$(echo "$line" | cut -f1)
value=$(echo "$line" | cut -f2)
echo " $login..."
 
db_query "INSERT INTO $tableNameCheck ($loginName, attribute, value, op) VALUES ('$login','CoovaChilli-Max-Total-Octets','$value', ':=');"
 
done <<< "$db_res"
db_query "DELETE FROM $tableNameReply WHERE attribute = 'CoovaChilli-Max-Total-Octets';"
fi
 
# Delete "CoovaChilli-Max-Input-Octets" and "CoovaChilli-Max-Output-Octets" RADIUS attributes
db_query "DELETE FROM $tableNameReply WHERE attribute = 'CoovaChilli-Max-Input-Octets';"
db_query "DELETE FROM $tableNameReply WHERE attribute = 'CoovaChilli-Max-Output-Octets';"
done
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-ldap.sh
0,0 → 1,139
#!/bin/bash
 
# $Id$
 
# alcasar-ldap.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# activation / désactivation de l'authentification des utilisateurs via un serveur LDAP externe
# enable / disable authentication of users via an extern LDAP server
 
usage="Usage: alcasar-ldap.sh {--on or -on } | {--off or -off} | --import-cert {certificatePath} | --test [-d]"
SED="/bin/sed -i"
CONF_FILE="/usr/local/etc/alcasar.conf"
LDAP_MODULE="/etc/raddb/mods-available/ldap-alcasar"
OPENLDAP_CONF='/etc/openldap/ldap.conf'
LDAPS_CERT_LOC='/etc/raddb/certs/alcasar-ldaps.crt'
LDAP_SERVER=$(grep '^LDAP_SERVER=' $CONF_FILE | cut -d"=" -f2) # hostname/IP address of the LDAP server
LDAP_USER=$(grep '^LDAP_USER=' $CONF_FILE | cut -d"=" -f2-) # LDAP username used by ALCASAR to read the remote directory
LDAP_PASSWORD=$(grep '^LDAP_PASSWORD=' $CONF_FILE | cut -d"=" -f2-) # its password
LDAP_BASE=$(grep '^LDAP_BASE=' $CONF_FILE | cut -d"=" -f2-) # Where to find the users (cn=**,dc=**,dc=**)
LDAP_UID=$(grep '^LDAP_UID=' $CONF_FILE | cut -d"=" -f2) # 'samaccountname' for A.D. - 'UID' for LDAP
LDAP_FILTER=$(grep '^LDAP_FILTER=' $CONF_FILE | cut -d"=" -f2-) # LDAP filter
LDAP_SSL=$(grep '^LDAP_SSL=' $CONF_FILE | cut -d"=" -f2-) # LDAP SSL status
LDAP_CERT_REQUIRED=$(grep '^LDAP_CERT_REQUIRED=' $CONF_FILE | cut -d"=" -f2-) # LDAP SSL certificate verifying
 
add_ldap_server_to_static_dhcp() {
if [[ "$LDAP_SERVER" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
ldap_server_ip="$LDAP_SERVER"
else
ldap_server_ip=$(dig +short $LDAP_SERVER)
[ -z "$ldap_server_ip" ] && return 1
fi
 
if [ -z "$(cat /usr/local/etc/alcasar-ethers | awk -v ldap_server_ip="$ldap_server_ip" '($2==ldap_server_ip)')" ]; then
ldap_server_mac=$(chilli_query list | awk -v ldap_server_ip="$ldap_server_ip" '($2==ldap_server_ip) {print $1}')
[ -z "$ldap_server_mac" ] && return 1
 
echo "$ldap_server_mac $ldap_server_ip" >> /usr/local/etc/alcasar-ethers
echo "$ldap_server_mac $ldap_server_ip #LDAP Server" >> /usr/local/etc/alcasar-ethers-info
fi
}
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]; then
nb_args=1
args="-h"
fi
 
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--on | -on)
$SED "s/^LDAP=.*/LDAP=on/g" $CONF_FILE
if [ "$LDAP_SSL" == 'on' ]; then
$SED "s/^\tserver =.*/\tserver = \"ldaps:\/\/${LDAP_SERVER//\"/\\\\\\\"}\"/g" $LDAP_MODULE
$SED "s/^\tport =.*/\tport = 636/g" $LDAP_MODULE
[ "$LDAP_CERT_REQUIRED" == 'on' ] && require_cert='demand' || require_cert='never'
$SED "s/^\t\t#?require_cert =.*/\t\trequire_cert = '$require_cert'/g" $LDAP_MODULE
echo "TLS_REQCERT $require_cert" > $OPENLDAP_CONF
[ -f "$LDAPS_CERT_LOC" ] && echo "TLS_CACERT $LDAPS_CERT_LOC" >> $OPENLDAP_CONF
else
$SED "s/^\tserver =.*/\tserver = \"ldap:\/\/${LDAP_SERVER//\"/\\\\\\\"}\"/g" $LDAP_MODULE
$SED "s/^\tport =.*/\tport = 389/g" $LDAP_MODULE
echo '' > $OPENLDAP_CONF
fi
$SED "s/^\tidentity =.*/\tidentity = \"${LDAP_USER//\"/\\\\\\\"}\"/g" $LDAP_MODULE
$SED "s/^\tpassword =.*/\tpassword = \"${LDAP_PASSWORD//\"/\\\\\\\"}\"/g" $LDAP_MODULE
$SED "s/^\tbase_dn =.*/\tbase_dn = \"${LDAP_BASE//\"/\\\\\\\"}\"/g" $LDAP_MODULE
[ -n "$LDAP_FILTER" ] && filter="$LDAP_FILTER" || filter='&'
$SED "s/^\t\tfilter =.*/\t\tfilter = \"(\&(${LDAP_UID//\"/\\\\\\\"}=%{%{Stripped-User-Name}:-%{User-Name}})(${filter//&/\\&}))\"/g" $LDAP_MODULE
if [ ! -e /etc/raddb/mods-enabled/ldap ]; then
ln -s $LDAP_MODULE /etc/raddb/mods-enabled/ldap
fi
[ -e /etc/raddb/sites-enabled/alcasar ] && rm /etc/raddb/sites-enabled/alcasar
ln -s /etc/raddb/sites-available/alcasar-with-ldap /etc/raddb/sites-enabled/alcasar
add_ldap_server_to_static_dhcp
/usr/bin/systemctl restart radiusd.service
;;
--off | -off)
$SED "s/^LDAP=.*/LDAP=off/g" $CONF_FILE
rm -f /etc/raddb/mods-enabled/ldap
[ -e /etc/raddb/sites-enabled/alcasar ] && rm /etc/raddb/sites-enabled/alcasar
ln -s /etc/raddb/sites-available/alcasar /etc/raddb/sites-enabled/alcasar
/usr/bin/systemctl restart radiusd.service
;;
--import-cert)
cert=$2
[ -z "$cert" ] && echo "$usage" && exit 1
 
[ ! -f "$cert" ] && { echo >&2 "ERR: certificate file \"$cert\" not found" ; exit 1; }
 
# TODO : convert DER format to PEM ?
cp -f "$cert" $LDAPS_CERT_LOC
chown root:radius $LDAPS_CERT_LOC
chmod 644 $LDAPS_CERT_LOC
 
if [ "$LDAP_CERT_REQUIRED" == 'on' ]; then
domainName=$(openssl x509 -noout -subject -in $LDAPS_CERT_LOC | cut -d' ' -f2- | sed 's@/[A-Za-z]\+=@\n@g' | tac | tr '\n' '.' | sed 's@\.\+$@@')
if [ "$domainName" != "$LDAP_SERVER" ]; then
echo 'WARN: the common name of the certificate is different from the server domain name'
fi
fi
 
$SED "s/^LDAP_SSL=.*/LDAP_SSL=on/g" $CONF_FILE
$SED "s/^\tserver =.*/\tserver = \"ldaps:\/\/${LDAP_SERVER//\"/\\\\\\\"}\"/g" $LDAP_MODULE
$SED "s/^\tport =.*/\tport = 636/g" $LDAP_MODULE
$SED "s@^#\?\t\tca_file =.*@\t\tca_file = $LDAPS_CERT_LOC@g" $LDAP_MODULE
[ "$LDAP_CERT_REQUIRED" == 'on' ] && require_cert='demand' || require_cert='never'
$SED "s/^#\?\t\trequire_cert =.*/\t\trequire_cert = '$require_cert'/g" $LDAP_MODULE
echo -e "TLS_CACERT $LDAPS_CERT_LOC\nTLS_REQCERT $require_cert" > $OPENLDAP_CONF
/usr/bin/systemctl restart radiusd.service
;;
--delete-cert)
[ -f "$LDAPS_CERT_LOC" ] && rm -f $LDAPS_CERT_LOC
;;
--test)
[ -n "$2" ] && [ "$2" == '-d' ] && debugOpt='-d229'
command -v ldapsearch &>/dev/null || { echo >&2 -e "ERR: ldapsearch is not installed\nrun 'dnf install openldap-clients'" ; exit 1; }
if [ "$LDAP_SSL" == 'on' ]; then
protocol='ldaps'
[ "$LDAP_CERT_REQUIRED" == 'on' ] && require_cert='demand' || require_cert='never'
export LDAPTLS_REQCERT="$require_cert"
[ -f "$LDAPS_CERT_LOC" ] && export LDAPTLS_CACERT="$LDAPS_CERT_LOC"
else
protocol='ldap'
fi
[ -n "$LDAP_FILTER" ] && filter="$LDAP_FILTER" || filter='&'
/usr/bin/ldapsearch $debugOpt -LLL -H "$protocol://$LDAP_SERVER" -x -D "$LDAP_USER" -w "$LDAP_PASSWORD" -b "$LDAP_BASE" "(&($LDAP_UID=*)($filter))" 1.1
;;
*)
echo "Argument inconnu : $1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-generate_log.sh
0,0 → 1,166
#!/bin/bash
#
# $Id$
#
#Corrélation et Generation des logs d'imputabilité au format PDF.
#Ce script permet de générer un fichier HTML qui sera converti en PDF a l'aide du RPM wkhtmltopdf.
#Ce PDF sera placé dans une archive protégé par un mot de passe.
#Pour extraire ce fichier PDF, il faudra installer le paquet p7zip.
#La génération de ce document préviendra les utilisateurs lors de leur prochaine connection. (utilisateur flagué dans le 4ème 'bit' de l'attribut FilterID de la BDD radius.
#
#Il est possible de demander les logs d'imputabilité :
#-depuis le début (pas d'argument)
#-à partir d'une date (un seul argument)
#-en spécifiant un intervale (deux arguments correspondant aux bornes respectives)
#Par Raphaël Pion
 
 
 
usage="Usage: alcasar-generate_log.sh PASSWORD && ({ '' } | { 'YYYY-MM-DD HH:MM:SS' } | { 'YYYY-MM-DD HH:MM:SS' 'YYYY-MM-DD HH:MM:SS' })"
nb_args=$#
DIR='/var/www/html/acc/backup/'
TMP_SQL="/tmp/log_sql.csv"
TMP_USERS="/tmp/log_users"
TMP_HTML="$DIR/log_nf.html"
TMP_PDF="$DIR/imputabilities_logs-$(date +%F).pdf"
PASSWD_FILE="/root/ALCASAR-passwords.txt"
DB_ROOT_PW=$(grep '^db_root=' $PASSWD_FILE | cut -d'=' -f 2-)
ARCHIVE_LOCATION="$DIR/imputabilities_logs.zip"
 
 
if [ $nb_args -eq 1 ]
then
QUERY="SELECT username,callingstationid,framedipaddress,acctstarttime,acctstoptime,acctinputoctets,acctoutputoctets,acctterminatecause FROM radacct ORDER BY acctstarttime INTO OUTFILE '$TMP_SQL' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n';"
SECTION_LOG="Extraction de tous les journaux"
fi
 
if [ $nb_args -eq 2 ]
then
QUERY="SELECT username,callingstationid,framedipaddress,acctstarttime,acctstoptime,acctinputoctets,acctoutputoctets,acctterminatecause FROM radacct WHERE acctstarttime >= '$2' ORDER BY acctstarttime INTO OUTFILE '$TMP_SQL' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n';"
SECTION_LOG="Extraction des journaux à partir du $2"
fi
 
if [ $nb_args -eq 3 ]
then
QUERY="SELECT username,callingstationid,framedipaddress,acctstarttime,acctstoptime,acctinputoctets,acctoutputoctets,acctterminatecause FROM radacct WHERE acctstarttime >= '$2' AND acctstarttime <= '$3' ORDER BY acctstoptime INTO OUTFILE '$TMP_SQL' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n';"
SECTION_LOG="Extraction des journaux entre $2 et $3"
fi
 
if [ $nb_args -eq 0 ]
then
echo $usage
exit
fi
 
 
if [ $nb_args -gt 3 ]
then
echo $usage
exit
fi
 
if [ -e $TMP_SQL ]
then
rm $TMP_SQL
fi
 
if [ -e $TMP_PDF ]
then
rm $TMP_PDF
fi
 
if [ -e $ARCHIVE_LOCATION ]
then
rm $ARCHIVE_LOCATION
fi
 
 
#get log information for each users
mysql -u root -p"$DB_ROOT_PW" -D radius -e "$QUERY"
 
#Create HTML document which contains every informations about users
echo "<!DOCTYPE html>" > $TMP_HTML
echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" >> $TMP_HTML
echo "<TITLE>ALCASAR Report</TITLE>" >> $TMP_HTML
echo "<link rel='stylesheet' type='text/css' href='../../css/bootstrap.min.css'>" >> $TMP_HTML
echo "<link rel='stylesheet' type='text/css' href='../../css/report.css'>" >> $TMP_HTML
echo "</HEAD>" >> $TMP_HTML
echo "<body>" >> $TMP_HTML
echo "<h1>$SECTION_LOG</h1>" >> $TMP_HTML
 
echo "<i><p style='text-align: right;'>Date de création $(date +%F)</p></i>" >> $TMP_HTML
echo "<font size='1'>" >> $TMP_HTML
cat $TMP_SQL | while read LIGNE_SQL
do
LOG_IP=$(echo $LIGNE_SQL | cut -d',' -f3)
LOG_DATE1=$(echo $LIGNE_SQL | cut -d',' -f4)
LOG_DATE2=$(echo $LIGNE_SQL | cut -d',' -f5)
 
LOG_Y1=$(echo $LOG_DATE1 | cut -d'-' -f1)
LOG_M1=$(echo $LOG_DATE1 | cut -d'-' -f2)
LOG_D1=$(echo $LOG_DATE1 | cut -d'-' -f3 | cut -d' ' -f1)
LOG_H1=$(echo $LOG_DATE1 | cut -d'-' -f3 | cut -d' ' -f2)
LOG_Y2=$(echo $LOG_DATE2 | cut -d'-' -f1)
LOG_M2=$(echo $LOG_DATE2 | cut -d'-' -f2)
LOG_D2=$(echo $LOG_DATE2 | cut -d'-' -f3 | cut -d' ' -f1)
LOG_H2=$(echo $LOG_DATE2 | cut -d'-' -f3 | cut -d' ' -f2)
DUMP=$(nfdump -q -R /var/log/nfsen/profiles-data/live/alcasar_netflow/ -t $LOG_Y1/$LOG_M1/$LOG_D1.$LOG_H1-$LOG_Y2/$LOG_M2/$LOG_D2.$LOG_H2 -O tstart -o "fmt:<tr><td class='numberLine'></td><td>%sa</td><td>%sp</td><td>%da</td><td>%dp</td><td>%ts</td></tr>" "ip $LOG_IP")
if [ ! -z "$DUMP" ]
then
echo "<div class='container'> " >> $TMP_HTML
echo "<table class='table table-striped'>" >> $TMP_HTML
echo "<thead>" >> $TMP_HTML
echo "<tr>" >> $TMP_HTML
echo "<th>Username</th>" >> $TMP_HTML
echo "<th>Client @MAC</th>" >> $TMP_HTML
echo "<th>Client @IP</th>" >> $TMP_HTML
echo "<th>Login Time</th>" >> $TMP_HTML
echo "<th>Logout Time</th>" >> $TMP_HTML
echo "<th>Upload</th>" >> $TMP_HTML
echo "<th>Download</th>" >> $TMP_HTML
echo "<th>Cause</th>" >> $TMP_HTML
echo "</tr></thead><tbody><tr>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f1) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f2) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f3) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f4) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f5) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f7) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f6) "</td>" >> $TMP_HTML
echo "<td>" $(echo $LIGNE_SQL | cut -d',' -f8) "</td>" >> $TMP_HTML
echo "</tr></tbody></table></div>" >> $TMP_HTML
echo "<div class='container mySpace'> " >> $TMP_HTML
echo "<table class='table table-striped'>" >> $TMP_HTML
echo "<thead>" >> $TMP_HTML
echo "<tr>" >> $TMP_HTML
echo "<th>N°</th>" >> $TMP_HTML
echo "<th>@IP src</th>" >> $TMP_HTML
echo "<th>Port src</th>" >> $TMP_HTML
echo "<th>@IP dst</th>" >> $TMP_HTML
echo "<th>Port dst</th>" >> $TMP_HTML
echo "<th>Date</th>" >> $TMP_HTML
echo "</tr></thead><tbody>" >> $TMP_HTML
echo $DUMP >> $TMP_HTML
echo "</tbody></table></div>" >> $TMP_HTML
fi
done
echo "</font>" >> $TMP_HTML
echo "</body>" >> $TMP_HTML
echo "</HTML>" >> $TMP_HTML
 
# inform users about that by setting the Alcasar-Imputability-Warning attribute
QUERY="INSERT INTO radreply (username, attribute, value, op) SELECT ui.username, 'Alcasar-Imputability-Warning', '1' , '=' FROM userinfo ui LEFT JOIN radreply rr ON rr.username = ui.username AND rr.attribute = 'Alcasar-Imputability-Warning' WHERE rr.username IS NULL;"
mysql -u root -p"$DB_ROOT_PW" -D radius -e "$QUERY"
 
/usr/bin/wkhtmltopdf $TMP_HTML $TMP_PDF
 
 
/usr/bin/7za a -tzip -p"$1" -mem=AES256 $ARCHIVE_LOCATION $TMP_PDF
chown apache:apache $ARCHIVE_LOCATION
 
 
rm $TMP_HTML
rm $TMP_SQL
rm $TMP_PDF
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-macup.sh
0,0 → 1,60
#!/bin/sh
#
# $Id$
#
# alcasar-macup.sh
#
# This script is distributed under the Gnu General Public License (GPL)
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
 
if [ -z "$CALLING_STATION_ID" ]; then
exit 1
fi
 
dbRootPass=$(grep ^db_root= $PASSWD_FILE | cut -d'=' -f2-)
 
chilli_query_res=$(chilli_query list mac $CALLING_STATION_ID)
[ -z "$chilli_query_res" ] && exit
 
is_connected=$(echo "$chilli_query_res" | awk '{ print $5 }')
current_mac=$CALLING_STATION_ID
 
if [ $is_connected == '0' ]; then
db_query="SELECT username, IFNULL((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(acctstoptime)), 0) AS timeout, acctterminatecause FROM radacct WHERE callingstationid='$current_mac' ORDER BY acctstarttime DESC LIMIT 1;"
db_res=$(mysql -u root -p"$dbRootPass" -D radius -e "$db_query" -Bs)
 
if [ -n "$db_res" ]; then
username=$(echo "$db_res" | cut -f1)
timeout=$(echo "$db_res" | cut -f2)
acctterminatecause=$(echo "$db_res" | cut -f3)
 
if [ "$acctterminatecause" != "User-Request" ]; then
db_query_additionalGroups=''
[ -n "$FILTER_ID" ] && db_query_additionalGroups="( SELECT attribute, value FROM radgroupreply WHERE groupname = '$FILTER_ID' AND (attribute='Alcasar-Reconnect-Timeout') ) UNION "
db_query="SELECT attribute, value FROM ( \
( SELECT attribute, value FROM radreply WHERE username = '$USER_NAME' AND (attribute='Alcasar-Reconnect-Timeout') ) UNION \
( SELECT attribute, value FROM radgroupreply gr LEFT JOIN radusergroup ug ON gr.groupname = ug.groupname WHERE username = '$USER_NAME' AND (attribute='Alcasar-Reconnect-Timeout') ORDER BY ug.priority ) UNION \
$db_query_additionalGroups \
( SELECT attribute, value FROM radgroupreply WHERE groupname = 'default' AND (attribute='Alcasar-Reconnect-Timeout') ) \
) attrs GROUP BY attribute;"
db_res=$(mysql -u root -p"$dbRootPass" -D radius -e "$db_query" -Bs)
 
reconnectTimeout=$(echo "$db_res" | awk '$1 == "Alcasar-Reconnect-Timeout" { print $2 }')
 
if [ -n "$reconnectTimeout" ] && [ $timeout -le $reconnectTimeout ]; then
for i in {1..10}; do
sleep 1
chilli_query authorize mac $current_mac username "$username"
chilli_query_res=$(chilli_query list mac $current_mac)
isPassing=$(echo "$chilli_query_res" | awk '{ print $3 }')
is_connected=$(echo "$chilli_query_res" | awk '{ print $5 }')
if [ "$is_connected" == '1' ] && [ "$isPassing" == 'pass' ]; then
logger -t alcasar-macup "The MAC address \"$current_mac\" is reconnected with user \"$username\"."
break
fi
done
fi
fi
fi
fi
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-dhcp.sh
0,0 → 1,76
#!/bin/bash
# $Id$
 
# alcasar-dhcp.sh
 
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# active ou desactive le service DHCP sur le réseau de consultation
# enable or disable the DHCP service on consultation LAN
 
SED="/bin/sed -i"
CHILLI_CONF_FILE="/etc/chilli.conf"
ALCASAR_CONF_FILE="/usr/local/etc/alcasar.conf"
 
# define DHCP parameters (LAN side)
PRIVATE_IP_MASK=`grep ^PRIVATE_IP= $ALCASAR_CONF_FILE|cut -d"=" -f2`
PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`
PRIVATE_NETMASK=`/bin/ipcalc -m $PRIVATE_IP_MASK | cut -d"=" -f2`
PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP $PRIVATE_NETMASK| cut -d"=" -f2`
PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP $PRIVATE_NETMASK |cut -d"=" -f2`
PRIVATE_NETWORK_MASK="$PRIVATE_NETWORK/$PRIVATE_PREFIX" # ie.: 192.168.182.0/24
EXT_DHCP_IP=`grep ^EXT_DHCP_IP= $ALCASAR_CONF_FILE|cut -d"=" -f2` # Adresse du serveur DHCP externe
RELAY_DHCP_IP=`grep ^RELAY_DHCP_IP= $ALCASAR_CONF_FILE|cut -d"=" -f2` # Adresse de l'agent Relay : IP interne (défaut 192.168.182.1) dans le cas de DHCP dans le LAN de consultation
RELAY_DHCP_IP=${RELAY_DHCP_IP:=$PRIVATE_IP} # IP externe (défaut x.y.z.t) dans le cas de DHCP du côté WAN
RELAY_DHCP_PORT=`grep ^RELAY_DHCP_PORT= $ALCASAR_CONF_FILE|cut -d"=" -f2` # Port de redirection vers le relay DHCP : 67 par défaut
RELAY_DHCP_PORT=${RELAY_DHCP_PORT:=67}
 
usage="Usage: alcasar-dhcp.sh {--on | -on} | {--off | -off} "
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
echo "$usage"
exit 1
fi
case $args in
-\? | -h | --h)
echo "$usage"
exit 0
;;
--off|-off) # disable DHCP service
$SED "s?^DHCP=.*?DHCP=off?g" $ALCASAR_CONF_FILE
$SED "s?.*statip.*?statip\t\t$PRIVATE_NETWORK_MASK?g" $CHILLI_CONF_FILE
$SED "s?^#nodynip.*?nodynip?g" $CHILLI_CONF_FILE
$SED "s@^#\?dynip.*@#dynip@g" $CHILLI_CONF_FILE
if [ -n "$EXT_DHCP_IP" ] && [ "$EXT_DHCP_IP" != "none" ]
then
$SED "s?.*dhcpgateway\s.*?dhcpgateway\t$EXT_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?.*dhcprelayagent.*?dhcprelayagent\t$RELAY_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?.*dhcpgatewayport.*?dhcpgatewayport\t$RELAY_DHCP_PORT?g" $CHILLI_CONF_FILE
else
$SED "s?.*dhcpgateway\s.*?#dhcpgateway\t\t$EXT_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?.*dhcprelayagent.*?#dhcprelayagent\t\t$RELAY_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?.*dhcpgatewayport.*?#dhcpgatewayport\t\t$RELAY_DHCP_PORT?g" $CHILLI_CONF_FILE
fi
/usr/bin/systemctl restart chilli
;;
--on|-on) # enable DHCP service on all range of IP addresses
$SED "s?^DHCP=.*?DHCP=on?g" $ALCASAR_CONF_FILE
$SED "s?^RELAY_DHCP_IP=.*?RELAY_DHCP_IP=$RELAY_DHCP_IP?g" $ALCASAR_CONF_FILE
$SED "s?^RELAY_DHCP_PORT=.*?RELAY_DHCP_PORT=$RELAY_DHCP_PORT?g" $ALCASAR_CONF_FILE
$SED "s?^.*statip.*?#statip?g" $CHILLI_CONF_FILE
$SED "s?^nodynip.*?#nodynip?g" $CHILLI_CONF_FILE
$SED "s@^#\?dynip.*@dynip\t\t$PRIVATE_NETWORK_MASK@g" $CHILLI_CONF_FILE
$SED "s?^dhcpgateway\s.*?#dhcpgateway\t$EXT_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?^dhcprelayagent.*?#dhcprelayagent\t$RELAY_DHCP_IP?g" $CHILLI_CONF_FILE
$SED "s?^dhcpgatewayport.*?#dhcpgatewayport\t$RELAY_DHCP_PORT?g" $CHILLI_CONF_FILE
/usr/bin/systemctl restart chilli
;;
*)
echo "Argument inconnu :$1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-bypass.sh
0,0 → 1,62
#!/bin/bash
# $Id$
 
# alcasar-bypass.sh
# by 3abtux and Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# activation / désactivation du contournement de l'authentification et du filtrage WEB
# enable / disable the bypass of authentication process and WEB filtering
 
usage="Usage: alcasar-bypass.sh {--on or -on } | {--off or -off}"
CONF_FILE="/usr/local/etc/alcasar.conf"
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2` # INTernal InterFace
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--on | -on)
/usr/local/bin/alcasar-logout.sh all
/usr/bin/systemctl stop chilli
cp -f /etc/sysconfig/network-scripts/bypass-ifcfg-$INTIF /etc/sysconfig/network-scripts/ifcfg-$INTIF
ifup $INTIF
sh /usr/local/bin/alcasar-iptables-bypass.sh
DHCP=`grep ^DHCP= $CONF_FILE|cut -d"=" -f2`
if [ $DHCP != off ]
then
/usr/bin/systemctl start dhcpd
fi
 
rm -f /etc/cron.d/alcasar-daemon-watchdog # don't restart daemons (specially coova)
echo "ALCASAR est en mode 'bypass'"
echo "ALCASAR is in 'bypass' mode"
;;
--off | -off)
cp -f /etc/sysconfig/network-scripts/default-ifcfg-$INTIF /etc/sysconfig/network-scripts/ifcfg-$INTIF
ifup $INTIF
/usr/bin/systemctl stop dhcpd
/usr/bin/systemctl start chilli
sh /usr/local/bin/alcasar-iptables.sh
# activation of the "daemon-watchdog" every 18'
cat << EOF > /etc/cron.d/alcasar-daemon-watchdog
# activation du "chien de garde" (daemon-watchdog) toutes les 18'
*/18 * * * * root /usr/local/bin/alcasar-daemon.sh > /dev/null 2>&1
EOF
echo "L'authentification et le filtrage sont actifs"
echo "Authentication and filtering system are enabled"
;;
*)
echo "Argument inconnu :$1";
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-file-clean.sh
0,0 → 1,31
#!/bin/bash
 
# alcasar-file-clean.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# clean alcasar conf files (remove empty lines, sort and control)
# nettoie les fichiers de conf d'alcasar (suppression des lignes vides, tri et contrôle)
 
SED="/bin/sed -i"
DIR_CONF="/usr/local/etc"
ALCASAR_SERVICES="$DIR_CONF/alcasar-services"
ALCASAR_IP_BLOCKED="$DIR_CONF/alcasar-ip-blocked"
ALCASAR_UAMDOMAIN="$DIR_CONF/alcasar-uamdomain"
ALCASAR_UAMALLOWED="$DIR_CONF/alcasar-uamallowed"
ALCASAR_CONF="$DIR_CONF/alcasar.conf"
 
# sort file content
for file in $ALCASAR_SERVICES $ALCASAR_IP_BLOCKED $ALCASAR_UAMDOMAIN $ALCASAR_UAMALLOWED
do
sort -k2n $file > /tmp/alcasar-tmp-sort
mv -f /tmp/alcasar-tmp-sort $file
done
 
# remove empty lines and put rights
for file in $ALCASAR_SERVICES $ALCASAR_IP_BLOCKED $ALCASAR_CONF $ALCASAR_UAMDOMAIN $ALCASAR_UAMALLOWED
do
$SED "/^$/d" $file
chown root:apache $file
chmod 660 $file
done
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-url_filter_wl.sh
0,0 → 1,103
#!/bin/bash
 
# Id: $Id$
 
# alcasar-url_filter.sh
# by REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Active / désactive : safesearch des moteurs de recherche
# Enable / disable : search engines safesearch
# Active / désactive : le filtrage des url contenant une adresse ip à la place d'un nom de domaine
# Enable / disable : filter of urls containing ip address instead of domain name
 
CONF_FILE="/usr/local/etc/alcasar.conf"
UNBOUND_WL_DOMAIN_FILTER_CONF="/etc/unbound/conf.d/whitelist/domainfilter.conf"
IP_WL="/usr/local/share/iptables-wl-enabled/ossi-ip-safesearch"
SED="/bin/sed -i"
safesearch="Off"
usage="Usage: alcasar-url_filter_wl.sh { -safesearch_on or -safesearch_off }"
 
nb_args=$#
 
googledomains="google.com. google.ad. google.ae. google.com.af. google.com.ag. google.com.ai. google.al. google.am. google.co.ao. google.com.ar. google.as. google.at. google.com.au. google.az. google.ba. google.com.bd. google.be. google.bf. google.bg. google.com.bh. google.bi. google.bj. google.com.bn. google.com.bo. google.com.br. google.bs. google.bt. google.co.bw. google.by. google.com.bz. google.ca. google.cd. google.cf. google.cg. google.ch. google.ci. google.co.ck. google.cl. google.cm. google.cn. google.com.co. google.co.cr. google.com.cu. google.cv. google.com.cy. google.cz. google.de. google.dj. google.dk. google.dm. google.com.do. google.dz. google.com.ec. google.ee. google.com.eg. google.es. google.com.et. google.fi. google.com.fj. google.fm. google.fr. google.ga. google.ge. google.gg. google.com.gh. google.com.gi. google.gl. google.gm. google.gp. google.gr. google.com.gt. google.gy. google.com.hk. google.hn. google.hr. google.ht. google.hu. google.co.id. google.ie. google.co.il. google.im. google.co.in. google.iq. google.is. google.it. google.je. google.com.jm. google.jo. google.co.jp. google.co.ke. google.com.kh. google.ki. google.kg. google.co.kr. google.com.kw. google.kz. google.la. google.com.lb. google.li. google.lk. google.co.ls. google.lt. google.lu. google.lv. google.com.ly. google.co.ma. google.md. google.me. google.mg. google.mk. google.ml. google.com.mm. google.mn. google.ms. google.com.mt. google.mu. google.mv. google.mw. google.com.mx. google.com.my. google.co.mz. google.com.na. google.com.nf. google.com.ng. google.com.ni. google.ne. google.nl. google.no. google.com.np. google.nr. google.nu. google.co.nz. google.com.om. google.com.pa. google.com.pe. google.com.pg. google.com.ph. google.com.pk. google.pl. google.pn. google.com.pr. google.ps. google.pt. google.com.py. google.com.qa. google.ro. google.ru. google.rw. google.com.sa. google.com.sb. google.sc. google.se. google.com.sg. google.sh. google.si. google.sk. google.com.sl. google.sn. google.so. google.sm. google.sr. google.st. google.com.sv. google.td. google.tg. google.co.th. google.com.tj. google.tk. google.tl. google.tm. google.tn. google.to. google.com.tr. google.tt. google.com.tw. google.co.tz. google.com.ua. google.co.ug. google.co.uk. google.com.uy. google.co.uz. google.com.vc. google.co.ve. google.vg. google.co.vi. google.com.vn. google.vu. google.ws. google.rs. google.co.za. google.co.zm. google.co.zw. google.cat."
 
youtubedomains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
 
if [ $nb_args -le 0 ]
then
echo "$usage"
exit 1
fi
 
while [ $nb_args -ge 1 ]
do
arg=${!nb_args}
case $arg in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
# Safe search activation
-safesearch_on | --safesearch_on)
safesearch="On"
;;
# Safe search desactivation
-safesearch_off | --safesearch_off)
safesearch="Off"
;;
*)
echo "Argument inconnu : $arg";
echo "$usage"
exit 1
;;
esac
nb_args=$(expr $nb_args - 1)
done
 
if [ $safesearch == "On" ]
then
[ -e $IP_WL ] && rm -f $IP_WL
 
# add 'SafeSearch' redirection for google searching
google_safe_server=`host -ta forcesafesearch.google.com | grep "address" | cut -d" " -f4` # retrieve google forcesafesearch ip
 
# config file header
echo "server:" > $UNBOUND_WL_DOMAIN_FILTER_CONF
 
for domain in $googledomains
do
echo -e "\tlocal-zone: \"$domain\" redirect" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"$domain A $google_safe_server\"" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
done
echo "add wl_ip_allowed $google_safe_server" >> $IP_WL
 
# add 'SafeSearch' redirection for youtube searching
youtube_safe_server=`host -ta restrict.youtube.com | grep "address" | cut -d" " -f4` # retrieve youtube restrict ip
for domain in $youtubedomains
do
echo -e "\tlocal-zone: \"$domain\" redirect" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"$domain A $youtube_safe_server\"" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
done
echo "add wl_ip_allowed $youtube_safe_server" >> $IP_WL
 
# add 'SafeSearch' redirection for bing searching
bing_safe_server=`host -ta strict.bing.com | grep "address" | cut -d" " -f4` # retrieve bing strict ip
echo -e "\tlocal-zone: \"www.bing.com\" redirect" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"www.bing.com A $bing_safe_server\"" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo "add wl_ip_allowed $bing_safe_server" >> $IP_WL
 
# add 'SafeSearch' redirection for qwant searching
qwant_safe_server=`host -ta safeapi.qwant.com | grep "address" | cut -d" " -f4` # retrieve qwant strict ip
echo -e "\tlocal-zone: \"api.qwant.com\" redirect" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo -e "\tlocal-data: \"api.qwant.com A $qwant_safe_server\"" >> $UNBOUND_WL_DOMAIN_FILTER_CONF
echo "add wl_ip_allowed $qwant_safe_server" >> $IP_WL
 
$SED 's/^WL_SAFESEARCH=.*/WL_SAFESEARCH=on/g' $CONF_FILE
else
[ -e $UNBOUND_WL_DOMAIN_FILTER_CONF ] && rm -f $UNBOUND_WL_DOMAIN_FILTER_CONF
[ -e $IP_WL ] && rm -f $IP_WL
 
$SED 's/^WL_SAFESEARCH=.*/WL_SAFESEARCH=off/g' $CONF_FILE
fi
systemctl restart unbound-whitelist
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id
\ No newline at end of property
/scripts/alcasar-profil.sh
0,0 → 1,245
#!/bin/bash
# $Id$
 
# alcasar-profil.sh
# by Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# Gestion des comptes liés aux profiles
# Manage the profil logins
 
DIR_BIN="/usr/local/bin" # scripts directory
ADM_PROFIL="admin"
PROFILS="backup manager"
ALL_PROFILS=`echo $ADM_PROFIL $PROFILS`
DIR_KEY="/usr/local/etc/digest"
SED="/bin/sed -i"
Lang=`echo $LANG|cut -c 1-2`
REALM="ALCASAR Control Center (ACC)"
 
# génère le htdigest
function htdigest () {
passwdfile="$1"
username="$2"
 
[ -f "$passwdfile" ] || touch "$passwdfile"
 
grep -q "${username}:${REALM}:" "$passwdfile" && existing_user=1 || existing_user=0
 
if [ $existing_user -eq 1 ]; then
echo "Changing password for user $username in realm $REALM"
else
echo "Adding user $username in realm $REALM"
fi
 
equal=0
while [ $equal -eq 0 ]; do
echo -n "New password: "
read -s pass_1
echo
echo -n "Confirm the new password: "
read -s pass_2
echo
 
if [ -n "$pass_1" ] && [ "$pass_1" != "$pass_2" ]; then
echo -e "\nThe passwords don't match.\n"
else
equal=1
fi
done
 
digest="${username}:${REALM}:"
digest+=$(echo -n "${username}:${REALM}:${pass_1}" | md5sum | cut -d" " -f1)
 
if [ $existing_user -eq 0 ]; then
echo "$digest" >> "$passwdfile"
else
sed -i "s/${username}:${REALM}:.*/${digest}/" "$passwdfile"
fi
}
 
# liste les comptes de chaque profile
function list () {
for i in $ALL_PROFILS
do
if [ $Lang == "fr" ]
then
echo -n "Comptes liés au profil '$i' : "
 
else
echo -n "accounts linked with profile '$i' : "
fi
account_list=`cat $DIR_KEY/key_only_$i | cut -d':' -f1|sort`
for account in $account_list
do
echo -n "$account "
done
echo
done
}
# ajoute les comptes du profil "admin" aux autres profils
# crée le fichier de clés contenant tous les compte (pour l'accès au centre de gestion)
function concat () {
> $DIR_KEY/key_all
for i in $PROFILS
do
cp -f $DIR_KEY/key_only_$ADM_PROFIL $DIR_KEY/key_$i
cat $DIR_KEY/key_only_$i >> $DIR_KEY/key_$i
cat $DIR_KEY/key_only_$i >> $DIR_KEY/key_all
done
cp -f $DIR_KEY/key_only_$ADM_PROFIL $DIR_KEY/key_$ADM_PROFIL
cat $DIR_KEY/key_only_$ADM_PROFIL >> $DIR_KEY/key_all
chown -R root:apache $DIR_KEY
chmod 640 $DIR_KEY/key_*
}
 
usage="Usage: alcasar-profil.sh [-l|--list] [-a|--add [profil]] [-d|--del] [-p|--pass]"
nb_args=$#
arg1=$1
arg2=$2
 
# on met en place la structure minimale
if [ ! -e $DIR_KEY/key_$ADM_PROFIL ]
then
touch $DIR_KEY/key_$ADM_PROFIL
fi
cp -f $DIR_KEY/key_$ADM_PROFIL $DIR_KEY/key_only_$ADM_PROFIL
for i in $PROFILS
do
if [ ! -e $DIR_KEY/key_only_$i ]
then
touch $DIR_KEY/key_only_$i
fi
done
concat
if [ $nb_args -eq 0 ]
then
echo $usage
exit 0
fi
case $arg1 in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--add|-a)
if [ $nb_args -eq 1 ]
then
# ajout d'un compte
list
if [ $Lang == "fr" ]
then
echo -n "Choisissez un profil ($ALL_PROFILS) : "
else
echo -n "Select a profile ($ALL_PROFILS) : "
fi
profil=''
while [ -z "$profil" ]; do
read profil
done
else
profil="$2"
fi
 
if ! echo $ALL_PROFILS | grep -qw $profil
then
if [ $Lang == "fr" ]
then
echo "Le profil indiqué n'existe pas"
else
echo "The given profile doesn't exist"
fi
exit 1
fi
 
if [ $Lang == "fr" ]
then
echo -n "Entrez le nom du compte à créer (profil '$profil') : "
else
echo "Enter the name of the account to create (profile '$profil') : "
fi
account=''
while [ -z "$account" ]; do
read account
done
# TODO : add check
# on teste s'il n'existe pas déjà
for i in $ALL_PROFILS
do
tmp_account=`cat $DIR_KEY/key_only_$i | cut -d':' -f1`
for j in $tmp_account
do
if [ "$j" = "$account" ]
then if [ $Lang == "fr" ]
then
echo "Ce compte existe déjà"
else
echo "This account already exists"
fi
exit 1
fi
done
done
htdigest $DIR_KEY/key_only_$profil "$account"
concat
list
;;
--del|-d)
# suppression d'un compte
list
if [ $Lang == "fr" ]
then
echo -n "entrez le nom du compte à supprimer : "
else
echo -n "enter the name of the account to remove : "
fi
account=''
while [ -z "$account" ]; do
read account
done
for i in $ALL_PROFILS; do
$SED "/^$account:/d" $DIR_KEY/key_only_$i
done
concat
list
;;
--pass|-p)
# changement du mot de passe d'un compte
list
if [ $Lang == "fr" ]
then
echo "Changement de mot de passe"
echo -n "Entrez le nom du compte : "
else
echo "Password change"
echo -n "Enter the name of the account : "
fi
read account
for i in $ALL_PROFILS
do
tmp_account=`cat $DIR_KEY/key_only_$i | cut -d':' -f1`
for j in $tmp_account
do
if [ "$j" = "$account" ]
then
htdigest $DIR_KEY/key_only_$i "$account"
fi
done
done
concat
;;
--list|-l)
# liste des comptes par profil
list
;;
*)
if [ $Lang == "fr" ]
then
echo "Argument inconnu :$1";
else
echo "Unknown argument : $i";
fi
echo "$usage"
exit 1
;;
esac
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-watchdog-hl.sh
0,0 → 1,29
#!/bin/bash
# $Id: alcasar-watchdog-hl/sh 2113 2017-01-08 22:43:26Z richard $
 
# alcasar-watchdog-hl.sh
# by 3abtux
# This script is distributed under the Gnu General Public License (GPL)
# - Ce script déconnecte les équipements réseau qui sont identifiés en 0.0.0.0 (lancé optionnellement par cron dans /etc/cron.d/alcasar-watchdog)
# - This script disconnects the network equipments which are identified in 0.0.0.0 (optionally run by cron in /etc/cron.d/alcasar-watchdog)
 
OLDIFS=$IFS
IFS=$'\n'
 
usage="Usage: alcasar-watchdog-hl.sh "
case $1 in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
*)
# searching for 0.0.0.0 IP
for system in `/usr/sbin/chilli_query list |grep "0\.0\.0\.0 dnat"`
do
active_mac=`echo $system | cut -d" " -f1`
echo "$(date "+[%x-%X] : ")alcasar-watchdog-hl : $active_mac has 0.0.0.0 IP address. Alcasar release the equipment." >> /var/Save/security/watchdog-hl.log
/usr/sbin/chilli_query dhcp-release $active_mac
done
;;
esac
IFS=$OLDIFS
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-archive.sh
0,0 → 1,142
#!/bin/bash
# $Id$
 
# alcasar-archive.sh
# by Franck BOUIJOUX and REXY
# This script is distributed under the Gnu General Public License (GPL)
 
# Script permettant
# - d'exporter dans un seul fichier les logs de traçabilités et la base des usagers (à des fins d'archivages).
# - Une fonction de chiffrement des logs a été implémentée dans ce script. Lisez la documentation d'exploitation pour l'activer.
# - nettoyage des archives supérieures à 1 an (365 jours)
 
# This script allows
# - export in one file the log files and user's base (in order to archive them).
# - a cypher fonction allows to protect these files. Read the exploitation documentation to enable it.
# - delete backup files older than one year (365 days)
 
DIR_SAVE="/var/Save" # répertoire accessible par webs
DIR_LOG="/var/log" # répertoire local des log
 
#DIR_SERVICE="squid lighttpd firewall" # répertoires contenant des logs utiles à exporter
DIR_BASE="$DIR_SAVE/base" # répertoire de sauvegarde de la base de données usagers
DIR_ARCHIVE="$DIR_SAVE/archive" # répertoire de sauvegarde des archives de log
NOW="$(date +%G%m%d-%Hh%M)" # date et heure du moment
DIR_TMP="/tmp/traceability-$NOW" # Répertoire temporaire d'export
FILE="traceability-$NOW.tar.gz" # Nom du fichier de l'archive
EXPIRE_DAY=365 # Nbre de jour avant suppression des fichiers journaux
CRYPT="0" # chiffrement des logs ( 0=non / 1=oui) --> Si oui alors la signature est automatiquement activée
# log files encryption ( 0=no / 1=yes) --> if yes, the signature is automaticly enabled
SIGN="0" # Signature/empreinte des logs ( 0=non / 1=oui ) ATTENTION : nécessite la clé privée !!!
# Signature of log files ( 0=no / 1=yes ) ATTENTION : need the private key !!!
GPG_USER="" # utilisateur autorisé à déchiffrer les logs. Sa clé publique doit être connu dans le portefeuille gnupg de root (/root/.gnupg)
# user allowed to decrypt the log files. Its public key must be known in the root keyring (/root/.gnupg)
 
usage="Usage: alcasar-archive.sh {--live or -l} | {--now or -n} | {--clean or -c}"
 
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
 
 
function cleanup() {
# Nettoyage des fichiers archives
cd $DIR_SAVE
find . \( -mtime +$EXPIRE_DAY \) -a \( -name '*.gz' -o -name '*.sql' -o -name '' -o -name 'gpg' \) -exec rm -f {} \;
} # end function cleanup
 
 
function crypt() {
# Chiffrement des logs dans /var/Save/
find . \( -mtime -7 -o -ctime 0 \) -a \( -name '*log-*.gz' \) -exec gpg --output $DIR_ARCHIVE/$file/{}.gpg --encrypt --recipient $GPG_USER {} \;
} # end function crypt
 
function archive() {
mkdir -p $DIR_ARCHIVE
mkdir -p $DIR_TMP
nb_files=`ls $DIR_LOG/firewall/traceability.log*.gz 2>/dev/null | wc -w`
if [ $nb_files -ne 0 ]; then
mv $(echo $(ls -rt $DIR_LOG/firewall/traceability.log*.gz | tail -n 1 -)) $DIR_TMP/traceability-HTTP-$NOW.gz
fi
nb_files=`ls $DIR_BASE/alcasar-users-database-*.sql.gz 2>/dev/null | wc -w`
if [ $nb_files -ne 0 ]; then
mv $(echo $(ls -rt $DIR_BASE/alcasar-users-database-*.sql.gz | tail -n 1 -)) $DIR_TMP/
fi
cd /var/log/nfsen/profiles-data/live/alcasar_netflow
nb_files=`find . -mtime -7 -name 'nfcapd.[0-9]*' | wc -l`
if [ $nb_files -ne 0 ]; then
find . -mtime -7 -name 'nfcapd.[0-9]*' | xargs tar -cf $DIR_TMP/traceability-ALL-$NOW.tar;
fi
cd /tmp/
nb_files=`ls traceability-$NOW/* 2>/dev/null | wc -w`
if [ $nb_files -ne 0 ]; then
tar cvzf /tmp/$FILE traceability-$NOW/*
else echo "no file to archive"
fi
} # end archive
 
# Core script
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
--clean | -c)
# Cleanup of files older than 365 days
cleanup
;;
--now | -n)
# Cleanup of files older than 365 days
cleanup
# make an archive
archive
# Saving of the database
/usr/local/bin/alcasar-mysql.sh --dump
# Encryption of the archive
if [ -e /tmp/$FILE ]; then
if [ $CRYPT -eq "1" ]; then
{
# 1 ) chiffrement/signature =1 ==> gpg --encrypt avec test de la clé présente
gpg --output $DIR_ARCHIVE/$FILE-crypt.gpg --armor --encrypt --recipient $GPG_USER /tmp/$FILE
}
elif [ $SIGN -eq "1" ]; then
{
# 2) signature = 1 Chiffrement = 0 --> gpg --encrypt idem test de la clé présente
gpg --output $DIR_ARCHIVE/$FILE-sign.gpg --sign --recipient $GPG_USER /tmp/$FILE
gpg --output $DIR_ARCHIVE/$FILE-sign.gpg --sign --recipient $GPG_USER --detach-sign /tmp/$FILE
}
else
{
# 3) chiffrement/signature = 0 --> cp simple avec suppression des droits d'écriture
cp /tmp/$FILE $DIR_ARCHIVE/.
}
fi
fi
rm -rf /tmp/traceability-*
chown root:apache $DIR_ARCHIVE/*
;;
--live | -l)
mkdir -p $DIR_ARCHIVE
mkdir -p /tmp/live
gap=7
cd /var/log/nfsen/profiles-data/live/alcasar_netflow
find . -mtime -$gap -name 'nfcapd.[0-9]*' | xargs tar -cf /tmp/live/traceability-ALL-$NOW.tar;
# Saving of the database
/usr/local/bin/alcasar-mysql.sh --dump
mv $(echo $(ls -rt $DIR_BASE/alcasar-users-database-*.sql.gz | tail -n 1 -)) /tmp/live/
cp /var/log/firewall/traceability.log /tmp/live/traceability-HTTP-$NOW.log
tar -czf $DIR_ARCHIVE/traceability-$NOW.tar.gz /tmp/live/*
rm -rf /tmp/live
;;
*)
echo "Unknown argument :$1";
echo "$usage"
exit 1
;;
esac
exit 0
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-version.sh
0,0 → 1,58
#!/bin/bash
# $Id$
 
# alcasar-version-list.sh
# by Richard REY
# This script is distributed under the Gnu General Public License (GPL)
 
# récupère les versions d'ALCASAR (stable et développement)
# download the ALCASAR versions (stable / dev)
 
SITE_VERSION="version.alcasar.net"
MAJ="False"
DNS_VERSION_L=`dig $SITE_VERSION txt | grep ^$SITE_VERSION | cut -d"\"" -f2`
DNS_VERSION=`echo $DNS_VERSION_L|cut -d" " -f1`
MAJ_DNS_VERSION=`echo $DNS_VERSION|cut -d"." -f1`
MIN_DNS_VERSION=`echo $DNS_VERSION|cut -d"." -f2`
UPD_DNS_VERSION=`echo $DNS_VERSION|cut -d"." -f3`
RUNNING_VERSION=`grep ^VERSION= /usr/local/etc/alcasar.conf|cut -d'=' -f2`
MAJ_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f1`
MIN_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f2|cut -c1`
UPD_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f3`
 
#compare major number
if [ $MAJ_RUNNING_VERSION -lt $MAJ_DNS_VERSION ]
then
MAJ="True"
fi
#compare minor number
if [ $MAJ_RUNNING_VERSION -eq $MAJ_DNS_VERSION ]
then
if [ $MIN_RUNNING_VERSION -lt $MIN_DNS_VERSION ]
then
MAJ="True"
fi
#compare update number
if [ $MIN_DNS_VERSION -eq $MIN_RUNNING_VERSION ]
then
if [ -n "$UPD_DNS_VERSION" ]
then
if [ -z "$UPD_RUNNING_VERSION" ]
then
MAJ="True"
else
if [ $UPD_RUNNING_VERSION -lt $UPD_DNS_VERSION ]
then
MAJ="True"
fi
fi
fi
fi
fi
 
if [ $MAJ = "True" ]
then
echo "An updated version is available ($DNS_VERSION)"
else
echo "The Running version ($RUNNING_VERSION) is up to date"
fi
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-logout.sh
0,0 → 1,55
#!/bin/bash
# $Id$
 
# alcasar-logout.sh
# by Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# Déconnexion d'un ou de tous les usagers
# Logout one user (or all users)
 
PASSWD_FILE="/root/ALCASAR-passwords.txt"
RADIUS_SECRET=$(grep '^secret_radius=' $PASSWD_FILE | cut -d'=' -f 2-)
OLDIFS=$IFS
IFS=$'\n'
 
usage="Usage: alcasar-logout.sh {user_name} | {all}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
nb_args=1
args="-h"
fi
case $args in
-\? | -h* | --h*)
echo "$usage"
exit 0
;;
all)
# Compute each equipments known by chilli
for system in `/usr/sbin/chilli_query list |grep -v "\.0\.0\.0"`
do
logout_users=""
active_session=`echo $system |cut -d" " -f5`
active_user=`echo $system|cut -d" " -f6`
active_mac=`echo $system | cut -d" " -f1`
# Logout only authenticated users
if [[ $(expr $active_session) -eq 1 ]]
then
# Don't logout MAC authenticated
if [ "$active_mac" != "$active_user" ]
then
logout_users=$logout_users" $active_user"
/usr/sbin/chilli_query logout $active_mac
fi
fi
done
echo "All users are now logout : ($logout_users)"
;;
*)
echo "User-Name = $args" | /usr/bin/radclient 127.0.0.1:3799 40 $RADIUS_SECRET
;;
esac
IFS=$OLDIFS
 
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
Added: svn:keywords
+Id Author Date
\ No newline at end of property
/scripts/alcasar-ticket-clean.sh
0,0 → 1,14
#!/bin/bash
 
# alcasar-ticket-clean.sh
# by Franck BOUIJOUX & Rexy
# This script is distributed under the Gnu General Public License (GPL)
 
# nettoyage des fichiers de mots de passe générés après l'import d'une liste de noms.
# nettoyage des ticket PDF généré lors de la création d'usager
# delete password files generated during the importation of a list of names
# delete PDF ticket generated when creating new account
 
find /tmp -name '*.pwd' -exec rm -f {} \;
find /var/www/html/acc/manager/htdocs -name '*.pdf' -exec rm -f {} \;
exit 0
Property changes:
Added: svn:eol-style
+LF
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-clean_radacct
0,0 → 1,52
#!/usr/bin/perl
#
# Clean stale open sessions from the radacct table.
# we only clean up sessions which are older than $back_days
# Works with mysql and postgresql
#
use POSIX;
use File::Temp qw(tempfile tempdir);
 
$conf=shift||'/etc/freeradius-web/admin.conf';
$back_days = 30;
 
 
open CONF, "<$conf"
or die "Could not open configuration file\n";
while(<CONF>){
chomp;
($key,$val)=(split /:\s*/,$_);
$sql_type = $val if ($key eq 'sql_type');
$sql_server = $val if ($key eq 'sql_server');
$sql_username = $val if ($key eq 'sql_username');
$sql_password = $val if ($key eq 'sql_password');
$sql_database = $val if ($key eq 'sql_database');
$sql_accounting_table = $val if ($key eq 'sql_accounting_table');
$sqlcmd = $val if ($key eq 'sql_command');
}
close CONF;
 
die "sql_command directive is not set in admin.conf\n" if ($sqlcmd eq '');
die "sql command '$sqlcmd' not found or does not seem to be executable\n" if (! -x $sqlcmd);
 
if ($sql_type eq 'mysql'){
$sql_password = (!$sql_password) ? '' : "-p$sql_password";
}
$sql_password =~ s/(\W)/\\$1/g;
 
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$date = POSIX::strftime("%Y-%m-%d %T",$sec,$min,$hour,($mday - $back_days),$mon,$year,$wday,$yday,$isdst);
print "$date\n";
if (POSIX::strftime("%Y-%m-%d %T",localtime) eq $date){
die "Could not set correct back date.\n";
}
 
$query = "DELETE FROM $sql_accounting_table WHERE AcctStopTime IS NULL AND AcctStartTime < '$date';";
print "$query\n";
my ($fh, $tmp_filename) = tempfile() or die "Could not open tmp file\n";
print $fh $query;
close $fh;
$command = "$sqlcmd -h$sql_server -u$sql_username $sql_password $sql_database < $tmp_filename" if ($sql_type eq 'mysql');
$command = "$sqlcmd -U $sql_username -f $tmp_filename $sql_database" if ($sql_type eq 'pg');
$command = "$sqlcmd '$sql_server' '$sql_port' '' '$sql_username' '$sql_password' < $tmp_filename" if ($sql_type eq 'sqlrelay');
`$command`;
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-monthly_tot_stats
0,0 → 1,64
#!/usr/bin/perl
use POSIX;
use File::Temp qw(tempfile tempdir);
 
# Log in the mtotacct table aggregated accounting information for
# each user spaning in one month period.
# If the current month has not ended it will log information up to
# the current month day
# Works only with mysql and postgresql
#
 
$conf=shift||'/etc/freeradius-web/admin.conf';
 
 
open CONF, "<$conf"
or die "Could not open configuration file\n";
while(<CONF>){
chomp;
($key,$val)=(split /:\s*/,$_);
$sql_type = $val if ($key eq 'sql_type');
$sql_server = $val if ($key eq 'sql_server');
$sql_username = $val if ($key eq 'sql_username');
$sql_password = $val if ($key eq 'sql_password');
$sql_database = $val if ($key eq 'sql_database');
$sql_accounting_table = $val if ($key eq 'sql_accounting_table');
$sqlcmd = $val if ($key eq 'sql_command');
}
close CONF;
 
die "sql_command directive is not set in admin.conf\n" if ($sqlcmd eq '');
die "sql command '$sqlcmd' not found or does not seem to be executable\n" if (! -x $sqlcmd);
 
if ($sql_type eq 'mysql'){
$sql_password = (!$sql_password) ? '' : "-p$sql_password";
}
$sql_password =~ s/(\W)/\\$1/g;
 
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
if ($mday == 1){
$mon--;
}
$date_start = POSIX::strftime("%Y-%m-%d",0,0,0,1,$mon,$year,$wday,$yday,$isdst);
$date_end = POSIX::strftime("%Y-%m-%d",0,0,0,$mday,$mon,$year,$wday,$yday,$isdst);
 
$query1 = "DELETE FROM mtotacct WHERE AcctDate = '$date_start';";
$query2 = "INSERT INTO mtotacct (UserName,AcctDate,ConnNum,ConnTotDuration,
ConnMaxDuration,ConnMinDuration,InputOctets,OutputOctets,NASIPAddress)
SELECT UserName,'$date_start',SUM(ConnNum),SUM(ConnTotDuration),
MAX(ConnMaxDuration),MIN(ConnMinDuration),SUM(InputOctets),
SUM(OutputOctets),NASIPAddress FROM totacct
WHERE AcctDate >= '$date_start' AND
AcctDate <= '$date_end' GROUP BY UserName,NASIPAddress;";
print "$query1\n";
print "$query2\n";
my ($fh, $tmp_filename) = tempfile() or die "Could not open tmp file\n";
print $fh "ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS.FF TZH:TZM';\n" if ($sql_type eq 'oracle');
print $fh $query1;
print $fh $query2;
close $fh;
$command = "$sqlcmd -h $sql_server -u $sql_username $sql_password $sql_database < $tmp_filename" if ($sql_type eq 'mysql');
$command = "$sqlcmd -U $sql_username -f $tmp_filename $sql_database" if ($sql_type eq 'pg');
$command = "$sqlcmd $sql_username/$pass" . "@" . "$sql_database <$tmpfile.$server" if ($sql_type eq 'oracle');
$command = "$sqlcmd '$sql_server' '$sql_port' '' '$sql_username' '$sql_password' < $tmp_filename" if ($sql_type eq 'sqlrelay');
`$command`;
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-tot_stats
0,0 → 1,61
#!/usr/bin/perl
use POSIX;
use File::Temp qw(tempfile tempdir);
 
# Log in the totacct table aggregated daily accounting information for
# each user.
# We keep a row per user for each day.
# Works with mysql and postgresql
#
 
$conf=shift||'/etc/freeradius-web/admin.conf';
 
 
open CONF, "<$conf"
or die "Could not open configuration file\n";
while(<CONF>){
chomp;
($key,$val)=(split /:\s*/,$_);
$sql_type = $val if ($key eq 'sql_type');
$sql_server = $val if ($key eq 'sql_server');
$sql_username = $val if ($key eq 'sql_username');
$sql_password = $val if ($key eq 'sql_password');
$sql_database = $val if ($key eq 'sql_database');
$sql_accounting_table = $val if ($key eq 'sql_accounting_table');
$sqlcmd = $val if ($key eq 'sql_command');
}
close CONF;
 
die "sql_command directive is not set in admin.conf\n" if ($sqlcmd eq '');
die "sql command '$sqlcmd' not found or does not seem to be executable\n" if (! -x $sqlcmd);
 
if ($sql_type eq 'mysql'){
$sql_password = (!$sql_password) ? '' : "-p$sql_password";
}
$sql_password =~ s/(\W)/\\$1/g;
 
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$date_start = POSIX::strftime("%Y-%m-%d %T",0,0,0,($mday - 1),$mon,$year,$wday,$yday,$isdst);
$date_small_start = POSIX::strftime("%Y-%m-%d",0,0,0,($mday - 1),$mon,$year,$wday,$yday,$isdst);
$date_end = POSIX::strftime("%Y-%m-%d %T",0,0,0,$mday,$mon,$year,$wday,$yday,$isdst);
 
$query1 = "DELETE FROM totacct WHERE AcctDate = '$date_start';";
$query2 = "INSERT INTO totacct (UserName,AcctDate,ConnNum,ConnTotDuration,
ConnMaxDuration,ConnMinDuration,InputOctets,OutputOctets,NASIPAddress)
SELECT UserName,'$date_small_start',COUNT(*),SUM(AcctSessionTime),
MAX(AcctSessionTime),MIN(AcctSessionTime),SUM(AcctInputOctets),
SUM(AcctOutputOctets),NASIPAddress FROM radacct
WHERE AcctStopTime >= '$date_start' AND
AcctStopTime < '$date_end' GROUP BY UserName,NASIPAddress;";
print "$query1\n";
print "$query2\n";
my ($fh, $tmp_filename) = tempfile() or die "Could not open tmp file\n";
print $fh "ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS.FF TZH:TZM';\n" if ($sql_type eq 'oracle');
print $fh $query1;
print $fh $query2;
close $fh;
$command = "$sqlcmd -h $sql_server -u $sql_username $sql_password $sql_database < $tmp_filename" if ($sql_type eq 'mysql');
$command = "$sqlcmd -U $sql_username -f $tmp_filename $sql_database" if ($sql_type eq 'pg');
$command = "$sqlcmd $sql_username/$pass" . "@" . "$sql_database <$tmpfile.$server" if ($sql_type eq 'oracle');
$command = "$sqlcmd '$sql_server' '$sql_port' '' '$sql_username' '$sql_password' < $tmp_filename" if ($sql_type eq 'sqlrelay');
`$command`;
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/scripts/alcasar-truncate_radacct
0,0 → 1,55
#!/usr/bin/perl
#
# Delete sessions from the radacct table which are older than $back_days
# Works with mysql and postgresql
#
use POSIX;
use File::Temp qw(tempfile tempdir);
 
$conf=shift||'/etc/freeradius-web/admin.conf';
$back_days = 365;
 
 
open CONF, "<$conf"
or die "Could not open configuration file\n";
while(<CONF>){
chomp;
($key,$val)=(split /:\s*/,$_);
$sql_type = $val if ($key eq 'sql_type');
$sql_server = $val if ($key eq 'sql_server');
$sql_username = $val if ($key eq 'sql_username');
$sql_password = $val if ($key eq 'sql_password');
$sql_database = $val if ($key eq 'sql_database');
$sql_accounting_table = $val if ($key eq 'sql_accounting_table');
$sqlcmd = $val if ($key eq 'sql_command');
}
close CONF;
 
die "sql_command directive is not set in admin.conf\n" if ($sqlcmd eq '');
die "sql command '$sqlcmd' not found or does not seem to be executable\n" if (! -x $sqlcmd);
 
if ($sql_type eq 'mysql'){
$sql_password = (!$sql_password) ? '' : "-p$sql_password";
}
$sql_password =~ s/(\W)/\\$1/g;
 
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$date = POSIX::strftime("%Y-%m-%d %T",$sec,$min,$hour,($mday - $back_days),$mon,$year,$wday,$yday,$isdst);
print "$date\n";
if (POSIX::strftime("%Y-%m-%d %T",localtime) eq $date){
die "Could not set correct back date.\n";
}
$query = "";
$query = "LOCK TABLES $sql_accounting_table WRITE;" if ($sql_type eq 'mysql');
$query .= "DELETE FROM $sql_accounting_table WHERE AcctStopTime < '$date' AND AcctStopTime IS NOT NULL ;";
$query .= "UNLOCK TABLES;" if ($sql_type eq 'mysql');
print "$query\n";
my ($fh, $tmp_filename) = tempfile() or die "Could not open tmp file\n";
print $fh "ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS.FF TZH:TZM';\n" if ($sql_type eq 'oracle');
print $fh $query;
close $fh;
$command = "$sqlcmd -h$sql_server -u$sql_username $sql_password $sql_database < $tmp_filename" if ($sql_type eq 'mysql');
$command = "$sqlcmd -U $sql_username -f $tmp_filename $sql_database" if ($sql_type eq 'pg');
$command = "$sqlcmd $sql_username/$pass" . "@" . "$sql_database <$tmpfile.$server" if ($sql_type eq 'oracle');
$command = "$sqlcmd '$sql_server' '$sql_port' '' '$sql_username' '$sql_password' < $tmp_filename" if ($sql_type eq 'sqlrelay');
`$command`;
Property changes:
Added: svn:executable
+*
\ No newline at end of property