# ============================================
# SIAKAD UNDARMA - NGINX Security Configuration
# Ubuntu Server + NGINX + PHP-FPM + MariaDB
# ============================================

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=general:10m rate=60r/m;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# Block bad user agents
map $http_user_agent $bad_bot {
    default 0;
    ~*(curl|wget|python|scrapy|nikto|sqlmap|nmap|masscan|zgrab) 1;
    ~*(bot|crawler|spider|scan) 1;
}

# Upstream PHP-FPM
upstream php_backend {
    server unix:/var/run/php/php8.2-fpm.sock;
    keepalive 32;
}

# HTTP to HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name siakad.undarma.ac.id www.siakad.undarma.ac.id;
    
    # Security: Hide nginx version
    server_tokens off;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://$server_name$request_uri;
    }
}

# HTTPS Server
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name siakad.undarma.ac.id;
    
    root /var/www/siakad/public;
    index index.php;
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/siakad.undarma.ac.id/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/siakad.undarma.ac.id/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/siakad.undarma.ac.id/chain.pem;
    
    # Modern SSL settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    
    # Security Headers
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'none';" always;
    
    # Hide server info
    server_tokens off;
    more_clear_headers Server X-Powered-By;
    
    # Block bad bots
    if ($bad_bot) {
        return 403;
    }
    
    # Deny access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    # Deny access to sensitive files
    location ~* \.(env|git|gitignore|gitattributes|lock|md)$ {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    # Protect storage and bootstrap
    location ~ ^/(storage|bootstrap|config|database|resources|routes|tests|vendor)/ {
        deny all;
        return 404;
    }
    
    # Rate limit login endpoints
    location ~ ^/(login|forgot-password|reset-password) {
        limit_req zone=login burst=3 nodelay;
        limit_conn addr 5;
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    # Rate limit API
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_conn addr 10;
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    # General rate limiting
    location / {
        limit_req zone=general burst=50 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    # PHP handling
    location ~ \.php$ {
        fastcgi_pass php_backend;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        
        # PHP security
        fastcgi_param PHP_VALUE "
            expose_php=Off
            display_errors=Off
            log_errors=On
            allow_url_fopen=Off
            allow_url_include=Off
            session.cookie_httponly=On
            session.cookie_secure=On
            session.cookie_samesite=Strict
            session.use_strict_mode=On
            memory_limit=256M
            max_execution_time=60
            upload_max_filesize=10M
            post_max_size=10M
        ";
        
        # Buffer settings
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        
        # Timeout settings
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
    }
    
    # Static file caching
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 6M;
        access_log off;
        add_header Cache-Control "public, immutable";
        add_header X-Frame-Options "DENY" always;
    }
    
    # Logging
    access_log /var/log/nginx/siakad-access.log combined buffer=512k flush=1m;
    error_log /var/log/nginx/siakad-error.log warn;
    
    # Request size limit
    client_max_body_size 10M;
    client_body_buffer_size 128k;
    
    # Timeout settings
    client_body_timeout 30s;
    client_header_timeout 30s;
    keepalive_timeout 30s;
    send_timeout 30s;
}
