-
Notifications
You must be signed in to change notification settings - Fork 0
Advanced Configuration
This guide covers advanced nginx-torblocker configuration patterns, performance optimization, integration with other modules, and complex use cases.
Advanced configuration builds upon basic torblock usage to provide sophisticated blocking strategies, performance tuning, conditional logic, and integration with security frameworks.
Configure memory settings for optimal performance:
http {
# Optimize for torblock performance
torblock on;
torblock_cache_size 10m; # Allocate memory for IP cache
torblock_max_entries 100000; # Maximum cached IPs
torblock_update_interval 1800000; # 30 minutes in milliseconds
# Nginx worker optimization
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
}
Implement efficient IP caching:
http {
torblock on;
# Cache configuration
torblock_cache_size 50m; # Large cache for high traffic
torblock_cache_timeout 7200000; # 2 hours
torblock_negative_cache on; # Cache non-Tor IPs too
torblock_negative_timeout 3600000; # 1 hour for negative cache
# Performance monitoring
log_format torblock_perf '$remote_addr [$time_local] '
'"$request" $status '
'cache_status="$torblock_cache_status" '
'lookup_time="$torblock_lookup_time"';
}
Combine torblock with rate limiting:
http {
torblock on;
# Define rate limiting zones
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/m;
limit_req_zone $torblock_status zone=tor_strict:5m rate=1r/m;
server {
listen 80;
server_name example.com;
# Different rate limits based on Tor status
location / {
# General rate limiting
limit_req zone=general burst=20 nodelay;
# Strict limiting for Tor users
if ($torblock_status = "blocked") {
limit_req zone=tor_strict burst=2;
}
root /var/www/html;
}
}
}
Implement time-sensitive Tor blocking:
http {
torblock on;
# Map time periods
map $time_iso8601 $is_business_hours {
~T(0[89]|1[0-7]) 1; # 8 AM - 5 PM
default 0;
}
server {
listen 80;
server_name business.example.com;
location / {
# Block Tor only during business hours
if ($is_business_hours) {
torblock on;
}
root /var/www/business;
}
location /maintenance {
# Always block Tor for sensitive operations
torblock on;
torblock_action 444; # Drop connection
root /var/www/maintenance;
}
}
}
Combine with GeoIP for location-based policies:
http {
torblock on;
# Load GeoIP module
geoip_country /usr/share/GeoIP/GeoIP.dat;
# Map countries to blocking policies
map $geoip_country_code $tor_policy {
US strict;
CA strict;
GB normal;
DE normal;
default permissive;
}
server {
listen 80;
server_name global.example.com;
location / {
# Apply different policies based on country
if ($tor_policy = "strict") {
torblock on;
torblock_action 403;
}
if ($tor_policy = "normal") {
torblock on;
torblock_action redirect;
torblock_redirect_url "/tor-notice.html";
}
# Permissive: allow Tor traffic
root /var/www/global;
}
}
}
Combine with user agent filtering:
http {
torblock on;
# Map suspicious user agents
map $http_user_agent $is_suspicious_ua {
~*bot 1;
~*crawler 1;
~*scanner 1;
~*curl 1;
~*wget 1;
default 0;
}
server {
listen 80;
server_name api.example.com;
location /api {
# Strict blocking for suspicious user agents + Tor
if ($torblock_status = "blocked") {
set $block_reason "tor";
}
if ($is_suspicious_ua) {
set $block_reason "${block_reason}_ua";
}
if ($block_reason ~ "tor_ua") {
return 403 "Access denied: Automated Tor access not allowed";
}
if ($block_reason = "tor") {
return 429 "Rate limited: Tor access restricted";
}
proxy_pass http://backend;
}
}
}
Create context-aware blocking responses:
http {
torblock on;
# Variables for dynamic responses
map $request_uri $block_category {
~/api/ "api";
~/admin/ "admin";
~/login "auth";
default "general";
}
server {
listen 80;
server_name secure.example.com;
# Custom error pages for different sections
error_page 403 = @tor_blocked;
location @tor_blocked {
internal;
# Set content type
add_header Content-Type "application/json" always;
# Dynamic JSON response based on category
if ($block_category = "api") {
return 403 '{"error":"tor_blocked","message":"API access via Tor is not permitted","code":4001}';
}
if ($block_category = "admin") {
return 403 '{"error":"admin_blocked","message":"Administrative access requires direct connection","code":4002}';
}
if ($block_category = "auth") {
return 403 '{"error":"auth_blocked","message":"Authentication via Tor is disabled","code":4003}';
}
# Default response
return 403 '{"error":"access_denied","message":"Tor access not permitted","code":4000}';
}
location / {
torblock on;
torblock_action 403;
root /var/www/secure;
}
}
}
Implement CAPTCHA challenges for Tor users:
http {
torblock on;
server {
listen 80;
server_name protected.example.com;
# CAPTCHA verification endpoint
location /verify-captcha {
internal;
# Proxy to CAPTCHA service
proxy_pass http://captcha-service;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Tor-Status $torblock_status;
}
location / {
# Check for Tor and existing verification
if ($torblock_status = "blocked") {
set $needs_captcha 1;
}
# Check for valid verification cookie
if ($cookie_tor_verified = "valid") {
set $needs_captcha 0;
}
# Redirect to CAPTCHA if needed
if ($needs_captcha = 1) {
return 302 /captcha-challenge?redirect=$request_uri;
}
root /var/www/protected;
}
location /captcha-challenge {
root /var/www/captcha;
index challenge.html;
}
}
}
Combine with Web Application Firewall:
http {
torblock on;
# Load ModSecurity
load_module modules/ngx_http_modsecurity_module.so;
server {
listen 80;
server_name webapp.example.com;
# Enable ModSecurity
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
location / {
# Custom ModSecurity rules for Tor traffic
modsecurity_rules '
SecRule REMOTE_ADDR "@detectTorExit" \
"id:1001,phase:1,block,msg:Tor Exit Node Detected"
SecRule TX:TORBLOCK_STATUS "@streq blocked" \
"id:1002,phase:2,pass,setvar:tx.tor_user=1"
SecRule TX:TOR_USER "@eq 1" \
"id:1003,phase:2,pass,setvar:tx.anomaly_score=+10"
';
torblock on;
torblock_action pass; # Let ModSecurity handle blocking
proxy_pass http://application;
}
}
}
Log format for Fail2Ban monitoring:
http {
torblock on;
# Detailed logging for security monitoring
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'tor_status="$torblock_status" '
'tor_asn="$torblock_asn" '
'response_time=$request_time '
'upstream_time=$upstream_response_time';
server {
listen 80;
server_name monitored.example.com;
access_log /var/log/nginx/security.log security;
location / {
torblock on;
torblock_action log; # Log but don't block
root /var/www/monitored;
}
location /admin {
torblock on;
torblock_action 403; # Block Tor for admin
# Additional logging for admin access attempts
access_log /var/log/nginx/admin-access.log security;
root /var/www/admin;
}
}
}
Route traffic based on Tor status:
upstream clean_backend {
server backend1.internal:8080;
server backend2.internal:8080;
keepalive 32;
}
upstream tor_backend {
server tor-backend.internal:8080;
keepalive 16;
}
upstream public_backend {
server public1.internal:8080;
server public2.internal:8080;
server public3.internal:8080;
}
http {
torblock on;
server {
listen 80;
server_name loadbalanced.example.com;
location / {
# Route based on Tor status
if ($torblock_status = "blocked") {
proxy_pass http://tor_backend;
}
if ($torblock_status = "clean") {
proxy_pass http://clean_backend;
}
# Default to public backend
proxy_pass http://public_backend;
# Common proxy settings
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Tor-Status $torblock_status;
}
}
}
Implement health checks considering Tor load:
upstream dynamic_backend {
server backend1.internal:8080 max_fails=3 fail_timeout=30s;
server backend2.internal:8080 max_fails=3 fail_timeout=30s;
server backend3.internal:8080 max_fails=2 fail_timeout=60s backup;
}
http {
torblock on;
# Variables for load distribution
map $torblock_status $backend_weight {
blocked tor_backend;
clean clean_backend;
default dynamic_backend;
}
server {
listen 80;
server_name adaptive.example.com;
location / {
# Health check endpoint
location /health {
access_log off;
return 200 "OK\n";
add_header Content-Type text/plain;
}
# Adaptive routing
proxy_pass http://$backend_weight;
# Tor-aware headers
proxy_set_header X-Tor-Exit-Node $torblock_exit_node;
proxy_set_header X-Tor-Country $torblock_country;
# Timeouts based on Tor status
if ($torblock_status = "blocked") {
proxy_read_timeout 60s;
proxy_connect_timeout 30s;
}
if ($torblock_status = "clean") {
proxy_read_timeout 30s;
proxy_connect_timeout 10s;
}
}
}
}
Export metrics for monitoring:
http {
torblock on;
# Metrics collection
log_format metrics 'torblock_requests_total{status="$torblock_status"} 1 $msec';
server {
listen 80;
server_name app.example.com;
# Metrics endpoint
location /metrics {
access_log /var/log/nginx/metrics.log metrics;
# Internal metrics
return 200 'torblock_cache_size $torblock_cache_size
torblock_cache_hits $torblock_cache_hits
torblock_cache_misses $torblock_cache_misses
torblock_blocked_requests $torblock_blocked_total
torblock_allowed_requests $torblock_allowed_total
';
add_header Content-Type text/plain;
}
location / {
# Application with Tor tracking
access_log /var/log/nginx/app.log combined;
access_log /var/log/nginx/metrics.log metrics;
torblock on;
root /var/www/app;
}
}
}
Configure real-time alerts:
http {
torblock on;
# Alert thresholds
map $torblock_status $alert_level {
blocked warning;
clean info;
default notice;
}
server {
listen 80;
server_name critical.example.com;
location / {
# High-value endpoint with alerting
if ($torblock_status = "blocked") {
# Log security event
access_log /var/log/nginx/security-alerts.log
'$remote_addr [$time_local] SECURITY_ALERT: '
'Tor access attempt to critical resource '
'"$request" from exit_node="$torblock_exit_node"';
# Return with alert header
add_header X-Security-Alert "tor-access-detected" always;
return 403 "Access denied: Security policy violation";
}
root /var/www/critical;
}
}
}
Test configuration with automation:
http {
torblock on;
server {
listen 80;
server_name test.example.com;
# Test endpoint for validation
location /test/tor-detection {
access_log off;
add_header Content-Type application/json always;
return 200 '{
"client_ip": "$remote_addr",
"tor_status": "$torblock_status",
"exit_node": "$torblock_exit_node",
"country": "$torblock_country",
"asn": "$torblock_asn",
"cache_status": "$torblock_cache_status",
"timestamp": "$time_iso8601"
}';
}
location / {
torblock on;
root /var/www/test;
}
}
}
Configuration for load testing:
http {
torblock on;
torblock_cache_size 100m; # Large cache for testing
torblock_update_interval 300000; # 5 minutes for testing
# Performance logging
log_format perf '$remote_addr [$time_local] '
'"$request" $status $request_time '
'tor_lookup_time=$torblock_lookup_time '
'cache_status=$torblock_cache_status';
server {
listen 80;
server_name perf-test.example.com;
access_log /var/log/nginx/performance.log perf;
location / {
torblock on;
# Minimal processing for performance testing
return 200 "OK";
add_header Content-Type text/plain;
}
}
}
Enable detailed debugging:
error_log /var/log/nginx/debug.log debug;
http {
torblock on;
torblock_debug on;
server {
listen 80;
server_name debug.example.com;
location / {
# Comprehensive debug headers
add_header X-Debug-Tor-Status $torblock_status always;
add_header X-Debug-Cache-Status $torblock_cache_status always;
add_header X-Debug-Lookup-Time $torblock_lookup_time always;
add_header X-Debug-Exit-Node $torblock_exit_node always;
torblock on;
root /var/www/debug;
}
}
}
Systematic validation approach:
#!/bin/bash
# Advanced configuration validation script
echo "=== Nginx Torblock Configuration Validation ==="
# Test basic syntax
echo "1. Testing basic syntax..."
nginx -t
# Test module loading
echo "2. Validating module loading..."
nginx -T | grep -q "load_module.*torblock" && echo "✓ Module loaded" || echo "✗ Module not loaded"
# Test torblock directives
echo "3. Checking torblock directives..."
nginx -T | grep -q "torblock on" && echo "✓ Torblock enabled" || echo "✗ Torblock not enabled"
# Test cache configuration
echo "4. Validating cache settings..."
nginx -T | grep -q "torblock_cache_size" && echo "✓ Cache configured" || echo "✗ Cache not configured"
# Test variables availability
echo "5. Testing variable access..."
curl -s -H "Host: test.example.com" http://localhost/test/tor-detection | jq .
echo "=== Validation Complete ==="
After mastering advanced configuration:
- Mixed Policies: Explore Mixed Policies for complex rule combinations
- Development: See Development Setup for custom modifications
- Building: Check Building from Source for compilation details
- Troubleshooting: Review Troubleshooting Guide for issue resolution