Skip to content

xclusivecyberdev/Automated-Linux-Hardening-Script

Repository files navigation

Linux System Hardening Automation Script

A comprehensive, production-ready Linux system hardening automation script that applies CIS benchmarks, disables insecure services, configures firewall rules, audits system security, and generates detailed compliance reports.

Features

🔒 CIS Benchmark Implementation

  • Filesystem hardening (disable unused filesystems, set sticky bits)
  • Access control configuration (AIDE installation, bootloader protection)
  • System settings hardening (ASLR, core dumps, kernel parameters)
  • User account and password policies
  • Network hardening (disable IP forwarding, source routing, enable SYN cookies)
  • Logging and auditing (auditd, rsyslog configuration)

🛡️ Service Management

  • Automatic detection and disabling of insecure services:
    • Legacy services (telnet, rsh, rlogin, tftp, etc.)
    • Unnecessary network protocols (DCCP, SCTP, RDS, TIPC)
    • Optional: Bluetooth, USB storage
  • xinetd service management
  • Service file permission auditing

🔥 Firewall Configuration

Supports multiple firewall systems with automatic detection:

  • UFW (Uncomplicated Firewall) - Ubuntu/Debian
  • firewalld - RHEL/CentOS/Fedora
  • iptables - Universal fallback

Features:

  • Default deny policy for incoming traffic
  • Configurable port allowlisting
  • SSH rate limiting protection
  • SYN flood protection
  • Port scan detection and blocking
  • Attack mitigation rules

🔍 Comprehensive System Audit

  • System information collection
  • User and authentication auditing
    • Root privilege checks
    • Empty password detection
    • Password aging policy validation
    • SSH configuration analysis
    • sudo configuration review
  • Filesystem security audit
    • World-writable files detection
    • Unowned files discovery
    • SUID/SGID binary enumeration
    • Home directory permission checks
  • Network security audit
    • Open port scanning
    • Promiscuous mode detection
    • IPv6 configuration review
  • Process auditing
  • Package update checking
  • Security tools inventory

📊 Compliance Reporting

Generate professional compliance reports in multiple formats:

  • HTML - Interactive, filterable reports with visual compliance scoring
  • JSON - Machine-readable format for automation
  • Text - Plain text for email or command-line viewing

Requirements

Supported Operating Systems

  • Ubuntu 18.04+
  • Debian 9+
  • CentOS 7+
  • RHEL 7+
  • Fedora 30+
  • Other systemd-based Linux distributions

Dependencies

  • bash 4.0+
  • jq (for JSON processing)
  • systemd
  • Root/sudo access

Optional:

  • aide or tripwire (file integrity monitoring)
  • auditd (system auditing)
  • ufw, firewalld, or iptables (firewall)

Installation

Quick Install

# Clone the repository
git clone https://github.com/yourusername/Automated-Linux-Hardening-Script.git
cd Automated-Linux-Hardening-Script

# Make the script executable
chmod +x linux-hardening.sh

# Install jq if not already installed
# Ubuntu/Debian:
sudo apt-get install -y jq

# RHEL/CentOS:
sudo yum install -y jq

# Fedora:
sudo dnf install -y jq

Usage

Basic Usage

Run the script with root privileges:

# Full hardening with all features (recommended)
sudo ./linux-hardening.sh --all

# Audit only (no changes made)
sudo ./linux-hardening.sh --audit-only --report html

# Dry run (preview changes without applying)
sudo ./linux-hardening.sh --dry-run --all

Command-Line Options

Usage: ./linux-hardening.sh [OPTIONS]

OPTIONS:
    -a, --audit-only        Run audit only without making changes
    -h, --harden            Apply hardening configurations
    -f, --firewall          Configure firewall rules
    -s, --services          Disable insecure services
    -c, --cis               Apply CIS benchmarks
    -r, --report FORMAT     Generate report (html|json|text)
    -A, --all              Run all hardening steps (default)
    --dry-run              Show what would be done without making changes
    --help                 Show this help message

Examples

# Audit system and generate HTML report
sudo ./linux-hardening.sh --audit-only --report html

# Apply CIS benchmarks only
sudo ./linux-hardening.sh --cis

# Configure firewall and disable insecure services
sudo ./linux-hardening.sh --firewall --services

# Full hardening with JSON report
sudo ./linux-hardening.sh --all --report json

# Preview all changes without applying them
sudo ./linux-hardening.sh --dry-run --all

Configuration

Edit config/hardening.conf to customize the script behavior:

# Firewall ports to allow
ALLOWED_TCP_PORTS="22,80,443"
ALLOWED_UDP_PORTS=""

# Security policies
DISABLE_USB_STORAGE="false"
DISABLE_IPV6="false"

# Password policies
MIN_PASSWORD_LENGTH="14"
PASSWORD_MAX_AGE="90"

# And many more options...

Output and Reports

Log Files

