Sunteți pe pagina 1din 132

JShielder

- 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

Autor: Jason Soto

Mail: jason_soto[AT]jsitech[DOT]com

Twitter: @JsiTech

Introduction 4
JShielder - Linux Server Hardening Script

Acerca del Autor y Creador de JShielder


Jason Soto, Profesional InfoSec/Linux, Penetration Tester, Ethical Hacking,
Gestión de la Seguridad, SysAdmin, Creador del blog Jsitech, Security Feed y IT
Talks.

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

Desarrollo: Bash Scripting, Python

IT Security/Ethical Hacking: Penetration Testing, Metasploit Framework, Ethical


Hacking, Linux/Windows Hardening, Wireless Security, Network Security

DevOps: Chef, Jenkins, Docker, Puppet

Cloud: OpenStack, CloudU Certification

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:

Acerca del Autor 5


JShielder - Linux Server Hardening Script

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.

Pueden seguir sus proyectos en Twitter

@JsiTech

@InfoSecFeed

@InfoSecFeed_EN

@TecnoTalks

Acerca del Autor 6


JShielder - Linux Server Hardening Script

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.

Basado en el Proyecto de Eugenia Bahit, JackTheStripper, y en el que colaboré


durante mucho tiempo.

Para mas información pueden visitar la página del proyecto en


www.jsitech.com/jshielder

Cuando ejecutas la herramienta como


root, esta se encarga de:

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 **

Nuevo en la Versión 2.0

Se Agrega la extensión de PHP Suhosin que protege el servidor contra fallas


Se retoma el uso de funciones para ser mas fácil la customización del Script
Se agrega la funcionalidad de Hacer un Deployment de Apache para Reverse Pro
Se agrega la funcionalidad de Hacer un Deployment de LEMP (En Desarrollo)..
Se agrega la funcionalidad de hacer un Deployment de Nginx compilado con Mod
Se ajusta para que corra perfectamente junto al Script de Despliegue seguro
NUEVO!!!! Se agrega Menú para ejecutar solo las funciones deseadas. Util cua

Que es Jshielder? 8
JShielder - Linux Server Hardening Script

Cambios Recientes

Agregado un Deployer general con la opción de seleccionar la Distribución qu


En caso de no hacerlo durante la instalación de la Distro, JShielder asiste
Se instala el Sistema de detección de Intrusos PSAD
Se crean los Banners (MOTD) para alertar a los usuarios no Autorizados y par
Se habilita la Monitoreo de Procesos con acct
Se configura un UMASK por defecto mas restrictivo
Se habilita las actualizaciones de seguridad Desatendidas (Opcional)
Se desactiva el Soporte para drives USB, para mejor seguridad (Opcional)
Se corren Procesos adicionales de Securización

En que se está trabajando

Reglas Más restrictivas en Iptables y opciones de Customización


Llevar JShielder a las otras Distros enfocadas a Servidores (CentOS, Debian,

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.

Jshielder fue creado para asistir a los Administradores de Sistemas y/o


Desarrolladores a hacer un despliegue seguro del Servidor Linux que va a alojar
su aplicación, de manera automatizada y con poca interacción del usuario que lo
ejecuta.

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
}

Esta primera función sencillamente se asegura de que la herramienta está siendo


ejecutada como el usuario root. Se requiere que sea con este usuario por todas
las modificaciones que debemos hacer en el Sistema Operativo. Si no se ejecuta
como root, el script se detiene y sale.

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.

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 "

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
}

No hay mucho que explicar de la función config_timezone. Con esta función


Jshielder asiste al usuario a configurar la zona horaria correcta para su servidor.

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
}

La función update_system se encarga de actualizar todo el sistema antes de


continuar con las siguientes funciones. Esto debe ser una práctica que debemos
seguir siempre ya que a diario salen fallas de seguridad y uno de nuestros
paquetes desactualizados puede convertirse en una amenaza. JSHielder tiene
una función donde automatiza esto. Lo veremos más adelante.

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.

La función sustituye el archivo login.defs con la plantilla que se encuentra en


templates/login.defs, y cambia el valor del umask en /etc/init.d/rc**.

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:

Cuando Jshielder asegura las conexiones remotas, (lo veremos mas


adelante) elimina por completo la capacidad de root de hacer conexiones
remotas al servidor

Si lograrán comprometer la cuenta del administrador tendrían ciertos accesos


administrativos en el servidor

Por estas 2 razones al quitar los accesos al usuario, en caso de ser


comprometido no es mucho lo que podrían hacer en el, tendrían que buscar la
forma de elevarse privilegios o comprometer la cuenta de root, lo que les haría
mas dificil afectar el servidor.

Lo que nos deja, que si un usuario desea hacer tareas administrativas en el


servidor, debe primero conectarse al servidor con su usuario y una vez dentro,
hacer el login con root.

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
}

Las funciones rsa_keygen y rsa_keycopy le dan el usuario los pasos a seguir


para crear una par de llaves RSA y copiarlas al servidor. Es un paso importante
ya que Jshielder bloquea por completo la autenticación por contraseñas
convencionales en los accesos remotos. La autenticación debe hacerse
únicamente con estas llaves.

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

Esta función se encarga de crear un sistema de archivos y montar la /tmp por


separado con algunas restricciones. Por que hacemos esto? El directorio /tmp
es donde los archivos temporales de las aplicaciones son alojados. Es posible
además que pueda ser usado para alojar ejecutables maliciosos para
comprometer el servidor. De no asegurarse puede dar espacio a ataques por
ejemplo como:

Procesos Maliciosos
Ataques de Denegación de servicio
Ejecución de scripts maliciosos

Jshielder monta la partición /tmp con nosuid y noexec que bloquea la


configuración de SUID/SGID y la posibilidad de ejecutar algún script malicioso.
Además crea la entrada correspondiente en /etc/fstab para montarlo en el
booteo.

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
}

La función secure_ssh se encarga de realizar una configuración segura del


sshd_config para protejer los accesos remotos al servidor. Hace uso de la
plantilla que se encuentra en templates/sshd_config, vamos a ver el contenido
de ese archivo:

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

Vamos a ver algunas de las opciones.

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.

PermitRootLogin no: Aquí le estamos diciendo que no le permita al usuario


root hacer login remoto a este servidor.

PasswordAuthentication no: Eliminar la autenticación por contraseñas


convencionales

AllowUsers USERNAME: aquí Jshielder coloca el usuario que creamos al


principio, y ese solo será el usuario permitido a hacer conexiones remotas al
servidor.

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

iptables -P INPUT DROP


iptables -P FORWARD DROP
iptables -P OUTPUT DROP

#Rules for PSAD

iptables -A INPUT -j LOG


iptables -A FORWARD -j LOG

# INPUT

set_iptables 26
JShielder - Linux Server Hardening Script

# Aceptar loopback input

iptables -A INPUT -i lo -p all -j ACCEPT

# Permitir Handshake de tres vias

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Detener Ataques Enmascarados

iptables -A INPUT -p icmp --icmp-type 13 -j DROP


iptables -A INPUT -p icmp --icmp-type 17 -j DROP
iptables -A INPUT -p icmp --icmp-type 14 -j DROP
iptables -A INPUT -p icmp -m limit --limit 1/second -j ACCEPT

# Descartar Paquetes Inválidos

iptables -A INPUT -m state --state INVALID -j DROP

iptables -A FORWARD -m state --state INVALID -j DROP

iptables -A OUTPUT -m state --state INVALID -j DROP

### Descartar Ataques de Spoofing


