Skip to content
ImagineWorld

Hardening Your Servers Using Ansible

node_idnode-book_learn-ansible_chapter-14-hardening-your-servers-using-ansible
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleHardening Your Servers Using Ansible
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Hardening Your Servers Using Ansible

Section titled “Chapter 14 — Hardening Your Servers Using Ansible”

One of the advantages of using an orchestration and configuration tool such as Ansible is that it can be utilized to generate and deploy a complex set of configurations in a repeatable task across many hosts. In this chapter, we will look at a tool that scans your hosts using Ansible, dynamically generates a remediation playbook, and then runs it for you.

We will also look at running two different security tools that scan the WordPress installation we have used throughout the previous chapters.

This chapter covers the following topics:

  • The scanning tools
  • The playbook

Following our excursion into the cloud, we will return to our local machine and launch an Ubuntu 22.04 virtual machine using Multipass; as we will be running a workload that requires a bit more disk space than we have been used to so far, we will be altering the specs of the virtual machine when we launch it to increase the disk space and RAM.

As we will be installing a lot of different software on the virtual machine, your Multipass virtual machine will need to be able to download packages from the internet; there will be around 3 GB of various packages and configuration files to download.

You can find a complete copy of the playbook accompanying this chapter in the repository at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter14.

Before we dive into the Playbook, let’s quickly look at the three tools we will be running, starting with the one that does the most, OpenSCAP.

First, we will be looking at one of Red Hat’s tools, called OpenSCAP. Before we continue, the next section will contain many abbreviations.

So, what is SCAP? The Security Content Automation Protocol (SCAP) is an open standard that encompasses several components, all of which are open standards themselves, to build a framework that allows you to automatically assess and remediate your hosts against the National Institute of Standards and Technology (NIST) Special Publication 800-53.

This publication is a catalog of controls applied to all U.S. federal IT systems, apart from those maintained by the National Security Agency (NSA). These controls have been effected to help implement the Federal Information Security Management Act (FISMA) of 2002 across U.S. federal departments.

SCAP is made up of the following components:

  • Asset Identification (AID) is a data model used for asset identification.
  • Asset Reporting Format (ARF) is a vendor-neutral and technology-agnostic data model for transporting information on assets between different reporting applications and services.
  • Common Configuration Enumeration (CCE) is a standard database of recommended configurations for common software. Each recommendation has a unique identifier. At the time of writing, the database hadn’t been updated for over a decade.
  • Common Configuration Scoring System (CCSS) is the continuation of CCE. It is used for generating a score for various software and hardware configurations across all types of deployments.
  • Common Platform Enumeration (CPE) identifies hardware assets, operating systems, and software in an organization’s infrastructure. Once identified, this data can then be used to search other databases to threat-assess the asset.
  • Common Weakness Enumeration (CWE) is a common language for dealing with and discussing the causes of weaknesses in system architecture, design, and code that may lead to vulnerabilities.
  • Common Vulnerabilities and Exposures (CVE) is a database of publicly acknowledged vulnerabilities. Most system administrators and IT professionals will have encountered the CVE database at some point. Each vulnerability receives a unique ID; for example, most people will know CVE-2014-0160, also known as Heartbleed. The Heartbleed vulnerability was a severe security flaw in OpenSSL (a cryptographic software library) that allowed attackers to steal sensitive information, such as passwords and private keys, from the memory of affected systems by exploiting a bug in the OpenSSL’s implementation of the transport layer security (TLS)/ datagram transport layer security (DTLS) heartbeat extension.
  • Common Vulnerability Scoring System (CVSS) is a method that helps capture the characteristics of a vulnerability to produce a normalized numerical score, which can then be used to describe the impact of a vulnerability, for example, low, medium, high, and critical.
  • Extensible Configuration Checklist Description Format (XCCDF) is an XML format for describing security checklists. It can also be used for configuration and benchmarks and provides a common language for all the parts of SCAP.
  • Open Checklist Interactive Language (OCIL) is a framework for expressing questions to an end user and the procedures to process the responses in a standardized way.
  • Open Vulnerability and Assessment Language (OVAL) is defined in XML and aims to standardize the transfer of security content across all of the tools and services offered by NIST, the MITRE Corporation, the United States Computer Emergency Readiness Team (US-CERT), and the United States Department of Homeland Security (DHS).
  • Trust Model for Security Automation Data (TMSAD) is an XML document that aims to define a common trust model that can be applied to the data being exchanged by all components that make up SCAP.

