---
# host-query / macos / t0 "Quick start"
#
# osquery on every Mac, asking the same questions on a schedule: who can sign
# in, what is set to start on its own, which system extensions are loaded,
# whether Gatekeeper and System Integrity Protection are on, and what is
# running from a deleted file. Answers are logged as changes.
#
# osquery publishes a new package with every release. From
# osquery.io/downloads, pick the macOS .pkg, check it, and set the two values
# under vars. Ansible reaches Macs over SSH, as it does Linux.
#
# Run:
#   ansible-playbook -i inventory.ini playbook.yml
#
# Verify:
#   ansible all -i inventory.ini -b -a "osqueryi --json 'select version from osquery_info'"
#   ansible all -i inventory.ini -b -a "tail -n 5 /var/log/osquery/osqueryd.results.log"
#
# In a managed fleet, grant osqueryd Full Disk Access with a privacy
# preferences profile from your device management service. Without it, some
# tables return nothing.

- name: Ask every Mac the same questions
  hosts: all
  become: true
  gather_facts: false

  vars:
    osquery_package_url: "" # change me: the macOS .pkg
    osquery_package_sha256: "" # change me: its SHA-256
    osqueryd: /opt/osquery/lib/osquery.app/Contents/MacOS/osqueryd

  tasks:
    - name: Stop if the package or its checksum was not set
      ansible.builtin.assert:
        that:
          - osquery_package_url is match('https://.+\.pkg$')
          - osquery_package_sha256 | length == 64
        fail_msg: Set osquery_package_url to the macOS .pkg, and osquery_package_sha256 to its SHA-256.

    - name: Download osquery, refusing it if the checksum differs
      ansible.builtin.get_url:
        url: "{{ osquery_package_url }}"
        dest: /private/var/tmp/osquery.pkg
        checksum: "sha256:{{ osquery_package_sha256 }}"
        mode: "0644"
      notify: Install the downloaded package

    # The binary is needed below, to check the configuration before it is used.
    - name: Install now, if a new package arrived
      ansible.builtin.meta: flush_handlers

    - name: Make the log folder
      ansible.builtin.file:
        path: /var/log/osquery
        state: directory
        owner: root
        group: wheel
        mode: "0750"

    - name: Write the daemon flags
      ansible.builtin.copy:
        dest: /var/osquery/osquery.flags
        owner: root
        group: wheel
        mode: "0640"
        content: |
          --config_path=/var/osquery/osquery.conf
          --logger_plugin=filesystem
          --logger_path=/var/log/osquery
          --disable_events=true
      notify: Restart osqueryd

    - name: Write the scheduled questions
      ansible.builtin.copy:
        dest: /var/osquery/osquery.conf
        owner: root
        group: wheel
        mode: "0640"
        content: |
          {
            "schedule": {
              "users": {
                "query": "SELECT uid, username, shell, directory FROM users WHERE uid >= 500 OR uid = 0;",
                "interval": 3600
              },
              "launch_items_at_load": {
                "query": "SELECT label, program, program_arguments, path FROM launchd WHERE run_at_load = '1';",
                "interval": 3600
              },
              "system_extensions": {
                "query": "SELECT identifier, team, state, path FROM system_extensions;",
                "interval": 3600
              },
              "gatekeeper": {
                "query": "SELECT assessments_enabled, dev_id_enabled FROM gatekeeper;",
                "interval": 3600
              },
              "sip": {
                "query": "SELECT config_flag, enabled FROM sip_config;",
                "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
              },
              "running_from_deleted_file": {
                "query": "SELECT pid, name, path, cmdline FROM processes WHERE on_disk = 0;",
                "interval": 300
              }
            }
          }
      notify: Restart osqueryd

    # Our own launch daemon, so the flag file it reads is the one written above.
    - name: Write the launch daemon
      ansible.builtin.copy:
        dest: /Library/LaunchDaemons/io.osquery.agent.plist
        owner: root
        group: wheel
        mode: "0644"
        content: |
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
          <plist version="1.0">
          <dict>
            <key>Label</key><string>io.osquery.agent</string>
            <key>ProgramArguments</key>
            <array>
              <string>{{ osqueryd }}</string>
              <string>--flagfile=/var/osquery/osquery.flags</string>
            </array>
            <key>RunAtLoad</key><true/>
            <key>KeepAlive</key><true/>
          </dict>
          </plist>
      notify: Restart osqueryd

    - name: Check whether the daemon is loaded
      ansible.builtin.command: launchctl print system/io.osquery.agent
      register: osquery_loaded
      changed_when: false
      failed_when: false

    - name: Load it if it is not
      ansible.builtin.command: launchctl bootstrap system /Library/LaunchDaemons/io.osquery.agent.plist
      when: osquery_loaded.rc != 0
      changed_when: true

  handlers:
    # installer checks the package's Apple signature and refuses an unsigned
    # or altered one, a second check after the checksum.
    - name: Install the downloaded package
      ansible.builtin.command: installer -pkg /private/var/tmp/osquery.pkg -target /
      changed_when: true
      notify: Restart osqueryd

    # Before the daemon is first loaded there is nothing to restart, and loading
    # it later starts it with the new files.
    - name: Restart osqueryd
      ansible.builtin.shell: |
        launchctl print system/io.osquery.agent > /dev/null 2>&1 || exit 0
        launchctl kickstart -k system/io.osquery.agent
      changed_when: true
