-
Notifications
You must be signed in to change notification settings - Fork 2
/
nginx updated 8g firewall rules v5.conf
253 lines (189 loc) · 12.7 KB
/
nginx updated 8g firewall rules v5.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# ============================================
# 8G Nginx Firewall Rules v5.0 - Refined
# ============================================
http {
# =========================
# 1. Define Blocking Conditions Using Maps
# =========================
# Define a separate log format for blocked requests
log_format blocked '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# Block based on Query String
map $query_string $block_query {
# XSS-related patterns
~*(?:document\.cookie|document\.write|alert|confirm|prompt|onload|onerror|onunload|onmouseover|onmouseout|onfocus|onblur|onsubmit|onreset|onabort|onresize|onscroll|onkeydown|onkeypress|onkeyup|onclick|ondblclick|ondrag|ondrop|onpaste|oncopy|oncut|onbeforeunload|onhashchange|onmessage|onpopstate|ondragstart|ondragend|ondragover|ondragleave|onmouseenter|onmouseleave|ontransitionend|onfocusin|onfocusout|onloadstart|onloadend|oninput|ontouchstart|ontouchmove|ontouchend|onpointerdown|onpointerup|onpointermove|onpointercancel|onwheel|onswipe|querySelector|execCommand|textContent|localStorage|sessionStorage|postMessage|MutationObserver|WebSocket|Geolocation|Notification|BroadcastChannel) 1;
# XSS and JavaScript Execution Patterns (Consolidated)
~*(?:eval\(|expression\(|%3C(?:iframe|img)%3E|<(?:iframe|img)|data:text/html;base64|javascript:) 1;
# SQL Injection patterns
~*(?:union\s+select|declare\s+|extract|information_schema|group_concat|concat_ws|version|substring|ascii|chr|bin|hex|unhex|base64|benchmark\(|sleep\(|load_file\(|outfile\(|into\s+outfile|into\s+dumpfile|char\(|substr\(|md5\(|sha1\(|grant|revoke|xp_cmdshell|openrowset\(|openquery\(|load\s+data\s+infile|union.*select.*from|or\s+1=1|exec\() 1;
# General attack function calls (Removed 'cast(' to eliminate duplication)
~*(?:case\s+when|limit\s+\d+|having\s+|null\s+|like\s+'%|mid\(|count\(|rand\(|xor\(|ifnull\(|char_length\(|soundex\(|pg_sleep\(|pg_cancel_backend\(|pg_terminate_backend\(|sleep\(|now\() 1;
# Additional SQL Injection patterns
~*(?:%23|--|%2d%2d|concat\(|load_file\(|union\s+select|or\s+1=1|or\s+'1'='1'|1--|coalesce\(|int\(|float\(|boolean\(|select\s+.*\s+current_user|concat_ws\(|group_concat\() 1;
# Very long query strings
~*([a-z0-9]{1000,}) 1; # Adjusted threshold from 3500 to 1000
# Sensitive file paths and protocols
~*(?:etc/(?:hosts|passwd|shadow|issue|fstab|group|gshadow)|proc/self/environ|ftp://|file://|%2e%2e(?:/|\\)|/var/www|/root|/boot|/tmp|/bin|/lib|/usr/share|/usr/local|\.ssh|\.gnupg|\.bash_history|id_rsa|\.pem|/etc/network|/etc/hostname|/etc/shadow|/etc/passwd|~|\$) 1;
# Command injection patterns
~*(?:cmd|command|chdir|mkdir|nc|netcat|sh|bash|ping|curl|wget|cat|rm|ls|ps|chmod|whoami|ifconfig|traceroute|xargs|system|exec|popen\(|proc_open\(|execve\(|nc\s+-e|nc\s+-lnvp|bash\s+-i|tar\s+-xvf|gpg\s+-d|lsof|openssl|tcpdump|strace|gdb|nmap|zcat|dd|cpio|awk|sed|ssh|scp|ftp) 1;
# PHP streams and other protocols
~*(?:php://(?:input|filter|temp|fd)|phar://|data:(?:text/html|image/svg)|expect(?:_open)?://|compress\.gz|zlib\.inflate|zip://|jar://|cve-\d{4}|cmdline) 1;
# Encoding sequences
~*(?:%00|%3c|%3e|%25|0x|%2e%2e(?:/|\\)|%3d%23|%2f%5c|~|%24|%3c%3fphp|\.\/|\.\\|%252e%252e%252f|%3d%7e|%252f) 1;
# Localhost and private IPs
~*(?:127\.0\.0\.1|localhost|::1|169\.254\.|metadata(?:\.google|\.aws|\.azure|\.cloud)|169\.254\.169\.254/latest/meta-data|/admin(?:/|$)|/root(?:/|$)|/tmp(?:/|$)|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|35\.\d{1,3}\.\d{1,3}\.\d{1,3}|100\.64\.\d{1,3}\.\d{1,3}) 1;
# DOCTYPE, ENTITY, file protocols
~*(?:<!DOCTYPE|<!ENTITY|SYSTEM|ENTITY|%3c%21(?:DOCTYPE|ENTITY)|zlib) 1;
# Excessive query parameters
~*((?:\?.*=.*){50,}|(?=.*=.*=.*=.*=.*=.*=.*=.*=.*=.*=)) 1;
# URL shorteners
~*(?:bit\.ly|t\.co|is\.gd|tinyurl\.com|goo\.gl|shorte\.st|%2F%2F(?:http|https)) 1;
# Multiple forward slashes
~*(?:\/){10,} 1;
default 0;
}
# Block based on Request URI
map $request_uri $block_uri {
# Consolidated Specific scripts, admin files, and Web shells/exploit scripts
~*(?:phpinfo|test\.php|debug\.php|adminer|mysqladmin|phpmyadmin|dbadmin|sysinfo\.php|shell\.php|remoteview\.php|gfshell\.php|c99\.php|r57\.php|wso\.php|backdoor\.php|phpremoteview|gfshell|symlink|shell_exec|testfile\.php|hacker\.php|pentest\.php|mysql_bypass|drupalgeddon|log4shell|cve-\d{4}|cmd\.php|phpunit|exploits|shell\.sh|cmdshell|phpterm|backdoor|webshell\.php|tiny_mce|image_upload|uploadfile\.php|server-status|error_log|php-errors|config\.php|setup\.php|readme\.md|install\.log) 1;
# Function calls and protocols
~*(?:eval\(|base64_decode\(|gzinflate\(|str_rot13\(|shell_exec\(|popen\(|proc_open\(|passthru\(|/dev/tcp|expect://|phar://|zip://|data:text/html|data:application|system\(|create_function\(|ini_set\(|open_basedir\(|ini_restore\() 1;
# File extensions
~*\.(?:cgi|asp|aspx|dll|exe|jsp|mdb|sql|ini|rar|py|sh|bat|pl|ps1|cmd|vbs|tmp|bak|pem|key|crt|pfx|der|csr|conf|log|db|logrotate|tar|gz|zip|7z|pdb|so|ko|elf|out|class|o)$ 1;
# Sensitive directories (Updated to make 'cve' more specific and removed duplicates)
~*(?:/)(?:etc|var|tmp|proc|dev|root|lib|home|logs|cache|boot|run|wp-includes|backup|dump|shadow|sysadmin|logrotate|audit|log|phpmyadmin|dbadmin|pma|upload|download|config|webshell|cve-\d{4}|readme|changelog|secret|hidden) 1;
# Very long URIs
~*([a-zA-Z0-9\._%]{1500,}) 1;
# Encoding sequences
~*(?:%20|\+|%2b|%2d|%2520|%3d|%253d|%25|%00|\.\.|\\\.|\/\/|%2f|%5c|/\.|%3b|0x) 1;
default 0;
}
# Block based on User Agent
map $http_user_agent $block_agent {
# Known security scanners and bots
~*(?:acunetix|dirbuster|nuclei|teleport|nikto|sqlmap|netsparker|nessus|floodgate|sqlinject|crawler|masscan|pshtt|sqlcheck|burpsuite|xsser|loadimpact|go-http-client|flood|bruteforce|httperf|w3af|webinspect|curl|python|ruby|openvas|xsstrike|dirsearch|whatweb|arachni|gobuster|ffuf|zap|joomscan|joomla-scan|drupalscan|cmsmap|hydra|sqlpowerinjector) 1;
# Headless browsers and automated tools
~*(?:headlesschrome|phantomjs|selenium|puppeteer|chromium|casperjs|scrapy|spider|nightmarejs|zap|go-http|bot|http\.client|wget|httpclient|httpunit|urlgrabber|autotool|serpapi|openai|ai|http_request|java|httpx|powershell) 1;
# Empty user agent
~*^$ 1; # Empty user agent
# Overly short user agents
~*^[a-zA-Z]{1,5}$ 1; # Overly short user agents
# Known scanners and probes
~*(?:masscan|spider|fetch|scanner|generic|probe|tcpdump|netcat|nping|zmap|zap) 1;
default 0;
}
# Block based on Referrer
map $http_referer $block_referer {
# Spam, phishing, and malicious traffic sources
~*(?:poker|sex|viagra|cialis|babes|nude|dating|adult|fetish|porn|pharma|spam|lotto|win-money|clickbank|seocheck|trafficanalytics|tracking\.com|pharmacy|web\.to|qr\.net|ow\.ly|adf\.ly|hyperlink|sharethis|bit\.do|semalt|todaperfeita|clicktrack|trackback|seo\.com|clicktarget|sitechecker|audit-check|ranktracker|hyperlinkmanager|trackingcheck|backlinktool|seo-audit) 1;
# Suspicious TLDs
~*([a-zA-Z0-9]{1,}\.(?:ru|cn|top|buzz|tk|xyz|icu|club|mobi|loan|science|trade|cam|date|stream|click|digital|finance|fund|global|biz|pro|win|work|lol|pw|ws|ga|gq|ml|cf)) 1;
# Suspicious protocols and encodings
~*(?:data:|base64,|javascript:|vbscript:|ftp://|%3a%2f%2f|\\|//|ftp:) 1;
default 0;
}
# Block based on HTTP Method
map $request_method $block_method {
# Uncommon or potentially harmful HTTP methods
~*(?:TRACE|TRACK|CONNECT|MOVE|PROPFIND|PROPPATCH|COPY|LOCK|UNLOCK|MKCOL) 1;
default 0;
}
# Combine All Blocking Conditions
map "$block_query $block_uri $block_agent $block_referer $block_method" $block_all {
~*1 1; # Blocks if any condition is met (only 1 and 0 are present)
default 0;
}
# =========================
# 2. Define Rate Limiting and Connection Limiting Zones
# =========================
# Rate Limiting Zone for Requests
limit_req_zone $binary_remote_addr zone=8g_limit:5m rate=5r/s; # Adjust zone size and rate as needed
# Connection Limiting Zone
limit_conn_zone $binary_remote_addr zone=conn_limit:5m; # Adjust zone size as needed
# =========================
# 3. Server Blocks
# =========================
# Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com; # Replace with your domain
# Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response
return 301 https://$host$request_uri;
}
# HTTPS Server Block
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com; # Replace with your domain
# SSL Configuration
ssl_certificate /path/to/cert.pem; # Replace with your SSL certificate path
ssl_certificate_key /path/to/key.pem; # Replace with your SSL certificate key path
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Apply Rate Limiting and Connection Limiting
limit_req zone=8g_limit burst=10 nodelay; # Adjust burst as needed
limit_conn conn_limit 10; # Adjust connection limit as needed
# Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self';" always;
# File Upload Restrictions
client_max_body_size 10M;
# Prevent Access to Sensitive Files
location ~* ^/(\.htaccess|\.htpasswd|\.ini|\.log|\.sh|\.inc|wp-config\.php|\.bak|\.swp|setup\.php|server-status|error\.php|composer\.lock|composer\.json|package-lock\.json|yarn\.lock|robots\.txt)$ {
deny all;
}
# Block Access to Hidden Files and Directories
location ~ /\. {
deny all;
}
# Block Backup, Log, and Compressed Archive Files
location ~* \.(?:log|backup|swp|db|sql|tar|gz|zip|bz2|bak|sav|tgz|7z|logrotate|bin|pfx|pgp|dmp)$ {
deny all;
}
# Rate Limiting for Specific Paths
location = /wp-login.php {
limit_req zone=8g_limit burst=3 nodelay; # Adjust burst as needed
# Additional security measures for wp-login.php can be added here
}
location = /xmlrpc.php {
limit_req zone=8g_limit burst=3 nodelay; # Adjust burst as needed
# Additional security measures for xmlrpc.php can be added here
}
# Restrict Access to Admin Panels and Sensitive Directories
location ~* /(admin(?:/|$)|adminer|mysqladmin|phpmyadmin|pma|myadmin|info\.php|debug\.php|backup|logs|webshell|\.git|\.svn)$ {
deny all;
}
# Handle Blocking of Malicious Requests using default 403
location / {
# Redirect to default 403 error page if block_all is set
if ($block_all = 1) {
return 403;
}
# Cache-Control Headers to Prevent Caching of Sensitive Pages
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
expires off;
# Your Application Configuration
try_files $uri $uri/ =404;
}
# Conditional Access Logging for Blocked Requests
access_log /var/log/nginx/blocked.log blocked if=$block_all;
# =========================
# 5. Additional Security Measures
# =========================
# Prevent Caching of Sensitive Data
location ~* /(?:wp-admin|wp-includes|cgi-bin|phpmyadmin|adminer|setup\.php|login\.php)$ {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
expires off;
}
# Optional: Implement Content Compression (ensure it doesn't interfere with security)
# gzip on;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Optional: Enable Access Logs for Monitoring (already handling blocked requests separately)
# access_log /var/log/nginx/access.log;
# Optional: Disable Server Tokens
server_tokens off;
}
}