Update block-ip.php

This commit is contained in:
SubleXBle
2025-07-28 11:06:06 +02:00
committed by GitHub
parent 3ef43ce756
commit 278aef5e75
+25 -40
View File
@@ -2,7 +2,7 @@
// includes/block-ip.php
/**
* Blocks an IP address using iptables and logs the action into blocklist.json
* Blocks an IP address by adding it to blocklist.json (no iptables calls).
*
* @param string $ip The IP address to block.
* @param string $jail The fail2ban jail or context (optional).
@@ -18,45 +18,10 @@ function blockIp($ip, $jail = 'unknown', $source = 'manual') {
];
}
// Check if IP is already blocked (optional enhancement)
// system("iptables -C INPUT -s $ip -j DROP 2>/dev/null", $alreadyBlocked);
// if ($alreadyBlocked === 0) {
// return [
// 'success' => true,
// 'message' => "IP $ip is already blocked."
// ];
// }
// Run iptables command
// Secure IP as Shell-Argument
$ipEscaped = escapeshellarg($ip);
// Path to IPTABLES (could be different on some systems)
$cmd = "sudo /usr/sbin/iptables -A INPUT -s $ipEscaped -j DROP 2>&1";
$output = [];
$exitCode = 0;
exec($cmd, $output, $exitCode);
if ($exitCode !== 0) {
return [
'success' => false,
'message' => "Failed to block IP $ip via iptables. Exit code: $exitCode. Output: " . implode("\n", $output)
];
}
// Prepare JSON archive entry
$entry = [
'ip' => $ip,
'jail' => $jail,
'source' => $source,
'timestamp' => date('c') // ISO 8601 format
];
$jsonFile = __DIR__ . '/archive/blocklist.json';
$data = [];
// Read existing blocklist
if (file_exists($jsonFile)) {
$existing = file_get_contents($jsonFile);
$data = json_decode($existing, true);
@@ -65,7 +30,7 @@ function blockIp($ip, $jail = 'unknown', $source = 'manual') {
}
}
// Avoid duplicates
// Check for existing IP
foreach ($data as $item) {
if ($item['ip'] === $ip) {
return [
@@ -75,11 +40,31 @@ function blockIp($ip, $jail = 'unknown', $source = 'manual') {
}
}
// New block entry with optional fields for future use
$entry = [
'ip' => $ip,
'jail' => $jail,
'source' => $source,
'timestamp' => date('c'), // ISO 8601 format
'expires' => null,
'reason' => '',
'active' => true,
'lastModified' => date('c'),
'tags' => []
];
$data[] = $entry;
file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
// Save updated blocklist
if (file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) === false) {
return [
'success' => false,
'message' => "Failed to write to blocklist.json."
];
}
return [
'success' => true,
'message' => "IP $ip was successfully blocked and logged."
'message' => "IP $ip was successfully added to blocklist.json."
];
}