Skip to content

Instantly share code, notes, and snippets.

@TFujiwara
Last active November 29, 2023 07:50
Show Gist options
  • Select an option

  • Save TFujiwara/8bef0d8bb199ae0c2577fac7f16be2c4 to your computer and use it in GitHub Desktop.

Select an option

Save TFujiwara/8bef0d8bb199ae0c2577fac7f16be2c4 to your computer and use it in GitHub Desktop.
Crea un vHost en nginx sin SSL pero con securizacion del mismo.
#!/bin/bash
# Verifica si el script se está ejecutando con privilegios de root
if [ "$EUID" -ne 0 ]; then
echo "Este script debe ejecutarse con privilegios de root."
exit 1
fi
# Verifica si se proporciona un nombre de dominio como argumento
if [ -z "$1" ]; then
echo "Uso: $(basename $0) <nombre_de_dominio> <version_php>"
exit 1
fi
domain="$1"
phpver="$2"
nginx_conf="/etc/nginx/sites-available/${domain}"
cloudflare_conf="/etc/nginx/conf.d/cloudflare.conf"
check_install_php() {
if ! dpkg-query -l "php${phpver}-fpm" &> /dev/null; then
echo "Instalando PHP ${phpver}-fpm..."
# Descomentar si no tenemos el repositorio añadido
#add-apt-repository ppa:ondrej/php -y
apt-get update
apt-get install -y "php${phpver}" "php${phpver}-fpm"
else
installed_version=$(dpkg-query -W "php${phpver}-fpm")
echo "PHP ${phpver}-fpm ya está instalado (versión $installed_version)."
fi
}
# Función para clonar el repositorio ngx_http_badbot y mover el archivo install-ngxblocker
clone_and_move_ngxblocker() {
ngxblocker_script="/usr/local/bin/install-ngxblocker"
ngxsetup_script="/usr/local/bin/setup-ngxblocker"
ngxupdate_script="/usr/local/bin/update-ngxblocker"
# Archivo jail.conf de Fail2Ban
jail_conf="/etc/fail2ban/jail.conf"
# Verifica si el archivo install-ngxblocker ya existe
if [ ! -e "$ngxblocker_script" ]; then
echo "Instalando las reglas de securización de NGINX..."
echo "Clonando el repositorio ngx_http_badbot..."
git clone https://github.com/mitchellkrogza/nginx-ultimate-bad-bot-blocker.git /tmp/ngxblocker
echo "Moviendo install-ngxblocker a /usr/local/sbin..."
mv /tmp/ngxblocker/install-ngxblocker "$ngxblocker_script"
chmod +x "$ngxblocker_script"
# Instalamos las reglas y damos permisos de ejecución a los scripts de setup y actualización
$ngxblocker_script -x
chmod +x $ngxsetup_script
chmod +x $ngxupdate_script
# Instalamos los archivos de configuración
$ngxsetup_script -x
echo "Copiando el directorio _fail2ban_addon a /etc/fail2ban..."
cp -r /tmp/ngxblocker/_fail2ban_addon /etc/fail2ban
echo "Instalando Fail2Ban..."
apt-get update
apt-get install -y fail2ban
# Añade configuración al final de jail.conf
echo "Añadiendo configuración a $jail_conf..."
cat >> "$jail_conf" <<EOL
[nginxrepeatoffender]
enabled = true
logpath = %(nginx_access_log)s
filter = nginxrepeatoffender
banaction = nginxrepeatoffender
bantime = -1 ; 1 day
findtime = 604800 ; 1 week
maxretry = 1
EOL
# Reinicia el servicio de Fail2Ban para aplicar los cambios
systemctl restart fail2ban
echo "Se ha reiniciado el servicio de Fail2Ban para aplicar los cambios."
else
echo "Las reglas de securización de NGINX ya están instaladas!"
fi
}
# Verificamos e instalamos PHP con FPM
check_install_php
# Instalamos las reglas de securizacion de NGINX
clone_and_move_ngxblocker
# Verifica si el archivo de configuración ya existe
if [ -e "$nginx_conf" ]; then
echo "El archivo de configuración para $domain ya existe."
exit 1
fi
# Verifica si el archivo cloudflare.conf ya existe
if [ ! -e "$cloudflare_conf" ]; then
echo "Configurando direcciones IP de Cloudflare en $cloudflare_conf..."
# Crea el archivo cloudflare.conf en /etc/nginx/conf.d/ con las direcciones IP de Cloudflare
echo "# Direcciones IP de Cloudflare" > "$cloudflare_conf"
echo "set_real_ip_from 103.21.244.0/22;" >> "$cloudflare_conf"
echo "set_real_ip_from 103.22.200.0/22;" >> "$cloudflare_conf"
echo "set_real_ip_from 103.31.4.0/22;" >> "$cloudflare_conf"
echo "set_real_ip_from 104.16.0.0/12;" >> "$cloudflare_conf"
echo "set_real_ip_from 108.162.192.0/18;" >> "$cloudflare_conf"
echo "set_real_ip_from 131.0.72.0/22;" >> "$cloudflare_conf"
echo "set_real_ip_from 141.101.64.0/18;" >> "$cloudflare_conf"
echo "set_real_ip_from 162.158.0.0/15;" >> "$cloudflare_conf"
echo "set_real_ip_from 172.64.0.0/13;" >> "$cloudflare_conf"
echo "set_real_ip_from 173.245.48.0/20;" >> "$cloudflare_conf"
echo "set_real_ip_from 188.114.96.0/20;" >> "$cloudflare_conf"
echo "set_real_ip_from 190.93.240.0/20;" >> "$cloudflare_conf"
echo "set_real_ip_from 197.234.240.0/22;" >> "$cloudflare_conf"
echo "set_real_ip_from 198.41.128.0/17;" >> "$cloudflare_conf"
echo "set_real_ip_from 199.27.128.0/21;" >> "$cloudflare_conf"
echo "set_real_ip_from 2400:cb00::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2606:4700::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2803:f800::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2405:b500::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2405:8100::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2c0f:f248::/32;" >> "$cloudflare_conf"
echo "set_real_ip_from 2a06:98c0::/29;" >> "$cloudflare_conf"
else
echo "El archivo $cloudflare_conf ya existe en /etc/nginx/conf.d/."
fi
# Crea el archivo de configuración NGINX para el vhost
cat > "$nginx_conf" <<EOF
server {
listen 80;
listen [::]:80;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
server_name $domain www.$domain;
include /etc/nginx/bots.d/ddos.conf;
include /etc/nginx/bots.d/blockbots.conf;
include /etc/nginx/conf.d/cloudflare.conf;
root /var/www/$domain;
index index.php index.html index.htm;
location / {
try_files \$uri \$uri/ =404;
}
location ~ \.php\$ {
include snippets/fastcgi-php.conf;
include fastcgi_params;
fastcgi_pass unix:/run/php/php${phpver}-fpm.sock; # Ajusta la versión de PHP según tu instalación
fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
}
# Otros ajustes de configuración según sea necesario
error_log /var/log/nginx/$domain.error.log;
access_log /var/log/nginx/$domain.access.log;
}
EOF
# Crea el enlace simbólico para activar el sitio
ln -s "$nginx_conf" "/etc/nginx/sites-enabled/"
# Crea la carpeta donde estarán los ficheros de la web
mkdir -p /var/www/$domain
# Da permisos al usuario www-data para poder ejecutar la web
chown -R www-data:www-data /var/www/$domain
# Checkea la configuración de NGINX, si hay algún error, no continuamos y aconsejamos corregir los errores manualmente
if nginx -t &> nginx_check.log; then
# Creamos el enlace simbolico para activar el sitio web o app en NGINX
ln -s "$nginx_conf" "/etc/nginx/sites-enabled"
# Recargamos la configuración una vez sabemos que esta bien
systemctl reload nginx
echo "Se ha creado el vhost para $domain con soporte para la versión $phpver de PHP."
echo -e "\033[41mATENCION: ACUERDATE DE AÑADIR LAS DIRECCIONES IP EN LA WHITELIST DEL FICHERO BLOCKBOTS.CONF\033[m"
else
echo "Error en la configuración de NGINX. Por favor, corrige los errores de forma manual antes de continuar. Más detalles:
cat nginx_check.log
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment