geoip_shop_manager.py aktualisiert

This commit is contained in:
2025-12-04 17:08:11 +01:00
parent 221737f7ba
commit 5f498edbae

View File

@@ -1,7 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
GeoIP Shop Blocker Manager - Final Fixed Version GeoIP Shop Blocker Manager - DACH Version
2-Component System: PHP blocking + Python watcher (systemd service) 2-Component System: PHP blocking + Python watcher (systemd service)
Blocks all IPs outside Germany, Austria, and Switzerland (DACH region)
""" """
import os import os
@@ -17,7 +18,7 @@ from pathlib import Path
VHOSTS_DIR = "/var/www/vhosts" VHOSTS_DIR = "/var/www/vhosts"
BACKUP_SUFFIX = ".geoip_backup" BACKUP_SUFFIX = ".geoip_backup"
BLOCKING_FILE = "geoip_blocking.php" BLOCKING_FILE = "geoip_blocking.php"
CACHE_FILE = "de_ip_ranges.cache" CACHE_FILE = "dach_ip_ranges.cache"
LOG_FILE = "geoip_blocked.log" LOG_FILE = "geoip_blocked.log"
CROWDSEC_QUEUE_FILE = "geoip_crowdsec_queue.log" CROWDSEC_QUEUE_FILE = "geoip_crowdsec_queue.log"
WATCHER_SCRIPT = "/usr/local/bin/geoip_crowdsec_watcher.py" WATCHER_SCRIPT = "/usr/local/bin/geoip_crowdsec_watcher.py"
@@ -27,7 +28,8 @@ ACTIVE_SHOPS_FILE = "/var/lib/crowdsec/geoip_active_shops.json"
# PHP GeoIP blocking script (no exec, just logging) # PHP GeoIP blocking script (no exec, just logging)
GEOIP_SCRIPT = '''<?php GEOIP_SCRIPT = '''<?php
/** /**
* GeoIP Blocking Script - Blocks all non-German IPs * GeoIP Blocking Script - Blocks all non-DACH IPs
* DACH = Germany (DE), Austria (AT), Switzerland (CH)
* Logs blocked IPs for CrowdSec watcher to process * Logs blocked IPs for CrowdSec watcher to process
* Valid until: {expiry_date} * Valid until: {expiry_date}
*/ */
@@ -55,18 +57,22 @@ $cache_duration = 86400; // 24 hours
$log_file = __DIR__ . '/{log_file}'; $log_file = __DIR__ . '/{log_file}';
$crowdsec_queue = __DIR__ . '/{crowdsec_queue}'; $crowdsec_queue = __DIR__ . '/{crowdsec_queue}';
// Function to download German IP ranges // Function to download DACH IP ranges (Germany, Austria, Switzerland)
function download_de_ranges() {{ function download_dach_ranges() {{
$ranges = []; $ranges = [];
$url = 'https://www.ipdeny.com/ipblocks/data/aggregated/de-aggregated.zone'; $countries = ['de', 'at', 'ch']; // Germany, Austria, Switzerland
$content = @file_get_contents($url);
if ($content !== false) {{ foreach ($countries as $country) {{
$lines = explode("\\n", trim($content)); $url = "https://www.ipdeny.com/ipblocks/data/aggregated/$country-aggregated.zone";
foreach ($lines as $line) {{ $content = @file_get_contents($url);
$line = trim($line);
if (!empty($line) && strpos($line, '/') !== false) {{ if ($content !== false) {{
$ranges[] = $line; $lines = explode("\\n", trim($content));
foreach ($lines as $line) {{
$line = trim($line);
if (!empty($line) && strpos($line, '/') !== false) {{
$ranges[] = $line;
}}
}} }}
}} }}
}} }}
@@ -84,27 +90,27 @@ function ip_in_range($ip, $cidr) {{
}} }}
// Load or download IP ranges // Load or download IP ranges
$de_ranges = []; $dach_ranges = [];
if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_duration) {{ if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_duration) {{
$de_ranges = unserialize(file_get_contents($cache_file)); $dach_ranges = unserialize(file_get_contents($cache_file));
}} else {{ }} else {{
$de_ranges = download_de_ranges(); $dach_ranges = download_dach_ranges();
if (!empty($de_ranges)) {{ if (!empty($dach_ranges)) {{
@file_put_contents($cache_file, serialize($de_ranges)); @file_put_contents($cache_file, serialize($dach_ranges));
}} }}
}} }}
// Check if visitor IP is from Germany // Check if visitor IP is from DACH region
$is_german = false; $is_dach = false;
foreach ($de_ranges as $range) {{ foreach ($dach_ranges as $range) {{
if (ip_in_range($visitor_ip, $range)) {{ if (ip_in_range($visitor_ip, $range)) {{
$is_german = true; $is_dach = true;
break; break;
}} }}
}} }}
// Block non-German IPs // Block non-DACH IPs
if (!$is_german) {{ if (!$is_dach) {{
$timestamp = date('Y-m-d H:i:s'); $timestamp = date('Y-m-d H:i:s');
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'; $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$request_uri = $_SERVER['REQUEST_URI'] ?? '/'; $request_uri = $_SERVER['REQUEST_URI'] ?? '/';
@@ -168,7 +174,7 @@ def add_to_crowdsec(ip, shop):
'--ip', ip, '--ip', ip,
'--duration', '72h', '--duration', '72h',
'--type', 'ban', '--type', 'ban',
'--reason', f'GeoIP: Non-DE IP blocked by {shop}' '--reason', f'GeoIP: Non-DACH IP blocked by {shop}'
] ]
try: try:
@@ -228,7 +234,7 @@ def process_queue_file(shop_path, shop):
return processed return processed
def main(): def main():
log("🚀 GeoIP CrowdSec Watcher started") log("🚀 GeoIP CrowdSec Watcher started (DACH mode)")
while True: while True:
try: try:
@@ -264,7 +270,7 @@ if __name__ == "__main__":
# Systemd service file # Systemd service file
SYSTEMD_SERVICE_CONTENT = '''[Unit] SYSTEMD_SERVICE_CONTENT = '''[Unit]
Description=GeoIP CrowdSec Watcher Service Description=GeoIP CrowdSec Watcher Service (DACH)
After=network.target crowdsec.service After=network.target crowdsec.service
Wants=crowdsec.service Wants=crowdsec.service
@@ -459,7 +465,8 @@ def activate_blocking(shop):
print(f"❌ index.php nicht gefunden") print(f"❌ index.php nicht gefunden")
return False return False
print(f"\n🔧 Aktiviere Hybrid GeoIP-Blocking für: {shop}") print(f"\n🔧 Aktiviere DACH GeoIP-Blocking für: {shop}")
print(" (Erlaubt: Deutschland, Österreich, Schweiz)")
print("=" * 60) print("=" * 60)
# Step 1: Install watcher service if not exists # Step 1: Install watcher service if not exists
@@ -520,7 +527,8 @@ def activate_blocking(shop):
print(" ✅ Shop registriert") print(" ✅ Shop registriert")
print("\n" + "=" * 60) print("\n" + "=" * 60)
print(f"Hybrid GeoIP-Blocking aktiviert für: {shop}") print(f"DACH GeoIP-Blocking aktiviert für: {shop}")
print(f" Erlaubte Länder: 🇩🇪 DE | 🇦🇹 AT | 🇨🇭 CH")
print(f" Gültig bis: {expiry.strftime('%Y-%m-%d %H:%M:%S CET')}") print(f" Gültig bis: {expiry.strftime('%Y-%m-%d %H:%M:%S CET')}")
print(f" PHP-Log: {os.path.join(httpdocs, LOG_FILE)}") print(f" PHP-Log: {os.path.join(httpdocs, LOG_FILE)}")
print(f" CrowdSec-Queue: {os.path.join(httpdocs, CROWDSEC_QUEUE_FILE)}") print(f" CrowdSec-Queue: {os.path.join(httpdocs, CROWDSEC_QUEUE_FILE)}")
@@ -540,7 +548,7 @@ def deactivate_blocking(shop):
log_file = os.path.join(httpdocs, LOG_FILE) log_file = os.path.join(httpdocs, LOG_FILE)
queue_file = os.path.join(httpdocs, CROWDSEC_QUEUE_FILE) queue_file = os.path.join(httpdocs, CROWDSEC_QUEUE_FILE)
print(f"\n🔧 Deaktiviere Hybrid GeoIP-Blocking für: {shop}") print(f"\n🔧 Deaktiviere DACH GeoIP-Blocking für: {shop}")
print("=" * 60) print("=" * 60)
# Step 1: Remove PHP blocking # Step 1: Remove PHP blocking
@@ -582,7 +590,7 @@ def deactivate_blocking(shop):
print(f" Service bleibt aktiv ({len(remaining_shops)} Shop(s) noch aktiv)") print(f" Service bleibt aktiv ({len(remaining_shops)} Shop(s) noch aktiv)")
print("\n" + "=" * 60) print("\n" + "=" * 60)
print(f"Hybrid GeoIP-Blocking deaktiviert für: {shop}") print(f"DACH GeoIP-Blocking deaktiviert für: {shop}")
print("=" * 60) print("=" * 60)
return True return True
@@ -651,7 +659,8 @@ def show_logs(shop):
def main(): def main():
"""Main menu""" """Main menu"""
print("\n" + "=" * 60) print("\n" + "=" * 60)
print(" GeoIP Shop Blocker Manager - Final") print(" GeoIP Shop Blocker Manager - DACH Version")
print(" Erlaubt: 🇩🇪 Deutschland | 🇦🇹 Österreich | 🇨🇭 Schweiz")
print(" PHP + CrowdSec Watcher (systemd service)") print(" PHP + CrowdSec Watcher (systemd service)")
print("=" * 60) print("=" * 60)
@@ -694,7 +703,7 @@ def main():
shop_idx = int(shop_choice) - 1 shop_idx = int(shop_choice) - 1
if 0 <= shop_idx < len(available_shops): if 0 <= shop_idx < len(available_shops):
selected_shop = available_shops[shop_idx] selected_shop = available_shops[shop_idx]
confirm = input(f"\n⚠️ Aktivieren für '{selected_shop}'? (ja/nein): ").strip().lower() confirm = input(f"\n⚠️ DACH-Blocking aktivieren für '{selected_shop}'? (ja/nein): ").strip().lower()
if confirm in ['ja', 'j', 'yes', 'y']: if confirm in ['ja', 'j', 'yes', 'y']:
activate_blocking(selected_shop) activate_blocking(selected_shop)
else: else:
@@ -749,7 +758,7 @@ def main():
active_shops = get_active_shops() active_shops = get_active_shops()
print(f"\n📊 Status:") print(f"\n📊 Status:")
print(f" Shops gesamt: {len(shops)}") print(f" Shops gesamt: {len(shops)}")
print(f" Aktive Blockings: {len(active_shops)}") print(f" Aktive DACH-Blockings: {len(active_shops)}")
if active_shops: if active_shops:
for shop in active_shops: for shop in active_shops:
print(f"{shop}") print(f"{shop}")