---
# Common task for configuring redirector with full encryption
# Shared across all providers

- name: Set a custom MOTD
  template:
    src: "../templates/motd-redirector.j2"
    dest: /etc/motd
    owner: root
    group: root
    mode: '0644'

- name: Update package cache with retries
  apt:
    update_cache: yes
    cache_valid_time: 0
  register: cache_update
  until: cache_update is success
  retries: 5
  delay: 10
  ignore_errors: false

- name: Install core packages first (high priority)
  apt:
    name:
      - nginx
      - nginx-extras
      - socat
      - jq
      - secure-delete
    state: present
    update_cache: no
  register: core_packages
  until: core_packages is success
  retries: 3
  delay: 5

- name: Install network utilities with fallbacks
  block:
    - name: Try to install net-tools
      apt:
        name: net-tools
        state: present
        update_cache: no
      register: net_tools_install

  rescue:
    - name: Install alternative network utilities
      apt:
        name:
          - iproute2
          - iputils-ping
          - netcat-openbsd
        state: present
        update_cache: no
      register: alt_network_tools

    - name: Create net-tools compatibility aliases
      copy:
        dest: /usr/local/bin/netstat
        content: |
          #!/bin/bash
          # Compatibility wrapper for netstat using ss
          ss "$@"
        mode: '0755'
      when: alt_network_tools is success

- name: Install PHP-FPM with version handling
  block:
    - name: Install PHP-FPM (latest available)
      apt:
        name: php-fpm
        state: present
        update_cache: no
      register: php_install

  rescue:
    - name: Install specific PHP version as fallback
      apt:
        name:
          - php7.4-fpm
          - php7.4-cli
        state: present
        update_cache: no
      register: php_fallback

- name: Install certbot with dependency handling
  block:
    - name: Install certbot and nginx plugin
      apt:
        name:
          - certbot
          - python3-certbot-nginx
        state: present
        update_cache: no
      register: certbot_install

  rescue:
    - name: Install certbot without problematic dependencies
      shell: |
        apt-get install -y --no-install-recommends certbot
        apt-get install -y --fix-broken || true
      register: certbot_manual
      ignore_errors: true

    - name: Install certbot via snap as ultimate fallback
      block:
        - name: Install snap if not present
          apt:
            name: snapd
            state: present

        - name: Install certbot via snap
          snap:
            name: certbot
            classic: yes

        - name: Create certbot symlink
          file:
            src: /snap/bin/certbot
            dest: /usr/bin/certbot
            state: link
      when: certbot_manual is failed

- name: Handle problematic Python dependencies
  block:
    - name: Try installing Python dependencies normally
      apt:
        name:
          - python3-requests-toolbelt
          - python3-zope.hookable
        state: present
        update_cache: no
      register: python_deps

  rescue:
    - name: Install Python dependencies via pip as fallback
      pip:
        name:
          - requests-toolbelt
          - zope.hookable
        state: present
      register: pip_install
      ignore_errors: true

    - name: Download and install packages manually if repositories are down
      shell: |
        cd /tmp
        # Try alternative repositories
        wget -q http://archive.ubuntu.com/ubuntu/pool/universe/p/python-requests-toolbelt/python3-requests-toolbelt_0.8.0-1.1_all.deb || \
        wget -q http://launchpad.net/ubuntu/+archive/primary/+files/python3-requests-toolbelt_0.8.0-1.1_all.deb || true
        
        if [ -f python3-requests-toolbelt_*.deb ]; then
          dpkg -i python3-requests-toolbelt_*.deb || apt-get install -f -y
        fi
      when: pip_install is failed
      ignore_errors: true

- name: Verify critical packages are installed
  command: "{{ item.cmd }}"
  register: package_verify
  failed_when: package_verify.rc != 0
  loop:
    - { cmd: "nginx -v", name: "nginx" }
    - { cmd: "socat -V", name: "socat" }
    - { cmd: "jq --version", name: "jq" }
    - { cmd: "which certbot", name: "certbot" }
  ignore_errors: true

