---
# host-log-shipping / windows / t0 "Quick start"
#
# Sysmon on every Windows source, and Windows Event Forwarding to one
# collector, so process starts, logons, and service installs outlive the
# machine that recorded them.
#
# Needs the two Windows collections on the machine running Ansible:
#   ansible-galaxy collection install ansible.windows:==3.3.0
#
# Inventory: a group called collector with one host, and a group called
# sources. Ansible reaches both over WinRM. All of them in one Active
# Directory domain, which is what lets the sources authenticate to the
# collector with Kerberos and no certificates.
#
# Change the three values under settings, then run:
#   ansible-playbook -i inventory.ini playbook.yml
#
# Verify:
#   On the collector: wecutil gr iac-baseline
#     Each source is listed with RunTimeStatus Active.
#   On a source, start any program, such as whoami.
#   On the collector, within a minute or two:
#     Get-WinEvent -LogName ForwardedEvents -MaxEvents 20 |
#       Where-Object ProviderName -eq 'Microsoft-Windows-Sysmon'

- name: Set up the collector
  hosts: collector
  gather_facts: false

  vars: &settings
    collector_fqdn: wec01.example.internal # change me: the collector's DNS name as sources see it
    sysmon_sha256: "" # change me: SHA-256 of Sysmon.zip, from Get-FileHash on a copy you checked
    sysmon_url: https://download.sysinternals.com/files/Sysmon.zip
    work_dir: C:\ProgramData\iac

  tasks:
    - name: Start the Windows Event Collector service and keep it on
      ansible.windows.win_service:
        name: Wecsvc
        start_mode: delayed
        state: started

    # Sources deliver to WinRM over HTTP on 5985. Kerberos encrypts the
    # messages inside, so HTTP here still means an encrypted channel.
    - name: Make sure WinRM listens on HTTP
      ansible.windows.win_powershell:
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param()
          $http = Get-ChildItem WSMan:\localhost\Listener |
            Where-Object { $_.Keys -contains 'Transport=HTTP' }
          if ($http) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess('WinRM', 'add an HTTP listener')) {
            New-Item -Path WSMan:\localhost\Listener -Transport HTTP -Address * -Force | Out-Null
          }

    # On Windows Server 2016 and 2019 the collector service may run in its own
    # process, and then it is not allowed to use the WinRM URLs and no event
    # ever arrives. Microsoft's fix is to grant both services. The two SIDs
    # are the WinRM and Wecsvc service identities, from Microsoft's article
    # "Event collector doesn't forward events".
    - name: Let the collector service use the WinRM URL
      ansible.windows.win_powershell:
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param()
          $winrm = 'S-1-5-80-569256582-2953403351-2909559716-1301513147-412116970'
          $wec = 'S-1-5-80-4059739203-877974739-1245631912-527174227-2996563517'
          $url = 'http://+:5985/wsman/'
          $now = (netsh http show urlacl url=$url) -join "`n"
          if ($now -match $wec) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess($url, 'grant WinRM and Wecsvc')) {
            netsh http delete urlacl url=$url | Out-Null
            netsh http add urlacl url=$url "sddl=D:(A;;GX;;;$winrm)(A;;GX;;;$wec)" | Out-Null
            if ($LASTEXITCODE -ne 0) { throw "netsh could not set the URL ACL for $url" }
          }

    - name: Make a folder for the subscription file
      ansible.windows.win_file:
        path: "{{ work_dir }}\\wef"
        state: directory

    # Source initiated: sources find the collector from their own setting, so
    # new machines join without anyone editing the subscription.
    - name: Write the subscription
      ansible.windows.win_copy:
        dest: "{{ work_dir }}\\wef\\iac-baseline.xml"
        content: |
          <Subscription xmlns="http://schemas.microsoft.com/2006/03/windows/events/subscription">
            <SubscriptionId>iac-baseline</SubscriptionId>
            <SubscriptionType>SourceInitiated</SubscriptionType>
            <Description>Security, System, and Sysmon from every domain computer and domain controller. Managed by Ansible.</Description>
            <Enabled>true</Enabled>
            <Uri>http://schemas.microsoft.com/wbem/wsman/1/windows/EventLog</Uri>
            <ConfigurationMode>MinLatency</ConfigurationMode>
            <Query><![CDATA[
              <QueryList>
                <Query Id="0">
                  <Select Path="Security">*</Select>
                  <Select Path="System">*</Select>
                  <Select Path="Microsoft-Windows-Sysmon/Operational">*</Select>
                </Query>
              </QueryList>
            ]]></Query>
            <ReadExistingEvents>false</ReadExistingEvents>
            <TransportName>HTTP</TransportName>
            <ContentFormat>RenderedText</ContentFormat>
            <Locale Language="en-US"/>
            <LogFile>ForwardedEvents</LogFile>
            <AllowedSourceNonDomainComputers></AllowedSourceNonDomainComputers>
            <AllowedSourceDomainComputers>O:NSG:BAD:P(A;;GA;;;DC)(A;;GA;;;DD)S:</AllowedSourceDomainComputers>
          </Subscription>
      register: subscription_file

    - name: Create the subscription, or replace it when the file changed
      ansible.windows.win_powershell:
        parameters:
          File: "{{ work_dir }}\\wef\\iac-baseline.xml"
          Replace: "{{ subscription_file.changed }}"
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param([string]$File, [bool]$Replace)
          wecutil gs iac-baseline *> $null
          $exists = $LASTEXITCODE -eq 0
          if ($exists -and -not $Replace) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess('iac-baseline', 'create the subscription')) {
            if ($exists) { wecutil ds iac-baseline | Out-Null }
            wecutil cs $File
            if ($LASTEXITCODE -ne 0) { throw "wecutil could not create the subscription from $File" }
          }