As you can imagine, thousands of man-years have gone into producing SCAP and its components to make its foundation. Some of the projects have been around in one form or another since the mid-90s, so they are well-established and considered the de facto standard when it comes to security best practices; however, I am sure you think that it all sounds very complicated – after all, these are standards that have been defined and are being maintained by scholars, security professionals, and government departments.

This is where OpenSCAP comes in. The OpenSCAP project, maintained by Red Hat and certified by NIST for supporting the SCAP standard, allows you to apply all the best practices we have discussed using a command-line client.

Note

The automatic remediation scripts in OpenSCAP are a work in progress, and there are known issues that we will address toward the end of the chapter. Because of this, your output may differ from that covered in this chapter.

OpenSCAP, like many Red Hat projects, has support for Ansible, and the current release introduces support for automatically generating Ansible playbooks to remediate non-conformance discovered during an OpenSCAP scan.

The next two tools we will be looking at will be scanning our WordPress site, starting with WPScan.

The second tool we will be running is called WPScan and we will use it to scan our WordPress site. WPScan is a command-line tool that can perform various security assessments and vulnerability tests on WordPress installations. It can detect common configuration errors, outdated themes, weak passwords, and other potential risks. WPScan is easy to install – especially as we will be using the container version and running it using Docker, which we will also be going for the third and final tool, OWASP ZAP.

Web vulnerabilities such as SQL injection, cross-site scripting, broken authentication, and insecure deserialization can threaten our WordPress site’s security and quality. To help identify and prioritize such vulnerabilities, we can use OWASP ZAP. This tool, the third and final one we will cover in the chapter, generates reports, alerts, and graphs that assist us in visualizing and addressing the findings. Moreover, OWASP ZAP is user-friendly and easy to install, making it a valuable resource for enhancing our site’s security and overall quality.

We will split the playbook into a few different roles to run the various scanning tools that will be running in the chapter – as you can see from the site.yml file, we are adding some conditions to the roles containing our tasks. The start of the file looks like all of the other playbook files we have been running:

- name: "Scan our WordPress Ansible Playbook and stack"
hosts: ansible_hosts
gather_facts: true
become: true
become_method: "ansible.builtin.sudo"
vars_files:
- 'group_vars/common.yml'

As mentioned, roles are where this playbook starts to differ from the previous playbooks we have been running up to this point in the book.

As you can see from the following source, we are defining tags alongside the roles themselves:

roles:
- { role: 'common', tags: ['openscap','scan'] }
- { role: 'docker', tags: ['docker','scan'] }

As you can see, we are using the openscap, scan, and docker tags followed by wordpress, which used the roles directly from Chapter 5, Deploying WordPress:

- { role: 'stack_install', tags: ['wordpress'] }
- { role: 'stack_config', tags: ['wordpress'] }
- { role: 'wordpress', tags: ['wordpress'] }

Finally, we have roles that run scans and openscap:

- { role: 'scan', tags: ['scan'] }
- { role: 'openscap', tags: ['openscap'] }

So, what does this mean? Well, later in the chapter, when it comes to running the playbook, we will only be running specific roles; for example, to run OpenSCAP, we will use the following commands:

$ ansible-playbook -i hosts site.yml --tags "openscap" --extra-vars "scap_options_remediation=true"
$ ansible-playbook -i hosts site.yml --tags "openscap"

When running the first command, it will run just the common and openscap roles and run the remediation Ansible Playbook and bash script, both of which will be automatically generated during the initial scan – it will also download a copy of the results, an implementation guide, a copy of the playbook, and a copy of the bash scripts.

The second of the two commands will rerun the scan host and download a copy of the results again.

Once we have finished running OpenSCAP, we will then redeploy our host and run the following:

$ ansible-playbook -i hosts site.yml --tags "wordpress"

This, as I am sure you will have guessed, will run the three wordpress roles. Then, with WordPress installed, we can run the following:

$ ansible-playbook -i hosts site.yml --tags "scan"

This will execute the common, docker, and scan roles.

We can also run these commands to run just one of the two scanning tools that the scan role runs:

$ ansible-playbook -i hosts site.yml --tags "scan" --extra-vars "scan_types=zap"
$ ansible-playbook -i hosts site.yml --tags "scan" --extra-vars "scan_types=wpscan"

But we are getting ahead of ourselves; let’s work our way through the preceding roles before we think about running the playbook.

This role contains a single task in roles/common/tasks/main.yml, and its only job is to set a fact containing the current date and time:

