# CVE-2026-40397 — Windows CLFS `clfs.sys` Integer Underflow in Reservation Accounting

---

## Summary

| **Product**           | Microsoft Windows — `clfs.sys` (Common Log File System kernel driver) |
|-----------------------|-----------------------------------------------------------------------|
| **Vendor**            | Microsoft Corporation |
| **Severity**          | High |
| **Affected Versions** | Windows 10 (all versions); Windows 11 (21H2–24H2); Windows Server 2016–2025 |
| **Impact**            | Elevation of Privilege — Local user to SYSTEM |
| **CVE ID**            | CVE-2026-40397 |
| **CWE**               | CWE-191: Integer Underflow (Wrap or Wraparound) |
| **Patch Available**   | Yes |
| **Patch Date**        | May 2026 — KB5089549 (first fix); July 2026 — KB5101650 (hardening) |

---

## CVSS 4.0 Detailed Scoring

**Base Score:** 8.5 (HIGH)
**Vector String:** `CVSS:4.0/AV:L/AC:L/AT:N/PR:L/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H`

| **Metric** | **Value** | **Rationale** |
|---|---|---|
| **Attack Vector (AV)** | Local | Requires local authenticated session |
| **Attack Complexity (AC)** | Low | BLF file format is documented; crafting an unaligned offset is trivial |
| **Attack Requirements (AT)** | None | CLFS is always present in all Windows installations |
| **Privileges Required (PR)** | Low | Standard user account; no administrative rights required |
| **User Interaction (UI)** | None | No interaction from any other user required |
| **Vulnerable System Confidentiality (VC)** | High | SYSTEM-level arbitrary kernel R/W via corrupted reservation size |
| **Vulnerable System Integrity (VI)** | High | Kernel pool metadata corruption enables token swap |
| **Vulnerable System Availability (VA)** | High | Kernel memory corruption causes BSOD |
| **Subsequent System Confidentiality (SC)** | High | SYSTEM access enables credential harvesting |
| **Subsequent System Integrity (SI)** | High | SYSTEM access enables persistence, rootkit deployment |
| **Subsequent System Availability (SA)** | High | Full system compromise |

---

## Product Description

`clfs.sys` is the kernel driver implementing the Common Log File System (CLFS), a general-purpose high-performance logging subsystem used by TxF (Transactional NTFS), Active Directory, MSDTC, and other Windows components. CLFS operates on Base Log Files (`.blf`) containing control records, general metadata, scratch blocks, and container descriptors. Log operations include reservation management — the kernel tracks how much space has been reserved for pending writes via `CClfsLogFcbPhysical` fields at offsets `+0x1d0` (reserved size) and `+0x1d8` (committed size).

CLFS has been a persistent source of kernel EoP vulnerabilities (CVE-2022-24521, CVE-2022-37969, CVE-2023-23376, CVE-2023-28252) due to its complex on-disk format and the trust placed in file-sourced metadata. CVE-2026-40397 continues this pattern — the vulnerability lies in the reservation accounting arithmetic, not the control record parsing that earlier CVEs targeted.

---

## Vulnerability Summary

`CClfsLogFcbPhysical::AdjustReservation` (extracted from the former inline code in `UnmarkLogFileContainers`) performs unsigned subtraction on reservation sizes without underflow guards. When a caller supplies an offset that isn't sector-aligned (not a multiple of 512 bytes), the `RawSectorAlign()` function produces alignment-dependent results that can make the intermediate subtraction `_Var6 - _Var7` underflow as unsigned, and then the outer subtraction `uVar5 - (...)` underflows again, producing a huge reservation size from a small/negative input. The corrupted reservation size is written back to the kernel `CClfsLogFcbPhysical` object at offset `+0x1d0`, enabling subsequent heap corruption via oversized reservation allocations.

---

## Prerequisites and Constraints

- Local authenticated session (standard user; no administrative rights required)
- CLFS is always present — it is a core Windows kernel component, not optional
- BLF files can be created in any user-writable directory via `CreateLogFile` API
- No kernel driver, special hardware, or pre-existing SYSTEM token required
- No user interaction or social engineering required
- The vulnerability is in reservation accounting, reachable via normal log operations after opening a crafted BLF

---

## Vulnerability Details

### Vulnerable Code Path

The vulnerability lives in the reservation-pointer arithmetic that used to execute inline within `CClfsLogFcbPhysical::UnmarkLogFileContainers`. In the May 2026 patch, this arithmetic was extracted into a new standalone function, `CClfsLogFcbPhysical::AdjustReservation` (address `0x14007feb0` in the post-patch binary), and a feature flag was added to gate a new alignment check.