- name: Create package installation report
  debug:
    msg: |
      C2ingRed Package Installation Status:
      ===================================
      Core Packages: {{ 'SUCCESS' if core_packages is success else 'FAILED' }}
      Network Tools: {{ 'SUCCESS' if net_tools_install is success else 'FALLBACK USED' }}
      PHP-FPM: {{ 'SUCCESS' if php_install is success else 'FALLBACK USED' if php_fallback is success else 'FAILED' }}
      Certbot: {{ 'SUCCESS' if certbot_install is success else 'FALLBACK USED' }}
      Python Deps: {{ 'SUCCESS' if python_deps is success else 'FALLBACK ATTEMPTED' }}
      
      Critical Services Verified:
      {% for item in package_verify.results %}
      - {{ item.item.name }}: {{ 'OK' if item.rc == 0 else 'MISSING' }}
      {% endfor %}

- name: Force fix broken packages if any installation failed
  shell: |
    apt-get update --fix-missing
    apt-get install -f -y
    dpkg --configure -a
  when: core_packages is failed or certbot_install is failed
  register: fix_broken
  ignore_errors: true

- name: Final package status check and remediation
  block:
    - name: Check for any remaining broken packages
      shell: apt-get check
      register: apt_check
      failed_when: false

    - name: List installed packages for verification
      shell: |
        echo "=== INSTALLED PACKAGES ==="
        dpkg -l | grep -E "(nginx|certbot|socat|jq|php)" || echo "Some packages missing"
        echo "=== BROKEN PACKAGES ==="
        apt-get check 2>&1 | grep -i "broken\|error" || echo "No broken packages detected"
      register: final_status

    - name: Display final installation status
      debug:
        var: final_status.stdout_lines

- name: Detect installed PHP-FPM service
  shell: |
    # Try to find any PHP-FPM service
    if systemctl list-units --type=service --all | grep -q 'php.*fpm'; then
      systemctl list-units --type=service --all | grep 'php.*fpm' | head -1 | awk '{print $1}' | sed 's/\.service//'
    else
      echo "php-fpm"
    fi
  register: php_fpm_service
  failed_when: false

- name: Ensure critical services are enabled
  systemd:
    name: "{{ item }}"
    enabled: yes
    state: started
  loop:
    - nginx
    - "{{ php_fpm_service.stdout }}"
  ignore_errors: true
  register: service_start

- name: Create operational readiness marker
  copy:
    dest: /tmp/c2ingred_packages_ready
    content: |
      C2ingRed Package Installation Complete
      Timestamp: {{ ansible_date_time.iso8601 }}
      Status: {{ 'READY' if core_packages is success else 'PARTIAL' }}
    mode: '0644'

- name: Create directories for operational scripts
  file:
    path: "{{ item }}"
    state: directory
    mode: '0700'
    owner: root
    group: root
  with_items:
    - /root/Tools
    - /root/Tools/shell-handler

- name: Copy clean-logs.sh script
  copy:
    src: "../../../common/files/clean-logs.sh"
    dest: /root/Tools/clean-logs.sh
    mode: '0700'
    owner: root
    group: root

- name: Copy redirector post-install script
  copy:
    src: "../../../common/files/post_install_redirector.sh"
    dest: "/root/Tools/post_install_redirector.sh"
    mode: '0700'
    owner: root
    group: root

- name: Copy port randomization script
  copy:
    src: "../../../common/files/randomize_ports.sh"
    dest: "/root/Tools/randomize_ports.sh"
    mode: '0700'
    owner: root
    group: root

- name: Create redirector post-install instructions
  copy:
    content: |
      ================================================================
      C2ingRed Redirector Post-Installation Instructions
      ================================================================
      
      To complete your setup with SSL certificates, run:
        /root/Tools/post_install_redirector.sh
      
      This script will guide you through:
      - Setting up Let's Encrypt certificates
      - Starting required services
      - Updating NGINX configuration
      
      For enhanced OPSEC, you can also randomize ports:
        /root/Tools/randomize_ports.sh
      
      Run these after you've configured your DNS records to point to this server.
    dest: "/root/POST_INSTALL_INSTRUCTIONS.txt"
    mode: '0644'
    owner: root
    group: root

- name: Copy shell handler script
  copy:
    src: "../../c2/files/havoc_shell_handler.sh"
    dest: /root/Tools/shell-handler/persistent-listener.sh
    mode: '0700'
    owner: root
    group: root

