Tag: detection engineering

  • Kerberoasting and AS-REP roasting: how service tickets get cracked offline, and what actually stops it

    Kerberoasting and AS-REP roasting: how service tickets get cracked offline, and what actually stops it

    The attack lives mostly outside your logs

    Flow diagram: an attacker with any domain user requests service tickets from the domain controller, carries them offline for cracking, with detection points and a bar comparison of RC4, AES256 and gMSA guessing speed

    The diagram shows where Kerberoasting is visible to defenders and why the encryption type changes the cost of guessing.

    Most Active Directory attacks that matter share one trait: the noisy part happens on the attacker’s own hardware. Kerberoasting is the cleanest example. Tim Medin presented it in 2014, and it still works in 2026 on a depressing share of the domains I get to look at, because it needs nothing but an ordinary domain account.

    Any authenticated user can ask a domain controller for a service ticket (a TGS) for any account that has a service principal name (SPN) registered. The KDC doesn’t check whether you’re allowed to use the service. Authorization is the service’s job. Part of that ticket is encrypted with a key derived from the service account’s password. So the attacker requests tickets for every SPN-bearing account, carries them away, and guesses passwords against them at GPU speed. No lockouts, no failed logons, no traffic to the target service.

    If the service account password is “Summer2019!” the game is over in seconds. If it’s 25 random characters, the game is also over, but in the defender’s favor.

    Why the encryption type decides everything

    The ticket is encrypted with whatever the account supports. For RC4 (etype 23), the key is the account’s NT hash, which is an unsalted MD4 of the password. Cracking it means computing MD4 and a couple of HMAC-MD5 rounds per guess. That is very fast on a GPU. Public hashcat benchmarks put a single modern card in the billions of guesses per second for this mode (hashcat mode 13100).

    For AES256 (etype 18, RFC 3962), the key comes from PBKDF2 with 4096 iterations and a salt built from the realm and principal name. Each guess costs thousands of HMAC computations, and the salt kills precomputed tables. Hashcat handles these too (modes 19600 for etype 17 and 19700 for etype 18), and the speed difference against RC4 is orders of magnitude. I won’t quote an exact ratio because it varies by card and by version.

    The attacker picks the encryption type in the request, and the KDC will usually go along with RC4 if the account allows it. That is why “AES only” on service accounts matters more than most password policy tweaks. It turns a weak password from an instant loss into a slow one, and a strong password from a hard problem into a practically impossible one.

    AS-REP roasting is the same idea, one step earlier

    Kerberos pre-authentication makes a client prove it knows the password before the KDC hands anything back. If an account has the “Do not require Kerberos preauthentication” flag (DONT_REQ_PREAUTH), anyone on the network can send an AS-REQ for that user and get back an AS-REP, part of which is encrypted with the user’s key. No domain credentials are needed at all, which is the difference from Kerberoasting. Hashcat mode 18200 covers the RC4 flavor.

    I’ve never found a legitimate modern reason for this flag. It exists for ancient Kerberos clients and for the occasional “temporary” fix that nobody reverted. One line finds them:

    Get-ADUser -Filter 'DoesNotRequirePreAuth -eq $true' -Properties DoesNotRequirePreAuth |
      Select-Object SamAccountName, Enabled

    Clear the flag, and if something breaks, fix the something.

    Finding your exposure

    Start by listing which user accounts carry SPNs and what encryption they advertise. Computer accounts have random 120-character passwords that rotate, so ignore them. User accounts are the problem.

    Get-ADUser -Filter 'ServicePrincipalName -like "*"' `
      -Properties ServicePrincipalName, PasswordLastSet, 'msDS-SupportedEncryptionTypes' |
      Select-Object SamAccountName, PasswordLastSet,
        @{n='EncTypes';e={$_.'msDS-SupportedEncryptionTypes'}},
        @{n='SPNs';e={$_.ServicePrincipalName -join ';'}}

    An empty or zero `msDS-SupportedEncryptionTypes` means the domain default applies, and for years that default allowed RC4. Microsoft has been tightening the KDC defaults away from RC4 over several rounds of updates, so check your own domain controllers’ behavior instead of assuming. Sort by `PasswordLastSet`. A service account whose password predates the person who currently runs the service is the first one I’d fix.

    The fixes, in the order I’d do them

    First, move service accounts to group managed service accounts (gMSA) wherever the software supports it. The domain generates a long random password and rotates it on a schedule (30 days by default), and nobody ever types it. Kerberoasting a gMSA gets the attacker a ticket they will never crack. Plenty of older software can’t use gMSAs, which is the whole reason the other fixes exist.

    Second, for accounts that must stay as ordinary users, set a long random password. Twenty-five characters from a password manager is fine. Length matters more than complexity rules here, because the attacker is guessing offline against the hash.

    Third, restrict the account to AES:

    Set-ADUser svc_sql -KerberosEncryptionType AES128,AES256

    Test this on a non-production service first. A service host or an old client that only speaks RC4 will start failing, and you want to learn that in a maintenance window. Also, changing the supported types doesn’t change the stored keys until the password is next changed, so reset the password after setting the flag.

    Fourth, strip privileges. A Kerberoastable account in Domain Admins is a disaster waiting for a lazy password. I’ve seen SQL service accounts with domain admin rights because someone once needed to get an install working. Cracking that one ticket is the whole engagement.

    Detection that has a decent signal-to-noise ratio

    Event ID 4769 (a Kerberos service ticket was requested) fires constantly in a normal domain, so alerting on it raw is useless. What works is filtering on shape.

    Ticket Encryption Type 0x17 (RC4) against a user-account SPN, in a domain where almost nothing should still negotiate RC4, is a strong signal. A single account requesting tickets for many different SPNs in a short window is the other. Roasting tools usually enumerate every SPN in one pass, so a burst of 4769 events from one client for dozens of services stands out against a baseline of one or two.

    For AS-REP roasting, look at event 4768 with Pre-Authentication Type 0 for any account. After you’ve cleared the flag, any hit is an attempt against an account that shouldn’t exist.

    My favorite control is cheap. Create a decoy user with an SPN that looks juicy (something like `MSSQLSvc/backup-sql01`), give it a 30-character random password and no real privileges, and alert on any ticket request for it. Nobody has a legitimate reason to request that ticket, so there’s no baseline to tune. The only caveat is that it catches the attacker who roasts everything, not the one who picks a single target.

    What this doesn’t solve

    Everything above makes cracking harder or noisier. None of it stops the ticket request, because the KDC is behaving as designed. If a domain account can be phished or purchased, the attacker gets to try. So pair it with controls on the first foothold: phishing-resistant MFA, tiering so service accounts can’t log on interactively to workstations, and limited blast radius for every account that holds an SPN.

    I’d also be wary of any assessment that reports Kerberoasting as “found 40 roastable accounts” as the finding. The useful measure is how many of those would fall to a 10-billion-guess wordlist attack and what each one can reach. A roastable account with a 25-character password and no privileges is mostly a note. A roastable account with a seven-year-old password in a privileged group is an incident you haven’t had yet.

  • Alert fatigue: tuning detections without going blind

    Alert fatigue: tuning detections without going blind

    Part 3 of 3 in the Detection engineering series. Part 1: Logging that actually helps an investigation. Part 2: Writing detections as code: Sigma rules tested against real logs.

    In 2013, attackers inside Target’s network set off malware alerts from a detection tool the company had recently deployed. The alerts reached Target’s security team, and the US Senate Commerce Committee’s 2014 kill chain analysis of the breach concluded they weren’t acted on in time. Roughly 40 million payment cards were stolen. The detection tool did its job. The process around it didn’t.

    I’ve seen that pattern more than once. When a team gets hundreds of alerts a day and nearly all of them are benign, people learn, quite rationally, that alerts are probably nothing. Then the real one gets the same treatment.

    This is part 3 of the series. Part 1 covered collecting the right events and part 2 covered writing and testing detections as code. This one is about living with them.

    Measure before you tune

    Illustrative Pareto chart of 30-day alert volume by detection rule, coloured by precision

    You can’t tune what you don’t count. For every rule, track three numbers over a rolling 30 days: how many alerts it produced, how many were true positives after triage, and how long triage took. Precision per rule (true positives divided by total alerts) is the most useful single figure, and it’s almost never on the SIEM dashboard by default.

    That means analysts have to record a disposition when they close an alert. Keep the choices small and honest: true positive, benign true positive (the rule matched what it was meant to, but the activity was authorised), false positive, and needs tuning. The “benign true positive” bucket matters, because an admin running a scanner is not the rule being wrong, and conflating the two leads to deleting good rules.

    When you plot alert volume by rule, you’ll nearly always find that a handful of rules generate most of the noise. Good: you don’t have to fix everything, only the top few.

    Tune narrowly

    The lazy fix for a noisy rule is excluding the whole host, the whole service account, or the whole subnet. Each of those is a hole an intruder can stand in. If your backup server is excluded from the PowerShell rule because its jobs are noisy, then PowerShell on the backup server is now invisible, and backup servers are exactly what ransomware operators go looking for.

    Make exceptions as specific as the evidence allows: the exact parent process, the exact command line or script path, ideally the file hash and the expected account. In Sigma that’s a named filter in the rule itself:

    detection:
      selection:
        Image|endswith: '\powershell.exe'
        CommandLine|contains: ' -EncodedCommand '
      filter_backup_job:
        ParentImage: 'C:\Program Files\BackupAgent\scheduler.exe'
        User: 'CORP\svc-backup'
        CommandLine|contains: 'C:\BackupAgent\scripts\prejob.ps1'
      condition: selection and not filter_backup_job

    If the backup agent is compromised and starts running something else, the filter no longer matches and the alert fires.

    Give every exception an owner and an expiry

    Exceptions accumulate like firewall rules. Nobody remembers why half of them exist, and nobody dares remove them. Store them in the repository with metadata, and let CI enforce it:

    # exceptions/powershell-encoded.yml
    rule_id: 0c4b3a9e-71d2-4f5e-9b8a-6e2d1c7f3a10
    filter: filter_backup_job
    reason: Vendor pre-job script uses encoded commands (ticket SEC-1432)
    owner: infra-backup
    expires: 2027-01-31
    import datetime, glob, sys, yaml
    
    today = datetime.date.today()
    expired = []
    for path in glob.glob("exceptions/*.yml"):
        with open(path) as f:
            doc = yaml.safe_load(f)
        if doc["expires"] <= today:
            expired.append(f'{path}: owner {doc["owner"]}, expired {doc["expires"]}')
    
    if expired:
        print("\n".join(expired))
        sys.exit(1)

    When an exception expires, the owner either renews it with a fresh justification or it goes away. I default to ninety days. It’s a little annoying, and that annoyance is what keeps the list short.

    Change what happens, not just whether it fires

    Not every detection should page a human. A lot of useful signals are weak on their own: a new admin tool on a workstation, a login from an unusual country, a service account authenticating interactively. Individually each one is noisy. Together, on the same host or user within a few hours, they tell a story.

    This is risk-based alerting. Low-fidelity rules don’t create alerts; they add a risk score to the user or host they involve. A separate correlation rule fires when an entity’s accumulated score crosses a threshold, or when signals from several distinct ATT&CK tactics appear together. Splunk documents this approach as its RBA framework, but you can build the same thing in any SIEM that can aggregate by entity over a time window.

    Alongside that, route by confidence. High-precision rules page someone. Medium ones land in a queue that’s worked during business hours. The rest feed risk scores and dashboards. A rule that has never produced a true positive in a year and doesn’t feed anything is a candidate for retirement, but only after you’ve confirmed it can still fire (see the next section), because a rule that never fires might be a rule that’s broken.

    Prove you’re not blind

    Tuning removes alerts. The danger is that you can’t easily see the alerts you removed, or the ones that stopped firing because a log source died. So you need a positive signal that coverage still exists.

    Part 2 described scheduled end-to-end tests: a harmless, known action on a test host that a specific rule must catch within minutes. Run those continuously, track the pass rate per rule, and treat a failure as an incident in the detection pipeline. Combine it with a per-source volume monitor so that a domain controller going quiet raises its own alert.

    I also like a quarterly review of the top 20 noisiest rules and every rule with zero alerts. The noisy ones need tuning. The silent ones need a test proving they still work.

    Watch the humans

    The last metric is about the analysts. If one person is triaging 200 alerts per shift, median triage time drops to seconds and the quality goes with it. Track alerts per analyst-hour and the share of alerts closed in under a minute. When those climb, the fix is in the rules, not in telling people to try harder.

    A healthy detection program is one where an alert is rare enough that people still feel a small jolt when one arrives. Getting there is mostly dull bookkeeping, and every hour of it pays off.

  • Writing detections as code: Sigma rules tested against real logs

    Writing detections as code: Sigma rules tested against real logs

    Part 2 of 3 in the Detection engineering series. Part 1: Logging that actually helps an investigation.

    Detection logic that lives only inside a SIEM’s web console has the same problems as server config edited by hand over SSH. Nobody reviews the change, nobody knows why a condition was added, and when a rule silently stops matching after a log format change, nobody notices for months. Treating detections as code fixes most of that, and Sigma is the most practical way I know to do it without tying yourself to one vendor.

    In part 1 we covered which events to collect. This part is about turning them into rules you can review, version and, most importantly, test.

    What Sigma actually is

    Detection-as-code pipeline: lint, convert, positive and negative fixtures, volume estimate, deploy, production feedback

    Sigma is an open, YAML-based format for describing log detections, maintained by the SigmaHQ project along with a large public rule repository. A rule describes the log source in abstract terms (process creation on Windows, say) and the matching logic as field conditions. A converter then translates it into your backend’s query language: Splunk SPL, Elasticsearch, Microsoft Sentinel’s KQL and many others through pySigma backends.

    The abstraction is the point. The same rule can run against Sysmon data in one environment and against an EDR’s process events in another, as long as a processing pipeline maps the field names.

    A rule worth having

    Here’s a rule for a pattern that turns up in a lot of web server compromises: the IIS worker process starting a command shell. Web applications rarely have a legitimate reason to do that, and a web shell almost always does.

    title: Command shell spawned by IIS worker process
    id: 6b1f3c52-8f0e-4b8a-9d3e-2c7a5e1f9b40
    status: experimental
    description: >
      Detects cmd.exe or PowerShell started by w3wp.exe, which usually
      indicates a web shell or command injection in a hosted application.
    references:
      - https://attack.mitre.org/techniques/T1505/003/
    author: canutethegreat
    date: 2026-10-14
    tags:
      - attack.persistence
      - attack.t1505.003
    logsource:
      category: process_creation
      product: windows
    detection:
      selection:
        ParentImage|endswith: '\w3wp.exe'
        Image|endswith:
          - '\cmd.exe'
          - '\powershell.exe'
          - '\pwsh.exe'
      filter_health_check:
        CommandLine|contains: '\inetpub\scripts\healthcheck.cmd'
      condition: selection and not filter_health_check
    falsepositives:
      - Application pools that deliberately shell out (document them in a filter)
    level: high

    Notice the filter. Real environments always have the one legacy app that shells out for a reason, and the right place to record that exception is in the rule, in version control, with a commit message saying who asked for it. Part 3 goes deeper on how to keep exceptions from eating your coverage.

    Converting and linting in CI

    The sigma-cli tool wraps pySigma. A minimal CI step that validates and converts every rule looks like this:

    pip install sigma-cli
    sigma plugin install splunk
    sigma plugin install sysmon
    
    # Fail the build on structural problems
    sigma check rules/
    
    # Produce backend queries as a build artifact
    sigma convert -t splunk -p sysmon rules/ -o build/splunk.conf

    sigma check catches malformed YAML, missing fields and duplicate IDs. Conversion failures matter too, because a modifier or field that your backend can’t express means the rule never runs where you think it does. I’ve seen rule sets where a quarter of the rules failed conversion and the failures were simply ignored.

    Testing against real logs

    Linting proves a rule is well formed. It says nothing about whether the rule fires on the activity you care about, or whether it fires on a Tuesday-morning patch run. For that you need recorded events.

    Keep two fixture directories next to each rule set. The positive fixtures contain events that must match, ideally captured from a lab machine where you reproduced the behaviour, or taken from public datasets such as the OTRF Security-Datasets project or the EVTX-ATTACK-SAMPLES collection. The negative fixtures contain normal activity from your own estate that must not match: a day of process events from a busy web server is a good start.

    To evaluate Sigma directly against EVTX files without a SIEM, WithSecure’s open source Chainsaw works well:

    chainsaw hunt tests/positive/ -s rules/ \
      --mapping mappings/sigma-event-logs-all.yml --json > out/positive.json
    chainsaw hunt tests/negative/ -s rules/ \
      --mapping mappings/sigma-event-logs-all.yml --json > out/negative.json

    Then a short script turns those results into pass or fail. The exact JSON layout varies between Chainsaw versions, so treat this as a sketch you adapt to the output you get:

    import json, sys
    
    def hits(path):
        with open(path) as f:
            return {d["name"] for doc in json.load(f) for d in doc.get("detections", [])}
    
    expected = {"Command shell spawned by IIS worker process"}
    pos, neg = hits("out/positive.json"), hits("out/negative.json")
    
    missing = expected - pos
    noisy = expected & neg
    if missing or noisy:
        print("did not fire:", sorted(missing))
        print("fired on benign data:", sorted(noisy))
        sys.exit(1)

    Now a rule change that breaks detection fails the build, and so does a change that would page someone on ordinary traffic. Most teams skip that second check, and it’s the one that stops analysts from muting your rules.

    Keep production honest too

    Fixtures drift away from reality. Log schemas change when an agent is upgraded, a field gets renamed, or Sysmon’s config stops collecting the event you depended on. Fixture tests won’t catch any of that, because the fixtures still have the old shape.

    The fix is a scheduled end-to-end check. On a dedicated test host, run a harmless action that a specific rule should catch (for the rule above, a test IIS site whose handler starts cmd.exe /c echo detection-test), then query the SIEM a few minutes later and confirm the alert exists. If it doesn’t, that is itself an alert, routed to whoever owns the pipeline. Frameworks like Atomic Red Team provide catalogued, benign test procedures mapped to ATT&CK techniques, which saves you writing your own for common cases.

    Review like you mean it

    A pull request for a detection should answer the same questions as any code review, plus a few of its own. What behaviour does it catch, and what’s the evidence? Which fixtures prove it? What’s the expected alert volume, measured by running the converted query over the last 30 days of real data? Who triages it, and what does the runbook say they should do first?

    That last question gets skipped constantly. A rule without a response plan just moves the problem from “we didn’t see it” to “we saw it and didn’t know what to do”.

    Once you have dozens of tested rules, the next problem shows up fast: too many alerts. That’s the subject of part 3.

    Other parts: Part 1: Logging that actually helps an investigation. Part 3: Alert fatigue: tuning detections without going blind.