iptables -A INPUT -s 10.0.0.0/8 -j DROP
iptables -A INPUT -s 169.254.0.0/16 -j DROP
iptables -A INPUT -s 172.16.0.0/12 -j DROP
iptables -A INPUT -s 127.0.0.0/8 -j DROP
iptables -A INPUT -s 192.168.0.0/24 -j DROP

iptables -A INPUT -s 224.0.0.0/4 -j DROP


iptables -A INPUT -d 224.0.0.0/4 -j DROP
iptables -A INPUT -s 240.0.0.0/5 -j DROP
iptables -A INPUT -d 240.0.0.0/5 -j DROP
iptables -A INPUT -s 0.0.0.0/8 -j DROP
iptables -A INPUT -d 0.0.0.0/8 -j DROP
iptables -A INPUT -d 239.255.255.0/24 -j DROP

set_iptables 27
JShielder - Linux Server Hardening Script

iptables -A INPUT -d 255.255.255.255 -j DROP

# Descartar paquetes RST Excesivos para Evitar Ataques Enmascarados

iptables -A INPUT -p tcp -m tcp --tcp-flags RST RST -m limit --limit 2/secon

# Cualquier IP que intente un Escaneo de Puertos sera Bloqueada por 24 Horas

iptables -A INPUT -m recent --name portscan --rcheck --seconds 86400 -j DR


iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DR

# Pasadas las 24 Horas, remover la IP Bloqueada por Escaneo de Puertos

iptables -A INPUT -m recent --name portscan --remove


iptables -A FORWARD -m recent --name portscan --remove

# Esta Regla agrega el Escaner de Puertos a la Lista de PortScan y Registra

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

# Permitir estos puertos desde Fuera

# 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

# ssh & sftp


iptables -A INPUT -p tcp -m tcp --dport 372 -j ACCEPT

# Permitir el Ping

set_iptables 28
JShielder - Linux Server Hardening Script

iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT

# OUTPUT

iptables -A OUTPUT -o lo -j ACCEPT


iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Permitir estos puertos desde Fuera

# 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

# ssh & sftp


iptables -A OUTPUT -p tcp -m tcp --dport 372 -j ACCEPT

# Limit SSH connection from a single IP

iptables -A INPUT -p tcp --syn --dport 372 -m connlimit --connlimit-above 2

# Permitir Pings

iptables -A OUTPUT -p icmp --icmp-type 0 -j ACCEPT

# No Permitir Forward

iptables -A FORWARD -j REJECT

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
}

La función install_secure_mysql instala y se asegura que se ejecute la


instalación segura de mysql. Reemplaza además la configuración por defecto de
my.cnf por una configuración mas segura haciendo uso de la plantilla que se
encuentra en templates/mysql. Veamos que contiene:

[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/

Aquí se optimizan algunos valores, se restringe las conexiones remotas, se


deshabilita local-infile que le impide a mysql leer archivos locales en el Host que
puede convertirse en un vector de ataque y se deshabilita la posibilidad de que
otros usuarios puedan ver las bases de datos.

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
}

Esta función sencillamente instala el servicio web de apache.

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

La función install_nginx_modsecurity instala nginx con el módulo


ModSecurity. Jshielder se encarga de instalar todas las dependencias
necesarias para compilar Nginx con ModSecurity.

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

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: Size Limits & Buffer Overflows ##


client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
## END: Size Limits & Buffer Overflows ##

## 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/*;

ModSecurity es un firewall de aplicaciones web que se ejecuta como modulo en


un servidor web y provee protección contra diversos ataques hacia nuestras
aplicaciones web. Nos permite monitorear el trafico HTTP y realiza análisis en
tiempo real. Es un producto desarrollado por Breach Security y está disponible
como Software Libre bajo la licencia GNU. Anteriormente ModSecurity solo
estaba disponible para servidores Apache pero ya está disponible para Microsoft
IIS y NginX.

El módulo cuenta con diversas funcionalidades:

Filtrado de Peticiones: los pedidos HTTP entrantes son analizados por el


módulo mod_security antes de pasarlos al servidor Web, a su vez, estos

install_nginx_modsecurity 37
JShielder - Linux Server Hardening Script

pedidos son comparados contra un conjunto de reglas predefinidas para


realizar las acciones correspondientes. Para realizar este filtrado se pueden
utilizar expresiones regulares, permitiendo que el proceso sea flexible.

Técnicas antievasión: las rutas y los parámetros son normalizados antes del
análisis para evitar técnicas de evasión.

Elimina múltiple barras (//)

Elimina directorios referenciados por si mismos (./)

Se trata de igual manera la y la / en Windows.

Decodificación de URL.

Reemplazo de bytes nulos por espacios ()

Comprensión del protocolo HTTP: al comprender el protocolo HTTP,


ModSecurity puede realizar filtrados específicos y granulares.

Análisis Post Payload: intercepta y analiza el contenido transmitido a través


del método POST.

Log de Auditoría: es posible dejar traza de auditoría para un posterior


análisis forense.

Filtrado HTTPS: al estar embebido como módulo, tiene acceso a los datos
después de que estos hayan sido descifrados.

Verificación de rango de Byte: permite detectar y bloquear Shellcodes,


limitando el rango de los bytes.

Monitoreo en Tiempo Real: Además de Registrar todo el tráfico HTTP,


ModSecurity puede monitorear el tráfico en tiempo real para detectar
ataques. Quiere Decir que ModSecurity actúa como una herramienta de
detección de intrusos.

A partir de su versión 2 ModSecurity agregó diversas funcionalidades que


mencionamos:

Cinco fases de procesamiento, incluyendo: encabezados del pedido (request


headers), cuerpo del pedido (request body), encabezados de respuesta
(response headers), cuerpo de respuesta (response body) y almacenamiento

install_nginx_modsecurity 38
JShielder - Linux Server Hardening Script

en bitácora (logging).

Opciones de transformación por regla.

Variables transaccionales.

Persistencia de datos (utilizado en seguimientos de direcciones IP, sesiones


de aplicación, y usuarios de aplicación).

Soporte para ranking de anomalías y correlación básica de eventos (los


contadores pueden ser automáticamente decrementados con el paso del
tiempo, las variables pueden expirar).

Soporte para aplicaciones Web e IDs de sesión.

Soporte para XML (parseo, validación, XPath).

bloqueo de IP

ModSecurity es una herramienta de Seguridad imprescindible y que ha


demostrado ser muy efectiva. Si eres un Administrador de Sistemas con
aplicaciones web criticas y que deben ser accedidas publicamente este es un
Firewall que merece su atención.

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
}

La función set_nginx_vhost se encarga de configurar el virtual host


correspondiente que apuntará a nuestra aplicación web. Hace uso de la plantilla
que se encuentra en templates/nginxvhost que se encarga de hacer una
configuración segura y habilitar ModSecurity para nuestra aplicación, además de
habilitar el soporte para PHP de nginx mediante PHP-FPM. Veamos que tiene el
archivo:

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;
}
}

# deny scripts inside writable directories


location ~* /(images|cache|media|logs|tmp)/.*.(php|pl|py|jsp|asp|sh|cg
return 403;
error_page 403 /403_error.html;
}

## Block download agenta


if ($http_user_agent ~* LWP::Simple|wget|libwww-perl) {
return 403;
}

## Block some nasty robots


if ($http_user_agent ~ (msnbot|Purebot|Baiduspider|Lipperhey|Mail.
return 403;
}

## Deny referal spam


if ( $http_referer ~* (jewelry|viagra|nude|girl|nudit|casino|poke
return 403;
}

location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

# With php5-cgi alone:


#fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;

set_nginx_vhost 41
JShielder - Linux Server Hardening Script

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_n


include fastcgi_params;
}
}

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
}