- name: "Set a fact for the date"
ansible.builtin.set_fact:
the_date: "{{ lookup('pipe', 'date +%Y-%m-%d-%H%M') }}"

You might think, “That seems a little basic.” However, as we will be using the the_date variable several times throughout the roles in this playbook, we only want it to be generated once as it will be used to create file and folder names that are then called later in tasks.

If we use {{ lookup('pipe', 'date +%Y-%m-%d-%H%M') }} to insert the date dynamically as part of other variables and tasks, we need to be cautious. This is because some parts of the playbook can take several minutes to finish running.

For instance, we may create a file called myfile-2024-02-16-1300.yml at one point in the playbook. However, if we dynamically set the date and time, and several tasks later, it takes five minutes for the playbook to get to that task, we could reference a file called myfile-2024-02-16-1305.yml. This would result in an error as the file does not exist. Therefore, we should only use the date and time lookup once during the playbook run.

This role contains all of the tasks and variables needed to install and configure Docker on our target host, much like the roles discussed in Chapter 4, Deploying a LAMP Stack, and Chapter 5, Deploying WordPress; this role uses the ansible.builtin.apt, ansible.builtin.apt_key, and ansible.builtin.apt_repository modules to do the following:

  1. Download and install the prerequisites required for Docker to run.
  2. Add the GNU Privacy Guard (GPG) key for the official Docker advanced packaging tool (APT) repository.
  3. Configure the official Docker APT repository.
  4. Install Docker itself along with the Docker command-line tool.
  5. Ensure that Docker is running and set to start on boot.

To review the full list of tasks and variables for this role, see the following:

Next, we have the roles that install WordPress.

As you have already seen from the site.yml file at the start of the Playbook section of this chapter, here, we are just reusing the roles that we discussed at length in Chapter 5, Deploying WordPress. If you want to review these, you can see them at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter05/roles.

As already mentioned, we will be using Docker to run WPScan and OWASP ZAP; this allows us to reuse the same tasks. Let’s look at roles/scan/tasks/main.yml; first, we need to pull the Docker image or images:

- name: "Pull the Docker image for the scanning tool"
community.docker.docker_image:
name: "{{ item.image }}"
source: "{{ item.source }}"
loop: "{{ scan }}"
when: "item.name in scan_types"
loop_control:
label: "{{ item.name }}"

We are switching it up slightly in that we are using loop rather than with_items; this gives more control over what happens when looping through. In this task, we are using label to show which of the scanning tools is currently processing.

You may also notice that we have a when condition; this allows us to run both of the scans or just one of the two by passing in the name of the scan in the scan_types variable. When we look at the variables in a moment, you will see that by default, we are passing in the names of both scanning tools.

This pattern of loop, loop_control, and when will be repeated throughout all the tasks in this role. We have a task that will create a folder on the virtual machine; we will be mounting this folder into the container at runtime so that we can keep a copy of the scan output:

- name: "Create the folder which we will mount inside the container"
ansible.builtin.file:
path: "{{ item.log.remote_folder }}"
state: "directory"
mode: "0777"
loop: "{{ scan }}"
when: "item.name in scan_types"
loop_control:
label: "{{ item.name }}"

Now, with the container image and folder created, we can run the scan:

- name: "Run the scan"
community.docker.docker_container:
detach: "{{ item.detach }}"
auto_remove: "{{ item.auto_remove }}"
name: "{{ item.name }}"
volumes: "{{ item.log.remote_folder }}:{{ item.container_folder }}"
image: "{{ item.image }}"
command: "{{ item.command }}"
register: docker_scan
ignore_errors: true
no_log: true
loop: "{{ scan }}"
when: "item.name in scan_types"
loop_control:
label: "{{ item.name }}"

As you can see, everything is being passed to the container as variables; this is how we can run two very different tools with a single common task, and more so later when we look at the variables.

You will have also noted that we are adding a few options to the end of this task; these are as follows:

  • register: Here, we are just registering the output of the task – nothing special here
  • ignore_errors: This tells Ansible to continue running should it detect an error; in our case, the containers we are running will purposely trigger an error code as they have been designed to halt and not proceed with any further tasks until the scan does not fail
  • no_log: This suppresses the output – as we save the output when running the scan, we do not need the output printed to the terminal when we run the task

As we are registering an output, the next task is a debug line. This follows the same pattern as debug tasks in other chapters, so we will be moving to the task that downloads a copy of the reports:

