Cybersecurity guides, explanations and reader checklists on whilenetworking.com

Student Project: Automating OS Hardening Scripts with Ansible to Enforce CIS Benchmarks on Virtual Machines

Implementing security controls manually across multiple virtual machines (VMs) is prone to human error, inconsistency, and time consumption. For IT students…

Implementing security controls manually across multiple virtual machines (VMs) is prone to human error, inconsistency, and time consumption. For IT students and junior engineers, mastering the automation of Operating System (OS) hardening using Ansible provides a critical bridge between theoretical knowledge and professional practice. This guide outlines a practical project designed to automate the enforcement of CIS Benchmarks on Linux systems. By leveraging Infrastructure as Code (IaC), you can ensure that every server in your lab environment adheres to a consistent, secure baseline without manual intervention.

Understanding the Scope and Prerequisites

Before writing any code, it is essential to understand the components involved. The CIS Benchmarks are publicly available, industry-standard security configurations developed by the Center for Internet Security (CIS). They provide detailed guidance on hardening specific operating systems, such as Ubuntu or RHEL/CentOS.

For this project, you will need:
* A virtualization platform like VirtualBox, VMware Workstation, or a cloud provider account.
* At least two Linux VMs (e.g., Ubuntu 22.04 LTS) to serve as your target hosts.
* One control node with Ansible installed.
* Basic knowledge of Linux command-line interfaces and SSH key management.

Important Note on Safety: Always perform these actions in an isolated lab environment or authorized test beds only. Modifying system configurations incorrectly can lead to service disruption or loss of data. Never apply unverified hardening scripts to production systems without a full backup and change management approval.

Setting Up the Ansible Control Node and Inventory

The first step is preparing your control node, which will act as the brain of your automation network. Ensure you have Ansible installed via your package manager (e.g., pip install ansible or using system repositories).

Next, define your inventory file, typically named hosts.ini. This file maps hostnames to their connection details. Create a file with the following structure:

[webservers]
vm-secure-01 ansible_host=192.168.100.10
vm-secure-02 ansible_host=192.168.100.11

[all:vars]
ansible_user=root
ansible_ssh_private_key_file=~/.ssh/id_rsa_lab
  • What this does: The [webservers] group defines the target machines. The [all:vars] section sets default variables, such as the SSH username and the path to your private key for authentication.
  • Verification: Run ansible -i hosts.ini all -m ping from your control node. You should see a successful connection response from both VMs. If you receive errors regarding keys or hostnames, verify your SSH configuration and firewall rules (allowing port 22).

Creating the CIS Hardening Playbook

The core of this project is the Ansible playbook, which contains a series of tasks to harden the system. We will focus on critical security controls defined in standard CIS benchmarks, such as disabling unnecessary services, setting strict file permissions, and configuring SSH access.

Create a file named cis_hardening.yml. Below is a concrete example of what the code should look like:

---
- name: Enforce CIS Benchmark Hardening on Ubuntu
  hosts: webservers
  become: true
  gather_facts: yes

  tasks:
    - name: Ensure SSH root login is disabled
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^PermitRootLogin"
        line: "PermitRootLogin prohibit-password"
        state: present

    - name: Disable password authentication for SSH
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^PasswordAuthentication"
        line: "PasswordAuthentication no"
        state: present

    - name: Ensure only specific users can login via SSH
      ansible.builtin.user:
        name: "{{ item }}"
        shell: /bin/bash
        append: yes
      loop:
        - admin_user
        - developer

    - name: Restrict file permissions on /etc/shadow
      ansible.builtin.file:
        path: /etc/shadow
        mode: '0400'
        owner: root
        group: shadow

    - name: Disable unused services (example: cups)
      ansible.builtin.service:
        name: cups
        enabled: no
        state: stopped
  • Explanation of Commands:
    • lineinfile: Modifies configuration files by adding or replacing lines. This is safer than blindly overwriting files.
    • user: Ensures only authorized accounts exist and sets their shell to /bin/bash.
    • file: Sets precise permission modes (e.g., 0400 for read-only root access on /etc/shadow).
    • service: Stops and disables background services that are not required, reducing the attack surface.