- name: Set up each source
  hosts: sources
  gather_facts: false

  vars: *settings

  tasks:
    - name: Stop if the Sysmon checksum was not set
      ansible.builtin.assert:
        that:
          - sysmon_sha256 | length == 64
        fail_msg: >-
          Set sysmon_sha256 at the top of the playbook. Download Sysmon.zip once, check its
          signature, and use the SHA-256 from Get-FileHash. The file changes with every release,
          so there is no safe default.

    - name: Make a folder for Sysmon
      ansible.windows.win_file:
        path: "{{ work_dir }}\\sysmon"
        state: directory

    - name: Download Sysmon, refusing it if the checksum differs
      ansible.windows.win_get_url:
        url: "{{ sysmon_url }}"
        dest: "{{ work_dir }}\\sysmon\\Sysmon.zip"
        checksum: "{{ sysmon_sha256 }}"
        checksum_algorithm: sha256
      register: sysmon_zip

    - name: Unpack Sysmon
      ansible.windows.win_powershell:
        parameters:
          Dir: "{{ work_dir }}\\sysmon"
          Force: "{{ sysmon_zip.changed }}"
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param([string]$Dir, [bool]$Force)
          if ((Test-Path "$Dir\Sysmon64.exe") -and -not $Force) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess($Dir, 'unpack Sysmon.zip')) {
            Expand-Archive -Path "$Dir\Sysmon.zip" -DestinationPath $Dir -Force
          }

    # Every event type is named, so nothing depends on Sysmon's defaults.
    # onmatch="exclude" with no rules logs every event of that type.
    # onmatch="include" with no rules logs none.
    - name: Write the Sysmon configuration
      ansible.windows.win_copy:
        dest: "{{ work_dir }}\\sysmon\\sysmonconfig.xml"
        content: |
          <Sysmon schemaversion="4.50">
            <HashAlgorithms>sha256</HashAlgorithms>
            <CheckRevocation/>
            <EventFiltering>
              <!-- 1: every process start, with its command line and parent -->
              <RuleGroup name="" groupRelation="or"><ProcessCreate onmatch="exclude"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><FileCreateTime onmatch="include"/></RuleGroup>
              <!-- 3: outbound connections from programs attackers and insiders lean on -->
              <RuleGroup name="" groupRelation="or">
                <NetworkConnect onmatch="include">
                  <Image condition="end with">\powershell.exe</Image>
                  <Image condition="end with">\pwsh.exe</Image>
                  <Image condition="end with">\rundll32.exe</Image>
                  <Image condition="end with">\regsvr32.exe</Image>
                  <Image condition="end with">\mshta.exe</Image>
                  <Image condition="end with">\certutil.exe</Image>
                  <Image condition="end with">\bitsadmin.exe</Image>
                  <Image condition="begin with">C:\Users\</Image>
                  <DestinationPort condition="is">22</DestinationPort>
                  <DestinationPort condition="is">3389</DestinationPort>
                </NetworkConnect>
              </RuleGroup>
              <RuleGroup name="" groupRelation="or"><ProcessTerminate onmatch="include"/></RuleGroup>
              <!-- 6: every driver load; rare, and a kernel foothold when it is not yours -->
              <RuleGroup name="" groupRelation="or"><DriverLoad onmatch="exclude"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><ImageLoad onmatch="include"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><CreateRemoteThread onmatch="exclude"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><RawAccessRead onmatch="exclude"/></RuleGroup>
              <!-- 10: anything opening LSASS, which is where credentials are read from -->
              <RuleGroup name="" groupRelation="or">
                <ProcessAccess onmatch="include">
                  <TargetImage condition="end with">\lsass.exe</TargetImage>
                </ProcessAccess>
              </RuleGroup>
              <!-- 11: files written where programs start themselves -->
              <RuleGroup name="" groupRelation="or">
                <FileCreate onmatch="include">
                  <TargetFilename condition="contains">\Start Menu\Programs\Startup\</TargetFilename>
                  <TargetFilename condition="begin with">C:\Windows\System32\Tasks\</TargetFilename>
                  <TargetFilename condition="end with">.hta</TargetFilename>
                </FileCreate>
              </RuleGroup>
              <!-- 12 to 14: registry places programs use to start themselves -->
              <RuleGroup name="" groupRelation="or">
                <RegistryEvent onmatch="include">
                  <TargetObject condition="contains">\CurrentVersion\Run</TargetObject>
                  <TargetObject condition="contains">\Image File Execution Options\</TargetObject>
                  <TargetObject condition="contains">\Winlogon\</TargetObject>
                  <TargetObject condition="end with">\ImagePath</TargetObject>
                </RegistryEvent>
              </RuleGroup>
              <RuleGroup name="" groupRelation="or"><FileCreateStreamHash onmatch="include"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><PipeEvent onmatch="include"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><WmiEvent onmatch="exclude"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><DnsQuery onmatch="include"/></RuleGroup>
              <!-- 23: off. Logging deletes also copies every deleted file to disk. -->
              <RuleGroup name="" groupRelation="or"><FileDelete onmatch="include"/></RuleGroup>
              <!-- 24: off. It records what people copy, passwords included. -->
              <RuleGroup name="" groupRelation="or"><ClipboardChange onmatch="include"/></RuleGroup>
              <RuleGroup name="" groupRelation="or"><ProcessTampering onmatch="exclude"/></RuleGroup>
            </EventFiltering>
          </Sysmon>
      register: sysmon_config

    - name: Install Sysmon, or load the new configuration
      ansible.windows.win_powershell:
        parameters:
          Dir: "{{ work_dir }}\\sysmon"
          Reload: "{{ sysmon_config.changed or sysmon_zip.changed }}"
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param([string]$Dir, [bool]$Reload)
          $installed = [bool](Get-Service -Name Sysmon64 -ErrorAction SilentlyContinue)
          # -c only reloads the configuration, so a new release is installed
          # by removing the running one first.
          $running = (Get-Item "$env:windir\Sysmon64.exe" -ErrorAction SilentlyContinue).VersionInfo.FileVersion
          $fresh = (Get-Item "$Dir\Sysmon64.exe" -ErrorAction SilentlyContinue).VersionInfo.FileVersion
          $upgrade = $installed -and $running -and $fresh -and ($running -ne $fresh)
          if ($installed -and -not $upgrade -and -not $Reload) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess('Sysmon64', 'install, upgrade, or reload')) {
            if ($upgrade) {
              & "$Dir\Sysmon64.exe" -u | Out-Null
              if ($LASTEXITCODE -ne 0) { throw "Sysmon $running would not uninstall (exit $LASTEXITCODE)" }
              $installed = $false
            }
            if ($installed) {
              & "$Dir\Sysmon64.exe" -c "$Dir\sysmonconfig.xml" | Out-Null
            } else {
              & "$Dir\Sysmon64.exe" -accepteula -i "$Dir\sysmonconfig.xml" | Out-Null
            }
            if ($LASTEXITCODE -ne 0) { throw "Sysmon rejected $Dir\sysmonconfig.xml (exit $LASTEXITCODE)" }
          }

    # The forwarder runs as NETWORK SERVICE, which cannot read the Security or
    # Sysmon logs by default. Without this the subscription shows the source
    # as active and those two logs never arrive.
    - name: Let the forwarder read the Security and Sysmon logs
      ansible.windows.win_powershell:
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param()
          $Ansible.Changed = $false
          foreach ($log in 'Security', 'Microsoft-Windows-Sysmon/Operational') {
            $line = wevtutil gl $log | Where-Object { $_ -like 'channelAccess:*' }
            $sddl = ($line -replace '^channelAccess:\s*', '').Trim()
            if ($sddl -like '*(A;;0x1;;;NS)*') { continue }
            $Ansible.Changed = $true
            if ($PSCmdlet.ShouldProcess($log, 'grant NETWORK SERVICE read')) {
              wevtutil sl $log "/ca:$sddl(A;;0x1;;;NS)"
              if ($LASTEXITCODE -ne 0) { throw "wevtutil could not update access on $log" }
            }
          }

    - name: Point the source at the collector
      ansible.windows.win_regedit:
        path: HKLM:\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
        name: "1"
        data: "Server=http://{{ collector_fqdn }}:5985/wsman/SubscriptionManager/WEC,Refresh=60"
        type: string
      notify: Tell the forwarder

    - name: Keep WinRM running, since it does the forwarding
      ansible.windows.win_service:
        name: WinRM
        start_mode: auto
        state: started

  handlers:
    # A policy refresh makes the forwarder read the new setting. Restarting
    # WinRM would also work, but would cut off Ansible's own connection.
    - name: Tell the forwarder
      ansible.windows.win_command: gpupdate /target:computer /force
      changed_when: true