- name: "Download the report"
ansible.builtin.fetch:
src: "{{ item.log.remote_folder }}{{ item.log.file }}"
dest: "{{ item.log.local_folder }}"
flat: true
mode: "0644"
loop: "{{ scan }}"
when: "item.name in scan_types"
loop_control:
label: "{{ item.name }}"

This uses the ansible.builtin.fetch module setting the flat option to true. This option copies the file rather than the full directory path. The final task removes the container, meaning that when we next run a scan, it will start from scratch and spawn a new container rather than reusing the one we have just finished using:

- name: "Remove the scan container"
community.docker.docker_container:
name: "{{ item.name }}"
state: "absent"
loop: "{{ scan }}"
when: "item.name in scan_types"
loop_control:
label: "{{ item.name }}"

Now that we know what the tasks look like, let us look at the variables, which can be found in roles/scan/defaults/main.yml. The first variable sets the scan we want to run, and as already mentioned, this gives the name of the two scans:

scan_types:
- "{{ common_scan_settings.dict.wpscan }}"
- "{{ common_scan_settings.dict.zap }}"

Next up in roles/scan/defaults/main.yml, we have a block of variables that could be commonly used across both scanning tools:

common_scan_settings:
detach: false
auto_remove: false
source: "pull"
local_folder: "output/"
report_name: "{{ the_date }}-results-"
dict:
wpscan: "wpscan"
zap: "zap"

Finally, we have the primary scan variable, which is the one we have been looping over; it starts with WPScan:

scan:
- name: "{{ common_scan_settings.dict.wpscan }}"
image: "wpscanteam/wpscan:latest"
source: "{{ common_scan_settings.source }}"
detach: "{{ common_scan_settings.detach }}"
auto_remove: "{{ common_scan_settings.auto_remove }}"
container_folder: "/tmp/{{ common_scan_settings.dict.wpscan }}/"
command: "--url http://{{ ansible_host }} --enumerate u --plugins-detection mixed --format cli-no-color --output /tmp/{{ common_scan_settings.dict.wpscan }}/{{ common_scan_settings.report_name }}{{ common_scan_settings.dict.wpscan }}.txt"
log:
remote_folder: "/tmp/{{ common_scan_settings.dict.wpscan }}/"
local_folder: "{{ common_scan_settings.local_folder }}"
file: "{{ common_scan_settings.report_name }}{{ common_scan_settings.dict.wpscan }}.txt"

The block that follows is the one for OSWAP ZAP:

- name: "{{ common_scan_settings.dict.zap}}"
image: "ghcr.io/zaproxy/zaproxy:stable"
source: "{{ common_scan_settings.source }}"
detach: "{{ common_scan_settings.detach }}"
auto_remove: "{{ common_scan_settings.auto_remove }}"
container_folder: "/zap/wrk/"
command: "zap-baseline.py -t http://{{ ansible_host }} -g gen.conf -r {{ common_scan_settings.report_name }}{{ common_scan_settings.dict.zap }}.html"
log:
remote_folder: "/tmp/{{ common_scan_settings.dict.zap }}/"
local_folder: "{{ common_scan_settings.local_folder }}"
file: "{{ common_scan_settings.report_name }}{{ common_scan_settings.dict.zap }}.html"

As you can see, we pass in the different container images and commands to run the scan while using the same variables. Because of this, we could keep the tasks used in the role completely neutral, meaning that we didn’t have to consider anything custom to the tool we were running.

That concludes the scan role, leaving us with, as I am sure you will have already guessed from how long the tool explanation was at the start of the chapter, the most complex role in the playbook: OpenSCAP.

When writing a playbook, it is essential to know how the tool you are automating works; given that OpenSCAP is a little complex, let’s review the steps needed to manually run a scan and remediate the problems it finds using an automatically generated Ansible playbook and a shell script.

Note

While the commands to run OpenSCAP follow, you do not need to follow along; these are provided to illustrate the process we need to follow in our Playbook role.

First, we need to download and install OpenSCAP itself, along with a few tools we will also need:

$ sudo apt-get install unzip curl libopenscap8

Next up, we need to download the actual content – these definitions cover several different operating systems and various levels of compliance. The GitHub repository for this content can be found at https://github.com/ComplianceAsCode/content, and at the time of writing, the current release is 0.1.71.

Get the release URL for the zip file, which contains the files we need from the releases page, then download and unzip on the host:

