DEV Community

Pratik Nalawade
Pratik Nalawade

Posted on • Updated on

Automating Security Audits and Server Hardening on Linux Servers with Bash Scripting

Introduction

In the world of IT and DevOps, security is paramount. Ensuring that Linux servers are secure from vulnerabilities, properly configured, and compliant with industry standards is crucial. This blog explores a Bash script I developed to automate security audits and server hardening on Linux servers, providing a modular, reusable solution that can be easily deployed across multiple environments.

Project Overview

The task was to create a comprehensive Bash script that not only audits security settings on a Linux server but also implements necessary hardening measures. This script aims to identify and address common security vulnerabilities, manage user and group permissions, enforce strict file and directory permissions, monitor services, and ensure that the server’s network configuration adheres to best practices.

Key Components

1. User and Group Audits

Objective: The goal here is to ensure that only authorized users have access to the server, and that their permissions are appropriate.

Code:

# List all users and groups on the server
echo "Listing all users:"
cut -d: -f1 /etc/passwd

echo "Listing all groups:"
cut -d: -f1 /etc/group

# Check for users with UID 0 (root privileges)
echo "Checking for non-standard users with UID 0:"
awk -F: '($3 == "0") {print}' /etc/passwd

# Check for users without passwords
echo "Checking for users without passwords:"
awk -F: '($2 == "") {print $1}' /etc/shadow
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script lists all users and groups by extracting them from /etc/passwd and /etc/group.
  • It identifies users with UID 0 (root privileges) to ensure no unauthorized users have root access.
  • The script also checks for users without passwords by inspecting the /etc/shadow file.

2. File and Directory Permissions

Objective: Ensure that sensitive files and directories are not accessible by unauthorized users.

Code:

# Scan for world-writable files and directories
echo "Scanning for world-writable files and directories:"
find / -xdev -type d -perm -0002 -exec ls -ld {} \;

# Check for .ssh directories with secure permissions
echo "Checking .ssh directories permissions:"
find /home -type d -name ".ssh" -exec chmod 700 {} \;

# Report SUID/SGID files
echo "Checking for SUID/SGID files:"
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f -exec ls -ld {} \;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script scans the entire file system for world-writable files and directories using the find command, which could pose a security risk.
  • It ensures .ssh directories are secure by setting their permissions to 700.
  • The script also identifies files with SUID/SGID bits set, which could allow unauthorized users to execute files with elevated privileges.

3. Service Audits

Objective: Ensure that only necessary and authorized services are running, and that they are configured securely.

Code:

# List all running services
echo "Listing all running services:"
systemctl list-units --type=service --state=running

# Check for unnecessary services
echo "Checking for unnecessary services:"
UNNECESSARY_SERVICES=(avahi-daemon cups)
for SERVICE in "${UNNECESSARY_SERVICES[@]}"; do
  systemctl is-active --quiet $SERVICE && echo "$SERVICE is running, consider disabling."
done

# Ensure critical services are running
echo "Checking critical services:"
CRITICAL_SERVICES=(sshd iptables)
for SERVICE in "${CRITICAL_SERVICES[@]}"; do
  systemctl is-active --quiet $SERVICE || echo "$SERVICE is not running!"
done
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script lists all running services using systemctl and checks for any unnecessary ones.
  • It verifies that critical services like sshd and iptables are running, ensuring that the server’s basic security mechanisms are in place.

4. Firewall and Network Security

Objective: Verify that the server’s firewall is configured correctly and that there are no insecure network settings.

Code:

# Verify if the firewall is active
echo "Checking if firewall is active:"
ufw status | grep -qw "active" || echo "Firewall is not active!"

# Report open ports and services
echo "Listing open ports:"
netstat -tuln

# Check for IP forwarding
echo "Checking for IP forwarding:"
sysctl net.ipv4.ip_forward
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script checks if the firewall (ufw) is active and configured properly.
  • It lists all open ports and their associated services using netstat.
  • The script also checks if IP forwarding is enabled, which could expose the server to security risks if not required.

5. IP and Network Configuration Checks

Objective: Ensure that the server’s IP addresses are properly configured and identified as public or private.

Code:

# List all IP addresses and classify them
echo "Listing all IP addresses:"
ip -o addr show | awk '{print $2, $4}'

# Identify public vs private IPs
echo "Identifying public vs private IP addresses:"
ip -o -4 addr list | awk '{print $4}' | while read IP; do
  if [[ $IP =~ ^10\.|^172\.16|^192\.168 ]]; then
    echo "$IP is private."
  else
    echo "$IP is public."
  fi
done
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script lists all IP addresses assigned to the server using the ip command.
  • It then classifies each IP address as public or private, providing a clear understanding of the server’s network exposure.

6. Security Updates and Patching

Objective: Ensure the server is up-to-date with the latest security patches.

Code:

# Check for available updates
echo "Checking for available updates:"
apt-get update -qq
apt-get upgrade -s | grep -i "security"

# Ensure automatic security updates are enabled
echo "Ensuring automatic security updates are enabled:"
dpkg-reconfigure --priority=low unattended-upgrades
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script checks for available security updates using apt-get.
  • It ensures that automatic security updates are enabled, reducing the risk of the server being compromised due to outdated software.

7. Log Monitoring

Objective: Detect any suspicious activity that could indicate a security breach.

Code:

# Check for suspicious log entries
echo "Checking for suspicious log entries:"
grep "Failed password" /var/log/auth.log | tail -10
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script searches the authentication log (/var/log/auth.log) for failed login attempts, which could indicate brute-force attacks or unauthorized access attempts.

8. Server Hardening Steps

Objective: Implement security best practices to harden the server.

Code:

# Disable root login via SSH
echo "Disabling root login via SSH:"
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl reload sshd

# Disable IPv6 if not required
echo "Disabling IPv6:"
echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
sysctl -p

# Secure GRUB with a password
echo "Securing GRUB with a password:"
grub2-mkpasswd-pbkdf2
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script disables root login via SSH to prevent unauthorized access.
  • It disables IPv6 if not required, reducing the server’s attack surface.
  • The script also secures the GRUB bootloader with a password to prevent unauthorized changes to boot parameters.

9. Custom Security Checks

Objective: Allow customization of the script to meet specific security policies.

Code:

# Example custom check: Ensure no files have '777' permissions
echo "Checking for files with 777 permissions:"
find / -type f -perm 0777 -exec ls -l {} \;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The script includes an example of a custom security check, ensuring that no files have overly permissive 777 permissions.
  • This modular design allows users to easily add or modify security checks according to their organization’s policies.

10. Reporting and Alerting

Objective: Provide a comprehensive summary report and optional alerts for critical issues.

Code:

# Generate summary report
REPORT="/var/log/security_audit_report.txt"
echo "Generating security audit report..."
{
  echo "Security Audit Report"
  date
  echo "---------------------------------"
  echo "User and Group Audits:"
  # Include results of user and group audits
  echo "File and Directory Permissions:"
  # Include results of permission checks
  echo "Service Audits:"
  # Include results of service audits
  echo "Firewall and Network Security:"
  # Include results of firewall and network checks
  echo "IP and Network Configuration:"
  # Include results of IP checks
} > $REPORT

# Send email alert if critical issues found
echo "Sending email alert if necessary..."
# Example: Send an alert if a critical issue is found
grep "CRITICAL" $REPORT && mail -s "Security Audit Alert" admin@example.com < $REPORT
Enter fullscreen mode Exit fullscreen mode

**

Explanation**:

  • The script generates a structured summary report that includes the results of all security checks and hardening steps.
  • If any critical issues are detected, the script can send an email alert to the administrator.

Challenges and Solutions

Dependency Management

One of the initial challenges was ensuring that all necessary tools and dependencies were installed on the server. For example, tools like netstat for network monitoring and chkrootkit for rootkit detection had to be installed manually if not already present. To resolve this, the script checks for required packages and installs them as needed.

Permission Issues

Running the script without appropriate permissions led to errors, particularly when modifying system files or changing configurations. This was resolved by running the script with sudo, ensuring that it had the necessary privileges to execute all commands.

Modular Design

Creating a modular script that could be easily extended or customized was another challenge. To achieve this, each audit or hardening step was encapsulated in its function, allowing for independent execution and easy updates. This approach made the script more maintainable and adaptable to different server environments.

Public vs. Private IP Identification

Identifying public versus private IP addresses required careful handling of the server’s network interfaces. By leveraging ip commands and regular expressions, the script accurately categorized each IP address and provided a clear summary in the final report.

Reporting and Alerting

Generating a comprehensive and readable report was essential for ensuring that the security audit results were actionable. The script formats the output into a structured report, with critical findings highlighted. Additionally, integrating email alerts for critical issues ensures that administrators are promptly notified of any urgent vulnerabilities.

How to Use the Script

Prerequisites

  • Ensure that your server is running a Linux distribution (e.g., Ubuntu, CentOS).
  • Install necessary packages like net-tools, chkrootkit, ufw, and unattended-upgrades.
  • Clone the script from the GitHub repository and give it executable permissions using chmod +x.

Running the Script

  1. Full Audit and Hardening: To run the full audit and hardening process, simply execute the script with sudo privileges:
   sudo ./security_audit_hardening.sh
Enter fullscreen mode Exit fullscreen mode
  1. Custom Checks: If you wish to run specific checks or hardening steps, modify the script’s configuration file to enable or disable particular modules.

  2. Reviewing Reports: After execution, the script will generate a summary report in the specified output directory. Review this report for any vulnerabilities or issues that require attention.

  3. Email Alerts: If configured, email alerts will be sent automatically for any critical findings.

Conclusion

This Bash script offers a powerful, automated solution for conducting security audits and hardening Linux servers. By addressing common vulnerabilities, enforcing strict security measures, and providing detailed reporting, it helps ensure that your servers remain secure and compliant with industry standards.

Check out the complete script and documentation on my GitHub![https://github.com/PRATIKNALAWADE/Audit-ServerHardening]

Top comments (0)