Linux Server Hardening Script
Linux Server Hardening Script
Linux Server Hardening Script
Table of Contents
Introduction 0
Acerca del Autor 0.1
Que es Jshielder? 1
Objetivo 2
Funciones de Jshielder 3
check_root 3.1
config_host 3.2
config_timezone 3.3
update_system 3.4
restrictive_umask 3.5
admin_user 3.6
rsa_keygen/keycopy 3.7
secure_tmp 3.8
secure_ssh 3.9
set_iptables 3.10
install_fail2ban 3.11
install_secure_mysql 3.12
install_apache 3.13
install_nginx_modsecurity 3.14
set_nginx_vhost 3.15
set_nginx_vhost_nophp 3.16
set_nginx_modsec_OwaspRules 3.17
install_secure_php 3.18
install_php_nginx 3.19
install_modsecurity 3.20
set_owasp_rules 3.21
secure_optimize_apache 3.22
2
JShielder - Linux Server Hardening Script
install_modevasive 3.23
install_qos_spamhaus 3.24
config_fail2ban 3.25
additional_packages 3.26
tune_secure_kernel 3.27
install_rootkit_hunter 3.28
tune_nano_vim_bashrc 3.29
daily_update_cronjob 3.30
install_portsentry 3.31
additional_hardening 3.32
install_unhide 3.33
install_tiger 3.34
install_psad 3.35
disable_compilers 3.36
apache_conf_restrictions 3.37
unattended_upgrades 3.38
enable_proc_acct 3.39
install_phpsuhosin 3.40
reboot_server 3.41
Ejecutando JShielder 4
Cierre 5
3
JShielder - Linux Server Hardening Script
Acerca de la Guía
Esta Guía fue creada con el fin de que los Administradores de Sistemas y
usuarios conozcan la herramienta JSHielder y como le puede asistir al momento
de hacer un despliegue de un servidor web en Linux de Forma Segura
Mail: jason_soto[AT]jsitech[DOT]com
Twitter: @JsiTech
Introduction 4
JShielder - Linux Server Hardening Script
Experiencia
Mas de 10 años de Experiencia en el Area de TI, en la Administración de
sistemas Linux y algunos años en Seguridad de Información.En Ocasiones da
consultorías en el area de Linux/Windows hardening, Seguridad y realiza test de
Penetración. Actualmente es el Encargado de Seguridad de información y Linux
SysAdmin en una organización.
Experiencia Informática
Sistemas Operativos: UNIX, GNU/Linux, Windows, Windows Server, Oracle
Solaris, FreeBSD
Proyectos
Constantemente hace publicaciones sobre Seguridad, Ethical Hacking, Linux
entre otros, en jsitech.com. La Idea es compartir el conocimiento con todos los
profesionales del área de la Tecnología de la Información especialmente en
Seguridad informática. Cuenta además con otros proyectos:
IT-Talks
Aquí creamos Hangouts periódicamente sobre temas del área de TI, que
incluyen, Seguridad, Desarrollo, Hacking, Administración de Sistemas, entre
otros.
Security Feed
Aquí Recopilamos los titulares de los Blogs más conocidos de Seguridad y Ethical
Hacking.
GitHub
En su cuenta de GitHub pueden ver los Scripts y otros proyectos en los que anda
trabajando. Aquí encontrarán los repo de JShielder, Otros Scripts y mas
contribuciones a diversas herramientas de Seguridad.
@JsiTech
@InfoSecFeed
@InfoSecFeed_EN
@TecnoTalks
Que es Jshielder?
JShielder es una herramienta Software libre que le permite al Administrador de
Sistemas hacer un despliegue Seguro de LAMP (Linux-Apache-Mysql/MariaDB-
PHP), LEMP (Linux-Nginx-MySQL/MariaDB-PHP), Reverse Proxy o Servidor para
hostear una aplicación de manera automatizada con poca interacción del usuario.
Que es Jshielder? 7
JShielder - Linux Server Hardening Script
Configurar un hostname;
Reconfigurar la zona horaria del sistema;
Actualizar el sistema operativo por completo, asegurando contar con las últi
Crear un nuevo usuario con privilegios de administrador, para que pueda mane
Generar las llaves públicas RSA necesarias, para que el acceso SSH a su serv
Configurar, optimizar y securizar el servicio SSH, haciéndolo inmune frente
Configurar el Firewall, generando reglas de seguridad estrictas en iptables
Reforzar la seguridad contra ataques por fuerza bruta, mediante la instalaci
NUEVO! Evita los escaneos de puertos, bloqueando las IP intrusivas con iptab
Instalar, configurar y optimizar MySQL para un rendimiento óptimo y un funci
Instalar, configurar y optimizar MariaDB para un rendimiento óptimo y un fun
Instalar, configurar y optimizar PHP 5, para que la ejecución de sus aplicac
Reforzar la seguridad de Apache, mediante la instalación, configuración y op
Se install RootKit Hunter
Se restringe el acceso de Root, solo pueden hacer login localmente
Cerramos Cron y AT, solo puede ser ejecutado por root
Se install el Sistema de Detección de Instrusos Tiger
Aseguramos el home de root y el archivo grub.cfg
Instalar paquetes adicionales que pueden ser elementales tanto para la gesti
Configurar Nano, Vim y su terminal, para que pueda trabajar cómodamente y co
Se Deshabilitan Compiladores
Se aseguran los archivos de configuración de Apache
Agregar tareas de actualización y mantenimiento periódicas al Cron, para evi
NUEVO!!! Hardening del Kernel para proteger el servidor de Varios Ataques vi
Se instala la Herramienta Unhide **
Que es Jshielder? 8
JShielder - Linux Server Hardening Script
Cambios Recientes
Que es Jshielder? 9
JShielder - Linux Server Hardening Script
Objetivo
Actualmente no existe un conocimiento amplio en la parte de la seguridad en los
Administradores de Sistemas o los mismos desarrolladores. La mayoría tienen la
mentalidad de que lo más importante es que tiene que funcionar y ya. No toman
en cuenta las implicaciones que tiene cuando uno de estos puntos es
comprometido.
Ya que como dije, muchas veces no se tiene ese conocimiento por lo menos
básico de seguridad y como llevarlo al despliegue de nuestras aplicaciones,
terminamos con aplicaciones publicadas a internet sin nada que lo proteja.
Dependiendo de seguridad perimetral que siempre va a dejar pasar un ataque si
va disfrazado como tráfico legítimo.
Objetivo 10
JShielder - Linux Server Hardening Script
Funciones de Jshielder
En este apartado vamos a ver todas las funciones que componen a Jshielder, con
el fin de que el usuario entienda que es lo que la herramienta va haciendo, que
paquete instala y con que finalidad.
Funciones de Jshielder 11
JShielder - Linux Server Hardening Script
check_root
check_root() {
if [ "$USER" != "root" ]; then
echo "Permission Denied"
echo "Can only be run by root"
exit
else
clear
f_banner
cat templates/texts/welcome
fi
}
check_root 12
JShielder - Linux Server Hardening Script
config_host
config_host() {
echo -e "\e[93m[?]\e[00m ¿Do you Wish to Set a HostName? (y/n): "; read conf
if [ "$config_host" == "y" ]; then
serverip=$(__get_ip)
echo " Type a Name to Identify this server :"
echo -n " (For Example: myserver): "; read host_name
echo -n " ¿Type Domain Name?: "; read domain_name
echo $host_name > /etc/hostname
hostname -F /etc/hostname
echo "127.0.0.1 localhost.localdomain localhost" >> /etc/hosts
echo "$serverip $host_name.$domain_name $host_name" >> /etc/hosts
#Creating Legal Banner for unauthorized Access
echo ""
echo "Creating legal Banners for unauthorized access"
spinner
cat templates/motd > /etc/motd
cat templates/motd > /etc/issue
cat templates/motd > /etc/issue.net
sed -i s/server.com/$host_name.$domain_name/g /etc/motd /etc/issue /etc/
echo "OK "
fi
say_done
}
La función config_host nos ayuda con la configuración del hostname del servidor
y crea las entradas correspondientes en /etc/hosts para la correcta resolución de
nombres. Cuando esto no está correctamente configurado es posible que
tengamos problemas con algunos servicios, tales como apache por ejemplo.
config_host 13
JShielder - Linux Server Hardening Script
echo -e "\e[93m[?]\e[00m ¿Do you Wish to Set a HostName? (y/n): "; read conf
if [ "$config_host" == "y" ]; then
serverip=$(__get_ip)
echo " Type a Name to Identify this server :"
echo -n " (For Example: myserver): "; read host_name
echo -n " ¿Type Domain Name?: "; read domain_name
echo $host_name > /etc/hostname
hostname -F /etc/hostname
echo "127.0.0.1 localhost.localdomain localhost" >> /etc/hosts
echo "$serverip $host_name.$domain_name $host_name" >> /etc/hosts
Otro de los pasos que ejecuta esta función es crear los banners para advertir
contra accesos no autorizados.
Hace uso de una plantilla que se encuentra en templates/motd. Vamos a ver que
contiene ese archivo:
Welcome to server.com
All connections are monitored and recorded
Unauthorized access to this server is prohibited
Any intrusion attempts will be reported to all Law Enforcement Agencies
Avoid Legal Charges, Disconnect NOW if you're not and authorized user!
Jshielder toma la variable del nombre del servidor y sustituye server.com con este
valor para copiarlo a las rutas, /etc/motd, /etc/issue, /etc/issue.net
config_host 14
JShielder - Linux Server Hardening Script
config_timezone
config_timezone(){
clear
f_banner
echo -e "\e[34m----------------------------------------------------------
echo -e "\e[93m[+]\e[00m We will now Configure the TimeZone"
echo -e "\e[34m----------------------------------------------------------
echo ""
sleep 10
dpkg-reconfigure tzdata
say_done
}
config_timezone 15
JShielder - Linux Server Hardening Script
update_system
update_system(){
clear
f_banner
echo -e "\e[34m----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Updating the System"
echo -e "\e[34m----------------------------------------------------------
echo ""
apt-get update
apt-get upgrade -y
say_done
}
update_system 16
JShielder - Linux Server Hardening Script
restrictive_umask
restrictive_umask(){
clear
f_banner
echo -e "\e[34m----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setting UMASK to a more Restrictive Value (027)"
echo -e "\e[34m----------------------------------------------------------
echo ""
spinner
cp templates/login.defs /etc/login.defs
sed -i s/umask\ 022/umask\ 027/g /etc/init.d/rc
echo ""
echo "OK"
say_done
}
UMASK son los permisos bases que se le dan a un archivo creado. Por defecto
linux lo tiene configurado con 022, que da acceso a lectura y escritura al dueño
de archivo, y acceso a lectura a grupos y otros. Jshielder configura el UMASK
para dar completo acceso al dueño del archivo, Lectura al grupo y restringe el
acceso a otros. Esto provee un control mas estricto.
restrictive_umask 17
JShielder - Linux Server Hardening Script
admin_user
admin_user(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m We will now Create a New User"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo -e "\e[93m[?]\e[00m Type the new username: "; read username
adduser $username
say_done
}
La función admin_user crea el usuario que es el único que podrá hacer login
remoto una vez Jshielder termine su ejecución. Inicialmente agregamos este
usuario al grupo sudo para darle permisos administrativos, pero en la última
versión decidimos eliminar ese acceso por las siguientes razonez:
admin_user 18
JShielder - Linux Server Hardening Script
rsa_keygen/keycopy
rsa_keygen(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Instructions to Generate an RSA KEY PAIR"
echo -e "\e[34m---------------------------------------------------------
echo ""
serverip=$(__get_ip)
echo " *** IF YOU DONT HAVE A PUBLIC RSA KEY, GENERATE ONE ***"
echo " Follow the Instruction and Hit Enter When Done"
echo " To receive a new Instruction"
echo " "
echo " RUN THE FOLLOWING COMMANDS"
echo -n " a) ssh-keygen -t rsa -b 4096 "; read foo1
echo -n " b) cat /home/$username/.ssh/id_rsa.pub >> /home/$username/
say_done
}
rsa_keycopy(){
echo " Run the Following Command to copy the Key"
echo " Press ENTER when done "
echo " ssh-copy-id -i $HOME/.ssh/id_rsa.pub $username@$serverip "
say_done
}
rsa_keygen/keycopy 19
JShielder - Linux Server Hardening Script
Es bueno mencionar que estas llaves deberán crearlas en la pc desde donde van
a estar realizando las conexiones remotas y no en el servidor. Al servidor solo le
copiarán la llave pública para hacer las validaciones de lugar.
rsa_keygen/keycopy 20
JShielder - Linux Server Hardening Script
secure_tmp
secure_tmp(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Securing /tmp Folder"
echo -e "\e[34m-----------------------------------------------------------
echo ""
echo -e "\e[93m[?]\e[00m ¿Did you Create a Separate /tmp partition during
if [ "$tmp_answer" == "n" ]; then
echo "We will create a FileSystem for the /tmp Directory and set Prope
dd if=/dev/zero of=/usr/tmpDISK bs=1024 count=2048000
mkdir /tmpbackup
cp -Rpf /tmp /tmpbackup
mount -t tmpfs -o loop,noexec,nosuid,rw /usr/tmpDISK /tmp
chmod 1777 /tmp
cp -Rpf /tmpbackup/* /tmp/
rm -rf /tmpbackup
echo "/usr/tmpDISK /tmp tmpfs loop,nosuid,noexec,rw 0 0" >> /et
sudo mount -o remount /tmp
rm -rf /var/tmp
ln -s /tmp /var/tmp
say_done
else
echo "Nice Going, Remember to set proper permissions in /etc/fstab"
echo ""
echo "Example:"
echo ""
echo "/dev/sda4 /tmp tmpfs loop,nosuid,noexec,rw 0 0 "
say_done
fi
}
secure_tmp 21
JShielder - Linux Server Hardening Script
Procesos Maliciosos
Ataques de Denegación de servicio
Ejecución de scripts maliciosos
secure_tmp 22
JShielder - Linux Server Hardening Script
secure_ssh
secure_ssh(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Securing SSH"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo -n " Securing SSH..."
spinner
sed s/USERNAME/$username/g templates/sshd_config > /etc/ssh/sshd_config;
chattr -i /home/$username/.ssh/authorized_keys
service ssh restart
say_done
}
secure_ssh 23
JShielder - Linux Server Hardening Script
Port 372
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 768
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 30
PermitRootLogin no
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication no
X11Forwarding no
AllowTcpForwarding no
PermitUserEnvironment no
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes
MaxStartups 2
Banner /etc/motd
AllowUsers USERNAME
secure_ssh 24
JShielder - Linux Server Hardening Script
Port 372 : Aquí configuramos el puerto donde vamos a hacer las conexiones
remotas. Muchos de los ataques de fuerza bruta van dirigidas al puerto por
defecto 22.
Protocol 2: Aquí le decimos al servidor que solo use este protocolo ya que la
versión 1 es vulnerable a diversos ataques.
Las demás opciones ponen ciertas restricciones en lo que podemos hacer con
ssh.
secure_ssh 25
JShielder - Linux Server Hardening Script
set_iptables
set_iptables(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setting IPTABLE RULES"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo -n " Setting Iptables Rules..."
spinner
sh templates/iptables.sh
cp templates/iptables.sh /etc/init.d/
ln -s /etc/init.d/iptables.sh /etc/rc2.d/S99iptables.sh
say_done
}
La función set_iptables configura las reglas de firewall del servidor Linux. Hace
uso del script que se encuentra en templates/iptables.sh. Jshielder copia el
script a /etc/init.d y crea el link simbólico correspondiente para que sea ejecutado
en el inicio. Veamos que contiene el script iptables.sh:
iptables -F
#Defaults
# INPUT
set_iptables 26
JShielder - Linux Server Hardening Script
set_iptables 27
JShielder - Linux Server Hardening Script
iptables -A INPUT -p tcp -m tcp --tcp-flags RST RST -m limit --limit 2/secon
iptables -A INPUT -p tcp -m tcp --dport 139 -m recent --name portscan --se
iptables -A INPUT -p tcp -m tcp --dport 139 -m recent --name portscan --se
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --se
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --se
# smtp
iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
# http
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
# https
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
# Permitir el Ping
set_iptables 28
JShielder - Linux Server Hardening Script
# OUTPUT
# smtp
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
# http
iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
# https
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
# Permitir Pings
# No Permitir Forward
No voy a explicar cada regla ya que las descripciones están ahí para que veamos
para que es cada una. Actualmente nos encontramos trabajando en reglas mucho
más estrictas y la capacidad de customizar las reglas durante la ejecución de
set_iptables 29
JShielder - Linux Server Hardening Script
JSHielder.
set_iptables 30
JShielder - Linux Server Hardening Script
install_fail2ban
install_fail2ban(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing Fail2Ban"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get install sendmail
apt-get install fail2ban
say_done
}
Esta función instala fail2ban. Esta herramienta actúa bloqueando las conexiones
remotas que hacen intentos de acceso por fuerza bruta. Al momento de
generarse un incidencia crea las reglas en iptables correspondiente para bloquear
la ip atacante.
install_fail2ban 31
JShielder - Linux Server Hardening Script
install_secure_mysql
install_secure_mysql(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing, Configuring and Optimizing MySQL"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get install mysql-server
echo -n " configuring MySQL............ "
cp templates/mysql /etc/mysql/my.cnf; echo " OK"
mysql_secure_installation
service mysql restart
say_done
}
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
install_secure_mysql 32
JShielder - Linux Server Hardening Script
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
local-infile=0
lc-messages-dir = /usr/share/mysql
skip-external-locking
bind-address = 127.0.0.1
key_buffer = 32M
max_allowed_packet = 1M
thread_stack = 128K
thread_cache_size = 8
myisam-recover = BACKUP
max_connections = 75
table_cache = 32
query_cache_limit = 1M
query_cache_size = 16M
log_error = /var/log/mysql/error.log
expire_logs_days = 10
max_binlog_size = 100M
skip-show-database
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
[isamchk]
key_buffer = 32M
!includedir /etc/mysql/conf.d/
install_secure_mysql 33
JShielder - Linux Server Hardening Script
install_apache
install_apache(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing Apache Web Server"
echo -e "\e[34m-----------------------------------------------------------
echo ""
apt-get install apache2
say_done
}
install_apache 34
JShielder - Linux Server Hardening Script
install_nginx_modsecurity
install_nginx_modsecurity(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Downloading and Compiling Nginx with ModSecurity"
echo -e "\e[34m-----------------------------------------------------------
echo ""
apt-get -y install git build-essential libpcre3 libpcre3-dev libssl-dev li
mkdir src
cd src/
git clone https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
./autogen.sh
./configure --enable-standalone-module
make
cd ..
wget http://nginx.org/download/nginx-1.9.7.tar.gz
tar xzvf nginx-1.9.7.tar.gz
cp ../templates/ngx_http_header_filter_module.c nginx-1.9.7/src/http/ngx_h
cd nginx-1.9.7/
./configure --user=www-data --group=www-data --with-pcre-jit --with-debug
make
make install
#Replacing Nginx conf with secure Configurations
cp ../../templates/nginx /usr/local/nginx/conf/nginx.conf
#Jason Giedymin Nginx Init Script
wget https://raw.github.com/JasonGiedymin/nginx-init-ubuntu/master/nginx -
chmod +x /etc/init.d/nginx
update-rc.d nginx defaults
mkdir /usr/local/nginx/conf/sites-available
mkdir /usr/local/nginx/conf/sites-enabled
say_done
}
install_nginx_modsecurity 35
JShielder - Linux Server Hardening Script
Esta función hace uso tambien de una plantilla para una configuración segura de
nginx.conf, esta plantilla se encuentra en templates/nginx. Veamos que
contiene el archivo:
user www-data;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
install_nginx_modsecurity 36
JShielder - Linux Server Hardening Script
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server_tokens off;
## Start: Timeouts ##
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;
## End: Timeouts ##
#gzip on;
include /usr/local/nginx/conf/sites-enabled/*;
install_nginx_modsecurity 37
JShielder - Linux Server Hardening Script
Técnicas antievasión: las rutas y los parámetros son normalizados antes del
análisis para evitar técnicas de evasión.
Decodificación de URL.
Filtrado HTTPS: al estar embebido como módulo, tiene acceso a los datos
después de que estos hayan sido descifrados.
install_nginx_modsecurity 38
JShielder - Linux Server Hardening Script
en bitácora (logging).
Variables transaccionales.
bloqueo de IP
Ya que Jshielder hace una instalación manual de Nginx, este no cuenta con los
scripts para poder manejar los servicios, es por eso que hacemos uso del Init
Script de Jason Giedman.
wget https://raw.github.com/JasonGiedymin/nginx-init-ubuntu/master/nginx -
chmod +x /etc/init.d/nginx
update-rc.d nginx defaults
mkdir /usr/local/nginx/conf/sites-available
mkdir /usr/local/nginx/conf/sites-enabled
say_done
install_nginx_modsecurity 39
JShielder - Linux Server Hardening Script
set_nginx_vhost
set_nginx_vhost(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setup Virtual Host for Nginx"
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Configure a Virtual Host"
echo " Type a Name to Identify the Virtual Host"
echo -n " (For Example: myserver.com) "; read vhost
touch /usr/local/nginx/conf/sites-available/$vhost
cd ../..
cat templates/nginxvhost >> /usr/local/nginx/conf/sites-available/$vhost
sed -i s/server.com/$vhost/g /usr/local/nginx/conf/sites-available/$vhost
ln -s /usr/local/nginx/conf/sites-available/$vhost /usr/local/nginx/conf/s
say_done
}
server {
listen 80;
server_name server.com;
location / {
ModSecurityEnabled on;
ModSecurityConfig modsecurity.conf;
root html/server.com;
index index.php index.html index.htm;
set_nginx_vhost 40
JShielder - Linux Server Hardening Script
location ~ .(gif|png|jpe?g)$ {
valid_referers none blocked server.com *.server.com;
if ($invalid_referer) {
return 403;
}
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
set_nginx_vhost 41
JShielder - Linux Server Hardening Script
set_nginx_vhost 42
JShielder - Linux Server Hardening Script
set_nginx_vhost_nophp
set_nginx_vhost_nophp(){
clear
f_banner
echo -e "\e[34m-------------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setup Virtual Host for Nginx"
echo -e "\e[34m-------------------------------------------------------------
echo -e "\e[93m[+]\e[00m Configure a Virtual Host"
echo " Type a Name to Identify the Virtual Host"
echo -n " (For Example: myserver.com) "; read vhost
touch /usr/local/nginx/conf/sites-available/$vhost
cd ../..
cat templates/nginxvhost_nophp >> /usr/local/nginx/conf/sites-available/$vho
sed -i s/server.com/$vhost/g /usr/local/nginx/conf/sites-available/$vhost
ln -s /usr/local/nginx/conf/sites-available/$vhost /usr/local/nginx/conf/sit
say_done
}
server {
listen 80;
server_name server.com;
location / {
ModSecurityEnabled on;
ModSecurityConfig modsecurity.conf;
root html/server.com;
index index.php index.html index.htm;
}
location ~ .(gif|png|jpe?g)$ {
valid_referers none blocked server.com *.server.com;
set_nginx_vhost_nophp 43
JShielder - Linux Server Hardening Script
if ($invalid_referer) {
return 403;
}
}
set_nginx_vhost_nophp 44
JShielder - Linux Server Hardening Script
set_nginx_modsec_OwaspRules
set_nginx_modsec_OwaspRules(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setting OWASP Rules for ModSecurity on Nginx"
echo -e "\e[34m-----------------------------------------------------------
echo ""
cd src/
wget https://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master -O
tar -zxvf owasp.tar.gz
owaspdir=$(ls -la | grep SpiderLabs | cut -d ' ' -f18)
cp ModSecurity/modsecurity.conf-recommended /usr/local/nginx/conf/modsecur
cp ModSecurity/unicode.mapping /usr/local/nginx/conf/
cd $owaspdir/
cat modsecurity_crs_10_setup.conf.example >> /usr/local/nginx/conf/modsecu
cd base_rules/
cat *.conf >> /usr/local/nginx/conf/modsecurity.conf
cp *.data /usr/local/nginx/conf/
cd ../../..
service nginx restart
say_done
}
set_nginx_modsec_OwaspRules 45
JShielder - Linux Server Hardening Script
set_nginx_modsec_OwaspRules 46
JShielder - Linux Server Hardening Script
install_secure_php
install_secure_php(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing, Configuring and Optimizing PHP"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get install php5 php5-cli php-pear
apt-get install php5-mysql python-mysqldb
echo -n " Replacing php.ini..."
cp templates/php /etc/php5/apache2/php.ini; echo " OK"
cp templates/php /etc/php5/cli/php.ini; echo " OK"
service apache2 restart
say_done
}
[PHP]
engine = On
short_open_tag = Off
asp_tags = Off
precision = 14
y2k_compliance = On
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 17
allow_call_time_pass_reference = Off
safe_mode = Off
safe_mode_gid = Off
install_secure_php 47
JShielder - Linux Server Hardening Script
safe_mode_include_dir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
safe_mode_protected_env_vars = LD_LIBRARY_PATH
open_basedir = "/var/www/html:/tmp"
disable_functions = proc_open, popen, disk_free_space, diskfreespace, set_ti
disable_classes =
zend.enable_gc = On
expose_php = Off
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
error_log = /var/log/php.log
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = Off
variables_order = "GPCS"
request_order = "GP"
register_globals = Off
register_long_arrays = Off
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "utf-8"
doc_root =
user_dir =
enable_dl = Off
install_secure_php 48
JShielder - Linux Server Hardening Script
file_uploads = On
upload_max_filesize = 2M
max_file_uploads = 20
allow_url_fopen = Off
allow_url_include = Off
default_socket_timeout = 60
[Date]
[filter]
[iconv]
[intl]
[sqlite]
[sqlite3]
[Pcre]
pcre.recursion_limit=1000
[Pdo]
[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[Phar]
install_secure_php 49
JShielder - Linux Server Hardening Script
[Syslog]
define_syslog_variables = Off
[mail function]
smtp_port = 25
mail.add_x_header = On
[SQL]
sql.safe_mode = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQL]
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
install_secure_php 50
JShielder - Linux Server Hardening Script
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 60
mysql.trace_mode = Off
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[OCI8]
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
install_secure_php 51
JShielder - Linux Server Hardening Script
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10
[bcmath]
bcmath.scale = 0
[browscap]
[Session]
session.save_handler = files
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 3600
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 0
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = Off
session.bug_compat_warn = Off
session.referer_check =
session.entropy_length = 0
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
[MSSQL]
mssql.allow_persistent = On
install_secure_php 52
JShielder - Linux Server Hardening Script
mssql.max_persistent = -1
mssql.max_links = -1
mssql.min_error_severity = 10
mssql.min_message_severity = 10
mssql.compatability_mode = Off
mssql.secure_connection = Off
[Assertion]
[COM]
[mbstring]
[gd]
[exif]
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[sysvshm]
[ldap]
ldap.max_links = -1
[mcrypt]
install_secure_php 53
JShielder - Linux Server Hardening Script
[dba]
[xsl]
install_secure_php 54
JShielder - Linux Server Hardening Script
install_php_nginx
install_php_nginx(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing, Configuring and Optimizing PHP/PHP-FP
echo -e "\e[34m-----------------------------------------------------------
echo ""
apt-get install php5-fpm php5 php5-cli php-pear
apt-get install php5-mysql python-mysqldb
echo -n " Replacing php.ini..."
cp templates/php /etc/php5/cli/php.ini; echo " OK"
cp templates/phpnginx /etc/php5/fpm/php.ini; echo "OK"
service php5-fpm restart
service nginx restart
say_done
}
install_php_nginx 55
JShielder - Linux Server Hardening Script
install_modsecurity
install_modsecurity(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing ModSecurity"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get install libxml2 libxml2-dev libxml2-utils
apt-get install libaprutil1 libaprutil1-dev
apt-get install libapache2-mod-security2
service apache2 restart
say_done
}
install_modsecurity 56
JShielder - Linux Server Hardening Script
set_owasp_rules
set_owasp_rules(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Setting UP OWASP Rules for ModSecurity"
echo -e "\e[34m---------------------------------------------------------
echo ""
a2enmod headers
service apache2 restart
say_done
}
set_owasp_rules 57
JShielder - Linux Server Hardening Script
set_owasp_rules 58
JShielder - Linux Server Hardening Script
Ejemplo:
10.0.0.5 prueba.com
$ vi /etc/modsecurity/modsecurity.conf
SecRuleEngine DetectionOnly
$ service apache2 reload
Luego interactuan con la aplicación y miren los logs de errores, cuando algo es
detectado por ModSecurity verán algo así.
[Mon Jan 04 08:42:41.378340 2016] [:error] [pid 1280] [client 23.92.*.*] Mod
[Mon Jan 04 08:42:42.019281 2016] [:error] [pid 1280] [client 23.92.*.*] Mod
El valor que nos interesa es el ID y con este podremos crear las excepciones en
Apache, solo es acceder al virtual host agregar una entrada como esta:
<LocationMatch "/wp-admin/update.php">
<IfModule security2_module>
SecRuleRemoveById 981173
</IfModule>
</LocationMatch>
set_owasp_rules 59
JShielder - Linux Server Hardening Script
<Directory "/var/www/wp-admin">
<IfModule security2_module>
SecRuleEngine Off
</IfModule>
</Directory>
set_owasp_rules 60
JShielder - Linux Server Hardening Script
secure_optimize_apache
secure_optimize_apache(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Optimizing Apache"
echo -e "\e[34m---------------------------------------------------------
echo ""
cp templates/apache /etc/apache2/apache2.conf
echo " -- Enabling ModRewrite"
spinner
a2enmod rewrite
service apache2 restart
say_done
}
<IfModule mpm_prefork_module>
StartServers 1
MinSpareServers 3
MaxSpareServers 6
MaxClients 24
MaxRequestsPerChild 3000
</IfModule>
secure_optimize_apache 61
JShielder - Linux Server Hardening Script
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
AccessFileName .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
<Directory />
Options -Indexes -Includes -ExecCGI
<LimitExcept GET POST HEAD>
deny from all
</LimitExcept>
</Directory>
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
secure_optimize_apache 62
JShielder - Linux Server Hardening Script
<IfModule security2_module>
Include /usr/share/modsecurity-crs/*.conf
Include /usr/share/modsecurity-crs/base_rules/*.conf
</IfModule>
IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
ServerSignature Off
ServerTokens Prod
FileETag None
Header unset ETag
TraceEnable off
ServerSignature Off
ServerTokens Prod
secure_optimize_apache 63
JShielder - Linux Server Hardening Script
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
Con esta sección controlamos que se pueden hacer desde el directorio raíz y
limitamos los accesos exclusivamente a GET, POST y HEAD.
FileETag None
Header unset ETag
TraceEnable off
secure_optimize_apache 64
JShielder - Linux Server Hardening Script
install_modevasive
install_modevasive(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing ModEvasive"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo -n " Type Email to Receive Alerts "; read inbox
apt-get install libapache2-mod-evasive
mkdir /var/log/mod_evasive
chown www-data:www-data /var/log/mod_evasive/
sed s/MAILTO/$inbox/g templates/mod-evasive > /etc/apache2/mods-availabl
service apache2 restart
say_done
}
install_modevasive 65
JShielder - Linux Server Hardening Script
<ifmodule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 60
DOSLogDir /var/log/mod_evasive
DOSEmailNotify MAILTO
DOSWhitelist 127.0.0.1
</ifmodule>
install_modevasive 66
JShielder - Linux Server Hardening Script
install_qos_spamhaus
install_qos_spamhaus(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing Mod_Qos/Spamhaus"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get -y install libapache2-mod-qos
cp templates/qos /etc/apache2/mods-available/qos.conf
apt-get -y install libapache2-mod-spamhaus
cp templates/spamhaus /etc/apache2/mods-available/spamhaus.conf
service apache2 restart
say_done
}
Qos
<IfModule qos_module.so>
# minimum request rate (bytes/sec at request reading):
QS_SrvRequestRate 120
install_qos_spamhaus 67
JShielder - Linux Server Hardening Script
# block clients violating some basic rules frequently (don't allows more t
# violations within 5 minutes):
QS_ClientEventBlockCount 20 300
QS_SetEnvIfStatus 400 QS_Block
QS_SetEnvIfStatus 401 QS_Block
QS_SetEnvIfStatus 403 QS_Block
QS_SetEnvIfStatus 404 QS_Block
QS_SetEnvIfStatus 405 QS_Block
QS_SetEnvIfStatus 406 QS_Block
QS_SetEnvIfStatus 408 QS_Block
QS_SetEnvIfStatus 411 QS_Block
QS_SetEnvIfStatus 413 QS_Block
QS_SetEnvIfStatus 414 QS_Block
QS_SetEnvIfStatus 417 QS_Block
QS_SetEnvIfStatus 500 QS_Block
QS_SetEnvIfStatus 503 QS_Block
QS_SetEnvIfStatus 505 QS_Block
QS_SetEnvIfStatus QS_SrvMinDataRate QS_Block
QS_SetEnvIfStatus NullConnection QS_Block
</IfModule>
spamhaus
install_qos_spamhaus 68
JShielder - Linux Server Hardening Script
MS_METHODS POST,PUT,OPTIONS,CONNECT
MS_WhiteList /etc/spamhaus.wl
MS_CacheSize 256
install_qos_spamhaus 69
JShielder - Linux Server Hardening Script
config_fail2ban
config_fail2ban(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Configuring Fail2Ban"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Configuring Fail2Ban......"
spinner
sed s/MAILTO/$inbox/g templates/fail2ban > /etc/fail2ban/jail.local
cp /etc/fail2ban/jail.local /etc/fail2ban/jail.conf
/etc/init.d/fail2ban restart
say_done
}
[DEFAULT]
ignoreip = 127.0.0.1/8
bantime = 3600
maxretry = 2
findtime = 600
usedns = warn
backend = auto
destemail = MAILTO
banaction = iptables-multiport
mta = sendmail
protocol = tcp
chain = INPUT
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(prot
config_fail2ban 70
JShielder - Linux Server Hardening Script
[ssh]
enabled = true
port = 372
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
[dropbear]
enabled = false
port = ssh
filter = sshd
logpath = /var/log/dropbear
maxretry = 6
[pam-generic]
enabled = false
filter = pam-generic
port = all
banaction = iptables-allports
port = anyport
logpath = /var/log/auth.log
maxretry = 6
[xinetd-fail]
enabled = false
filter = xinetd-fail
port = all
banaction = iptables-multiport-log
logpath = /var/log/daemon.log
maxretry = 2
[ssh-ddos]
enabled = false
config_fail2ban 71
JShielder - Linux Server Hardening Script
port = 372
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
[apache]
enabled = false
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 6
[apache-multiport]
enabled = false
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 6
[apache-noscript]
enabled = false
port = http,https
filter = apache-noscript
logpath = /var/log/apache*/*error.log
maxretry = 6
[apache-overflows]
enabled = false
port = http,https
filter = apache-overflows
logpath = /var/log/apache*/*error.log
maxretry = 2
[vsftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = vsftpd
logpath = /var/log/vsftpd.log
maxretry = 6
config_fail2ban 72
JShielder - Linux Server Hardening Script
[proftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 6
[pure-ftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = pure-ftpd
logpath = /var/log/auth.log
maxretry = 6
[wuftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = wuftpd
logpath = /var/log/auth.log
maxretry = 6
[postfix]
enabled = false
port = smtp,ssmtp
filter = postfix
logpath = /var/log/mail.log
[couriersmtp]
enabled = false
port = smtp,ssmtp
filter = couriersmtp
config_fail2ban 73
JShielder - Linux Server Hardening Script
logpath = /var/log/mail.log
[courierauth]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = courierlogin
logpath = /var/log/mail.log
[sasl]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = sasl
logpath = /var/log/mail.log
[dovecot]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = dovecot
logpath = /var/log/mail.log
# DNS Servers
[named-refused-tcp]
enabled = false
port = domain,953
protocol = tcp
filter = named-refused
logpath = /var/log/named/security.log
config_fail2ban 74
JShielder - Linux Server Hardening Script
additional_packages
additional_packages(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing Additional Packages"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Install tree............."; apt-get install tree
echo "Install Python-MySQLdb..."; apt-get install python-mysqldb
echo "Install WSGI............."; apt-get install libapache2-mod-wsgi
echo "Install PIP.............."; apt-get install python-pip
echo "Install Vim.............."; apt-get install vim
echo "Install Nano............."; apt-get install nano
echo "Install pear............."; apt-get install php-pear
echo "Install DebSums.........."; apt-get install debsums
echo "Install apt-show-versions"; apt-get install apt-show-versions
echo "Install PHPUnit..........";
pear config-set auto_discover 1
mv phpunit-patched /usr/share/phpunit
echo include_path = ".:/usr/share/phpunit:/usr/share/phpunit/PHPUnit" >>
echo include_path = ".:/usr/share/phpunit:/usr/share/phpunit/PHPUnit" >>
service apache2 restart
say_done
}
additional_packages 75
JShielder - Linux Server Hardening Script
additional_packages 76
JShielder - Linux Server Hardening Script
tune_secure_kernel
tune_secure_kernel(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Tuning and Securing the Linux Kernel"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Securing Linux Kernel"
spinner
cp templates/sysctl.conf /etc/sysctl.conf; echo " OK"
cp templates/ufw /etc/default/ufw
sysctl -e -p
say_done
}
tune_secure_kernel 77
JShielder - Linux Server Hardening Script
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Enable ExecShield
kernel.exec-shield = 1
tune_secure_kernel 78
JShielder - Linux Server Hardening Script
kernel.randomize_va_space = 1
tune_secure_kernel 79
JShielder - Linux Server Hardening Script
# Reduce KeepAlive
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
# Disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
tune_secure_kernel 80
JShielder - Linux Server Hardening Script
install_rootkit_hunter
install_rootkit_hunter(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing RootKit Hunter"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Rootkit Hunter is a scanning tool to ensure you are you're clean o
install_rootkit_hunter 81
JShielder - Linux Server Hardening Script
install_rootkit_hunter 82
JShielder - Linux Server Hardening Script
tune_nano_vim_bashrc
tune_nano_vim_bashrc(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Tunning bashrc, nano and Vim"
echo -e "\e[34m---------------------------------------------------------
echo ""
# Tune .bashrc
echo "Tunning .bashrc......"
spinner
cp templates/bashrc-root /root/.bashrc
cp templates/bashrc-user /home/$username/.bashrc
chown $username:$username /home/$username/.bashrc
echo "OK"
say_done
# Tune Vim
echo "Tunning Vim......"
spinner
tunning vimrc
echo "OK"
# Tune Nano
echo "Tunning Nano......"
spinner
tunning nanorc
echo "OK"
}
tune_nano_vim_bashrc 83
JShielder - Linux Server Hardening Script
bashrc-root
HISTCONTROL=ignoredups:ignorespace
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
tune_nano_vim_bashrc 84
JShielder - Linux Server Hardening Script
xterm-color) color_prompt=yes;;
esac
force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
color_prompt=yes
else
color_prompt=
fi
fi
tune_nano_vim_bashrc 85
JShielder - Linux Server Hardening Script
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
function md5 {
php -r "echo md5('$1') . chr(10);"
}
bashrc-user
HISTCONTROL=ignoredups:ignorespace
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
tune_nano_vim_bashrc 86
JShielder - Linux Server Hardening Script
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
color_prompt=yes
else
color_prompt=
fi
fi
tune_nano_vim_bashrc 87
JShielder - Linux Server Hardening Script
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
function md5 {
php -r "echo . md5('$1') . chr(10);"
}
nanorc
tune_nano_vim_bashrc 88
JShielder - Linux Server Hardening Script
vimrc
tune_nano_vim_bashrc 89
JShielder - Linux Server Hardening Script
runtime! debian.vim
if has("syntax")
syntax on
endif
if has("autocmd")
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "nor
endif
if has("autocmd")
filetype plugin indent on
endif
if filereadable("/etc/vim/vimrc.local")
source /etc/vim/vimrc.local
endif
tune_nano_vim_bashrc 90
JShielder - Linux Server Hardening Script
daily_update_cronjob
daily_update_cronjob(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Adding Daily System Udpdate Cron Job"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Creating Daily Cron Job"
spinner
job="@daily apt-get update; apt-get dist-upgrade -y"
touch job
echo $job >> job
crontab job
rm job
say_done
}
daily_update_cronjob 91
JShielder - Linux Server Hardening Script
install_portsentry
install_portsentry(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing PortSentry"
echo -e "\e[34m---------------------------------------------------------
echo ""
apt-get install portsentry
mv /etc/portsentry/portsentry.conf /etc/portsentry/portsentry.conf-origi
cp templates/portsentry /etc/portsentry/portsentry.conf
sed s/tcp/atcp/g /etc/default/portsentry > salida.tmp
mv salida.tmp /etc/default/portsentry
/etc/init.d/portsentry restart
say_done
}
install_portsentry 92
JShielder - Linux Server Hardening Script
TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667,12345,123
UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,37444,34555,31335,32770,3277
ADVANCED_PORTS_TCP="1024"
ADVANCED_PORTS_UDP="1024"
ADVANCED_EXCLUDE_TCP="113,139"
ADVANCED_EXCLUDE_UDP="520,138,137,67"
IGNORE_FILE="/etc/portsentry/portsentry.ignore"
HISTORY_FILE="/var/lib/portsentry/portsentry.history"
BLOCKED_FILE="/var/lib/portsentry/portsentry.blocked"
RESOLVE_HOST = "0"
BLOCK_UDP="1"
BLOCK_TCP="1"
SCAN_TRIGGER="0"
# EOF
install_portsentry 93
JShielder - Linux Server Hardening Script
additional_hardening
additional_hardening(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Running additional Hardening Steps"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Running Additional Hardening Steps...."
spinner
echo tty1 > /etc/securetty
chmod 0600 /etc/securetty
chmod 700 /root
chmod 600 /boot/grub/grub.cfg
#Protect Against IP Spoofing
echo nospoof on >> /etc/host.conf
#Remove AT and Restrict Cron
apt-get purge at
echo " Securing Cron "
touch /etc/cron.allow
chmod 600 /etc/cron.allow
awk -F: '{print $1}' /etc/passwd | grep -v root > /etc/cron.deny
echo "Do you want to Disable USB Support for this Server? y/n" ; read us
if [ "$usb_answer" == "y" ]; then
echo "blacklist usb-storage" | sudo tee -a /etc/modprobe.d/blacklist.
update-initramfs -u
echo "OK"
say_done
else
echo "OK"
say_done
fi
}
additional_hardening 94
JShielder - Linux Server Hardening Script
apt-get purge at
echo " Securing Cron "
touch /etc/cron.allow
chmod 600 /etc/cron.allow
awk -F: '{print $1}' /etc/passwd | grep -v root > /etc/cron.deny
additional_hardening 95
JShielder - Linux Server Hardening Script
echo "Do you want to Disable USB Support for this Server? y/n" ; read us
if [ "$usb_answer" == "y" ]; then
echo "blacklist usb-storage" | sudo tee -a /etc/modprobe.d/blacklist.
update-initramfs -u
echo "OK"
say_done
else
echo "OK"
additional_hardening 96
JShielder - Linux Server Hardening Script
install_unhide
install_unhide(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing UnHide"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Unhide is a forensic tool to find hidden processes and TCP/UDP por
sleep 1
apt-get -y install unhide
echo " Unhide is a tool for Detecting Hidden Processes "
echo " For more info about the Tool use the manpages "
echo " man unhide "
say_done
}
unhide (ps)*
install_unhide 97
JShielder - Linux Server Hardening Script
unhide-TCP
Ejemplos de uso:
$ unhide proc
$ unhide brute
install_unhide 98
JShielder - Linux Server Hardening Script
$ unhide sys
install_unhide 99
JShielder - Linux Server Hardening Script
install_tiger
install_tiger(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing Tiger"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Tiger is a security tool that can be use both as a security audit
sleep 1
apt-get -y install tiger
echo " For More info about the Tool use the ManPages "
echo " man tiger "
say_done
}
install_tiger 100
JShielder - Linux Server Hardening Script
install_psad
install_psad(){
clear
f_banner
echo -e "\e[34m-------------------------------------------------------------
echo -e "\e[93m[+]\e[00m Install PSAD"
echo -e "\e[34m-------------------------------------------------------------
echo " PSAD is a piece of Software that actively monitors you Firewall Logs
or attack event is in Progress. It can alert and Take action to deter
NOTE:
IF YOU ARE ONLY RUNNING THIS FUNCTION, YOU MUST ENABLE LOGGING FOR ip
"
echo ""
echo "Do you want to install PSAD (Recommended)? y/n " ; read psad_answer
if [ "$psad_answer" == "y" ]; then
echo "Type an Email Address to Receive PSAD Alerts: " ; read inbox1
apt-get install psad
sed s/INBOX/$inbox1/g templates/psad.conf
sed s/hostname/$host_name.$domain_name/g templates/psad.conf > /etc/psa
psad --sig-update
service psad restart
echo "Installation and Configuration Complete"
echo "Run service psad status, for detected events"
echo ""
say_done
else
echo "OK"
say_done
fi
}
install_psad 101
JShielder - Linux Server Hardening Script
#
############################################################################
#
# This is the configuration file for psad (the Port Scan Attack Detector).
# Normally this file gets installed at /etc/psad/psad.conf, but can be put
# anywhere in the filesystem and then the path can be specified on the
# command line argument "-c <file>" to psad. All three psad daemons (psad,
# kmsgsd, and psadwatchd) reference this config file.
#
# Each line has the form "<variable name> <value>;". Note the semi-
# colon after the <value>. All characters after the semicolon will be
# ignored to provide space for comments.
#
############################################################################
#
### Specify the home and external networks. Note that by default the
### ENABLE_INTF_LOCAL_NETS is enabled, so psad automatically detects
### all of the directly connected subnets and uses this information as
### the HOME_NET variable.
HOME_NET any;
EXTERNAL_NET any;
### The FW_SEARCH_ALL variable controls how psad will parse iptables
### messages. If it is set to "Y" then psad will parse all iptables
### messages for evidence of scan activity. If it is set to "N" then
install_psad 102
JShielder - Linux Server Hardening Script
### psad will only parse those iptables messages that contain logging
### prefixes specified by the FW_MSG_SEARCH variable below. Logging
### prefixes are set with the --log-prefix command line option to iptables.
### Setting FW_SEARCH_ALL to "N" is useful for having psad only analyze
### iptables messages that are logged out of a specific iptables chain
### (multiple strings can be searched for, see the comment above the
### FW_MSG_SEARCH variable below) or a specific logging rule for example.
### FW_SEARCH_ALL is set to "Y" by default since usually people want psad
### to parse all iptables messages.
FW_SEARCH_ALL Y;
### The FW_MSG_SEARCH variable can be modified to look for logging messages
### that are specific to your firewall configuration (specified by the
### "--log-prefix" option. For example, if your firewall uses the
### string "Audit" for packets that have been blocked, then you could
### set FW_MSG_SEARCH to "Audit"; The default string to search for is
### "DROP". Both psad and kmsgsd reference this file. NOTE: You can
### specify this variable multiple times to have psad search for multiple
### strings. For example to have psad search for the strings "Audit" and
### "Reject", you would use the following two lines:
#FW_MSG_SEARCH Audit;
#FW_MSG_SEARCH REJECT;
FW_MSG_SEARCH DROP;
### Set the type of syslog daemon that is used. The SYSLOG_DAEMON
### variable accepts four possible values: syslogd, syslog-ng, ulogd,
### or metalog. Note: this variable is only used if ENABLE_SYSLOG_FILE is
### disabled, and this in turn will mean that the legacy kmsgsd daemon will
### collect firewall logs from syslog via the old named pipe mechanism.
SYSLOG_DAEMON syslogd;
### What type of interface configuration do you use? Set this variable to
### "iproute2" if you want to use the iproute2 type configuration.
### iproute2 does not use aliases for multi-homed interfaces and
### ifconfig does not show secondary addresses for multi-homed interfaces.
#IFCFGTYPE iproute2;
IFCFGTYPE ifconfig;
install_psad 103
JShielder - Linux Server Hardening Script
### A scan may also reach a danger level if the scan trips
### a signature or if the scanning ip is listed in
### auto_ips so a danger level is automatically
### assigned.
DANGER_LEVEL1 5; ### Number of packets.
DANGER_LEVEL2 15;
DANGER_LEVEL3 150;
DANGER_LEVEL4 1500;
DANGER_LEVEL5 10000;
### Set the interval (in seconds) psad will use to sleep before
### checking for new iptables log messages
CHECK_INTERVAL 5;
### Set the minimum range of ports that must be scanned before
### psad will send an alert. The default is 1 so that at
### least two port must be scanned (p2-p1 >= 1). This can be set
### to 0 if you want psad to be extra paranoid, or 30000 if not.
PORT_RANGE_SCAN_THRESHOLD 1;
### For IP protocol scan detection (nmap -sO). While it may be relatively
### common for a host to trigger on tcp, udp, and icmp, it is more unusual i
### a host triggers on, say, five different IP protocols
PROTOCOL_SCAN_THRESHOLD 5;
### If "Y", means that scans will never timeout. This is useful
### for catching scans that take place over long periods of time
### where the attacker is trying to slip beneath the IDS thresholds.
ENABLE_PERSISTENCE Y;
### Specify how often to timeout old scan data relative to CHECK_INTERVAL
### iterations. This feature is only used if ENABLE_PERSISTENCE is disabled
### Note that for psad processes that have tracked a lot of scans, it is
install_psad 104
JShielder - Linux Server Hardening Script
### Limit the number of src->dst IP pairs that psad will track. The default
### is zero (i.e. unlimited), but if psad is running on a system with limite
### memory, this can be handy to restrict psad's memory usage. It is best t
### combine this option with disabling ENABLE_PERSISTENCE so that older scan
### are deleted and therefore newer scans will on average continue to be
### tracked. A good non-zero value is, say, 50000, but this will vary
### depending on available system memory.
MAX_SCAN_IP_PAIRS 0;
### By default, psad acquires iptables log data from the /var/log/messages
### file which the local syslog daemon (usually) writes iptables log message
### to. If the ENABLE_SYSLOG_FILE variable below is set to "N", then psad
### reconfigures syslog to write iptables log data to the
### /var/lib/psad/psadfifo fifo file where the messages are picked up by kms
### written to the file /var/log/psad/fwdata for analysis by psad. On some
### systems, having syslog communicate log data to kmsgsd can be problematic
### (syslog configs and external factors such as Apparmor and SELinux can pl
### a role here), so leaving the ENABLE_SYSLOG_FILE variable set to "Y" is
### usually recommended.
ENABLE_SYSLOG_FILE Y;
IPT_WRITE_FWDATA Y;
IPT_SYSLOG_FILE /var/log/syslog;
### When enabled, this instructs psad to write the "msg" field
install_psad 105
JShielder - Linux Server Hardening Script
install_psad 106
JShielder - Linux Server Hardening Script
### Minimum danger level a scan must reach before any logging or
### alerting is done. The EMAIL_ALERT_DANGER_LEVEL variable below
### only refers to email alerts; the MIN_DANGER_LEVEL variable
### applies to everything from email alerts to whether or not the
### IP directory is created within /var/log/psad/. Hence
### MIN_DANGER_LEVEL should be set less than or equal to the value
### assigned to the EMAIL_ALERT_DANGER_LEVEL variable.
MIN_DANGER_LEVEL 1;
### Only send email alert if danger level >= to this value.
EMAIL_ALERT_DANGER_LEVEL 1;
install_psad 107
JShielder - Linux Server Hardening Script
EMAIL_LIMIT 0;
### By default, psad maintains a counter for each scanning source address,
### but by enabling this variable psad will maintain email counters for
### each victim address that is scanned as well.
ENABLE_EMAIL_LIMIT_PER_DST N;
### If "Y", send a status email message when an IP has reached the
### EMAIL_LIMIT threshold.
EMAIL_LIMIT_STATUS_MSG Y;
### This variable is used to have psad throttle the email alerts it sends,
### and implemented as a per-IP threshold. That is, if EMAIL_THROTTLE
### is set to "10", then psad will only send 1/10th as many emails for each
### scanning IP as it would have normally. All other variables also apply,
### so this throttle value is taken into account after everything else. The
### default of zero means to not apply any throttling.
EMAIL_THROTTLE 0;
### If "Y", send email for all newly logged packets from the same
### source ip instead of just when a danger level increases.
ALERT_ALL Y;
### If "Y", then psad will import old scan source ip directories
### as current scans instead of moving the directories into the
### archive directory.
IMPORT_OLD_SCANS N;
### syslog facility and priority (the defaults are usually ok)
### The SYSLOG_FACILITY variable can be set to one of LOG_LOCAL{0-7}, and
### SYSLOG_PRIORITY can be set to one of LOG_INFO, LOG_DEBUG, LOG_NOTICE,
### LOG_WARNING, LOG_ERR, LOG_CRIT, LOG_ALERT, or LOG_EMERG
SYSLOG_IDENTITY psad;
SYSLOG_FACILITY LOG_LOCAL7;
SYSLOG_PRIORITY LOG_INFO;
install_psad 108
JShielder - Linux Server Hardening Script
### Specify how often to log the TOP_* information (i.e. how many
### CHECK_INTERVAL iterations before the data is logged again).
TOP_SCANS_CTR_THRESHOLD 1;
### If you have a DShield user id you can set it here. The
### default is "0".
DSHIELD_USER_ID 0;
### Threshold danger level for DShield data; a scan must reach this
### danger level before associated packets will be included in an
### alert to DShield. Note that zero is the default since this
### will allow DShield to apply its own logic to determine what
### constitutes a scan (_all_ iptables log messages will be included
install_psad 109
JShielder - Linux Server Hardening Script
install_psad 110
JShielder - Linux Server Hardening Script
AUTO_BLOCK_DL2_TIMEOUT $AUTO_BLOCK_TIMEOUT;
AUTO_BLOCK_DL3_TIMEOUT $AUTO_BLOCK_TIMEOUT;
AUTO_BLOCK_DL4_TIMEOUT $AUTO_BLOCK_TIMEOUT;
AUTO_BLOCK_DL5_TIMEOUT 0; ### permanent
### Only block if the iptables log message matches the following regex
AUTO_BLOCK_REGEX ESTAB; ### from fwsnort logging prefixes
### Control whether "renew" auto-block emails get sent. This is disabled
### by default because lots of IPs could have been blocked, and psad
### should not generate a renew email for each of them.
ENABLE_RENEW_BLOCK_EMAILS N;
install_psad 111
JShielder - Linux Server Hardening Script
### "Rule_position": Defines the position where rule are added within the
### To_chain.
###
### The following defaults make sense for most installations, but note
### it is possible to include blocking rules in, say, the "nat" table
### using this functionality as well. The following three lines provide
### usage examples:
#IPT_AUTO_CHAIN1 DROP, src, filter, INPUT, 1, PSAD_BLOCK_INPUT,
#IPT_AUTO_CHAIN2 DROP, dst, filter, OUTPUT, 1, PSAD_BLOCK_OUTPU
#IPT_AUTO_CHAIN3 DROP, both, filter, FORWARD, 1, PSAD_BLOCK_FOR
IPT_AUTO_CHAIN1 DROP, src, filter, INPUT, 1, PSAD_BLOCK_INPUT, 1
IPT_AUTO_CHAIN2 DROP, dst, filter, OUTPUT, 1, PSAD_BLOCK_OUTPUT,
IPT_AUTO_CHAIN3 DROP, both, filter, FORWARD, 1, PSAD_BLOCK_FORWA
### Flush all existing rules in the psad chains at psad start time.
FLUSH_IPT_AT_INIT Y;
### Prerequisite check for existence of psad chains and jump rules
IPTABLES_PREREQ_CHECK 1;
### Set the number of times an ip can be seen before another whois
### lookup is issued.
WHOIS_LOOKUP_THRESHOLD 20;
### Use this option to force all whois information to contain ascii-only dat
### Sometime whois information for IP addresses in China and other countries
### can contain non-ascii data. If this option is enabled, then any non-
### ascii characters will be replaced with "NA".
ENABLE_WHOIS_FORCE_ASCII N;
### This variable forces all whois lookups to be done against the source IP
### even when they are associated with a directly connected local network.
### is usually a good idea to leave this setting as the default of 'N'.
install_psad 112
JShielder - Linux Server Hardening Script
ENABLE_WHOIS_FORCE_SRC_IP N;
### Set the number of times an ip can be seen before another dns
### lookup is issued.
DNS_LOOKUP_THRESHOLD 20;
### This can be set to 0 to have psad not place any limit on the
### number of times it will attempt to remove data from
### /var/log/psad/.
DISK_MAX_RM_RETRIES 10;
install_psad 113
JShielder - Linux Server Hardening Script
### Email subject line config. Change these prefixes if you want
### psad to generate email alerts that say something other than
### the following.
MAIL_ALERT_PREFIX [psad-alert];
MAIL_STATUS_PREFIX [psad-status];
MAIL_ERROR_PREFIX [psad-error];
MAIL_FATAL_PREFIX [psad-fatal];
### Directories
INSTALL_ROOT /;
PSAD_DIR $INSTALL_ROOT/var/log/psad;
PSAD_RUN_DIR $INSTALL_ROOT/var/run/psad;
PSAD_FIFO_DIR $INSTALL_ROOT/var/lib/psad;
PSAD_LIBS_DIR $INSTALL_ROOT/usr/lib/psad;
PSAD_CONF_DIR $INSTALL_ROOT/etc/psad;
PSAD_ERR_DIR $PSAD_DIR/errs;
CONF_ARCHIVE_DIR $PSAD_CONF_DIR/archive;
SCAN_DATA_ARCHIVE_DIR $PSAD_DIR/scan_archive;
ANALYSIS_MODE_DIR $PSAD_DIR/ipt_analysis;
SNORT_RULES_DIR $PSAD_CONF_DIR/snort_rules;
FWSNORT_RULES_DIR /etc/fwsnort/snort_rules; ### may not exist
### Files
FW_DATA_FILE $PSAD_DIR/fwdata;
ULOG_DATA_FILE $PSAD_DIR/ulogd.log;
FW_CHECK_FILE $PSAD_DIR/fw_check;
DSHIELD_EMAIL_FILE $PSAD_DIR/dshield.email;
SIGS_FILE $PSAD_CONF_DIR/signatures;
install_psad 114
JShielder - Linux Server Hardening Script
PROTOCOLS_FILE $PSAD_CONF_DIR/protocols;
ICMP_TYPES_FILE $PSAD_CONF_DIR/icmp_types;
ICMP6_TYPES_FILE $PSAD_CONF_DIR/icmp6_types;
AUTO_DL_FILE $PSAD_CONF_DIR/auto_dl;
SNORT_RULE_DL_FILE $PSAD_CONF_DIR/snort_rule_dl;
POSF_FILE $PSAD_CONF_DIR/posf;
P0F_FILE $PSAD_CONF_DIR/pf.os;
IP_OPTS_FILE $PSAD_CONF_DIR/ip_options;
PSAD_FIFO_FILE $PSAD_FIFO_DIR/psadfifo;
ETC_HOSTS_DENY_FILE /etc/hosts.deny;
ETC_SYSLOG_CONF /etc/syslog.conf;
ETC_RSYSLOG_CONF /etc/rsyslog.conf;
ETC_SYSLOGNG_CONF /etc/syslog-ng/syslog-ng.conf;
ETC_METALOG_CONF /etc/metalog/metalog.conf;
STATUS_OUTPUT_FILE $PSAD_DIR/status.out;
ANALYSIS_OUTPUT_FILE $PSAD_DIR/analysis.out;
INSTALL_LOG_FILE $PSAD_DIR/install.log;
FW_ERROR_LOG $PSAD_ERR_DIR/fwerrorlog;
PRINT_SCAN_HASH $PSAD_DIR/scan_hash;
install_psad 115
JShielder - Linux Server Hardening Script
### iptables command output and error collection files; these are
### used by IPTables::ChainMgr
IPT_OUTPUT_FILE $PSAD_DIR/psad.iptout;
IPT_ERROR_FILE $PSAD_DIR/psad.ipterr;
install_psad 116
JShielder - Linux Server Hardening Script
dfCmd /bin/df;
fwcheck_psadCmd $INSTALL_ROOT/usr/sbin/fwcheck_psad;
psadwatchdCmd $INSTALL_ROOT/usr/sbin/psadwatchd;
kmsgsdCmd $INSTALL_ROOT/usr/sbin/kmsgsd;
psadCmd $INSTALL_ROOT/usr/sbin/psad;
install_psad 117
JShielder - Linux Server Hardening Script
install_psad 118
JShielder - Linux Server Hardening Script
disable_compilers
disable_compilers(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Disabling Compilers"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Disabling Compilers....."
spinner
chmod 000 /usr/bin/as >/dev/null 2>&1
chmod 000 /usr/bin/byacc >/dev/null 2>&1
chmod 000 /usr/bin/yacc >/dev/null 2>&1
chmod 000 /usr/bin/bcc >/dev/null 2>&1
chmod 000 /usr/bin/kgcc >/dev/null 2>&1
chmod 000 /usr/bin/cc >/dev/null 2>&1
chmod 000 /usr/bin/gcc >/dev/null 2>&1
chmod 000 /usr/bin/*c++ >/dev/null 2>&1
chmod 000 /usr/bin/*g++ >/dev/null 2>&1
spinner
echo ""
echo " If you wish to use them, just change the Permissions"
echo " Example: chmod 755 /usr/bin/gcc "
echo "OK"
say_done
}
``````
disable_compilers 119
JShielder - Linux Server Hardening Script
Ejemplo:
disable_compilers 120
JShielder - Linux Server Hardening Script
apache_conf_restrictions
apache_conf_restrictions(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Restricting Access to Apache Config Files"
echo -e "\e[34m---------------------------------------------------------
echo ""
echo "Restricting Access to Apache Config Files......"
spinner
chmod 750 /etc/apache2/conf* >/dev/null 2>&1
chmod 511 /usr/sbin/apache2 >/dev/null 2>&1
chmod 750 /var/log/apache2/ >/dev/null 2>&1
chmod 640 /etc/apache2/conf-available/* >/dev/null 2>&1
chmod 640 /etc/apache2/conf-enabled/* >/dev/null 2>&1
chmod 640 /etc/apache2/apache2.conf >/dev/null 2>&1
echo "OK"
say_done
}
apache_conf_restrictions 121
JShielder - Linux Server Hardening Script
unattended_upgrades
unattended_upgrades()
unattended_upgrades(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Enable Unattended Security Updates"
echo -e "\e[34m-----------------------------------------------------------
echo ""
echo -e "\e[93m[?]\e[00m ¿Do you Wish to Enable Unattended Security Update
if [ "$unattended" == "y" ]; then
dpkg-reconfigure -plow unattended-upgrades
else
clear
fi
}
unattended_upgrades 122
JShielder - Linux Server Hardening Script
enable_proc_acct
enable_proc_acct(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Enable Process Accounting"
echo -e "\e[34m-----------------------------------------------------------
echo ""
apt-get install acct
touch /var/log/wtmp
echo "OK"
}
enable_proc_acct 123
JShielder - Linux Server Hardening Script
install_phpsuhosin
install_phpsuhosin(){
clear
f_banner
echo -e "\e[34m-----------------------------------------------------------
echo -e "\e[93m[+]\e[00m Installing PHP Suhosin Extension"
echo -e "\e[34m-----------------------------------------------------------
echo ""
echo 'deb http://repo.suhosin.org/ ubuntu-trusty main' >> /etc/apt/sources
#Suhosin Key
wget https://sektioneins.de/files/repository.asc
apt-key add repository.asc
apt-get update
apt-get install php5-suhosin-extension
php5enmod suhosin
service apache2 restart
echo "OK"
say_done
}
install_phpsuhosin 124
JShielder - Linux Server Hardening Script
reboot_server
reboot_server(){
clear
f_banner
echo -e "\e[34m---------------------------------------------------------
echo -e "\e[93m[+]\e[00m Final Step"
echo -e "\e[34m---------------------------------------------------------
echo ""
replace USERNAME $username SERVERIP $serverip < templates/texts/bye
echo -n " ¿Were you able to connect via SSH to the Server using $usernam
read answer
if [ "$answer" == "y" ]; then
reboot
else
echo "Server will not Reboot"
echo "Bye."
fi
}
reboot_server 125
JShielder - Linux Server Hardening Script
Ejecutando JShielder
Ya que conocemos las funciones de Jshielder, vamos a ver el menú que tenemos
cuando ejecutamos la herramienta y que funciones ejecuta.
Accedemos a la carpeta
$ cd JShielder/
#!/bin/bash
# JShielder v2.0
# Linux Hardening Script
#
# Jason Soto
# www.jsitech.com
# Twitter = @JsiTech
############################################################################
f_banner(){
echo
echo "
_ ____ _ _ _ _
| / ___|| |__ (_) ___| | __| | ___ _ __
_ | \___ \| '_ \| |/ _ \ |/ _ |/ _ \ '__|
| |_| |___) | | | | | __/ | (_| | __/ |
\___/|____/|_| |_|_|\___|_|\__,_|\___|_|
Linux Automated Hardening Script for Linux Servers
Developed By Jason Soto @JsiTech "
echo
echo
############################################################################
menu=""
until [ "$menu" = "10" ]; do
clear
f_banner
echo
echo -e "\e[34m-------------------------------------------------------------
echo -e "\e[93m[+]\e[00m SELECT YOUR LINUX DISTRIBUTION"
echo -e "\e[34m-------------------------------------------------------------
echo ""
echo "1. Ubuntu Server 14.04 LTS"
echo "2. Ubuntu Server 15.04"
echo "3. Linux CentOS 6 (Coming Soon)"
echo "4. Linux CentOS 7 (Coming Soon)"
echo "5. Debian GNU/Linux 7 (Coming Soon)"
echo "6. Debian GNU/Linux 8 (Coming Soon)"
echo "7. Red Hat Linux 6 (Coming Soon)"
echo "8. Red Hat Linux 7 (Coming Soon)"
echo "9. Fedora Server 23 (Coming Soon)"
echo "10. Exit"
echo
read menu
case $menu in
1)
cd UbuntuServer_14.04LTS/
chmod +x jshielder.sh
./jshielder.sh
;;
2)
cd UbuntuServer_15.04/
chmod +x jshielder.sh
./jshielder.sh
;;
10)
break
;;
*) ;;
esac
done
Tenemos el menu para Seleccionar la Distro, Por el Momento JSHielder solo está
disponible para las distros Ubuntu Server 14.04LTS y 15.04. Al Seleccionar la
Distro el Script se encarga de ejecutar la versión de Jshielder para esa distro.
Veamos el menu que tenemos al momento de que se ejecute JShielder para la
Distro de Elección:
----------------------------------------------------------------------------
[+] SELECT THE DESIRED OPTION
----------------------------------------------------------------------------
1. LAMP Deployment
2. Reverse Proxy Deployment With Apache
3. LEMP Deployment (Under Development, Testing)
4. Reverse Proxy Deployment with Nginx (ModSecurity)
5. Running With SecureWPDeployer or JSDeployer Script
6. Customized Run (Only run desired Options)
7. Exit
------------------------------------------------------------------------
[+] SELECT THE DESIRED OPTION
----------------------------------------------------------------------------
Cierre
Aquí Finalizamos con esta guía de Jshielder esperando que haya sido de gran
ayuda. Esta Guía puede servir de consulta para uso de la herramienta o para
aprender a hacer un hardening adecuado de sus servidores de manera manual.
Mail: jason_soto[AT]jsitech[DOT]com
Twitter: @JsiTech
Cierre 132