$ wget https://github.com/ComplianceAsCode/content/releases/download/v0.1.71/scap-security-guide-0.1.71.zip
unzip scap-security-guide-0.1.71.zip

Now that we have OpenSCAP and the definition files installed, we can get some information on what is available for our Ubuntu 22.04 operating system:

$ sudo oscap info --fetch-remote-resources scap-security-guide-0.1.71/ssg-ubuntu2204-ds.xml

This will give us the name of the profile we want to use; in our case, it is xccdf_org.ssgproject.content_profile_cis_level1_server. Once we have this, we can run the scan itself:

$ oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis_level1_server --results-arf result.xml --report report.html scap-security-guide-0.1.71/ssg-ubuntu2204-ds.xml

This will generate two output files: an HTML copy of a report containing everything that needs fixing in a nicely digestible format we can read, and a second XML file containing the same information in a format OpenSCAP can read.

We can then take the XML file and generate a more detailed guide on how we could resolve the issues found by running the following:

$ sudo oscap xccdf generate guide --profile xccdf_org.ssgproject.content_profile_cis_level1_server scap-security-guide-0.1.71/ssg-ubuntu2204-ds.xml > guide.html

However, as this book is about Ansible, it would be better to have a Playbook to fix as many of the issues as possible, and running the following command will give us just that:

$ sudo oscap xccdf generate fix --fetch-remote-resources --fix-type ansible --result-id "" result.xml > playbook.yml

Finally, not everything can be resolved using the Playbook method, so having a bash script to fix any issues that can’t be resolved by running the playbook is also a great idea as it will mean less manual work for us to do:

$ sudo oscap xccdf generate fix --fetch-remote-resources --fix-type bash --result-id "" result.xml > bash.sh

Now we have the Playbook and bash script; we need to run them, copy the playbook to our local machine, and run it using the following:

$ ansible-playbook -i hosts --become -become-method=sudo output/ansiblevm-playbook.yml

Then we go back to the virtual machine, and run the bash script using the following:

$ sudo bash bash.sh

You will have seen a lot of output, but if everything goes as planned when you rerun the scan, you should see a lot of issues being reported.

Note

The code in the repo contains the variables and tasks for a feature we will not cover here, as the content we are downloading from GitHub can take up a lot of space on your drive. These tasks are included to remove any unneeded files.

So, now that we have an idea of the steps we need to automate, let’s dive straight in.

First, let’s look at the variables, which can be found in roles/openscap/default/main.yml, and that we will be using within our tasks.

Start with the option that, if set to true, will execute the remediation Playbook and Bash script:

scap_options_remediation: false

Next, we have the packages needed to run OpenSCAP and OpenSCAP itself:

scap_packages:
- "unzip"
- "curl"
- "libopenscap8"

Then we have information to download the content from GitHub; note that we are passing the API URL and not the direct download link (more on why later in the chapter):

openscap_download:
openscap_github_release_api_url: "https://api.github.com/repos/ComplianceAsCode/content/releases/latest"
dest: "/tmp/scap-security-guide"

Now we have a long list of filenames and details on the profile we need to use:

openscap_scan:
ssg_file_name: "{{openscap_download.dest}}/ssg-{{ ansible_facts.distribution | lower }}{{ ansible_facts.distribution_version | replace('.','') }}-ds.xml"
profile_search: "cis_level1_server"
output_dir: "/tmp/"
output_file_xml: "{{ inventory_hostname }}-result.xml"
output_file_html: "{{ inventory_hostname }}-report.html"
output_file_guide: "{{ inventory_hostname }}-guide.html"
output_file_playbook: "{{ inventory_hostname }}-playbook.yml"
output_file_bash: "{{ inventory_hostname }}-bash.sh"
local_output_dir: "output/{{ the_date }}-openscap-results"

Notice that we are trying not to hardcode any values; for example, when referring to the operating system, we use {{ ansible_facts.distribution | lower }}{{ ansible_facts.distribution_version | replace('.','') }}, which, in our case, gives us ubuntu2204. This means that if OpenSCAP supports it, we can run our Playbook on other Ubuntu distributions without making any changes.

The tasks that use these variables can be found in roles/openscap/tasks/main.yml; we begin with two tasks that install OpenSCAP, the first of which makes sure that the APT cache and our operating system are both up to date:

- name: "Update apt cache and upgrade packages"
ansible.builtin.apt:
name: "*"
state: "latest"
update_cache: "yes"

The tasks immediately after installing OpenSCAP itself and the other packages we need:

