---
# host-query / windows / t0 "Quick start"
#
# osquery on every Windows machine, asking the same questions on a schedule:
# local accounts and administrators, scheduled tasks, services set to start
# automatically, autostart entries, WMI subscriptions, unsigned drivers, and
# what listens on the network. Answers are logged as changes.
#
# Needs the Windows collection on the machine running Ansible:
#   ansible-galaxy collection install ansible.windows:==3.3.0
#
# osquery publishes a new installer with every release. From
# osquery.io/downloads, pick the Windows .msi, check it, and set the two
# values under vars.
#
# Run:
#   ansible-playbook -i inventory.ini playbook.yml
#
# Verify:
#   ansible all -i inventory.ini -m ansible.windows.win_shell -a "Get-Service osqueryd"
#   ansible all -i inventory.ini -m ansible.windows.win_shell -a "Get-Content 'C:\Program Files\osquery\log\osqueryd.results.log' -Tail 5"

- name: Ask every Windows machine the same questions
  hosts: all
  gather_facts: false

  vars:
    osquery_msi_url: "" # change me: the Windows .msi
    osquery_msi_sha256: "" # change me: its SHA-256
    osquery_dir: C:\Program Files\osquery

  tasks:
    - name: Stop if the installer or its checksum was not set
      ansible.builtin.assert:
        that:
          - osquery_msi_url is match('https://.+\.msi$')
          - osquery_msi_sha256 | length == 64
        fail_msg: Set osquery_msi_url to the Windows .msi, and osquery_msi_sha256 to its SHA-256.

    - name: Download osquery, refusing it if the checksum differs
      ansible.windows.win_get_url:
        url: "{{ osquery_msi_url }}"
        dest: C:\Windows\Temp\osquery.msi
        checksum: "{{ osquery_msi_sha256 }}"
        checksum_algorithm: sha256

    - name: Install it
      ansible.windows.win_package:
        path: C:\Windows\Temp\osquery.msi
        state: present
      notify: Restart osqueryd

    - name: Make the log folder
      ansible.windows.win_file:
        path: "{{ osquery_dir }}\\log"
        state: directory

    - name: Write the daemon flags
      ansible.windows.win_copy:
        dest: "{{ osquery_dir }}\\osquery.flags"
        content: |
          --config_path={{ osquery_dir }}\osquery.conf
          --logger_plugin=filesystem
          --logger_path={{ osquery_dir }}\log
          --disable_events=true
      notify: Restart osqueryd

    - name: Write the scheduled questions
      ansible.windows.win_copy:
        dest: "{{ osquery_dir }}\\osquery.conf"
        content: |
          {
            "schedule": {
              "local_users": {
                "query": "SELECT uid, username, type, directory FROM users WHERE type = 'local';",
                "interval": 3600
              },
              "local_administrators": {
                "query": "SELECT u.username FROM users u JOIN user_groups ug USING (uid) JOIN groups g USING (gid) WHERE g.groupname = 'Administrators';",
                "interval": 3600
              },
              "scheduled_tasks": {
                "query": "SELECT name, action, path, enabled, hidden FROM scheduled_tasks;",
                "interval": 3600
              },
              "automatic_services": {
                "query": "SELECT name, display_name, path, start_type, user_account FROM services WHERE start_type LIKE 'AUTO_START%';",
                "interval": 3600
              },
              "autostart_entries": {
                "query": "SELECT path, name, source FROM autoexec;",
                "interval": 3600
              },
              "wmi_command_consumers": {
                "query": "SELECT name, command_line_template, executable_path FROM wmi_cli_event_consumers;",
                "interval": 3600
              },
              "unsigned_drivers": {
                "query": "SELECT description, service, image FROM drivers WHERE signed = 0;",
                "interval": 3600
              },
              "listening_ports": {
                "query": "SELECT p.name, p.path, lp.port, lp.address, lp.protocol FROM listening_ports lp JOIN processes p USING (pid) WHERE lp.port != 0;",
                "interval": 3600
              }
            }
          }
      notify: Restart osqueryd

    # The service is pointed at the flag file above by name, so which flags
    # it reads does not depend on how the installer set it up.
    - name: Point the service at the flag file
      ansible.windows.win_powershell:
        parameters:
          Flags: "{{ osquery_dir }}\\osquery.flags"
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param([string]$Flags)
          $svc = Get-CimInstance Win32_Service -Filter "Name='osqueryd'"
          if (-not $svc) { if ($WhatIfPreference) { return }; throw 'The osqueryd service is missing. Did the install succeed?' }
          $exe = if ($svc.PathName -match '^"([^"]+)"') { $Matches[1] } else { ($svc.PathName -split ' ')[0] }
          $want = "`"$exe`" --flagfile=`"$Flags`""
          if ($svc.PathName -eq $want) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess('osqueryd', "run as $want")) {
            sc.exe config osqueryd binPath= $want | Out-Null
            if ($LASTEXITCODE -ne 0) { throw 'sc.exe could not change the osqueryd service command line' }
          }
      notify: Restart osqueryd

    - name: Make sure osqueryd is automatic and running
      ansible.windows.win_service:
        name: osqueryd
        start_mode: auto
        state: started

  handlers:
    - name: Restart osqueryd
      ansible.windows.win_service:
        name: osqueryd
        state: restarted