Executing the Playbook and Verifying Results

Once your playbook is saved, navigate to the directory containing it and execute it using the command line:

ansible-playbook -i hosts.ini cis_hardening.yml

Expected Output:
Upon successful execution, you will see output indicating that each task completed successfully on every host in the inventory. You might see lines like changed: [vm-secure-01] or ok: [vm-secure-02]. The changed status indicates a modification was made, while ok means the state was already correct (idempotency).

Verification Steps:
To confirm the hardening worked as intended, log into your VMs manually using SSH. Check the modified files:
1. Run grep -i "permitrootlogin" /etc/ssh/sshd_config. It should show prohibit-password.
2. Run ls -l /etc/shadow. The permissions should be -r-------- (400).
3. Check service status with systemctl status cups. It should be inactive and disabled.

Common Errors and Troubleshooting

When working with automation scripts, errors are inevitable. Here are common issues students encounter and how to fix them:

  • SSH Connection Refused: This usually means the SSH port is blocked by a firewall or the key file path in your inventory is incorrect. Ensure your virtual network allows traffic on port 22.
  • Privilege Escalation Errors: If you see Error: Could not resolve hostname, check if sudo is configured to allow passwordless execution for specific users, as Ansible uses become: true to switch to root.
  • Module Not Found: Ensure your Ansible version supports the modules used (e.g., ansible.builtin.lineinfile). Older versions might require using community.general or specific collection names.

Industry Application and Student Practice Task

In a real-world scenario, an organization would integrate this playbook into their CI/CD pipeline. When a new VM is provisioned via Terraform or Cloud-init, the hardening script runs automatically before the system goes live. This ensures “security by default.”

Student Practice Task:
To deepen your understanding, modify the playbook to include a task that creates a log rotation policy for /var/log/auth.log. Add a cron job entry that runs an audit script every night to check if any unauthorized users have logged in. Document your changes and explain how you would test this against a simulated intrusion attempt without causing damage to production data.

Insurance Context: Risk Mitigation and Policy Verification

While this article focuses on technical implementation, understanding the insurance implications of hardening is vital for a complete security posture. Cybersecurity insurance policies often require evidence of “reasonable security measures.” Implementing CIS benchmarks via automation can serve as documented proof of due diligence.

Hypothetical Insurance Scenario:
Imagine your organization suffers a ransomware attack because a server was not hardened. The insurer investigates and finds that the system lacked basic SSH restrictions and had known vulnerabilities unpatched. They may deny coverage if they determine you failed to follow industry standards like CIS benchmarks.

Practical Steps for Verification:
1. Document Everything: Keep your Ansible playbooks, version history (using Git), and execution logs. Insurers often request “evidence of control.”
2. Check Policy Terms: Do not assume a policy covers all cyber events. Review your specific policy document for exclusions related to “negligence” or failure to patch systems.
3. Consult Authorities: If unsure about what constitutes “reasonable security,” refer to industry frameworks like NIST SP 800-53 or CIS Benchmarks themselves, which are often cited in insurance underwriting guidelines.

Common Mistake: Assuming that buying cyber insurance automatically covers losses resulting from poor configuration management. Most policies have sub-limits for data breaches and may exclude claims if the organization failed to implement basic hardening controls. Always verify the specific definitions of “cyber incident” and “business interruption” in your contract.

Conclusion

Automating OS hardening with Ansible is a powerful skill that combines defensive security, scripting, and operational efficiency. By following the steps outlined above—setting up an inventory, writing idempotent playbooks, and verifying configurations—you can build a secure baseline for any virtual environment. Remember that technology alone is not enough; maintaining documentation of these controls is equally important for both incident response and insurance compliance. Start with a small lab project, iterate on your scripts, and gradually scale the automation to larger environments as you gain confidence.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.