La función set_nginx_vhost_nophp realiza los mismos pasos que la función


set_nginx_vhost a excepción que no configura el soporte para PHP. Hace uso
de la plantilla que se encuentra en templates/nginxvhost_nophp:

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;
}
}

# deny scripts inside writable directories


location ~* /(images|cache|media|logs|tmp)/.*.(php|pl|py|jsp|asp|sh|cg
return 403;
error_page 403 /403_error.html;
}

## Block download agenta


if ($http_user_agent ~* LWP::Simple|wget|libwww-perl) {
return 403;
}

## Block some nasty robots


if ($http_user_agent ~ (msnbot|Purebot|Baiduspider|Lipperhey|Mail.
return 403;
}

## Deny referal spam


if ( $http_referer ~* (jewelry|viagra|nude|girl|nudit|casino|poke
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
}

La función set_nginx_modsec_OwaspRules se encarga de descargar y poner


en funcionamiento las reglas de ModSecurity de OWASP que serán las que
estarán protegiendo nuestra aplicación web. Jshielder las copia en los directorios
correspondiente y activa la configuración.

Ya que cuando descargamos las reglas y las descomprimimos, es posible que la


carpeta resultante cambie la numeración es por eso que hacemos uso de la
variable owaspdir que lo que hace es listar los directorios en nuestra ruta actual,
busca el que se llama Spiderlabs y extrae el nombre para poder ingresar a el y
copiar los archivos correspondiente.

set_nginx_modsec_OwaspRules 45
JShielder - Linux Server Hardening Script

owaspdir=$(ls -la | grep SpiderLabs | cut -d ' ' -f18)

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
}

La función install_secure_php instala PHP con soporte para MySQL y


reemplaza la configuración de php.ini por una configuración segura haciendo uso
de la plantilla que se encuentra en templates/php. Veamos la configuración:

[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]

En esta configuración deshabilitamos algunas opciones que pueden llevar a php


a mostrar información sensible tanto de php como del servidor. Lo más
importante es la directiva disable_functions, donde se deshabilitan todas las
funciones que se consideran peligrosas en PHP y que pueden llevar a ejecutar
algún ataque y comprometer el servidor.

disable_functions = proc_open, popen, disk_free_space, diskfreespace, set_ti

**Nota: Según su aplicación es posible que requieran hacer uso de algunas de


estas funciones, pero se recomienda que busquen una alternativa o la habiliten
en caso de ser extrictamente necesario.

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
}

La función install_php_nginx hace exactamente lo mismo que la función


install_secure_php**, con la diferencia que instala el soporte para nginx PHP-
FPM.

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
}

La función install_modsecurity se encarga de instalar el Firewall de Aplicaiones


Web ModSecurity para el servicio Web Apache. A diferencia de Nginx, podemos
instalar ModSecurity desde los repos.

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 ""

