#!/bin/bash

# Ubuntu Security Hardening Script
# Author: Aloke Majumder
# GitHub: https://github.com/alokemajumder
# License: MIT License

# DISCLAIMER:
# This script is provided "AS IS" without warranty of any kind, express or implied. The author expressly disclaims any and all warranties, 
# express or implied, including any warranties as to the usability, suitability or effectiveness of any methods or measures this script 
# attempts to apply. By using this script, you agree that the author shall not be held liable for any damages resulting from the use of this script.


# Step 1: Gather user input for necessary paths and choices with default options
echo "Enter the path to your initial Ansible hosts file (inventory) or press Enter to use the default ('./hosts.ini'):"
read -r INITIAL_HOSTS_FILE
INITIAL_HOSTS_FILE="${INITIAL_HOSTS_FILE:-./hosts.ini}"  # Default path

echo "Enter the path where you want to save the list of impacted hosts or press Enter to use the default ('./impacted_hosts.ini'):"
read -r IMPACTED_HOSTS_FILE
IMPACTED_HOSTS_FILE="${IMPACTED_HOSTS_FILE:-./impacted_hosts.ini}"  # Default path

echo "Do you want to automatically run the fix playbook on impacted hosts? (yes/no) [default: no]:"
read -r RUN_FIX
RUN_FIX="${RUN_FIX:-no}"  # Default choice

echo "Enter the path to save the final remediation report or press Enter to use the default ('./remediation_report.txt'):"
read -r FINAL_REPORT_PATH
FINAL_REPORT_PATH="${FINAL_REPORT_PATH:-./remediation_report.txt}"  # Default path

PLAYBOOK_DIR="./cve_2024_3094_playbooks"
mkdir -p "$PLAYBOOK_DIR"

# Step 2: Create the check vulnerability playbook
cat << EOF > "$PLAYBOOK_DIR/check_vulnerability.yml"
---
- name: Identify Vulnerable Hosts for CVE-2024-3094
  hosts: all
  become: yes
  tasks:
    - name: Gather package facts from all hosts
      ansible.builtin.package_facts:
        manager: auto
    - name: Check for vulnerable xz-utils version
      set_fact:
        is_vulnerable: "{{ 'xz' in ansible_facts.packages and ansible_facts.packages['xz'][0].version in ['5.6.0', '5.6.1'] }}"
    - name: Create a list of vulnerable hosts
      lineinfile:
        path: "$IMPACTED_HOSTS_FILE"
        line: "{{ inventory_hostname }}"
        create: yes
      when: is_vulnerable
      delegate_to: localhost
      run_once: true
EOF

# Step 3: Create the fix vulnerability playbook
cat << EOF > "$PLAYBOOK_DIR/fix_vulnerable_hosts.yml"
---
- name: Remediate CVE-2024-3094 on Identified Vulnerable Hosts and Generate Report
  hosts: all
  become: yes
  vars:
    report_path: "$FINAL_REPORT_PATH"
    stable_version: "5.4.6"
    stable_version_url: "https://excellmedia.dl.sourceforge.net/project/lzmautils/xz-5.4.6.tar.bz2"
    xz_downloaded: "/tmp/xz-\${stable_version}.tar.bz2"
  tasks:
    - name: Check for 'make' and 'gcc' installation
      ansible.builtin.package:
        name: "{{ item }}"
        state: present
      loop:
        - make
        - gcc

    - name: Attempt to upgrade xz-utils to the latest version
      ansible.builtin.package:
        name: xz
        state: latest
      register: upgrade_result

    - name: Attempt to downgrade xz-utils if upgrade fails
      block:
        - name: Download xz-utils version 5.4.6
          get_url:
            url: "{{ stable_version_url }}"
            dest: "{{ xz_downloaded }}"
          when: upgrade_result is failed

        - name: Extract and install xz-utils version 5.4.6
          command: tar -xjf "{{ xz_downloaded }}" -C /tmp && cd /tmp/xz-{{ stable_version }} && ./configure && make && make install
          args:
            creates: "/usr/local/bin/xz"
          when: upgrade_result is failed
      register: downgrade_result

    - name: Compile success results for reporting and suggest restarting sshd
      lineinfile:
        path: "{{ report_path }}"
        line: "Host {{ inventory_hostname }}: xz-utils processed. Consider restarting sshd."
        create: yes
      when: upgrade_result.changed or downgrade_result is defined and downgrade_result.changed

    - name: Note hosts requiring manual intervention in the report
      lineinfile:
        path: "{{ report_path }}"
        line: "Host {{ inventory_hostname }}: Manual effort needed to remediate xz-utils."
        create: yes
      when: not upgrade_result.changed and (downgrade_result is not defined or not downgrade_result.changed)
EOF

# Step 4: Execute the playbooks based on user choices
echo "Ansible playbook files have been set up in $PLAYBOOK_DIR."

# Check for vulnerable hosts and handle outcomes
ansible-playbook -i "$INITIAL_HOSTS_FILE" "$PLAYBOOK_DIR/check_vulnerability.yml"
if [ ! -s "$IMPACTED_HOSTS_FILE" ]; then
    echo "No vulnerable hosts found. No further actions are required."
    echo "Exiting..."
    exit 0
fi

# If vulnerable hosts found, either run the fix or notify user depending on choice
if [[ "$RUN_FIX" == "yes" ]]; then
    ansible-playbook -i "$IMPACTED_HOSTS_FILE" "$PLAYBOOK_DIR/fix_vulnerable_hosts.yml"
    echo "Playbooks executed. Check $FINAL_REPORT_PATH for the remediation report."
else
    echo "Vulnerable hosts detected. Review the list at $IMPACTED_HOSTS_FILE."
    echo "To remediate, run 'ansible-playbook -i $IMPACTED_HOSTS_FILE $PLAYBOOK_DIR/fix_vulnerable_hosts.yml'."
    echo "A summary report will be generated in $FINAL_REPORT_PATH."
    ansible-playbook -i "$IMPACTED_HOSTS_FILE" "$PLAYBOOK_DIR/fix_vulnerable_hosts.yml" --tags report_only
fi

echo "Operation completed. Exiting..."
exit 0