- name: Configure shell handler script with C2 IP
  replace:
    path: /root/Tools/shell-handler/persistent-listener.sh
    regexp: 'C2_HOST="127.0.0.1"'
    replace: 'C2_HOST="{{ c2_ip }}"'

- name: Configure shell handler script with listening port
  template:
    src: "../../c2/files/havoc_shell_handler.sh"
    dest: "/root/Tools/shell_handler.sh"
    mode: 0755
  vars:
    listen_port: "{{ shell_handler_port | default(8083) }}"

- name: Create shell handler service
  template:
    src: "../templates/shell-handler.service.j2"
    dest: /etc/systemd/system/shell-handler.service
    mode: '0644'
    owner: root
    group: root

- name: Configure NGINX for zero-logging if enabled
  template:
    src: "../templates/nginx.conf.j2"
    dest: /etc/nginx/nginx.conf
    mode: '0644'
    owner: root
    group: root
  when: zero_logs | default(false) | bool

- name: Create payload directory
  file:
    path: /var/www/resources
    state: directory
    mode: '0755'
    owner: www-data
    group: www-data

- name: Include traffic flow configuration
  include_tasks: "../../common/tasks/traffic_flow_config.yml"

# Run port randomization if enabled
- name: Run port randomization if enabled
  include_tasks: "../../common/tasks/port_randomization.yml"
  when: randomize_ports | default(true) | bool

# Add just before configuring NGINX
- name: Check if snakeoil certificates exist
  stat:
    path: /etc/ssl/certs/ssl-cert-snakeoil.pem
  register: snakeoil_cert

- name: Generate self-signed certificates if snakeoil not available
  block:
    - name: Create directory for self-signed certificates
      file:
        path: /etc/nginx/conf.d
        state: directory
        mode: '0755'

    - name: Generate self-signed certificate
      shell: |
        openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
        -keyout /etc/nginx/conf.d/selfsigned.key \
        -out /etc/nginx/conf.d/selfsigned.crt \
        -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
      args:
        creates: /etc/nginx/conf.d/selfsigned.crt
  when: not snakeoil_cert.stat.exists

# Configure nginx for dual HTTP/HTTPS with complete encryption
- name: Configure NGINX for secure C2 redirection
  template:
    src: "../templates/redirector-site.conf.j2"
    dest: /etc/nginx/sites-available/default
    mode: '0644'
    owner: root
    group: root

- name: Create legitimate-looking index.html
  template:
    src: "../templates/redirector-index.html.j2"
    dest: /var/www/html/index.html
    mode: '0644'
    owner: www-data
    group: www-data

- name: Create SSL certificate setup instructions
  template:
    src: "../templates/setup-cert.sh.j2"
    dest: /root/Tools/setup-cert.sh
    mode: '0700'
    owner: root
    group: root

- name: Configure NGINX stream module for TCP traffic
  template:
    src: "../templates/stream.conf.j2"
    dest: /etc/nginx/modules-enabled/stream.conf
    mode: '0644'
    owner: root
    group: root

- name: Create credential harvesting directory
  file:
    path: /var/www/login
    state: directory
    mode: '0755'
    owner: www-data
    group: www-data

# Create secure storage outside web root
- name: Create secure credential storage
  file:
    path: /var/private/creds
    state: directory
    mode: '0700'  # Only owner access
    owner: www-data
    group: www-data

- name: Deploy credential harvesting page
  template:
    src: "../templates/fake-login.html.j2"
    dest: "/var/www/login/auth.html"
    mode: '0644'
    owner: www-data
    group: www-data

- name: Deploy credential capture script
  template:
    src: "../templates/capture.php.j2"
    dest: "/var/www/login/process.php"
    mode: '0644'
    owner: www-data
    group: www-data

- name: Install PHP for credential processing
  apt:
    name: php-fpm
    state: present
    update_cache: yes    

- name: Start and enable shell handler service
  systemd:
    name: shell-handler
    state: started
    enabled: yes
    daemon_reload: yes

- name: Set up cron job for log cleaning if zero-logs enabled
  cron:
    name: "Clean logs"
    minute: "0"
    hour: "*/6"
    job: "/root/Tools/clean-logs.sh > /dev/null 2>&1"
  when: zero_logs | default(false) | bool