for archivo in /usr/share/modsecurity-crs/base_rules/*


do ln -s $archivo /usr/share/modsecurity-crs/activated_rules/
done

for archivo in /usr/share/modsecurity-crs/optional_rules/*


do ln -s $archivo /usr/share/modsecurity-crs/activated_rules/
done
spinner
echo "OK"

sed s/SecRuleEngine\ DetectionOnly/SecRuleEngine\ On/g /etc/modsecurity/


mv salida /etc/modsecurity/modsecurity.conf

echo 'SecServerSignature "AntiChino Server 1.0.4 LS"' >> /usr/share/mods


echo 'Header set X-Powered-By "Plankalkül 1.0"' >> /usr/share/modsecurit
echo 'Header set X-Mamma "Mama mia let me go"' >> /usr/share/modsecurity

a2enmod headers
service apache2 restart
say_done
}

La Función set_owasp_rules, se encarga de crear los respectivos links


simbólicos para que apache pueda hacer uso de estas reglas y proteger nuestras
aplicaciones web.

set_owasp_rules 57
JShielder - Linux Server Hardening Script

for archivo in /usr/share/modsecurity-crs/base_rules/*


do ln -s $archivo /usr/share/modsecurity-crs/activated_rules/
done

for archivo in /usr/share/modsecurity-crs/optional_rules/*


do ln -s $archivo /usr/share/modsecurity-crs/activated_rules/
done
spinner
echo "OK"

Por defecto ModSecurity se instala en Modo Detección, es decir, hace logging


de los ataques pero no los detiene. Jshielder se encarga de activar ModSecurity
en la ejecución mediante el comando:

sed s/SecRuleEngine\ DetectionOnly/SecRuleEngine\ On/g /etc/modsecurity/mods


mv salida /etc/modsecurity/modsecurity.conf

Cambiamos además los Headers de respuesta para dar la menor información


posible de nuestro servidor en caso de reconocimiento pasivo.

echo 'SecServerSignature "AntiChino Server 1.0.4 LS"' >> /usr/share/mods


echo 'Header set X-Powered-By "Plankalkül 1.0"' >> /usr/share/modsecurit
echo 'Header set X-Mamma "Mama mia let me go"' >> /usr/share/modsecurity

Es bueno mencionar y esto va igual para la configuración de ModSecurity tanto


para apache como para Nginx, ya que Jshielder lo activa por defecto, es posible
que tengamos algunos temas con nuestra aplicación en caso de que algo de la
aplicación llegue a matchear con alguna regla de ModSecurity, además de que
tampoco podremos acceder a la aplicación via la IP que por seguridad tambien se
bloquea. Vamos a darle algunos pasos a seguir y voy a iniciar con lo de la IP.

Si es necesario que durante el despliegue de la aplicación necesiten acceder por


la IP, pueden crear una entrada en su archivo de Hosts, con un nombre
apuntando a la IP de nuestro servidor.

set_owasp_rules 58
JShielder - Linux Server Hardening Script

Ejemplo:

Tengo un Servidor Linux con IP 10.0.0.5 y Asegurado con ModSecurity, aún no le


he asignado un Dominio por lo que debo trabajar vía la IP, que puedo Hacer?

Accedemos a /etc/hosts y agregamos

10.0.0.5 prueba.com

Si la aplicación está disparando reglas y bloqueando el acceso, lo que debemos


hacer es colocar ModSecurity en modo DetectionOnly y mediante los Logs ir
viendo los ID de las reglas que matchean. Usando esta información podemos ir
creando excepciones en apache para que ModSecurity nos los bloquee. Para
colocar ModSecurity en DetectionOnly deben seguir los siguientes pasos:

$ 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>

Si queremos deshabilitar por completo ModSecurity para un directorio lo hacemos


así:

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
}

La función secure_optimize_apache reemplaza la configuración por defecto de


apache por una configuración mas segura haciendo uso de la plantilla que se
encuentra en templates/apache, veamos que contiene el archivo:

Mutex file:${APACHE_LOCK_DIR} default


PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 1000
KeepAliveTimeout 2

<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

# Include module configuration:


Include mods-enabled/*.load
Include mods-enabled/*.conf

# Include ports listing


Include ports.conf

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\


LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" com
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer

<IfModule security2_module>
Include /usr/share/modsecurity-crs/*.conf
Include /usr/share/modsecurity-crs/base_rules/*.conf
</IfModule>

LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf

ServerSignature Off
ServerTokens Prod

ErrorDocument 404 "Archivo no encontrado"


ErrorDocument 500 "Tareas de mantenimiento en curso. Disculpe las molestias"

FileETag None
Header unset ETag
TraceEnable off

Aquí optimizamos algunos valores, cargamos las reglas de ModSecurity y


agregamos algunas directivas de seguridad. Para mencionar algunas:

ServerSignature Off
ServerTokens Prod

secure_optimize_apache 63
JShielder - Linux Server Hardening Script

Con estas directivas protegemos de divulgar informaciones sensibles del servidor


apache que luego pueden ser utilizadas para crear un vector de ataque.

<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>

Aquí protegemos nuestro arhivo .htaccess en caso de que estemos utilizando


alguno.

Options -Indexes -Includes -ExecCGI



deny from all

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

Estas directivas protegen con ataques para conseguir información sensible o


ataques para robar información de cookies.

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
}

La función install_modevasive instala ModEvasive. Este módulo ayuda a


proteger el servidor contra ataques DDoS, o Ataques de Denegación de
Servicios, provee acciones de evasión y reporta el abuso mediante los logs o
correos. Trabaja creando una tabla dinámica interna de direcciones IP y URIs así
como denegando direcciones que cumplan con lo siguiente:

Solicitando la Misma página varias veces


Hacer mas de 50 solicitudes concurrentes
Hacer solicitudes mientras está en lista negra

La Función solicita el correo para completar la configuración y copiarla a la ruta


correspondiente, hace uso de la plantilla que se encuentra en templates/mod-
evasive:

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>

La Sección de DOSEmailNotify es sustituida con el correo ingresado por el


usuario

sed s/MAILTO/$inbox/g templates/mod-evasive > /etc/apache2/mods-available/mo

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
}

La función install_qos_spamhaus instala los módulos de apache Mod_Qos y


Mod_SpamHaus que protegen el servidor de Ataques DOS como el Slowroris
(qos), y contra ataques de Inyección DNS usados por los Spammers. Hace uso
de las plantillas que se encuentran en templates/qos y templates/spamhaus.

Qos

<IfModule qos_module.so>
# minimum request rate (bytes/sec at request reading):
QS_SrvRequestRate 120

# limits the connections for this virtual host:


QS_SrvMaxConn 100

# allows keep-alive support till the server reaches 600 connections:


QS_SrvMaxConnClose 600

# allows max 50 connections from a single ip address:


QS_SrvMaxConnPerIP 50

install_qos_spamhaus 67
JShielder - Linux Server Hardening Script

#Maximum Number of active TCP connections


MaxClients 192

#Disable keep-alive when 70% of the TCP connections are occupied


QS_SrvMaxConnClose 70%

#Minimum request/response speed


QS_SrvMinDataRate 150 1200

# 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
}

La función config_fail2ban reemplaza la configuración por defecto de fail2ban


haciendo uso de la plantilla que se encuentra en templates/fail2ban. Contiene
configuraciones para servicios como SSH, apache, entre otros. Veamos el
contenido del archivo:

[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

action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(pr


%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protoco
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(p
%(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s",
action = %(action_mw)s

[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
}

La función additional_packages instala algunos paquetes que pueden asistir al


desarrollador y al administrador de sistemas, otros son para cuestiones de
seguridad. Vamos a ver en detalle cada uno.

echo "Install tree............."; apt-get install tree

Nos da una visión estructurada de los archivos y directorios.

additional_packages 75
JShielder - Linux Server Hardening Script

echo "Install Python-MySQLdb..."; apt-get install python-mysqldb

Interfaz de Python para MySQL

echo "Install PIP.............."; apt-get install python-pip

Para instalación de módulos de Python

echo "Install pear............."; apt-get install php-pear

Framework y sistema de distribución para componentes de PHP reutilizables.

echo "Install DebSums.........."; apt-get install debsums

Revisa el checksum de paquetes instalados

echo "Install apt-show-versions"; apt-get install apt-show-versions

Muestra las versiones de los paquetes

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" >>

PHPUnit es un framework de pruebas para detectar fallas.

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
}

La función tune_secure_kernel agrega directivas a sysctl.conf para pasarle a


kernel configuración en tiempo de ejecución. Estas directivas aumentan el nivel
de seguridad del servidor ya que controlan ciertos aspectos de funcionamiento
directamente en el kernel. Hace uso de la plantilla que se encuentra en
templates/sysctl.conf. Veamos que contiene el archivo, las descripciones
indican el objetivo de las directivas.

# Kernel sysctl configuration file for Ubuntu


# Modified by Jason Soto <jason_soto@jsitech.com>
#
# For binary values, 0 is disabled, 1 is enabled. See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding


net.ipv4.ip_forward = 0

# Controls source route verification


net.ipv4.conf.default.rp_filter = 1

tune_secure_kernel 77
JShielder - Linux Server Hardening Script

# Do not accept source routing


net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel


kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies


net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.


net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

# Controls the default maxmimum size of a mesage queue


kernel.msgmnb = 65536

# Controls the maximum size of a message, in bytes


kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes


kernel.shmmax = 68719476736

# Controls the maximum number of shared memory segments, in pages


kernel.shmall = 4294967296

######### GENERAL SECURITY OPTIONS ################

# Automatically Reboot Server in 30 Seconds after a Kernel Panic


vm.panic_on_oom = 1
kernel.panic = 30
kernel.panic_on_oops = 30

# Enable ExecShield
kernel.exec-shield = 1

tune_secure_kernel 78
JShielder - Linux Server Hardening Script

kernel.randomize_va_space = 1

########## COMMUNICATIONS SECURITY ##############


# No Redirections
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Do not Accept Packets with SRR


net.ipv4.conf.all.accept_source_route = 0

# Do not accept Redirections


net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.all.secure_redirects = 0

# Disable Packets Forwarding


net.ipv4.ip_forward = 0
net.ipv4.conf.all.forwarding = 0
net.ipv4.conf.default.forwarding = 0
net.ipv6.conf.all.forwarding = 0
net.ipv6.conf.default.forwarding = 0

# Log Suspicious Packets


net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# Ignore ICMP ECHO or TIMESTAMP sent by broadcast/multicast


net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_timestamps = 0

# Protect Against 'syn flood attack'


net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 5
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 4096

tune_secure_kernel 79
JShielder - Linux Server Hardening Script

# Enable Reverse Source Validation (Protects Against IP Spoofing)


net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Ignore Bogus Error Response


net.ipv4.icmp_ignore_bogus_error_responses = 1

# 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

- MD5 hash compare


- Look for default files used by rootkits
- Wrong file permissions for binaries
- Look for suspected strings in LKM and KLD modules
- Look for hidden files
- Optional scan within plaintext and binary files "
sleep 1
cd rkhunter-1.4.2/
sh installer.sh --layout /usr --install
cd ..
rkhunter --update
rkhunter --propupd
echo " ***To Run RootKit Hunter ***"
echo " rkhunter -c --enable all --disable none"
echo " Puede ver el reporte detallado en /var/log/rkhunter.log"
say_done
}

RootKit Hunter es una herramienta que escanea el servidor en busca de


rootkits, backdoors o exploits locales. La Función install_rootkit_hunter instala
esta herramienta, la actualiza y hace el escaneo inicial.

Si desean correr la herramienta solo deben ejecutar:

install_rootkit_hunter 81
JShielder - Linux Server Hardening Script

$ rkhunter -c --enable all --disable none

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

La Función tune_nano_bashrc optimiza los bashrc, vim, y nano para un mejor


funcionamiento y darle mas comodidad al usuario vía el uso de alias. Hace uso
de las plantillas en templates/bashrc-root, bashrc-user, nanorc, vimrc. Hace
ademas uso de la función tunning en helper.sh.

# Copy Local Config Files


function tunning() {
whoapp=$1
cp templates/$whoapp /root/.$whoapp
cp templates/$whoapp /home/$username/.$whoapp
chown $username:$username /home/$username/.$whoapp
say_done
}

Veamos el contenido de los archivos:

bashrc-root

[ -z "$PS1" ] && return

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

# set a fancy prompt (non-color, unless we know we "want" color)


case "$TERM" in

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

if [ "$color_prompt" = yes ]; then


PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir


case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac

# enable color support of ls and also add handy aliases


if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(d
alias ls='ls -lh --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi

# some more ls aliases

tune_nano_vim_bashrc 85
JShielder - Linux Server Hardening Script

alias ll='ls -alF --color=auto'


alias la='ls -A --color=auto'
alias l='ls -CF --color=auto'
alias .='cd ..'
alias ls='ls -l --color=auto'
alias arestart='service apache2 restart'
alias sysupdate='apt-get update; apt-get upgrade -y'
alias doinstall='apt-get install'
alias mv='mv -i'
alias cp='cp -i'
alias rm='rm -i'
alias mysql='mysql -uroot -p'
alias tree='tree --dirsfirst'

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

function md5 {
php -r "echo md5('$1') . chr(10);"
}

bashrc-user

[ -z "$PS1" ] && return

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

# set a fancy prompt (non-color, unless we know we "want" color)


case "$TERM" in
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

if [ "$color_prompt" = yes ]; then


PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir


case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac

# enable color support of ls and also add handy aliases


if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(d

tune_nano_vim_bashrc 87
JShielder - Linux Server Hardening Script

alias ls='ls -lh --color=auto'


alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi

# some more ls aliases


alias ll='ls -alF --color=auto'
alias la='ls -A --color=auto'
alias l='ls -CF --color=auto'
alias .='cd ..'
alias ls='ls -l --color=auto'
alias arestart='sudo service apache2 restart'
alias sysupdate='sudo apt-get update; sudo apt-get upgrade -y'
alias doinstall='sudo apt-get install'
alias mv='mv -i'
alias cp='cp -i'
alias rm='rm -i'
alias mysql='mysql -uroot -p'
alias tree='tree --dirsfirst'

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

set autoindent " identación automática


unset backup " no crear backups file~
set const " muestra la posición del cursor en la barra de esta
set morespace " usa la primera línea debajo del título para codear
set nowrap " no wrapear el texto
set tabsize 4 " Identación de 4 espacios en blanco
set tabstospaces " Convierte los tabulados a espacios

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

set showmatch " Show matching brackets.


set ignorecase " Do case insensitive matching
set hlsearch " Resaltar la búsqueda
set incsearch " Incremental search
set mouse=a " Enable mouse usage (all modes)
set number " Mostrar los números de línea
set textwidth=80 " Fijar ancho de línea en 80 caracteres
set softtabstop=4
set shiftwidth=4
set tabstop=4
set expandtab

"set showcmd " Show (partial) command in status line.


"set smartcase " Do smart case matching
"set autowrite " Automatically save before commands like :next and :m
"set hidden " Hide buffers when they are abandoned

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
}

La función daily_update_cronjob crea la tarea de cron para la actualización


diaria del sistema completo. Esta función proximamente será elimanada ya que
hacemos uso de unattended upgrades.

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
}

La Función install_portsentry, instala PortSentry que es un sistema de detección


que nos ayuda a proteger nuestro servidor de escaneos de puerto. Hace uso de
la plantilla templates/portsentry para la configuración.

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"

KILL_ROUTE="/sbin/route add -host $TARGET$ reject"


KILL_HOSTS_DENY="ALL: $TARGET$ : DENY"
KILL_RUN_CMD_FIRST = "0"
KILL_RUN_CMD="/sbin/blockip $TARGET$"

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

La función additional_hardening sigue algunos pasos para mejorar el nivel de


seguridad de nuestro servidor. Vamos verlos en detalle.

echo tty1 > /etc/securetty

Pasando solo esta directiva a /etc/securetty restringimos el acceso de root solo a


una terminal local. Es por esto que para las tareas administrativas deben hacer
un acceso remoto al servidor con el usuario que crearon y una vez dentro se
cambian al usuario root.

chmod 0600 /etc/securetty


chmod 700 /root
chmod 600 /boot/grub/grub.cfg

En esta sección colocamos permisos mas restrictivos a archivos críticos.

echo nospoof on >> /etc/host.conf

Aquí protegemos al servidor contra el IP Spoofing.

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

Aquí eliminamos AT y restringimos el uso de cron exclusivamente a root.

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"

En esta sección a opción del usuario se deshabilita el soporte para


almacenamiento USB.

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
}

La función install_unhide instala la herramienta forense unhide a nuestro


servidor.

Unhide es una herramienta desarrollada por Yago Jesus y Patrick Gouin


enfocada a indentificar anomalías inicialmente para sistemas Unix/Linux, pero
según vi en la página del proyecto hay una versión para sistemas Windows. Estas
anomalías son detectadas por la herramienta indentificando procesos y puertos
TCP/UDP ocultos, que son, sin duda síntomas de un RootKit en el sistema.

Unhide para Linux emplea las siguientes técnicas para la detección

unhide (ps)*

Detecta procesos ocultos y a su vez emplea seis técnicas


Compara la salida de /proc contra /bin/ps
Compara la información obtenida de /bin/ps con la info obtenida recorriendo
el filesystem de /proc.
Compara la información obtenida de /bin/ps con la obtenida de syscalls o

install_unhide 97
JShielder - Linux Server Hardening Script

llamadas del sistema (syscall scanning)


Búsqueda por fuerza bruta de todos los PIDs del sistema (PIDs bruteforcing)
Búsqueda al reverso, verifica que todos los hilos visto por ps también sean
vistos por el Kernel (/bin/ps vs /proc, procfs, syscall)
Rápida comparación /proc, recorrido procfs y syscall vs salida /bin/ps

unhide-TCP

Identifica puertos TCP/UDP en escucha que no se muestran en /bin/nestat


haciendo un brute forcing de todos los puertos TCP/UDP disponibles.

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
}

La Función install_tiger instala el sistema de seguridad tiger. Tiger puede ser


usado como un auditor de seguridad y sistema de detección de intrusos.
Durante la instalación deben configurar los passphrases,que deben recordarlas
para aceptar cambios en el sistema de archivos. Para mas información sobre la
herramienta pueden ejecutar man tiger.

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

iptables -A INPUT -j LOG


iptables -A FORWARD -j LOG

"
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

La Función install_psad instala la herramienta PSAD. PSAD es una herramienta


que monitorea activamente los logs del firewall de Linux para determinar si hay
en progreso un escaneo o un ataque. Puede alertar o tomar acción para mitigar el
ataque. Se hace una configuración haciendo uso de la plantilla que se encuentra
en templates/psad.conf.

#
############################################################################
#
# 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.
#
############################################################################
#

### Supports multiple email addresses (as a comma separated


### list).
EMAIL_ADDRESSES INBOX;

### Machine hostname


HOSTNAME hostname;

### 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;

### Danger levels. These represent the total number of


### packets required for a scan to reach each danger level.

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;

### Search for snort "sid" values generated by fwsnort


### or snort2iptables
SNORT_SID_STR SID;

### 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;

### This is used only if ENABLE_PERSISTENCE = "N";


SCAN_TIMEOUT 3600; ### seconds

### 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

### advisable to leave this threshold at the default value of 5 or greater


### because the scan tracking hash may be quite large.
PERSISTENCE_CTR_THRESHOLD 5;

### 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;

### If "Y", means all signatures will be shown since


### the scan started instead of just the current ones.
SHOW_ALL_SIGNATURES N;

### Allow reporting methods to be enabled/restricted. This keyword can


### accept values of "nosyslog" (don't write any messages to syslog),
### "noemail" (don't send any email messages), or "ALL" (to generate both
### syslog and email messages). "ALL" is the default. Both "nosyslog"
### and "noemail" can be combined with a comma to disable all logging
### and alerting.
ALERTING_METHODS ALL;

### 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

### associated with Snort rule matches to syslog.


ENABLE_SIG_MSG_SYSLOG Y;
SIG_MSG_SYSLOG_THRESHOLD 10;
SIG_SID_SYSLOG_THRESHOLD 10;

### TTL values are decremented depending on the number of hops


### the packet has taken before it hits the firewall. We will
### assume packets will not jump through more than 20 hops on
### average.
MAX_HOPS 20;

### Do not include any timestamp included within kernel logging


### messages (Ubuntu systems commonly have this)
IGNORE_KERNEL_TIMESTAMP Y;

### FIXME: try to mitigate the affects of the iptables connection


### tracking bug by ignoring tcp packets that have the ack bit set.
### Read the "BUGS" section of the psad man page. Note that
### if a packet matches a snort SID generated by fwsnort (see
### http://www.cipherdyne.org/fwsnort/)
### then psad will see it even if the ack bit is set. See the
### SNORT_SID_STR variable.
IGNORE_CONNTRACK_BUG_PKTS Y;

### define a set of ports to ignore (this is useful particularly


### for port knocking applications since the knock sequence will
### look to psad like a scan). This variable may be defined as
### a comma-separated list of port numbers or port ranges and
### corresponding protocol, For example, to have psad ignore all
### tcp in the range 61000-61356 and udp ports 53 and 5000, use:
### IGNORE_PORTS tcp/61000-61356, udp/53, udp/5000;
IGNORE_PORTS NONE;

### allow entire protocols to be ignored. This keyword can accept


### a comma separated list of protocols. Each protocol must match
### the protocol that is specified in an iptables log message (case
### insensitively, so both "TCP" or "tcp" is ok).
### IGNORE_PROTOCOL tcp,udp;
IGNORE_PROTOCOLS NONE;

install_psad 106
JShielder - Linux Server Hardening Script

### allow packets to be ignored based on interface (this is the


### "IN" interface in iptables logging messages).
IGNORE_INTERFACES NONE;

### Ignore these specific logging prefixes


IGNORE_LOG_PREFIXES NONE;

### 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;

### Enable detection of malicious activity that is delivered via IPv6. If


### ip6tables is not logging any traffic, then psad won't know anything
### about IPv6, or this variable can be set to "N" (this would be slightly
### faster if ip6tables isn't logging anything).
ENABLE_IPV6_DETECTION Y;

### Treat all subnets on local interfaces as part of HOME_NET (this


### means that these networks do not have to be manually defined)
ENABLE_INTF_LOCAL_NETS Y;

### Include MAC addresses in email alert


ENABLE_MAC_ADDR_REPORTING N;

### Look for the iptables logging rule (fwcheck_psad is executed)


ENABLE_FW_LOGGING_CHECK Y;

### Send no more than this number of emails for a single


### scanning source IP. Note that enabling this feature may cause
### alerts for real attacks to not be generated if an attack is sent
### after the email threshold has been reached for an IP address.
### This is why the default is set to "0".

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;

### Port thresholds for logging and -S and -A output.


TOP_PORTS_LOG_THRESHOLD 500;
STATUS_PORTS_THRESHOLD 20;

install_psad 108
JShielder - Linux Server Hardening Script

### Signature thresholds for logging and -S and -A output.


TOP_SIGS_LOG_THRESHOLD 500;
STATUS_SIGS_THRESHOLD 50;

### Attackers thresholds for logging and -S and -A output.


TOP_IP_LOG_THRESHOLD 500;
STATUS_IP_THRESHOLD 25;

### 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;

### Send scan logs to dshield.org. This is disabled by default,


### but is a good idea to enable it (subject to your site security
### policy) since the DShield service helps to track the bad guys.
### For more information visit http://www.dshield.org
ENABLE_DSHIELD_ALERTS N;

### dshield.org alert email address; this should not be changed


### unless the guys at DShield have changed it.
DSHIELD_ALERT_EMAIL reports@dshield.org;

### Time interval (hours) to send email alerts to dshield.org.


### The default is 6 hours, and cannot be less than 1 hour or
### more than 24 hours.
DSHIELD_ALERT_INTERVAL 6; ### hours

### If you have a DShield user id you can set it here. The
### default is "0".
DSHIELD_USER_ID 0;

### If you want the outbound DShield email to appear as though it


### is coming from a particular user address then set it here.
DSHIELD_USER_EMAIL NONE;

### 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

### in DShield email alerts).


DSHIELD_DL_THRESHOLD 0;

### List of servers. Fwsnort supports the same variable resolution as


#### Snort.
HTTP_SERVERS $HOME_NET;
SMTP_SERVERS $HOME_NET;
DNS_SERVERS $HOME_NET;
SQL_SERVERS $HOME_NET;
TELNET_SERVERS $HOME_NET;

#### AOL AIM server nets


AIM_SERVERS [64.12.24.0/24, 64.12.25.0/24, 64.12.26.14/24, 6

### Configurable port numbers


HTTP_PORTS 80;
SHELLCODE_PORTS !80;
ORACLE_PORTS 1521;

### If this is enabled, then psad will die if a rule in the


### /etc/psad/signatures file contains an unsupported option (otherwise
### a syslog warning will be generated).
ENABLE_SNORT_SIG_STRICT Y;

### If "Y", enable automated IDS response (auto manages


### firewall rulesets).
ENABLE_AUTO_IDS N;

### Block all traffic from offending IP if danger


### level >= to this value
AUTO_IDS_DANGER_LEVEL 5;

### Set the auto-blocked timeout in seconds (the default


### is one hour).
AUTO_BLOCK_TIMEOUT 3600;

### Set the auto-blocked timeout in seconds for each danger


### level - zero means to block permanently. Each of these
### can be set independently
AUTO_BLOCK_DL1_TIMEOUT $AUTO_BLOCK_TIMEOUT;

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

### Enable regex checking on log prefixes for active response


ENABLE_AUTO_IDS_REGEX N;

### 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;

### By setting this variable to N, all auto-blocking emails can be


### suppressed.
ENABLE_AUTO_IDS_EMAILS Y;

### Enable iptables blocking (only gets enabled if


### ENABLE_AUTO_IDS is also set)
IPTABLES_BLOCK_METHOD Y;

### Specify chain names to which iptables blocking rules will be


### added with the IPT_AUTO_CHAIN{n} keyword. There is no limit on the
### number of IPT_AUTO_CHAIN{n} keywords; just increment the {n} number
### to add an additional IPT_AUTO_CHAIN requirement. The format for this
### variable is: <Target>,<Direction>,<Table>,<From_chain>,<Jump_rule_positi
### <To_chain>,<Rule_position>.
### "Target": Can be any legitimate iptables target, but should usually
### just be "DROP".
### "Direction": Can be "src", "dst", or "both", which correspond to the
### INPUT, OUTPUT, and FORWARD chains.
### "Table": Can be any iptables table, but the default is "filter".
### "From_chain": Is the chain from which packets will be jumped.
### "Jump_rule_position": Defines the position within the From_chain where
### the jump rule is added.
### "To_chain": Is the chain to which packets will be jumped. This is the
### main chain where psad rules are added.

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;

### Enable tcp wrappers blocking (only gets enabled if


### ENABLE_AUTO_IDS is also set)
TCPWRAPPERS_BLOCK_METHOD N;

### Set the whois timeout


WHOIS_TIMEOUT 60; ### seconds

### 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;

### Enable psad to run an external script or program (use at your


### own risk!)
ENABLE_EXT_SCRIPT_EXEC N;

### Define an external program to run after a scan is caught.


### Note that the scan source ip can be specified on the command
### line to the external program through the use of the "SRCIP"
### string (along with some appropriate switch for the program).
### Of course this is only useful if the external program knows
### what to do with this information.
### Example: EXTERNAL_SCRIPT /path/to/script --ip SRCIP -v;
EXTERNAL_SCRIPT /bin/true;

### Control execution of EXTERNAL_SCRIPT (only once per IP, or


### every time a scan is detected for an ip).
EXEC_EXT_SCRIPT_PER_ALERT N;

### Disk usage variables


DISK_CHECK_INTERVAL 300; ### seconds

### This can be set to 0 to disable disk checking altogether


DISK_MAX_PERCENTAGE 95;

### 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;

### Enable archiving of old scan directories at psad startup.


ENABLE_SCAN_ARCHIVE N;

### Truncate fwdata file at startup


TRUNCATE_FWDATA Y;

install_psad 113
JShielder - Linux Server Hardening Script

### Only archive scanning IP directories that have reached a danger


### level greater than or equal to this value. Archiving old
### scanning ip directories only takes place at psad startup.
MIN_ARCHIVE_DANGER_LEVEL 1;

### 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];

### URL for getting the latest psad signatures


SIG_UPDATE_URL http://www.cipherdyne.org/psad/signatures;

### These next two are psadwatchd vars


PSADWATCHD_CHECK_INTERVAL 5; ### seconds
PSADWATCHD_MAX_RETRIES 10;

### 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;

### PID files


PSAD_PID_FILE $PSAD_RUN_DIR/psad.pid;
PSAD_CMDLINE_FILE $PSAD_RUN_DIR/psad.cmd;
KMSGSD_PID_FILE $PSAD_RUN_DIR/kmsgsd.pid;
PSADWATCHD_PID_FILE $PSAD_RUN_DIR/psadwatchd.pid;

### List of ips that have been auto blocked by iptables


### or tcpwrappers (the auto blocking feature is disabled by
### default, see the psad man page and the ENABLE_AUTO_IDS
### variable).
AUTO_BLOCK_IPT_FILE $PSAD_DIR/auto_blocked_iptables;
AUTO_BLOCK_TCPWR_FILE $PSAD_DIR/auto_blocked_tcpwr;

### File used internally by psad to add iptables blocking


### rules to a running psad process
AUTO_IPT_SOCK $PSAD_RUN_DIR/auto_ipt.sock;

FW_ERROR_LOG $PSAD_ERR_DIR/fwerrorlog;
PRINT_SCAN_HASH $PSAD_DIR/scan_hash;

### /proc interface for controlling ip forwarding


PROC_FORWARD_FILE /proc/sys/net/ipv4/ip_forward;

install_psad 115
JShielder - Linux Server Hardening Script

### Packet counters for tcp, udp, and icmp protocols


PACKET_COUNTER_FILE $PSAD_DIR/packet_ctr;

### Top scanned ports


TOP_SCANNED_PORTS_FILE $PSAD_DIR/top_ports;

### Top signature matches


TOP_SIGS_FILE $PSAD_DIR/top_sigs;

### Top attackers


TOP_ATTACKERS_FILE $PSAD_DIR/top_attackers;

### Counter file for Dshield alerts


DSHIELD_COUNTER_FILE $PSAD_DIR/dshield_ctr;

### Counter file for iptables prefixes


IPT_PREFIX_COUNTER_FILE $PSAD_DIR/ipt_prefix_ctr;

### 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;

### system binaries


iptablesCmd /sbin/iptables;
ip6tablesCmd /sbin/ip6tables;
shCmd /bin/sh;
wgetCmd /usr/bin/wget;
gzipCmd /bin/gzip;
mknodCmd /bin/mknod;
psCmd /bin/ps;
mailCmd /bin/mail;
sendmailCmd /usr/sbin/sendmail;
ifconfigCmd /sbin/ifconfig;
ipCmd /sbin/ip;
killallCmd /usr/bin/killall;
netstatCmd /bin/netstat;
unameCmd /bin/uname;
whoisCmd $INSTALL_ROOT/usr/bin/whois_psad;

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;

Para visualizar si PSAD a detectado algo, ejecutamos:

$ service psad status

Veremos algo así:

Status of Port Scan Attack Detector:


[+] psadwatchd (pid: 3219) %CPU: 0.0 %MEM: 0.0
Running since: Sun Dec 27 10:03:13 2015

[+] psad (pid: 3213) %CPU: 2.6 %MEM: 4.9


Running since: Sun Dec 27 10:03:13 2015
Command line arguments: [none specified]
Alert email address(es): jason_soto@jsitech.com

[+] Version: psad v2.2.1

[+] Top 50 signature matches:


"ICMP Destination Unreachable Port Unreachable" (icmp), Count: 298,
"ICMP PING" (icmp), Count: 209, Unique sources: 75, Sid: 384
"MISC MS Terminal Server communication attempt" (tcp), Count: 177, U
"MISC Microsoft SQL Server communication attempt" (tcp), Count: 161,
"BACKDOOR DoomJuice file upload attempt" (tcp), Count: 153, Unique s
"ICMP Destination Unreachable Communication with Destination Host is A
"BACKDOOR win-trin00 connection attempt" (udp), Count: 62, Unique so
"MISC Radmin Default install options attempt" (tcp), Count: 62, Uniq
"SCAN UPnP communication attempt" (udp), Count: 40, Unique sources:
"MISC VNC communication attempt" (tcp), Count: 40, Unique sources: 2
"ICMP Destination Unreachable Host Unreachable" (icmp), Count: 37, U
"ICMP PING Sun Solaris" (icmp), Count: 31, Unique sources: 6, Sid:
"MISC Microsoft PPTP communication attempt" (tcp), Count: 24, Unique
"POLICY HP JetDirect LCD communication attempt" (tcp), Count: 17, Un

install_psad 117
JShielder - Linux Server Hardening Script

"MISC PCAnywhere communication attempt" (tcp), Count: 10, Unique sou


"ICMP Destination Unreachable Communication Administratively Prohibite
"MISC Windows popup spam attempt" (udp), Count: 8, Unique sources: 2
"MISC HP Web JetAdmin communication attempt" (tcp), Count: 8, Unique
"ICMP Destination Unreachable Network Unreachable" (icmp), Count: 5,
"ICMP Destination Unreachable Fragmentation Needed and DF bit was set"
"ICMP redirect host" (icmp), Count: 3, Unique sources: 1, Sid: 472
"BACKDOOR netbus Connection Cttempt" (tcp), Count: 2, Unique sources
"DOS DB2 dos communication attempt" (tcp), Count: 2, Unique sources:
"BACKDOOR Doly 2.0 Connection attempt" (tcp), Count: 2, Unique sourc
"POLICY vncviewer Java applet communication attempt" (tcp), Count: 2,
"ICMP Echo Reply" (icmp), Count: 2, Unique sources: 2, Sid: 408
"BACKDOOR SatansBackdoor.2.0.Beta, or BackConstruction 2.1 Connection
"ICMP traceroute" (icmp), Count: 1, Unique sources: 1, Sid: 385
"BACKDOOR GateCrasher Connection attempt" (tcp), Count: 1, Unique so

SRC: 103.56.112.170, DL: 2, Dsts: 1, Pkts: 1, Total protocols: 1, Unique si

DST: 23.92.*.*, Local IP


Scanned ports: TCP 5900, Pkts: 1, Chain: INPUT, Intf: eth0
Total scanned IP protocols: 1, Chain: INPUT, Intf: eth0
Signature match: "MISC VNC communication attempt"
TCP, Chain: INPUT, Count: 1, DP: 5900, SYN, Sid: 100202

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
}
``````

La Función disable_compilers se encarga de deshabilitar todos los


compiladores en nuestro sistema. El objetivo de esto es reducir las posibilidades
de que puedan compilar e instalar un troyano, backdoor o rootkit.

Si por alguna razón necesitamos algunos de los compiladores, solo debemos


cambiar los permisos.

disable_compilers 119
JShielder - Linux Server Hardening Script

Ejemplo:

$ chmod 755 /urs/bin/gcc

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
}

La Función apache_conf_restrictions coloca permisos mas restrictivos a los


archivos de configuración de apache.

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
}

La función unattended_upgrades activa a opción del usuario las actualizaciones


desantentidas que tiene como proposito mantener el sistema siempre actualizado
sin la interacción del administrador de sistema.

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"
}

La Función enable_proc_acct instala acct, que es una herramienta que


monitorea la actividad de los usuarios y procesos en el sistema. Nos provee de
diversas herramientas para monitorear las actividades de los procesos.

ac, muestra las estadísticas de las conexiones y desconexiones de los


usuarios en horas
lastcomm, muestra la información de comandos ejecutados
accton, activa y desactiva la contabilidad
sa. Sumariza la información de comandos ejecutados
last y lastb, muestra un listado de los últimos usuarios conectados

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
}

La Función install_phpsuhosin instala Suhosin para PHP. Suhosin es un


sistema de protección avanzado para instalaciones de PHP. Fue diseñado para
proteger los servidores de fallas conocidas y no conocidas en el core y las
aplicaciones de PHP.

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
}

La Función reboot_server es el último paso de Jshielder, Le pide al usuario que


intente una conexión por ssh con las llaves y el nuevo puerto, si todo va bien solo
tiene que enviar a reiniciar el servidor.

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.

Como descargo JShielder

$ git clone https://github.com/Jsitech/JShielder

Accedemos a la carpeta

$ cd JShielder/

Tendremos el Deployer General de JShielder, veamos que tiene el script:

#!/bin/bash

# JShielder v2.0
# Linux Hardening Script
#
# Jason Soto
# www.jsitech.com
# Twitter = @JsiTech

# Tool URL = www.jsitech.com/jshielder


# us.jsitech.com/jshielder

# Based from JackTheStripper Project


# Credits to Eugenia Bahit

# A lot of Suggestion Taken from The Lynis Project


# www.cisofy.com/lynis
# Credits to Michael Boelen @mboelen

Ejecutando JShielder 126


JShielder - Linux Server Hardening Script

############################################################################

f_banner(){
echo
echo "
_ ____ _ _ _ _
| / ___|| |__ (_) ___| | __| | ___ _ __
_ | \___ \| '_ \| |/ _ \ |/ _ |/ _ \ '__|
| |_| |___) | | | | | __/ | (_| | __/ |
\___/|____/|_| |_|_|\___|_|\__,_|\___|_|
Linux Automated Hardening Script for Linux Servers
Developed By Jason Soto @JsiTech "
echo
echo

############################################################################

#Check if Running with root user

if [ "$USER" != "root" ]; then


echo "Permission Denied"
echo "Can only be run by root"
exit
else
clear
f_banner
fi

menu=""
until [ "$menu" = "10" ]; do

clear
f_banner

echo
echo -e "\e[34m-------------------------------------------------------------
echo -e "\e[93m[+]\e[00m SELECT YOUR LINUX DISTRIBUTION"

Ejecutando JShielder 127


JShielder - Linux Server Hardening Script

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

Ejecutando JShielder 128


JShielder - Linux Server Hardening Script

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

LAMP Deployment: Hace un deployment de un servidor LAMP (Linux-


Apache-MySQL/MariaDB-PHP) con todos los pasos de Hardening de
Jshielder
Reverse Proxy Deployment With Apache: Hace un deployment de un
Servidor Reverse Proxy basado en Apache. Sigue todos los pasos de
Hardening de JShielder, pero no instala php, mysql.
LEMP Deployment: Hace un deployment de un servidor LEMP (Linux-
NginX-MySQL/MariaDB-PHP )con todos los pasos de Hardening de
Jshielder. Puede ser utlizado si se desea desplegar una aplicación web
customizada.
Reverse Proxy Deployment with Nginx (ModSecurity): Hace un
deployment de un Servidor Reverse Proxy basado en Nginx. Sigue todos los
pasos de Hardening de JShielder, pero no instala php, mysql. Puede ser
utlizado si se desea desplegar una aplicación web customizada.
Running With SecureWPDeployer or JSDeployer Script: Esta opción
debe ser seleccionado cuando ejecutamos JShielder mediante el script de
Deployment Seguro de WordPress, SecureWPDeployer o Joomla.

Ejecutando JShielder 129


JShielder - Linux Server Hardening Script

JSDeployer. Sigue todo el proceso de LAMP Deployment de Jshielder pero


omite el paso de Reiniciar el Servidor para continuar con el Deployment de
WordPress o Joomla.

Customized Run (Only run desired Options): Esta Opción le da al usuario


un menu para ejecutar solo las funciones deseadas.

Ejecutando JShielder 130


JShielder - Linux Server Hardening Script

------------------------------------------------------------------------
[+] SELECT THE DESIRED OPTION
----------------------------------------------------------------------------

1. Configure Host Name, Create Legal Banners, Update Hosts Files


2. Configure Timezone
3. Update System
4. Create Admin User
5. Instructions to Generate and move Private/Public key Pair
6. Secure SSH Configuration
7. Set Restrictive IPTable Rules
8. Install and Configure Fail2Ban
9. Install, Optimize and Secure Apache
10. Install Nginx with ModSecurity Module and Set OwaspRules
11. Set Nginx Vhost with PHP
12. Set Nginx Vhost
13. Install and Secure PHP for Apache Server
14. Install and Secure PHP for Nginx Server
15. Install ModSecurity (Apache)and Set Owasp Rules
16. Install ModEvasive
17. Install ModQos and SpamHaus
18. Tune and Secure Linux Kernel
19. Install RootKit Hunter
20. Tune Vim, Nano, Bashrc
21. Install PortSentry
22. Secure tty, root home, grub configs, cron
23. Install Unhide
24. Install Tiger
25. Disable Compilers
26. Enable Unnatended Upgrades
27. Enable Process Accounting
28. Install PHP Suhosin
29. Install and Secure MySQL
30. Set More Restrictive UMASK Value (027)
31. Secure /tmp Directory
32. Install PSAD IDS
33. Exit

Ejecutando JShielder 131


JShielder - Linux Server Hardening Script

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.

De necesitar alguna ayuda, estoy a la orden siempre.

Autor: Jason Soto

Mail: jason_soto[AT]jsitech[DOT]com

Twitter: @JsiTech

Cierre 132

S-ar putea să vă placă și