Pre-patch, the critical code path is:

```
CClfsLogFcbPhysical::UnmarkLogFileContainers()
  → [inline reservation arithmetic]
    → ExAcquireResourceExclusiveLite(this+200, 1)
    → _Var2 = *(this + 0x1d8)    // committed size
    → uVar5 = *(this + 0x1d0)    // reserved size
    → _Var8 = *param_2            // caller-supplied offset (from BLF metadata)
    → if (_Var8 < 0):
        _Var8 = _Var2 + _Var8     // adjust offset relative to committed
        _Var6 = RawSectorAlign(this, _Var8)   // align adjusted offset
        _Var7 = RawSectorAlign(this, _Var2)   // align committed size
        *(this+0x1d8) = _Var8     // update committed
        uVar11 = uVar5 - (_Var6 - _Var7)     // *** INTEGER UNDERFLOW ***
        *(this+0x1d0) = uVar11    // write corrupted reservation size
```

### The Underflow

The subtraction `uVar5 - (_Var6 - _Var7)` is performed as unsigned 64-bit arithmetic. When the caller-supplied offset `*param_2` is not sector-aligned (i.e., `offset & 0x1ff != 0`), `RawSectorAlign` can produce results where `_Var6 < _Var7` due to sector boundary effects. This makes `(_Var6 - _Var7)` wrap to a very large unsigned value, and the outer subtraction then wraps `uVar5` to another huge value, which is stored as the new reservation size at `this+0x1d0`.

An attacker who controls the BLF metadata (the offset supplied via `*param_2`) can craft an unaligned offset that triggers the underflow, producing a reservation size of ~2^64, which corrupts the kernel pool when the oversized reservation is subsequently used.

### The Fix

The May 2026 patch (KB5089549) adds `CClfsLogFcbPhysical::AdjustReservation` with a `Feature_1201914170` feature flag gating an alignment check:

```c
// AdjustReservation — post-patch
uVar5 = Feature_1201914170__private_IsEnabledDeviceUsageNoInline();
if (((int)uVar5 != 0) && ((*param_2 & 0x1ff) != 0)) {
    return -0x3ffffff3;  // STATUS_INVALID_PARAMETER
}
// ... proceed to reservation arithmetic only if offset is sector-aligned
```

The check `*param_2 & 0x1ff != 0` requires the offset to be a multiple of 512 bytes (sector-aligned) before `RawSectorAlign` and the subtraction run. Without it, an unaligned offset can trigger the underflow chain.

### July 2026 Hardening (KB5101650)

The July 2026 patch adds further hardening across the CLFS snapshot path. The same feature flag mechanism (`FUN_140011880`, which reads `DAT_14002a8b8` and checks bit 0x10 for staging rollout) is now called from three additional locations:

1. **`FUN_140038da4`** (constructor-like function) — if the feature flag is enabled, zeroes a 0x2000-byte buffer at `param_1 + 0x14` via `FUN_140018c00` (memset). This ensures snapshot metadata structures are clean-initialized, preventing use of stale reservation values.

2. **`FUN_1400396a0`** (renamed from `FUN_140039668`, `CClfsBaseFileSnapshot::CopyImage`) — if the feature flag is enabled, iterates 0x400 entries starting at `param_1 + 0xa0`, calling `FUN_140064760` and `FUN_140064860` to validate and re-anchor each entry. This prevents snapshot-based reservation confusion.

3. **`FUN_14007e920`** (replacement for deleted `FUN_14007e7d0`) — adds the same 0x400-entry validation loop after the existing cleanup logic, gated by the feature flag.

These changes close secondary attack surfaces where snapshot metadata could carry unvalidated reservation values that bypass the primary `AdjustReservation` alignment check.

---

## Affected Binary Versions

| **Binary** | **Version** | **Status** |
|---|---|---|
| clfs.sys | ≤ 10.0.28000.1896 (pre-May 2026) | Vulnerable |
| clfs.sys | 10.0.28000.2113 (May 2026, KB5089549) | Fixed (primary), feature-flagged |
| clfs.sys | 10.0.26100.8737 (pre-July 2026) | Vulnerable to snapshot path |
| clfs.sys | 10.0.26100.8875 (July 2026, KB5101650) | Hardened (snapshot path closed) |

---

## Detection Guidance

### YARA Rules

#### Rule 1 — Exploit Binary (memory/disk scan)

Detects binaries containing the API combination and BLF manipulation patterns consistent with CVE-2026-40397 exploitation targeting the reservation accounting underflow.