- name: "Install common packages"
ansible.builtin.apt:
state: "present"
pkg: "{{ scap_packages }}"

Now, we create the directory where we will be storing the OpenSCAP content we will be downloading from GitHub:

- name: "Create the directory to store the scap security guide content"
ansible.builtin.file:
path: "{{ openscap_download.dest }}"
state: "directory"
mode: "0755"

With our destination folder in place, we can now download the content and unarchive it:

- name: "Download the latest scap security guide content"
ansible.builtin.unarchive:
src: "{{ lookup('url', '{{ openscap_download.openscap_github_release_api_url }}', split_lines=false) | from_json | json_query('assets[?content_type==\`application/zip\`].browser_download_url') | last }}"
dest: "{{ openscap_download.dest }}"
creates: "{{ openscap_download.dest }}/README.md"
list_files: true
remote_src: true
register: scap_download_result

On the face of it, while it looks a little complicated, there is quite a bit going on; let’s break down how we are getting the value to populate into the src key.

We use Ansible’s lookup plugin to fetch and process data from the GitHub API, giving us the latest release information for the OpenSCAP Content GitHub repository:

  • {{ lookup('url', '{{ openscap_download.openscap_github_release_api_url }}', split_lines=false) }}: The lookup plugin is being used here with the url lookup type, which fetches data from the given URL that is specified by the openscap_download.openscap_github_release_api_url variable, which points to the API endpoint for the latest release of a GitHub repository (https://api.github.com/repos/ComplianceAsCode/content/releases/latest). The split_lines=false parameter ensures that the fetched content is not split into lines, preserving its JSON structure.
  • | from_json: This part of the code takes the output from the lookup plugin, which is expected to be a JSON string, and converts it into an Ansible data structure (such as a dictionary or a list) that can be further processed.
  • | json_query('assets[?content_type==`application/zip`].browser_download_url'): This uses the json_query filter with a JMESPath expression to query the converted JSON data. The 'assets[?content_type==`application/zip`].browser_download_url' query looks for items in the assets array where content_type is application/zip, and then extracts browser_download_url. This URL is typically used to directly download the asset from a browser.
  • | last: Finally, the last filter is used to get the last URL from the list of URLs returned by the json_query filter. We are doing this as there might be multiple assets with the application/zip content type, but we are only interested in the most recent or last one listed.

This means that we do not have to hardcode the version number of the latest release into our Playbook, which is helpful as the OpenSCAP content repo is updated at least once every few weeks.

The other options we are passing to the ansible.builtin.unarchive module are as follows:

  • dest: The destination directory on the target machine where the archive will be extracted is specified
  • creates: This parameter is used as a conditional check to prevent re-downloading and extracting the archive if a particular file exists
  • list_files: When set to true, this option lists all the files in the archive file; we will use this list to copy the files to our destination folder
  • remote_src: Setting this to true indicates that the source archive is located on a remote server, not on the control machine running Ansible; this is needed to download content directly from a URL

The following two tasks move the files to the root of openscap_download.dest as they would have been unarchived to a folder containing the version number – which we don’t want to use, as it could change between runs:

- name: "Move scap security guide content to the correct location"
ansible.builtin.shell: "mv {{ openscap_download.dest }}/{{ scap_download_result.files[0] }}/* {{ openscap_download.dest }}"
when: scap_download_result.changed
- name: "Remove the downloaded scap security guide content"
ansible.builtin.file:
path: "{{ openscap_download.dest }}/{{ scap_download_result.files[0] }}"
state: "absent"
when: scap_download_result.changed

Note that we are only running these tasks when the task that downloads the files has changed.

The final bit of information we need before we can run the OpenSCAP scan is which profile to use. To get this, we need to run the command to print information on the profiles available for our operating system:

- name: "Get information of the SCAP profiles available for the target system"
ansible.builtin.command: "oscap info –profiles –fetch-remote-resources {{ openscap_scan.ssg_file_name }}"
register: scap_info

Now that we have the information on the available profiles registered as scap_info, we can filter this list based on the contents of openscap_scan.profile_search and set a fact:

- name: "Extract profile name based on our selection criteria"
ansible.builtin.set_fact:
profile_name: "{{ scap_info.stdout_lines | select('search', openscap_scan.profile_search) | map('regex_replace', '^(.*?):.*$', '\\1') | first }}"

With the fact set, we can run the scan itself:

- name: "Run OpenSCAP scan"
ansible.builtin.command: "oscap xccdf eval --profile {{ profile_name }} --results-arf {{ openscap_scan.output_dir }}{{ openscap_scan.output_file_xml }} --report {{ openscap_scan.output_dir }}{{ openscap_scan.output_file_html }} {{ openscap_scan.ssg_file_name }}"
ignore_errors: true
no_log: true
register: scap_scan

As you can see, we are suppressing the output by using no_log: true; this is because we don’t really need to see the output at this stage and can ignore errors, like in the previous role where we ran WPScan and OSWAP ZAP.

Now that we have the output of the scan, we need to create a folder on our Ansible host to copy the output files to the following:

- name: "Ensure the local output directory exists"
ansible.builtin.file:
path: "{{ openscap_scan.local_output_dir }}"
state: directory
mode: "0755"
delegate_to: "localhost"
become: false

As you can see, we are using delegate_to to ensure that Ansible runs the task on localhost, and we are telling it not to become a privileged user.

Now we can fetch the output.xml and report.html files:

- name: "Copy the SCAP report and results file to local machine"
ansible.builtin.fetch:
src: "{{ item }}"
dest: "{{ openscap_scan.local_output_dir }}/"
flat: true
mode: "0644"
with_items:
- "{{ openscap_scan.output_dir }}{{ openscap_scan.output_file_xml }}"
- "{{ openscap_scan.output_dir }}{{ openscap_scan.output_file_html }}"

Next, we need to generate the guide and remediation files:

- name: "generate SCAP guide"
ansible.builtin.command: "oscap xccdf generate guide --profile {{ profile_name }} {{ openscap_scan.ssg_file_name }}"
ignore_errors: true
register: scap_guide

You may have noticed we are not saving a file here; we are just registering the output. That is because all of the content for the guide is output to the screen when the command is run, so rather than direct the output to a file on the virtual machine and copy it, we can capture the output and then create a file on our local machine that contains this content, essentially a fancy copy + paste from the remote host to our local one:

- name: "Copy SCAP guide to local machine"
ansible.builtin.copy:
content: "{{ scap_guide.stdout }}"
dest: "{{ openscap_scan.local_output_dir }}/{{ openscap_scan.output_file_guide }}"
mode: "0644"
when: scap_guide is defined
delegate_to: "localhost"
become: false

This is then repeated for the remediation Ansible Playbook:

- name: "Generate SCAP fix playbook"
ansible.builtin.command: "oscap xccdf generate fix --fetch-remote-resources --fix-type ansible --result-id '' {{ openscap_scan.output_dir }}{{ openscap_scan.output_file_xml }}"
ignore_errors: true
register: scap_playbook
- name: "Copy SCAP playbook to local machine"
ansible.builtin.copy:
content: "{{ scap_playbook.stdout }}"
dest: "{{ openscap_scan.local_output_dir }}/{{ openscap_scan.output_file_playbook }}"
mode: "0644"
when: scap_playbook is defined
delegate_to: "localhost"
become: false

Then again, for the remediation Bash script:

- name: "Generate SCAP fix bash script"
ansible.builtin.command: "oscap xccdf generate fix --fetch-remote-resources --fix-type bash --result-id '' {{ openscap_scan.output_dir }}{{ openscap_scan.output_file_xml }}"
ignore_errors: true
register: scap_bash_script
- name: "Copy SCAP bash script to local machine"
ansible.builtin.copy:
content: "{{ scap_bash_script.stdout }}"
dest: "{{ openscap_scan.local_output_dir }}/{{ openscap_scan.output_file_bash }}"
mode: "0644"
when: scap_bash_script is defined
delegate_to: "localhost"
become: false

The remaining tasks in the role deal with the remediation work, starting with the playbook:

- name: "Run the remediation playbook"
ansible.builtin.command: "ansible-playbook -i {{ inventory_file }} --become --become-method sudo {{ openscap_scan.local_output_dir }}/{{ openscap_scan.output_file_playbook }}"
when: scap_options_remediation
delegate_to: "localhost"
become: false
register: remediation_playbook

Then, as we never kept a copy of the bash script on the target virtual machine, we need to copy it back there:

- name: "Copy the remediation bash script to the target machine"
ansible.builtin.copy:
src: "{{ openscap_scan.local_output_dir }}/{{ openscap_scan.output_file_bash }}"
dest: "{{ openscap_scan.output_dir }}"
mode: "0755"
when: scap_options_remediation

Once copied, we can run the script:

- name: "Run the remediation bash script"
ansible.builtin.command: "bash {{ openscap_scan.output_dir }}{{ openscap_scan.output_file_bash }}"
when: scap_options_remediation
register: remediation_bash_script

With that task, the role is complete, and we now have all the pieces in place to run our playbook.

In Chapter 1, Installing and Running Ansible, we covered the installation and usage of Multipass; since then, we have been launching our local virtual machines using the same commands. In this chapter, as we need a little more disk space and RAM, we are going to be adding a few extra options when we launch the virtual machine:

$ multipass launch -n ansiblevm --cloud-init cloud-init.yaml --disk 10G --memory 4G

Once the virtual machine has launched, you can get the IP address of the host by running the following:

$ multipass info ansiblevm

Once you have the IP address, create a copy of hosts.example, calling its hosts and updating the IP address as we have done in previous chapters. Once your hosts inventory file is in place, we can start to run the playbook, starting with the OpenSCAP scan:

$ ansible-playbook -i hosts site.yml --tags "openscap" --extra-vars "scap_options_remediation=true"

As you can see, we are running using the openscap tag and setting the scap_options_remediation variable to true; if you recall, the default for this variable is false, meaning the remediation tasks will be executed during this playbook run.

Once completed, you will find several files in the output folder on your local machine; if you are not following along, then you can find a copy of the output at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter14/examples/01-scap_options_remediation_true.

As you can see from the following screen, on the initial run, we had 98 failed results:

Figure 14.1 – The initial results

As we ran the remediation tasks as part of the playbook run, we know that the score should now be improved, so let’s rerun the playbook – this time skipping the remediation tasks altogether:

$ ansible-playbook -i hosts site.yml --tags "openscap"

Once completed, you should have another folder of results; again, you can view the results at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter14/examples/02-scap_options_remediation_false:

Figure 14.2 – The updated results

As you can see, this has dramatically improved the score, and we only have six failures this time.

Next, we need to install WordPress; let’s start afresh with that. To make a fresh start, run the following commands to terminate the virtual machine and replace it with a new one:

$ multipass stop ansiblevm
$ multipass delete --purge ansiblevm
$ multipass launch -n ansiblevm --cloud-init cloud-init.yaml --disk 10G --memory 4G
$ multipass info ansiblevm

Update the hosts file with the new IP address and then run the following command to install WordPress:

$ ansible-playbook -i hosts site.yml --tags "wordpress"

With WordPress installed, you can run the WPScan and OSWAP ZAP scans with the following command:

$ ansible-playbook -i hosts site.yml --tags "scan"

Once completed, you will have the scan results in the output folder; you can find examples of the results at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter14/examples. The folder also contains the entire output from each of the playbook runs so far up to this point in the chapter.

Also, as mentioned at the start of the chapter, you can run each of the scans independently of each other using the following commands:

$ ansible-playbook -i hosts site.yml --tags "scan" --extra-vars "scan_types=zap"
$ ansible-playbook -i hosts site.yml --tags "scan" --extra-vars "scan_types=wpscan"

Once you have finished running the playbooks, you can remove the virtual machine by running the following:

$ multipass stop ansiblevm
$ multipass delete --purge ansiblevm

With the virtual machine cleaned up, that concludes our look at using Ansible to scan and harden our server.

Before we move on to the next chapter, I recommend you look at the remediation playbook, which was generated when we first ran OpenSCAP.

It can be found at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/blob/main/Chapter14/examples/01-scap_options_remediation_true/ansiblevm-playbook.yml, and as you can see, it contains over 4,600 lines of code!

In this chapter, we generated a playbook to remediate any CIS level-1 non-compliance errors found during a scan. As well as being cool, it is also convenient if you imagine you are running a few dozen servers that all need to be compliant and that all need an entire audit history.

You now have the foundations of a playbook that you can use to target those hosts daily, audit them, and store the results away from the host itself. Also, if you need to, depending on your configuration, you have a way of automatically resolving any non-conformance found during the scan.

We also ran scans against our WordPress installation and again stored the results away from the host itself – while the WPScan and OSWAP ZAP scans didn’t include any remediation, you could quickly review the results and update your WordPress deployment script to remediate the issues raised at deployment time.

So far, we have been running our Ansible Playbooks from our local machine; in the next chapter, it is time to move from running our Ansible code from our local machines into the cloud and look at how we can use Azure DevOps Pipelines and GitHub Actions to execute our playbooks.