info('Starting the firewall cycle command...'); // Get the logs $filename = $this->argument('filename'); $this->info('Reading logs from file: ' . $filename); if(empty($filename)){ $filename = 'full'; } $filePath = '/var/log/asterisk/' . $filename; if (!file_exists($filePath)) { $this->error('Log file does not exist: ' . $filePath); return 1; } // Initialize IP address count array $ipCount = []; // Open the log file and process it line by line $this->info('Extracting and counting IP addresses from logs...'); $handle = fopen($filePath, 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { // Extract IP addresses from the current line if it contains a failed login attempt if (strpos($line, 'Failed to authenticate') !== false) { preg_match('/for \'([0-9\.]+):[0-9]+\'/', $line, $matches); if (isset($matches[1])) { $ip = $matches[1]; if (isset($ipCount[$ip])) { $ipCount[$ip]++; } else { $ipCount[$ip] = 1; } } } } fclose($handle); } else { $this->error('Unable to open log file: ' . $filePath); return 1; } // Block the IP addresses that have too many failed login attempts $this->info('Blocking IP addresses with too many failed login attempts...'); foreach ($ipCount as $ip => $count) { if ($count > 5) { $this->info('Blocking IP: ' . $ip . ' with ' . $count . ' failed attempts.'); if($ip == '0.0.0.0'){ continue; } shell_exec('iptables -A INPUT -s ' . $ip . ' -j DROP'); } } $file_name = 'ips-'.date('Y-m-d_H-i-s').'.json'; $this->info('Saving IP addresses to '.$file_name.' JSON file...'); $ipCount_encoded = json_encode($ipCount); file_put_contents('/var/log/asterisk/'.$file_name, $ipCount_encoded); $this->info('Firewall cycle command completed.'); return 0; } }