```yara
rule CVE_2026_40397_CLFS_Reservation_Underflow_Exploit {
    meta:
        description = "Detects exploit binaries targeting CVE-2026-40397 CLFS reservation integer underflow"
        cve         = "CVE-2026-40397"
        severity    = "CRITICAL"
        author      = "OnlyFm252 / STAR Labs SG"
        date        = "2026-07-22"
        filetype    = "PE"

    strings:
        /* CLFS Win32 APIs */
        $api_create  = "CreateLogFile" ascii wide
        $api_add     = "AddLogContainer" ascii wide
        $api_reserve = "ReserveAndAppendLog" ascii wide
        $api_flush   = "FlushLogBuffers" ascii wide
        $api_alloc   = "AllocReservedLog" ascii wide

        /* Manipulation patterns */
        $blf_ext     = ".blf" ascii wide nocase
        $log_prefix  = "LOG:" ascii wide

        /* Sector-alignment bypass — unaligned offset constants */
        $unaligned_1 = { FF 01 00 00 }  /* 0x1ff mask */
        $unaligned_2 = { 00 02 00 00 }  /* 0x200 sector size */

        /* NtSetInformationFile / WriteFile for BLF patching */
        $patch_1     = "WriteFile" ascii wide
        $patch_2     = "SetFilePointer" ascii wide

    condition:
        uint16(0) == 0x5A4D
        and $api_create
        and ($api_reserve or $api_alloc)
        and $blf_ext
        and ($unaligned_1 or $unaligned_2)
        and 1 of ($patch_*)
}
```

#### Rule 2 — Malformed BLF with Unaligned Reservation Offset (on-disk artifact)

Detects BLF files where reservation-related metadata fields contain non-sector-aligned values, indicating potential exploitation of the underflow.

```yara
rule CVE_2026_40397_Malformed_BLF_Reservation {
    meta:
        description = "Detects CLFS BLF files with non-sector-aligned reservation offsets (CVE-2026-40397 artifact)"
        cve         = "CVE-2026-40397"
        severity    = "HIGH"
        author      = "OnlyFm252 / STAR Labs SG"
        date        = "2026-07-22"
        filetype    = "BLF"

    strings:
        /* CLFS base record signature pattern */
        $clfs_sig = { C5 0A C4 01 }

    condition:
        filesize < 2MB
        and $clfs_sig

        /* Check reservation fields in control record for non-sector-aligned values.
           Reservation offset is stored in the LogFcb metadata block. If any 64-bit
           value at the known reservation-offset positions has bits 0-8 set (& 0x1ff != 0),
           it's non-sector-aligned — the exact trigger for the underflow. */
        and for any i in (0x1d0, 0x5d0, 0x9d0):
            (uint16(i) & 0x1ff != 0 and uint16(i) != 0)
}
```

### Sigma Rules

#### Rule 1 — CLFS BLF Creation in User-Writable Directory

```yaml
title: CLFS BLF File Creation in Suspicious Location (CVE-2026-40397)
id: a3f8b2c1-4d5e-4f6a-b7c8-9d0e1f2a3b4c
status: experimental
description: |
    Detects creation of CLFS Base Log Files (.blf) in user-writable directories,
    which is a precursor to CVE-2026-40397 exploitation. Legitimate CLFS usage
    typically creates BLF files in system directories.
references:
    - https://onlyfm252.starlabs.sg/cve/CVE-2026-40397/
author: OnlyFm252 / STAR Labs SG
date: 2026-07-22
tags:
    - attack.privilege_escalation
    - attack.t1068
    - cve.2026.40397
logsource:
    product: windows
    category: file_event
detection:
    selection:
        TargetFilename|endswith: '.blf'
        TargetFilename|contains:
            - '\Users\'
            - '\Temp\'
            - '\ProgramData\'
            - '\AppData\'
            - '\Public\'
    filter_legitimate:
        Image|endswith:
            - '\svchost.exe'
            - '\lsass.exe'
            - '\services.exe'
            - '\TxfLog\'
    condition: selection and not filter_legitimate
level: high
falsepositives:
    - Custom applications using CLFS for legitimate logging
    - Development environments testing CLFS APIs
```

#### Rule 2 — Suspicious CLFS API Sequence

