Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save TFujiwara/b0496f0f65cfcc8bd4109b7cb1423600 to your computer and use it in GitHub Desktop.
Crea un vHost en nginx con SSL y con securizacion aplicada.
#!/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> <ruta_certificado_ssl> <ruta_clave_privada_ssl> <version_php>"
exit 1
fi
domain="$1"
cert_path="$2"
key_path="$3"
phpver="$4"
ssl_key="/etc/ssl/$domain/key.pem"
ssl_cert="/etc/ssl/$domain/cert.pem"
nginx_conf="/etc/nginx/sites-available/${domain}"
cloudflare_conf="/etc/nginx/conf.d/cloudflare.conf"
# Función para verificar e instalar PHP con FPM si es necesario
check_install_php() {
if ! dpkg-query -l "php${phpver}-fpm" &> /dev/null; then
echo "Instalando PHP ${phpver}-fpm..."
apt-get update
apt-get install -y "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"
# Verifica si el archivo install-ngxblocker ya existe
if [ ! -e "$ngxblocker_script" ]; then
echo "Instalando las reglas de securizacion 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 ejecucion a los scripts de setup y actualizacion
$ngxblocker_script -x
chmod +x $ngxsetup_script
chmod`+x $ngxupdate_script
# Instalamos los archivos de configuracion
$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
# Archivo jail.conf de Fail2Ban
jail_conf="/etc/fail2ban/jail.conf"
echo "Añadiendo configuración a $jail_conf..."
# Agrega la configuración al final de jail.conf
cat <<EOL >> "$jail_conf"
[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 securizacion 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;
# Descomentar una vez se tengan los certificados SSL
listen 443 ssl http2;
listen [::]:443 ssl http2;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# Certificados SSL
ssl_certificate /etc/ssl/$domain/cert.pem;
ssl_certificate_key /etc/ssl/$domain/key.pem;
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/"
# Copia los certificados SSL y los renombra a los nombres que hay en la configuracíon para no fallar estrepitosamente, además de crear subcarpeta.
mkdir -p /etc/ssl/$domain
cp "$cert_path" "$ssl_cert"
cp "$key_path" "$ssl_key"
# 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 SSL para $domain con soporte para la version $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