Write a python program which exhaustively assesses the user's Linux box and identifies…
- User
Write a python program which exhaustively assesses the user's Linux box and identifies the most likely risks
- Assistant
Creating a comprehensive Python script to assess a Linux system for potential security risks involves checking various aspects such as installed packages, running services, open ports, firewall status, user privileges, and more. Below is a Python script that performs several of these checks. Please note that some of these operations may require elevated permissions (
sudo) to execute successfully.Important: Running scripts with elevated privileges can be risky. Ensure you understand the code and its implications before executing it on your system.
#!/usr/bin/env python3 import os import subprocess import socket import sys import pwd from datetime import datetime def run_command(command): """Run a shell command and return its output.""" try: result = subprocess.run(command, shell=True, text=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return result.stdout.strip() except subprocess.CalledProcessError as e: return f"Error: {e.stderr.strip()}" def check_os_info(): print("=== OS Information ===") print(run_command("uname -a")) print() def check_kernel_version(): print("=== Kernel Version ===") print(run_command("uname -r")) print() def check_upgradable_packages(): print("=== Upgradable Packages ===") upgradable = run_command("apt list --upgradable 2>/dev/null || yum check-update 2>/dev/null") if "Error:" not in upgradable and upgradable: print(upgradable) else: print("No upgradable packages found or unable to check.") print() def check_installed_packages(): print("=== Installed Packages ===") packages = run_command("dpkg -l 2>/dev/null || rpm -qa 2>/dev/null") if "Error:" not in packages and packages: print(f"Total installed packages: {len(packages.splitlines())}") else: print("Unable to retrieve installed packages.") print() def check_running_services(): print("=== Running Services ===") services = run_command("systemctl list-units --type=service --state=running") print(services) print() def check_enabled_services(): print("=== Enabled Services ===") enabled = run_command("systemctl list-unit-files --type=service | grep enabled") print(enabled) print() def check_open_ports(): print("=== Open Ports ===") try: for port in range(1, 1025): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: result = s.connect_ex(('localhost', port)) if result == 0: service = run_command(f"lsof -i :{port} -sTCP:LISTEN -P -n | grep LISTEN") print(f"Port {port}: Open - {service}") except Exception as e: print(f"Error checking open ports: {e}") print() def check_firewall_status(): print("=== Firewall Status ===") status = run_command("ufw status || firewall-cmd --state") print(status) print() def check_sudo_users(): print("=== Users with Sudo Privileges ===") sudo_users = run_command("grep -Po '^sudo.+:\K.*$' /etc/group") print(sudo_users if sudo_users else "No sudo users found or unable to check.") print() def check_root_login_allowed(): print("=== SSH Root Login Allowed ===") ssh_config = "/etc/ssh/sshd_config" if os.path.exists(ssh_config): with open(ssh_config, 'r') as f: for line in f: if line.strip().startswith("PermitRootLogin"): print(line.strip()) break else: print("PermitRootLogin not explicitly set.") else: print("SSH configuration file not found.") print() def check_password_strength(): print("=== User Password Strength ===") # This is a placeholder. Checking password strength programmatically is non-trivial. print("This check requires integration with PAM or password auditing tools.") print() def check_login_attempts(): print("=== Failed Login Attempts ===") log = run_command("grep 'Failed password' /var/log/auth.log || grep 'authentication failure' /var/log/secure") print(log if log else "No failed login attempts found or unable to access logs.") print() def check_disk_usage(): print("=== Disk Usage ===") disk = run_command("df -h") print(disk) print() def check_memory_usage(): print("=== Memory Usage ===") mem = run_command("free -h") print(mem) print() def check_recent_logs(): print("=== Recent System Logs ===") logs = run_command("journalctl -p warning -n 20") print(logs if logs else "No recent warnings or unable to access logs.") print() def generate_report(): report_filename = f"security_audit_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" with open(report_filename, 'w') as report: original_stdout = sys.stdout sys.stdout = report perform_checks() sys.stdout = original_stdout print(f"Report generated: {report_filename}") def perform_checks(): check_os_info() check_kernel_version() check_upgradable_packages() check_installed_packages() check_running_services() check_enabled_services() check_open_ports() check_firewall_status() check_sudo_users() check_root_login_allowed() check_password_strength() check_login_attempts() check_disk_usage() check_memory_usage() check_recent_logs() def main(): print("Linux Security Audit Tool") print("=========================\n") perform_checks() generate_choice = input("Do you want to generate a report file? (y/n): ").lower() if generate_choice == 'y': generate_report() if __name__ == "__main__": if os.geteuid() != 0: print("It's recommended to run this script with sudo for comprehensive results.") main()Features of the Script
-
OS Information & Kernel Version: Retrieves and displays basic information about the operating system and kernel version.
-
Package Management:
- Upgradable Packages: Checks for any packages that can be upgraded.
- Installed Packages: Lists the number of installed packages.
-
Services:
- Running Services: Displays currently running services.
- Enabled Services: Lists services that are enabled to start on boot.
-
Network:
- Open Ports: Scans ports 1-1024 to identify open ports and the services listening on them.
- Firewall Status: Checks the status of the firewall (supports
ufwandfirewalld).
-
User Privileges:
- Sudo Users: Identifies users with sudo privileges.
- SSH Root Login: Checks if root login is permitted over SSH.
-
Security Logs:
- Failed Login Attempts: Parses authentication logs for failed login attempts.
- Recent System Logs: Retrieves recent warnings and higher priority logs.
-
System Resources:
- Disk Usage: Shows disk usage statistics.
- Memory Usage: Displays memory usage.
-
Password Strength: Placeholder for password strength checks. Implementing this securely would require integration with PAM or specialized auditing tools.
-
Report Generation: Option to generate a timestamped report of the audit.
Usage Instructions
-
Save the Script: Save the script to a file, for example,
linux_security_audit.py. -
Make the Script Executable:
chmod +x linux_security_audit.py -
Run the Script: It's recommended to run the script with
sudoto ensure all checks have the necessary permissions.sudo ./linux_security_audit.py -
Follow Prompts: After displaying the audit results, you'll be prompted to generate a report file. Enter
yto generate and save the report.
Notes and Recommendations
-
Enhancements:
- Password Strength: Integrate with tools like
pwscoreor check password policies defined in PAM. - Vulnerability Scanning: Incorporate checks for known vulnerabilities in installed packages using tools like
lynisorOpenVAS. - File Integrity: Implement file integrity checks using tools like
AIDEorTripwire. - Log Monitoring: Use more advanced log analysis for better insights.
- Password Strength: Integrate with tools like
-
Permissions: Ensure the script is run with appropriate permissions to access system files and logs. Running as a non-root user may limit the information retrieved.
-
Existing Tools: While this script provides a foundational audit, consider using established security auditing tools for more comprehensive analysis:
- Lynis: https://cisofy.com/lynis/
- OpenVAS: https://www.openvas.org/
- Chkrootkit: http://www.chkrootkit.org/
-
Security Considerations: Always handle audit reports securely, as they contain sensitive information about your system's configuration and potential vulnerabilities.
Disclaimer
This script is provided for educational purposes and as a starting point for system security assessments. It is not a substitute for professional security audits. Always ensure you understand the operations performed by any script and tailor it to your specific security requirements.
-