```yaml
title: Suspicious CLFS Reservation API Sequence (CVE-2026-40397)
id: b4c9d3e2-5f6a-4b7c-c8d9-0e1f2a3b4c5d
status: experimental
description: |
    Detects a process loading clfsw32.dll and then performing rapid file I/O
    on .blf files — consistent with the create-close-patch-reopen pattern
    used to exploit CVE-2026-40397.
references:
    - https://onlyfm252.starlabs.sg/cve/CVE-2026-40397/
author: OnlyFm252 / STAR Labs SG
date: 2026-07-22
tags:
    - attack.privilege_escalation
    - attack.t1068
    - cve.2026.40397
logsource:
    product: windows
    category: image_load
detection:
    selection_dll:
        ImageLoaded|endswith: '\clfsw32.dll'
    filter_system:
        Image|endswith:
            - '\svchost.exe'
            - '\lsass.exe'
            - '\services.exe'
            - '\wininit.exe'
            - '\System'
    condition: selection_dll and not filter_system
level: medium
falsepositives:
    - Legitimate applications using CLFS for transactional logging
    - Database engines using CLFS
```

### Sysmon Rules

#### Sysmon Configuration — CVE-2026-40397 Detection

```xml
<Sysmon schemaversion="4.90">
  <EventFiltering>

    <!-- Event ID 11: BLF file creation in user-writable directories -->
    <FileCreate onmatch="include">
      <Rule name="CVE-2026-40397: BLF file creation" groupRelation="and">
        <TargetFilename condition="end with">.blf</TargetFilename>
        <TargetFilename condition="contains any">\Users\;\Temp\;\Public\;\AppData\</TargetFilename>
      </Rule>
    </FileCreate>

    <!-- Event ID 7: clfsw32.dll loaded by non-system process -->
    <ImageLoad onmatch="include">
      <Rule name="CVE-2026-40397: CLFS DLL load by non-system process" groupRelation="and">
        <ImageLoaded condition="end with">clfsw32.dll</ImageLoaded>
        <Image condition="excludes">svchost.exe</Image>
        <Image condition="excludes">lsass.exe</Image>
        <Image condition="excludes">services.exe</Image>
        <Image condition="excludes">wininit.exe</Image>
      </Rule>
    </ImageLoad>

    <!-- Event ID 1: Process creation with CLFS exploitation indicators -->
    <ProcessCreate onmatch="include">
      <Rule name="CVE-2026-40397: Process with BLF argument">
        <CommandLine condition="contains">.blf</CommandLine>
      </Rule>
    </ProcessCreate>

    <!-- Event ID 23: BLF file deletion (cleanup after exploitation) -->
    <FileDelete onmatch="include">
      <Rule name="CVE-2026-40397: BLF file cleanup" groupRelation="and">
        <TargetFilename condition="end with">.blf</TargetFilename>
        <TargetFilename condition="contains any">\Users\;\Temp\;\Public\</TargetFilename>
      </Rule>
    </FileDelete>

  </EventFiltering>
</Sysmon>
```

---

## Remediation

1. **Apply patches immediately:** KB5089549 (May 2026) provides the primary fix; KB5101650 (July 2026) hardens the snapshot path.
2. **Verify feature flag activation:** The fix is gated by `Feature_1201914170`. On systems where Microsoft hasn't yet enabled this flag for the cohort, the fix is inert. Check via `reg query "HKLM\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides"` for the feature ID.
3. **Deploy detection rules:** Use the YARA, Sigma, and Sysmon rules above to detect exploitation attempts.
4. **Monitor for BLF creation in user directories:** Legitimate CLFS usage rarely creates `.blf` files in `\Users\`, `\Temp\`, or `\Public\`.
5. **Enable Driver Verifier for clfs.sys** on high-value targets to catch pool corruption early (will BSOD on exploitation attempt rather than allowing silent corruption).

---

## References

- Diff report: [clfs.sys KB5089549 diff (May 2026)](/data/patch_diffs/clfs_sys-kb5089549-40397.md)
- Diff report: [clfs.sys KB5101650 ghidriff diff (July 2026)](/data/patch_diffs/clfs_sys-kb5101650-ghidriff.md)
- Pre-patch binary: [clfs-2026-04.sys](/data/patch_diffs/binaries/clfs-2026-04.sys) (10.0.28000.1896)
- Post-patch binary: [clfs-2026-05.sys](/data/patch_diffs/binaries/clfs-2026-05.sys) (10.0.28000.2113)
- Hardened binary: [clfs-2026-07.sys](/data/patch_diffs/binaries/clfs-2026-07.sys) (10.0.26100.8875)
- CLFS vulnerability history: CVE-2022-24521, CVE-2022-37969, CVE-2023-23376, CVE-2023-28252

<sub>Analysis by OnlyFm252 / STAR Labs SG. Diff source: ghidriff (Ghidra 12.0.4, VersionTrackingDiff engine). This report covers only CVE-2026-40397 (CWE-191, integer underflow in reservation accounting); the same May 2026 patch also covers CVE-2026-40407 (CWE-122, heap-based buffer overflow) — see that CVE's report.</sub>