All operations are logged to logs/hardening-YYYYMMDD-HHMMSS.log

Results Files

Detailed JSON results are saved to logs/results-YYYYMMDD-HHMMSS.json

Reports

Reports are saved to the reports/ directory:

  • HTML: compliance-report-YYYYMMDD-HHMMSS.html
  • JSON: compliance-report-YYYYMMDD-HHMMSS.json
  • Text: compliance-report-YYYYMMDD-HHMMSS.txt

Sample Output

╔═══════════════════════════════════════════════════════════════════╗
║                                                                   ║
║     Linux System Hardening Automation Script                     ║
║     CIS Benchmark Compliance & Security Auditing Tool            ║
║                                                                   ║
╚═══════════════════════════════════════════════════════════════════╝

[INFO] Starting Linux System Hardening
[INFO] Log file: logs/hardening-20250117-120000.log

╔════════════════════════════════════════════════════════════════════╗
║ SYSTEM AUDIT                                                       ║
╚════════════════════════════════════════════════════════════════════╝

[INFO] Running system security audit...
[SUCCESS] System audit completed

╔════════════════════════════════════════════════════════════════════╗
║                         SUMMARY REPORT                            ║
╠════════════════════════════════════════════════════════════════════╣
║  Total Checks:    156                                             ║
║  Passed:          142                                             ║
║  Failed:          8                                               ║
║  Warnings:        6                                               ║
╚════════════════════════════════════════════════════════════════════╝

Compliance Score: 91%

Security Considerations

⚠️ Important Warnings

  1. Always backup your system before running hardening scripts
  2. Test in a non-production environment first
  3. Review the configuration file before running
  4. Keep SSH access - The script preserves SSH access, but review firewall rules
  5. Container environments - Some checks are automatically skipped in containers

What Gets Modified

The script modifies the following:

Files

  • /etc/modprobe.d/* - Disable unused filesystems and protocols
  • /etc/sysctl.conf and /etc/sysctl.d/* - Kernel parameters
  • /etc/security/limits.conf - Resource limits
  • /etc/security/pwquality.conf - Password quality
  • /etc/login.defs - Login policies
  • /etc/audit/rules.d/* - Audit rules
  • Firewall configurations (ufw/firewalld/iptables)

Services

  • Disables insecure/unnecessary services
  • Enables security services (auditd, rsyslog)
  • Configures firewall service

Backups

  • All modified files are backed up with timestamp
  • Backups stored alongside original files with .backup.YYYYMMDD-HHMMSS extension

Compliance Standards

This script implements controls from:

  • CIS Distribution Independent Linux Benchmark v2.0
  • CIS Ubuntu Linux Benchmark
  • CIS Red Hat Enterprise Linux Benchmark
  • NIST Cybersecurity Framework
  • PCI DSS requirements

Architecture

linux-hardening.sh          # Main entry point
├── lib/
│   ├── utils.sh           # Utility functions
│   ├── cis_benchmarks.sh  # CIS benchmark implementations
│   ├── services.sh        # Service management
│   ├── firewall.sh        # Firewall configuration
│   ├── audit.sh           # System auditing
│   └── report.sh          # Report generation
├── config/
│   └── hardening.conf     # Configuration file
├── reports/               # Generated reports
├── logs/                  # Execution logs and results
└── templates/             # Report templates

Troubleshooting

Common Issues

Issue: Script fails with "command not found: jq"

# Solution: Install jq
sudo apt-get install jq  # Ubuntu/Debian
sudo yum install jq      # RHEL/CentOS

Issue: Permission denied

# Solution: Run with sudo/root
sudo ./linux-hardening.sh --all

Issue: Locked out after firewall configuration

# Prevention: The script always allows SSH (port 22)
# Recovery: Access via console and run:
sudo ufw allow 22
sudo ufw reload

Issue: Service won't start after hardening

# Solution: Check logs and adjust configuration
tail -f /var/log/syslog
# Review what was changed in the log file

Development

Adding Custom Checks

  1. Add your check function to the appropriate module in lib/
  2. Use the record_check function to track results:
check_id="CUSTOM-001"
if [[ condition ]]; then
    record_check "$check_id" "Check title" "PASS" "Description" "Remediation"
else
    record_check "$check_id" "Check title" "FAIL" "Description" "Fix instructions"
fi

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new features
  4. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This script makes significant changes to system configuration. While it follows security best practices:

  • Test thoroughly in non-production environments first
  • Review all changes before applying to production systems
  • Understand the implications of each hardening measure
  • Maintain backups of your systems
  • No warranty is provided - use at your own risk

Author

Created as part of the Linux System Hardening Automation project.

Acknowledgments

  • Center for Internet Security (CIS) for the benchmark standards
  • The Linux security community
  • Contributors and testers

Support

For issues, questions, or contributions:

  • Open an issue on GitHub
  • Review the documentation
  • Check existing issues for solutions

Stay Secure! 🔒

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages