OS Hardening

Ubuntu 22.04 LTS Jammy

Actual Process of creating new virtual Machine

  1. Install ubuntu server (minimized) and configure network connections while installation process.

  2. For better OS secuirty, ubuntu 22.04 have some benchmark of recommend partitions to secure the virtual machine, those are Recommended partitions and options

/boot 
/home 
/var/log 
/var/log/audit 
/var/tmp 

These are the mountpoints of the different partitions 3. Don’t install Openssh-Server 4. Install necessary packages: sudo apt-get -y install git net-tools procps --no-install-recommends.

  1. Clone the repository DevOps Automation Scripts in DevOps Model Organisation from Github
git clone https://github.com/DevOps-Model/DevOps-Automation-Scripts.git
  1. GO the folder named Hardening/ where all our hardening files are stored we need to look at the two important files those are

    • ubuntu.cfg
    • ubuntu.sh
    • checkScore.sh
  2. File ubuntu.cfg is the configuration file for hardening process and we need to modify this file before start the actual hardening process

    • FW_ADMIN - The IP addresses that will be able to connect with SSH, separated by spaces.
    • SSH_GRPS - Which group the users have to be member of in order to acess via SSH, separated by spaces.
    • SSH_PORT - Port to use for SSH login
    • CHANGEME - Add some text in this variable to make script know, you have read it
    • ADMINEMAIL - Add a valid email address, so PSAD can send notifications.

    Example Content of ubuntu.cfg file

    FW_ADMIN='127.0.0.1 172.21.4.50 172.21.0.0/16
    SSH_GRPS='sudo devopsadmin'
    SSH_PORT='59222'
    CHANGEME = 'read'
    
  3. Then run the file on the server you are aimed to harden it

    bash ubuntu.sh
    

    In ubuntu.sh file have all functions for hardening process, files in the Hardening folder got utilised and harden the server in every possible way.

    It generally take around 20 minutes to complete the process
    

    After the process Completion, need to check the Score of Hardening which shows how server got security through hardening

Analyse the Hardening

  • To Check the Hardening score of the server, run the file named checkScore.sh and read the ouput line by line
    bash checkScore.sh
    

Analyse the output

      - Checking for system binaries that are required by Debian Tests...
    - Checking /bin...                                        [ FOUND ]
    - Checking /sbin...                                       [ FOUND ]
    - Checking /usr/bin...                                    [ FOUND ]
    - Checking /usr/sbin...                                   [ FOUND ]
    - Checking /usr/local/bin...                              [ FOUND ]
    - Checking /usr/local/sbin...                             [ FOUND ]
  - Authentication:
    - PAM (Pluggable Authentication Modules):

  [WARNING]: Test DEB-0001 had a long execution: 18.894469 seconds

      - libpam-tmpdir                                         [ Installed and Enabled ]
  - File System Checks:
    - DM-Crypt, Cryptsetup & Cryptmount:
      - Checking / on /dev/vda5                               [ NOT ENCRYPTED ]
      - Checking /boot on /dev/vda3                           [ NOT ENCRYPTED ]
      - Checking /opt on /dev/vda6                            [ NOT ENCRYPTED ]
      - Checking /data on /dev/vda4                           [ NOT ENCRYPTED ]
      - Checking /export/vdb on /dev/vdb                      [ NOT ENCRYPTED ]
  - Software:
    - apt-listbugs                                            [ Installed and enabled for apt ]
    - apt-listchanges                                         [ Installed and enabled for apt ]
    - needrestart                                             [ Installed ]
    - fail2ban                                                [ Installed with jail.local ]

Explanation of Debian Tests Report

System Binaries Check
  • Verifies the presence of essential system directories and binaries.
  • Key paths checked: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, and /usr/local/sbin.
  • All were found, confirming the system is equipped with necessary files.
Authentication
  • Evaluates authentication modules.
  • PAM (Pluggable Authentication Modules): Confirms that libpam-tmpdir is installed and active for secure temporary directories.
  • Note: A warning indicates the test for this took 18.822 seconds, which might require investigation.
File System Checks
  • Checks if the file systems on various partitions are encrypted for security.
  • None of the partitions (/, /boot, /opt, /data, /export/vdb) are encrypted. Lack of encryption could be a security vulnerability.
Software Checks
  • Verifies the presence and functionality of key software tools:
    • apt-listbugs: Alerts about critical bugs in packages during updates.
    • apt-listchanges: Displays changelogs for updated packages.
    • needrestart: Identifies services requiring a restart after updates.
    • fail2ban: Provides brute force protection and is properly configured with a jail.local file.
[+] Boot and services
------------------------------------
  - Service Manager                                           [ systemd ]
  - Checking UEFI boot                                        [ DISABLED ]
  - Checking presence GRUB2                                   [ FOUND ]
    - Checking for password protection                        [ NONE ]
  - Check running services (systemctl)                        [ DONE ]
        Result: found 39 running services
  - Check enabled services at boot (systemctl)                [ DONE ]
        Result: found 68 enabled services
  - Check startup files (permissions)                         [ OK ]
  - Running 'systemd-analyze security'
        - auditd.service:                                     [ EXPOSED ]

We do not perform any actions in the section of Boot and Services

Explanation of Boot and Services Report

  • The service manager in use is systemd, responsible for managing services on the system.
  • The UEFI boot mechanism is disabled, indicating that the system relies on legacy BIOS-based booting.
  • The GRUB2 bootloader is present, but it lacks password protection, which could expose the bootloader to unauthorized changes.
  • The system currently has 39 running services as identified by systemctl.
  • A total of 68 services are enabled to start automatically at boot time.
  • Permissions for startup files are configured correctly, indicating no immediate vulnerabilities in this area.
  • The systemd-analyze security tool flagged auditd.service as exposed, suggesting it might need additional security hardening.
[+] Kernel
------------------------------------
  - Checking default run level                                [ RUNLEVEL 5 ]
  - Checking CPU support (NX/PAE)
    CPU support: PAE and/or NoeXecute supported               [ FOUND ]
  - Checking kernel version and release                       [ DONE ]
  - Checking kernel type                                      [ DONE ]
  - Checking loaded kernel modules                            [ DONE ]
      Found 93 active modules
  - Checking Linux kernel configuration file                  [ FOUND ]
  - Checking default I/O kernel scheduler                     [ NOT FOUND ]
  - Checking for available kernel update                      [ OK ]
  - Checking core dumps configuration
    - configuration in systemd conf files                     [ DISABLED ]
    - configuration in etc/profile                            [ DISABLED ]
    - 'hard' configuration in security/limits.conf            [ DISABLED ]
    - 'soft' config in security/limits.conf (implicit)        [ DISABLED ]
    - Checking setuid core dumps configuration                [ DISABLED ]
  - Check if reboot is needed                                 [ NO ]
  • logins and openfiles are mentioned in the file /etc/security/limits.conf.
  • Please make sure if reboot is needed in the above results.
  • Default I/O kernel scheduler is not found, which may need attention.
  • Kernel update status is OK, indicating no urgent need for updates.
  • Core dumps configuration is disabled across systemd, /etc/profile, and security/limits.conf.
[+] Users, Groups and Authentication
------------------------------------
  - Administrator accounts                                    [ OK ]
  - Unique UIDs                                               [ OK ]
  - Consistency of group files (grpck)                        [ OK ]
  - Unique group IDs                                          [ OK ]
  - Unique group names                                        [ OK ]
  - Password file consistency                                 [ OK ]
  - Password hashing methods                                  [ SUGGESTION ]
  - Password hashing rounds (minimum)                         [ CONFIGURED ]
  - Query system users (non daemons)                          [ DONE ]
  - NIS+ authentication support                               [ NOT ENABLED ]
  - NIS authentication support                                [ NOT ENABLED ]
  - Sudoers file(s)                                           [ FOUND ]
    - Permissions for directory: /etc/sudoers.d               [ OK ]
    - Permissions for: /etc/sudoers                           [ OK ]
    - Permissions for: /etc/sudoers.d/015_passwdtimeout       [ OK ]
    - Permissions for: /etc/sudoers.d/016_timestamptimeout    [ OK ]
    - Permissions for: /etc/sudoers.d/013_pwfeedback          [ OK ]
    - Permissions for: /etc/sudoers.d/README                  [ OK ]
    - Permissions for: /etc/sudoers.d/012_logfile             [ OK ]
    - Permissions for: /etc/sudoers.d/014_visiblepw           [ OK ]
  - PAM password strength tools                               [ OK ]
  - PAM configuration files (pam.conf)                        [ FOUND ]
  - PAM configuration files (pam.d)                           [ FOUND ]
  - PAM modules                                               [ FOUND ]
  - LDAP module in PAM                                        [ NOT FOUND ]
  - Accounts without expire date                              [ SUGGESTION ]
  - Accounts without password                                 [ OK ]
  - Locked accounts                                           [ FOUND ]
  - User password aging (minimum)                             [ CONFIGURED ]
  - User password aging (maximum)                             [ CONFIGURED ]
  - Checking expired passwords                                [ FOUND ]
  - Checking Linux single user mode authentication            [ OK ]
  - Determining default umask
    - umask (/etc/profile and /etc/profile.d)                 [ OK ]
    - umask (/etc/login.defs)                                 [ OK ]
  - LDAP authentication support                               [ NOT ENABLED ]
  - Logging failed login attempts                              [ENABLED]
  • Password hashing methods need improvement; current configuration is functional but suboptimal.
  • Password aging policies are configured for both minimum and maximum durations.
  • PAM (Pluggable Authentication Module) configurations, files, and modules are present and operational, but LDAP integration is not enabled.
  • Sudoers files and directory permissions are correctly set and secure.
  • USB storage driver and device authorization are disabled for security.
  • USBGuard configuration blocks unauthorized USB devices effectively.
  • DNS search domains and /etc/resolv.conf options are correctly configured; duplicate entries in /etc/hosts require cleanup.
  • Hostname mapping to localhost is missing in /etc/hosts.
  • Package managers, including dpkg, are functional, with security repositories and package audits in place.
  • Vulnerable packages are not found; unattended upgrades are enabled.
Need to Work Frequently
  • If Vulnerable Packages are found, try running apt upgrade and check the score.
  • Try mapping all hostnames to one ip like
ps-in-demo1a-node01 ps-in-pxc1a-node01 ps-in-ms1a-node01 172.21.0.94
[+] USB Devices
------------------------------------
  - Checking usb-storage driver (modprobe config)             [ DISABLED ]
  - Checking USB devices authorization                        [ DISABLED ]
  - Checking USBGuard                                         [ FOUND ]
    - Configuration                                           [ FOUND ]
      - Restore controller device state                       [ false ]
      - Rule for controllers connected before daemon starts   [ block ]
      - Rule for devices connected before daemon starts       [ block ]
      - Rule for devices inserted after daemon starts         [ block ]
      - Rule for devices not in RuleFile                      [ block ]
    - RuleFile                                                [ FOUND ]
      - Controllers & Devices allow                           [ 2 ]
      - Controllers & Devices block                           [ 0 ]
      - Controllers & Devices reject   
  • No frequnently works on the above configuration, need to run the hardening enahnce script using ansible controller node.
[+] Name services
------------------------------------
  - Checking search domains                                   [ FOUND ]
  - Checking /etc/resolv.conf options                         [ FOUND ]
  - Searching DNS domain name                                 [ UNKNOWN ]
  - Checking /etc/hosts
    - Duplicate entries in hosts file                         [ FOUND ]
    - Presence of configured hostname in /etc/hosts           [ FOUND ]
    - Hostname mapped to localhost                            [ NOT FOUND ]
    - Localhost mapping to IP address     
  • Ensure proper configuration of search domains for DNS resolution.
  • Maintain correct DNS options in the /etc/resolv.conf file.
  • Investigate the absence of the DNS domain name to verify proper setup.
  • Remove duplicate entries from the /etc/hosts file to avoid conflicts.
  • Verify the system hostname is correctly mapped in the /etc/hosts file.
  • Add a mapping for the hostname to 127.0.0.1 if it is missing.
  • Confirm localhost is mapped to 127.0.0.1 and [::1] in /etc/hosts.
[+] Ports and packages
------------------------------------
  - Searching package managers
    - Searching dpkg package manager                          [ FOUND ]
      - Querying package manager
    - Query unpurged packages                                 [ FOUND ]
    - debsums utility                                         [ FOUND ]
      - Cron job for debsums                                  [ FOUND ]
  - Checking security repository in sources.list file         [ OK ]
  - Checking APT package database                             [ OK ]
  - Checking vulnerable packages                              [ OK ]

  [WARNING]: Test PKGS-7392 had a long execution: 32.358770 seconds

  - Checking upgradeable packages                             [ SKIPPED ]
  - Checking package audit tool                               [ INSTALLED ]
    Found: apt-check
  - Toolkit for automatic upgrades (unattended-upgrade)       [ FOUND ]
  • Ensure the package manager (dpkg) is installed and functioning correctly.
  • Regularly clean up unpurged packages to free up space and maintain system hygiene.
  • Use the debsums utility and its cron job to verify package integrity periodically.
  • Confirm that security repositories are correctly configured in the sources.list file for secure package updates.
  • Keep the APT package database up-to-date to prevent dependency or update issues.
  • Regularly check for and address vulnerable packages to maintain system security.
  • Manually verify upgradeable packages if automated checks are skipped.
  • Use package audit tools (e.g., apt-check) to monitor package health and vulnerabilities.
  • Configure and enable automatic upgrades (unattended-upgrade) to apply critical updates without manual intervention.
  • Run apt upgrade if vulnerable packages are found.
[+] Networking
------------------------------------
  - Checking IPv6 configuration                               [ ENABLED ]
      Configuration method                                    [ MANUAL ]
      IPv6 only                                               [ NO ]
  - Checking configured nameservers
    - Testing nameservers
        Nameserver: 127.0.0.53                                [ OK ]
        Nameserver: 1.1.1.1                                   [ OK ]
    - DNSSEC supported (systemd-resolved)                     [ YES ]
  - Checking default gateway                                  [ DONE ]
  - Getting listening ports (TCP/UDP)                         [ DONE ]
  - Checking promiscuous interfaces                           [ OK ]
  - Checking waiting connections                              [ OK ]
  - Checking status DHCP client                               [ NOT ACTIVE ]
  - Checking for ARP monitoring software                      [ NOT FOUND ]
  - Uncommon network protocols                                [ NOT FOUND ]
  • Ensure IPv6 is configured correctly, either in manual or automatic mode, depending on the network requirements.
  • Ensure the default gateway is configured correctly for proper network routing.
  • Regularly check listening ports for TCP/UDP to monitor network activity and security.
  • Monitor waiting connections to detect any potential issues with network performance or unauthorized access.
  • Decide whether to enable the DHCP client or configure static IPs based on the network setup.
[+] SSH Support
------------------------------------
  - Checking running SSH daemon                               [ FOUND ]
    - Searching SSH configuration                             [ FOUND ]
    - OpenSSH option: AllowTcpForwarding                      [ OK ]
    - OpenSSH option: ClientAliveCountMax                     [ OK ]
    - OpenSSH option: ClientAliveInterval                     [ OK ]
    - OpenSSH option: Compression                             [ OK ]
    - OpenSSH option: FingerprintHash                         [ OK ]
    - OpenSSH option: GatewayPorts                            [ OK ]
    - OpenSSH option: IgnoreRhosts                            [ OK ]
    - OpenSSH option: LoginGraceTime                          [ OK ]
    - OpenSSH option: LogLevel                                [ OK ]
    - OpenSSH option: MaxAuthTries                            [ OK ]
    - OpenSSH option: MaxSessions                             [ OK ]
    - OpenSSH option: PermitRootLogin                         [ SUGGESTION ]
    - OpenSSH option: PermitUserEnvironment                   [ OK ]
    - OpenSSH option: PermitTunnel                            [ OK ]
    - OpenSSH option: Port                                    [ OK ]
    - OpenSSH option: PrintLastLog                            [ OK ]
    - OpenSSH option: StrictModes                             [ OK ]
    - OpenSSH option: TCPKeepAlive                            [ OK ]
    - OpenSSH option: UseDNS                                  [ OK ]
    - OpenSSH option: X11Forwarding                           [ OK ]
    - OpenSSH option: AllowAgentForwarding                    [ OK ]
    - OpenSSH option: AllowUsers                              [ FOUND ]
    - OpenSSH option: AllowGroups                             [ FOUND ]

This is the main part that contributes more to the hardening score.

  • Ensure the SSH daemon is running and properly configured to allow secure remote access.
  • Review and configure SSH options to ensure optimal security, including settings for AllowTcpForwarding, ClientAliveCountMax, ClientAliveInterval, Compression, FingerprintHash, GatewayPorts, IgnoreRhosts, LoginGraceTime, LogLevel, MaxAuthTries, MaxSessions, PermitUserEnvironment, PermitTunnel, Port, PrintLastLog, StrictModes, TCPKeepAlive, UseDNS, and X11Forwarding.
  • Disable or restrict PermitRootLogin to prevent root-level access via SSH, which could be a security risk.
  • Use AllowUsers and AllowGroups to specify which users and groups are authorized for SSH access, enforcing the principle of least privilege.
  • Regularly audit SSH configurations to ensure that insecure settings are not enabled, and sensitive information is protected.
[+] Logging and files
------------------------------------
  - Checking for a running log daemon                         [ OK ]
    - Checking Syslog-NG status                               [ NOT FOUND ]
    - Checking systemd journal status                         [ FOUND ]
    - Checking Metalog status                                 [ NOT FOUND ]
    - Checking RSyslog status                                 [ FOUND ]
    - Checking RFC 3195 daemon status                         [ NOT FOUND ]
    - Checking minilogd instances                             [ NOT FOUND ]
  - Checking logrotate presence                               [ OK ]
  - Checking remote logging                                   [ NOT ENABLED ]
  - Checking log directories (static list)                    [ DONE ]
  - Checking open log files                                   [ DONE ]
  - Checking deleted files in use                             [ FILES FOUND ]
  • A log daemon is running on the system, ensuring logging functionality.
  • Syslog-NG and Metalog services are not found, but the system uses systemd journal and RSyslog for logging.
  • RFC 3195 and minilogd daemons are not found, indicating they are not used.
  • Logrotate is installed, ensuring proper log rotation and management.
  • Remote logging is not enabled, suggesting that logs are not being forwarded to external systems.
  • Log directories and open log files have been verified successfully.
  • Deleted files in use have been found, which may require further investigation to ensure proper file handling.
[+] Cryptography
------------------------------------
  - Checking for expired SSL certificates [0/152]             [ NONE ]

  [WARNING]: Test CRYP-7902 had a long execution: 35.088716 seconds

  - Found 0 encrypted and 1 unencrypted swap devices in use.  [ OK ]
  - Kernel entropy is sufficient                              [ YES ]
  - HW RNG & rngd                                             [ NO ]
  - SW prng                                                   [ YES ]
  - MOR variable not found                                    [ WEAK ]
  • Run apt install rng-tools to install random number generator tool to increase the score.
  • A log daemon is running on the system, ensuring logging functionality.
  • Logrotate is installed, ensuring proper log rotation and management.
  • Remote logging is not enabled, suggesting that logs are not being forwarded to external systems.
  • Log directories and open log files have been verified successfully.
  • Deleted files in use have been found, which may require further investigation to ensure proper file handling.
[+] Security frameworks
------------------------------------
  - Checking presence AppArmor                                [ FOUND ]
    - Checking AppArmor status                                [ ENABLED ]
        Found 67 unconfined processes
  - Checking presence SELinux                                 [ NOT FOUND ]
  - Checking presence TOMOYO Linux                            [ FOUND ]
    - Checking TOMOYO Linux status                            [ DISABLED ]
  - Checking presence grsecurity                              [ NOT FOUND ]
  - Checking for implemented MAC framework                    [ OK ]
  • Ensure that security frameworks like AppArmor are installed and properly configured to protect the system from unauthorized access and privilege escalation.
  • Keep AppArmor enabled, but regularly audit the list of unconfined processes (67 unconfined processes in this case) and confine them as necessary.
  • Consider enabling SELinux(if redhat systems) for additional security, as it provides robust mandatory access control (MAC) mechanisms.
  • If TOMOYO Linux is being used, ensure it is properly configured and enabled, but note that it is currently disabled in this setup.
  • Consider using grsecurity for enhanced security if required, although it is not found in this configuration.
  • Ensure that at least one MAC framework is implemented, as verified by the system’s current configuration.
[+] Software: file integrity
------------------------------------
  - Checking file integrity tools
    - AIDE                                                    [ FOUND ]
      - AIDE config file                                      [ FOUND ]
      - AIDE database                                         [ FOUND ]
  - dm-integrity (status)                                     [ DISABLED ]
  - dm-verity (status)                                        [ DISABLED ]
      - AIDE config (Checksum)                                [ OK ]
  - Checking presence integrity tool                          [ FOUND ]
  • Verify AIDE is running on your system systemctl status aide.service which is Advanced Intrusion Detection System.
  • The file integrity tool AIDE is installed and configured, with both its config file and database found.
  • dm-integrity is not enabled, which could be considered for additional file integrity checks at the block device level.
  • dm-verity is also disabled, which is another option for verifying file integrity at the block device level.
  • The AIDE configuration checksum is verified as OK, indicating that the integrity of configuration files is intact.
  • An additional file integrity tool is present, though not specified in detail.
[+] Software: System tooling
------------------------------------
  - Checking automation tooling
  - Automation tooling                                        [ NOT FOUND ]
  - Checking presence of Fail2ban                             [ FOUND ]
    - Checking Fail2ban jails                                 [ ENABLED ]
  - Checking for IDS/IPS tooling                              [ FOUND ]
  • Consider installing and configuring automation tooling to streamline system management tasks and enhance operational efficiency.
  • Ensure that Fail2ban is installed and properly configured to protect against unauthorized login attempts by enabling and configuring jails.
  • Make sure fail2ban is running systemctl status fail2ban.service
  • Regularly review and update Fail2ban jails to ensure they cover all relevant services and potential attack vectors.
  • Use IDS/IPS tooling to monitor for and prevent malicious activity on the system, ensuring they are correctly implemented and configured for optimal security.
[+] Software: Malware
------------------------------------
  - Checking chkrootkit                                       [ FOUND ]
  - Checking Rootkit Hunter                                   [ FOUND ]
  - Malware software components                               [ FOUND ]
    - Active agent                                            [ NOT FOUND ]
    - Rootkit scanner                                         [ FOUND ]
  • Ensure that rootkit detection tools like chkrootkit and Rootkit Hunter are installed and regularly updated to identify potential rootkits or malware. If not installed, run like apt install chkrootkit
  • Regularly run rootkit scanners to detect any suspicious activity and mitigate the risk of rootkit infections.
  • Monitor for the presence of any active malware agents and take immediate action if any are found.
  • Keep malware software components up to date to ensure protection against the latest threats.

Others

Do not Change the File Permissions, Home Directories and Kernel COnfiguration section.

Check Hardening Score and Factors Impacts on It

To assess the hardening score of a virtual machine (VM) using Lynis, follow these steps:

  1. Locate the Log File:
    The Lynis log file is located at /var/log/lynis.log.

  2. Search for the Hardening Index:

    • Navigate to the end of the file using a text editor or tools like tail.
    • Look for a line similar to the following:
      2024-12-27 00:20:14 Hardening index : [88] [#################   ]
      
    • Alternatively, use the grep command to search for the hardening index:
      grep -iR 'Hardening index :' /var/log/lynis.log
      
  3. Review Test Details:

    • Check the preceding lines in the same log file for details about specific tests and results. Example:
      2024-12-27 00:20:13 ====
      2024-12-27 00:20:13 Performing test ID HRDN-7220 (Check if one or more compilers are installed)
      2024-12-27 00:20:13 Test: Check if one or more compilers can be found on the system
      2024-12-27 00:20:13 Result: found installed compiler. See top of logfile which compilers have been found or use /usr/bin/grep to filter on 'compiler'
      2024-12-27 00:20:14 Hardening: assigned partial number of hardening points (1 of 3). Currently having 318 points (out of 361)
      
  4. Interpreting the Results:

    • The hardening index should ideally be 90 or above. If the score is below this threshold, investigate specific tests in the log file to identify areas for improvement.
    • Compare the total points and assigned points in the log to understand where improvements can be made.

For a hardening score below 90, prioritize resolving the issues flagged in the log file to enhance system security.

Parition Recommendations for Strict Hardening

Here are the recommended partitions and options for strict hardening:

  1. /boot

    • Purpose: Contains the boot loader and kernel files.
    • Recommendation: Keep it separate to prevent accidental modification or tampering of critical boot files.
    • Options: Mount with noexec, nosuid, and nodev to prevent execution, suid scripts, and device file usage.
  2. /home

    • Purpose: Stores user data and configuration files.
    • Recommendation: Isolate user files to prevent direct access from critical system areas.
    • Options: Use noexec, nosuid, and nodev to restrict execution, suid scripts, and device files in user directories.
  3. /var/log

    • Purpose: Stores system and application log files.
    • Recommendation: Keep logs in a separate partition for better security and management. Ensure logs are not tampered with.
    • Options: Mount with noexec, nosuid, and nodev to prevent execution, suid scripts, and device files. Use log2syslog for logging critical logs.
  4. /var/log/audit

    • Purpose: Stores audit logs that track security-related events.
    • Recommendation: Isolate audit logs for easier monitoring and management. These logs are crucial for security audits.
    • Options: Ensure that the partition is mounted with noexec, nosuid, and nodev. Make sure logs are stored securely and regularly reviewed.
  5. /var/tmp

    • Purpose: Temporary files used by applications, especially those requiring persistence across reboots.
    • Recommendation: Separate it from the root filesystem to prevent misuse of the system’s temporary storage space.
    • Options: Mount with noexec, nosuid, nodev, and tmpfs (for ephemeral storage). This ensures temporary files cannot execute or contain devices.

By isolating these partitions and applying the correct mounting options, you can significantly improve system hardening and prevent misuse of the file system.

Enhancing the Hardening Score with Ansible Playbook.

In today’s environment, security is paramount, and hardening your systems is an essential part of maintaining a secure infrastructure. One effective way to enhance security is through automation, and using tools like Ansible can simplify the process. Below is a simple guide to running Ansible playbooks that will apply security hardening enhancements and boost your system’s security score.

Step 1: Ensure Connectivity with Target Hosts

Before applying any hardening configurations, we need to ensure that the Ansible master node can communicate with the target machines. This is done by modifying the hosts file and running a simple ping test.

  1. Modify the Hosts File:
    On the Ansible master node (IP: 172.21.0.81), edit the /etc/ansible/hosts file to include the target machines where you will apply the hardening playbooks. The hosts file should look like this:

    [targets]
    172.21.0.82
    172.21.0.83
    
  2. Ping the Target Machines:
    Use Ansible’s ping module to ensure the master node can communicate with the target systems:

    ansible -m ping all
    

    If everything is set up correctly, you should see a “pong” response from each target machine:

    172.21.0.82 | SUCCESS | rc=0 >> {
        "ping": "pong"
    }
    172.21.0.83 | SUCCESS | rc=0 >> {
        "ping": "pong"
    }
    
Step 2: Run the Hardening Playbook

Once connectivity is confirmed, the next step is to run the hardening enhancement playbook to apply security hardening configurations.

  1. Run the Playbook:
    On the Ansible master node, execute the following command to apply the hardening configurations:

    ansible-playbook /path/to/your/repository/Devops_Automation_Scripts/hardening/ansible/playbooks/hardening_enhancement.yml
    
  2. Monitor Task Execution:
    Ansible will start applying the tasks in the playbook. Check that all tasks run successfully. If any task fails, it will be displayed in the output, and you will need to review and resolve any issues. An example of a successful output:

    TASK [Check security settings] ***
    ok: [172.21.0.82]
    ok: [172.21.0.83]
    
    TASK [Apply hardening rules] ***
    changed: [172.21.0.82]
    changed: [172.21.0.83]
    
    TASK [Verify hardening score] ***
    ok: [172.21.0.82] => (item=hardening_score) => {
        "msg": "Score 93"
    }
    
Step 3: Verify the Hardening Score

After the playbook has finished running, you should verify the system’s hardening score. The goal is to reach a score of 93 or more.

If the score is below the desired threshold, you may need to investigate the playbook output for any missed hardening tasks or configurations.

Post Problems of Hardening

Post Problems of Hardening: AppArmor and PSAD Issues

After applying system hardening configurations, certain issues related to AppArmor and PSAD (Port Scan Attack Detector) may arise. Below is a rough guide to address and resolve these issues.

AppArmor Issues

Problem:
AppArmor may block necessary processes and operations due to restrictive profiles, leading to failures in processes like MySQL and wsrep services.

Solution:
To resolve this, you need to update the AppArmor configuration to grant the necessary permissions for the affected processes. Follow these steps:

  1. Grant Permissions for MySQL:
    The file path for MySQL in AppArmor configuration is:

    /etc/apparmor.d/usr.sbin.mysqld
    

    Ensure that the MySQL process has read, write, and update permissions to avoid blocking.

  2. Grant Permissions for wsrep Service:
    Similarly, for the wsrep service, the configuration file path is:

    /etc/apparmor.d/usr.bin.wsrep_sst_xtrabackup-v2
    

    You need to ensure proper permissions for read and write access for this service as well.

  3. Grant Permissions for Custom Data Directories:
    If you have custom data directories that need to be accessed by MySQL or wsrep, ensure that read and write permissions are granted for these directories. This can be done by updating the AppArmor profile and adding the following entries for the custom directories:

    /path/to/custom/data/** rw,
    

After making these changes, reload the AppArmor profiles to apply the updates:

sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld
sudo apparmor_parser -r /etc/apparmor.d/usr.bin.wsrep_sst_xtrabackup-v2
sudo systemctl reload apparmor

PSAD Issues

Problem:
PSAD (Port Scan Attack Detector) may block legitimate IP addresses due to false-positive port scan detection, potentially interrupting network traffic or causing security monitoring to flag safe IPs.

Solution:
To allow trusted IPs or networks that are incorrectly flagged as port scanners, follow these steps:

  1. Locate the Configuration File:
    PSAD configuration for allowed IPs can be found in the following file:

    /etc/psad/auto_dl
    
  2. Add IPs to the Whitelist:
    If certain IPs are being incorrectly blocked by PSAD, you can manually add them to the configuration file with a 0 value to indicate “no danger” for those hosts. Add the IP addresses or subnets to this file as shown below:

    172.21.2.152 0;
    172.21.0.45 0;
    172.21.0.0/16 0;
    

    This will tell PSAD that these IPs are not involved in port scanning and should be allowed to communicate.

  3. Configure Scan Detection Behavior:
    PSAD can also be configured to ignore certain types of port scan traffic. To modify this:

    • Remove Specific Port Scans:
      You can remove specific TCP, UDP, or any port scans from being flagged by PSAD.
    • Adjust IP Range Blocking:
      If needed, modify the configuration to allow specific IP ranges to bypass detection, ensuring that legitimate traffic from these ranges is not blocked.

After updating the configuration, restart the PSAD service to apply the changes:

sudo systemctl restart psad