A logon arrives at LSA. One branch goes to our authentication package, which almost nothing takes. The normal path goes to MSV1_0, which checks the password, then calls our sub-authentication filter (Auth0, Msv1_0SubAuthenticationFilter) for a veto, and builds the token if there is no objection. The filter decides on the RID from the SAM and never reads the hashes.
Open original
A logon arrives at LSA. One branch goes to our authentication package, which almost nothing takes. The normal path goes to MSV1_0, which checks the password, then calls our sub-authentication filter (Auth0, Msv1_0SubAuthenticationFilter) for a veto, and builds the token if there is no objection. The filter decides on the RID from the SAM and never reads the hashes.
enroll.exe writes the DPAPI-encrypted secret under the SID, and two presence markers: one keyed by the RID of the account, one by its name. The markers come first, so a failed enrollment only makes LSA stricter. The credential provider reads and decrypts the secret. The sub-authentication filter reads the RID marker, the authentication package the name marker, each with a single registry call, because DPAPI and account lookups would call back into LSA.
Open original
enroll.exe writes the DPAPI-encrypted secret under the SID, and two presence markers: one keyed by the RID of the account, one by its name. The markers come first, so a failed enrollment only makes LSA stricter. The credential provider reads and decrypts the secret. The sub-authentication filter reads the RID marker, the authentication package the name marker, each with a single registry call, because DPAPI and account lookups would call back into LSA.
The two MSV1_0 hooks side by side. Left the sub-authentication routine (Auth1 to AuthN): it only runs when a logon selects its package number, which a normal SMB logon never does. MSV1_0 hands it challenge, response and hashes, because the password check is its job, and trusts STATUS_SUCCESS. My first version never checked the password and approved without one. Right the sub-authentication filter (Auth0): MSV1_0 checks the password first and refuses a wrong one without asking the filter. The filter sees the RID and the logon level and can only veto with STATUS_INVALID_WORKSTATION. STATUS_SUCCESS means no objection, and MSV1_0 builds the token.
Open original
The two MSV1_0 hooks side by side. Left the sub-authentication routine (Auth1 to AuthN): it only runs when a logon selects its package number, which a normal SMB logon never does. MSV1_0 hands it challenge, response and hashes, because the password check is its job, and trusts STATUS_SUCCESS. My first version never checked the password and approved without one. Right the sub-authentication filter (Auth0): MSV1_0 checks the password first and refuses a wrong one without asking the filter. The filter sees the RID and the logon level and can only veto with STATUS_INVALID_WORKSTATION. STATUS_SUCCESS means no objection, and MSV1_0 builds the token.
the admin café

Menu / Windows

Build Your Own 2FA for the Windows Logon, Part 2: Inside LSA

The credential provider from Part 1 only sees the logon screen. Part 2 goes into LSA to close the paths it can't reach, with an authentication package and an MSV1_0 sub-authentication filter in C++.

Lukas·Oct 1, 2026·updated ·32 min · French Press 32 min · French Press· Advanced · Strong

Foreword

This is the second part. In Part 1 we built a working TOTP second factor for the Windows logon: a credential provider with a tile, a filter that hides the other tiles, replay protection, a lockout and logging.

At the end of that article I kept repeating the same limit. The credential provider only sits in the UI, so it only sees the UI. Network logon over SMB, runas, scheduled tasks, WinRM, service logons: none of them touch our tile, so none of them ask for a code. I wrote back then that the check would have to move into LSA, and that maybe I would try that in another article. Well, here it is.

This time we write code that runs inside lsass.exe, and that is a lot more dangerous than Part 1. A broken credential provider costs you a tile and you can still get in over Safe Mode. A broken authentication package can stop LSA from starting, and a machine without LSA doesn't boot. And no, Safe Mode doesn't help either.

Important: Everything in this article is a throwaway-VM exercise. Take a snapshot before every single reboot. Have your BitLocker recovery key ready and know how to edit the registry offline from WinRE. If you only want to harden a real machine, read the chapter "Two ways to close the non-interactive paths" and then stop.

One more thing about the state of the code. It compiles for x64, and the exports are checked. But I have not run it on a live LSA yet. Don't trust it until you have tested it yourself, under a kernel debugger, in a VM you can roll back.

note

Changelog, October 2026. I changed this article four times after it first went up. The details are next to the code.

  • Wrong hook. My first version used Msv1_0SubAuthenticationRoutine and assumed MSV1_0 still checks the password afterwards. It doesn't. With that routine the password check is the routine's job, and mine never did one, so a logon that selected it got in without a password. The code uses Msv1_0SubAuthenticationFilter now. It runs after the password check and can only refuse. If you installed the old TacSubAuth.dll, run the new install-subauth.ps1 or uninstall-subauth.ps1, both remove the old registration. The chapter "The sub-authentication filter" explains what went wrong.
  • Three bugs from the Part 3 audit. The audit of Part 3 found three bugs that its filter had copied from this one. A failed registry read let an enrolled account through, catch (...) never caught an access violation, and swprintf_s could end lsass on an overflow. All three are fixed here too.
  • A review against Microsoft's documentation. The authentication package follows the same lsass rules as the filter and returns the account name for the audit record. Both DLLs only return status codes the documentation lists, so the veto is STATUS_INVALID_WORKSTATION. The filter sets all its out-parameters, and no DPAPI code goes into lsass anymore.
  • A missing SAM record. The filter returned "no objection" for a network logon when MSV1_0 passed no SAM record, so "I couldn't tell" came out as "yes". It now refuses that logon. Interactive and pass-through logons without a record keep their old answer. Ristretto's filter in Part 3 got the same fix.

All the code is in this article again. The project is on GitHub: Doppio.

Prerequisites

  • Part 1, or at least the repo. The LSA code uses the same secret store.
  • A Windows 10/11 or Server VM that you can delete. Not a VM you care about.
  • A snapshot. Before every reboot, not once at the beginning.
  • Visual Studio 2026 or 2022 (Community is enough) or the Build Tools, with the "Desktop development with C++" workload.
  • Your BitLocker recovery key, if the VM is encrypted.
  • A WinRE way to edit the registry offline. Boot the install media, open a command prompt, reg load the offline SYSTEM hive. Practice this before you need it.
  • RunAsPPL turned off on the test VM. More about this in the install chapter, because it will otherwise cost you an evening.
  • Ideally a kernel debugger. You cannot attach Visual Studio to lsass.

What this closes and what not

Same as in Part 1, first the limits, then the code.

Closed, if MSV1_0 calls our filter: Network logons for an enrolled account, by the sub-authentication filter. Those are the SMB and remote-access paths from the list above. Take that "if" seriously. Microsoft documents the filter for domain controllers, and whether MSV1_0 also calls it for local accounts on your workstation is the first thing you have to check in the VM.

Not closed: Batch and service logons. They don't arrive at MSV1_0 as network logons, so our filter has no objection. For those you still need the user rights from the next chapter.

Also not closed: runas, the UAC credential prompt and any program that calls LogonUser interactively. Those are interactive logons without our tile. No user right separates them from the console logon, and the filter has no reason to refuse them. They still take the password alone.

A side effect: RDP with Network Level Authentication checks the password with a network logon before the session starts. For an enrolled account the filter refuses that, just like the deny right does. More about this in the install chapter.

And the authentication package closes nothing in practice. It is only ever called when a logon addresses it by package id, which no normal logon does. It's only in the project because it shows how the layer works.

Here is the same in one table, together with the tile from Part 1:

PathLogon typeTile (Part 1)Sub-auth filterDeny rights
Console logon, unlock2, 7asks for the codeno objectionnot touched
RDP, NLA off10asks for the codeno objectionnot touched
RDP with NLA3, then 10asks for the coderefuses the NLA step"deny network" refuses it too
SMB, WinRM, WMI3never calledrefuses, if MSV1_0 calls it"deny network"
IIS or WinRM with Basic auth8never calledprobably no objection, untested"deny network", untested
Scheduled task4never calledno objection"deny batch"
Service5never calledno objection"deny service"
runas, UAC prompt2never calledno objectionnothing to deny

The LSA code makes the decision, and the user rights do the enforcement. You want both.

Two ways to close the non-interactive paths

There are two ways to do this, and they are very different.

The supported way needs no code at all. Windows already has the switch: the "Deny log on ..." user rights. There is one each for network, batch, services and RDP. Set them for the account and those paths are closed, while the console logon with the 2FA tile keeps working. There is a script for it in the repo:

PowerShell
.\deny-noninteractive.ps1 alice

On a real machine, this is what you want. It survives reboots, it cannot crash anything, and it took me ten minutes to write. If your goal is hardening, do this and skip the rest of the article.

The educational way is to write the code that makes that decision yourself, inside LSA. You do not need it for the hardening above. You want it if you want to understand the layer, or build toward something bigger later: push approval, central policy, a TPM-bound secret. That is the rest of this article.

How LSA fits together

The extension points

LSA is a collection of packages. MSV1_0 checks passwords against the local SAM, Kerberos does domain tickets, Negotiate picks between them. Each one is a DLL, and Windows has a few documented ways to add your own. For sub-authentication there are two different hooks, and the difference matters a lot. I learned that the hard way:

Extension pointRegistryCalled
Authentication package...\Lsa\Authentication Packagesonly for logons that address it by id
Sub-authentication routine...\Lsa\MSV1_0\Auth1 ... AuthNby MSV1_0, only for logons that select it, and then it has to check the password itself
Sub-authentication filter...\Lsa\MSV1_0\Auth0by MSV1_0, after it has checked the password, to veto
Security Support Provider (SSP/AP)...\Lsa\Security Packagesfor logons across the board
Password filter...\Lsa\Notification Packageson password changes

We build the authentication package and the filter. The SSP/AP is the interesting and dangerous one, and it gets its own chapter at the end, including why I am not building it.

Where our two pieces sit

This is the part that took me longest to get straight, so here it is as a picture:

The difference is who calls whom. Our authentication package waits to be addressed and is therefore mostly idle. Our sub-auth filter is called by MSV1_0, from inside the processing of a logon that MSV1_0 is already handling, after the password check. That's why it sees logons the other one never sees.

Architecture of the LSA part

Part 2 adds these files to the project:

FilePurpose
ap.h/.cppThe authentication package. Denies non-interactive logons addressed to it
subauth_filter.h, subauth.cppThe MSV1_0 sub-authentication filter (Auth0). The part that can actually refuse something
TacAuthPackage.def, TacSubAuth.defThe exports, because LSA looks them up by name
install-authpackage.ps1, uninstall-authpackage.ps1Registration of the authentication package
install-subauth.ps1, uninstall-subauth.ps1Registration of the sub-auth filter
deny-noninteractive.ps1The supported way, no code in LSA
build-lsa.batBuilds only the two LSA DLLs
lsasafe.hThe rules for code in lsass, shared by both DLLs: a string builder without the CRT and the exception filter
store_index.cpp, storekeys.hThe two index reads. The only part of the store that goes into lsass
tests/native/test_lsa.cppRuns the real LSA code on Linux, against a fake registry

And it reads two small indexes that the store from Part 1 writes. The code for that turned out to be the hardest part of this article, so it gets its own chapter and its own file.

The authentication package

What LSA calls

You add your DLL's base name to a single registry value:

HKLM\SYSTEM\CurrentControlSet\Control\Lsa
    Authentication Packages = msv1_0   (REG_MULTI_SZ)

LSA loads it at boot and calls the functions it exports, by name. The ones that matter:

  • LsaApInitializePackage runs once, at load. You get a dispatch table with LSA's own heap allocator, and you hand back your package name.
  • LsaApLogonUserEx2 runs once per logon that targets your package. This is where the decision happens.
  • LsaApCallPackage and its two siblings are a side channel for tools to talk to the package later. We stub them.
  • LsaApLogonTerminated is cleanup when a logon session ends.

Because the exports are looked up by name, they are plain C linkage and listed in a .def file. Nothing decorated.

ap.h:

C++
#pragma once
//
// Doppio LSA authentication package (SKELETON).
//
// This runs inside LSA (lsass.exe), not in LogonUI. An authentication package
// is only invoked for logons that address it by package id, so by itself it
// does NOT see the standard network/batch logon paths - those go to MSV1_0 /
// Negotiate. To gate those, see the sub-authentication filter (subauth.cpp),
// which MSV1_0 calls after it has validated a logon.
//
// Policy of this skeleton: for an enrolled account, deny every NON-interactive
// logon that reaches us. Interactive and unlock are left to the credential
// provider, which already asks for the TOTP.
//
// Be clear about what that is worth: NOTHING as a security control. A logon
// only reaches this package if the caller asks for it by package id, and every
// such logon fails anyway - denied with STATUS_ACCOUNT_RESTRICTION, or declined
// with STATUS_INVALID_LOGON_TYPE, because this package never builds a token. No
// real logon path is closed by loading it. It is here to show the LSA package
// interface and the logging, nothing more. The path that actually matters is
// the sub-authentication filter (subauth.cpp) or, on a real machine, the user
// rights.
//
// It does follow the lsass rules in lsasafe.h all the same (no heap or CRT of
// our own on the logon path, SEH around the decision), because the DLL is
// loaded into lsass at every boot once it is registered, and "it fails the
// logon anyway" is no comfort if it faults while doing so.
//
// WARNING: this code runs in lsass.exe. A bug here does not fail one tile - it
// can crash LSA and leave the machine unbootable, past Safe Mode. Only ever
// load it in a throwaway VM with a snapshot, and debug it over a kernel
// debugger (WinDbg on a second machine). See the article chapter
// "2FA inside LSA" for the setup and the honest limits.
//
// The exports are looked up by name by LSA, so they are C-linkage and listed
// in TacAuthPackage.def.

#define SECURITY_WIN32
#include <windows.h>
#include <sspi.h>
#include <ntsecapi.h>
#include <ntsecpkg.h>

extern "C"
{
    NTSTATUS NTAPI LsaApInitializePackage(
        ULONG AuthenticationPackageId,
        PLSA_DISPATCH_TABLE LsaDispatchTable,
        PLSA_STRING Database,
        PLSA_STRING Confidentiality,
        PLSA_STRING* AuthenticationPackageName);

    NTSTATUS NTAPI LsaApLogonUserEx2(
        PLSA_CLIENT_REQUEST ClientRequest,
        SECURITY_LOGON_TYPE LogonType,
        PVOID ProtocolSubmitBuffer,
        PVOID ClientBufferBase,
        ULONG SubmitBufferSize,
        PVOID* ProfileBuffer,
        PULONG ProfileBufferSize,
        PLUID LogonId,
        PNTSTATUS SubStatus,
        PLSA_TOKEN_INFORMATION_TYPE TokenInformationType,
        PVOID* TokenInformation,
        PUNICODE_STRING* AccountName,
        PUNICODE_STRING* AuthenticatingAuthority,
        PUNICODE_STRING* MachineName,
        PSECPKG_PRIMARY_CRED PrimaryCredentials,
        PSECPKG_SUPPLEMENTAL_CRED_ARRAY* CachedCredentials);

    NTSTATUS NTAPI LsaApCallPackage(
        PLSA_CLIENT_REQUEST ClientRequest, PVOID ProtocolSubmitBuffer,
        PVOID ClientBufferBase, ULONG SubmitBufferLength,
        PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength,
        PNTSTATUS ProtocolStatus);

    NTSTATUS NTAPI LsaApCallPackageUntrusted(
        PLSA_CLIENT_REQUEST ClientRequest, PVOID ProtocolSubmitBuffer,
        PVOID ClientBufferBase, ULONG SubmitBufferLength,
        PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength,
        PNTSTATUS ProtocolStatus);

    NTSTATUS NTAPI LsaApCallPackagePassthrough(
        PLSA_CLIENT_REQUEST ClientRequest, PVOID ProtocolSubmitBuffer,
        PVOID ClientBufferBase, ULONG SubmitBufferLength,
        PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength,
        PNTSTATUS ProtocolStatus);

    VOID NTAPI LsaApLogonTerminated(PLUID LogonId);
}

A word about the includes, because I lost quite some time on them. ntsecpkg.h does not compile on its own. You need SECURITY_WIN32 defined and sspi.h included before it, otherwise you get a wall of errors about undeclared types. And ntstatus.h clashes with windows.h, so instead of including it I define the status values I return by hand.

The logon type

LsaApLogonUserEx2 gets handed the SECURITY_LOGON_TYPE directly. That is an enum, and it tells you exactly what kind of logon this is without parsing anything:

ValueNameWhat it is
2Interactiveconsole logon
3NetworkSMB and most remote access
4Batchscheduled tasks
5Serviceservice accounts
7Unlockunlock after locking the screen
8NetworkCleartexte.g. IIS basic auth
9NewCredentialsrunas /netonly
10RemoteInteractiveRDP
11CachedInteractivecached domain credentials
12CachedRemoteInteractiveRDP with cached domain credentials
13CachedUnlockunlock with cached domain credentials

Interactive, Unlock and RemoteInteractive all have a UI where our tile from Part 1 asks for the code. Those we let through, and the three cached types too, because they only exist for domain accounts. The other five have no UI, so for an enrolled account there is no way to ask for a second factor. So we refuse them.

Reading the account name from the submit buffer

In my first draft I left one thing deliberately off: reading which account is logging in. Without it the package can only deny everyone, which is useless. With it, the hard part is doing it safely.

The account name lives in the submit buffer, in a UNICODE_STRING. The catch is that its Buffer is not a pointer we can follow, and it comes in two forms. Either it's an address in the client's address space. Then LSA hands us ClientBufferBase, the address the buffer had over there, and we relocate it into our own copy. Or it's already an offset from the start of the buffer. That's how Winlogon and LogonUI pack a KERB_INTERACTIVE_UNLOCK_LOGON, with the same KerbInteractiveUnlockLogonPack that our tile uses in Part 1. My first version only knew the first form and read a packed buffer as an empty name.

Get this wrong and you dereference a wild pointer inside lsass, at boot. So every step is bounds-checked, and anything that does not add up gives an empty name. Then the package declines instead of denying. Both fail the logon, only the status code and the log line are different.

Why the check is a plain registry read

My first version did the obvious thing. Resolve the name to a SID with LookupAccountName, then call LoadSecretKey from Part 1 to decrypt the secret and confirm it exists. That works in a test, and it's exactly how you get a boot loop.

The reason is where this code runs. The sub-authentication filter runs inside MSV1_0's logon processing, inside lsass, with LSA's locks held. LookupAccountName calls back into LSA. CryptUnprotectData with machine scope calls back into lsass's own DPAPI. Re-entering LSA from a call LSA is already in the middle of is how you deadlock the logon path.

You will not see it in a user-mode test, because in a test your process is not lsass and there is no lock to deadlock on. You see it when the VM hangs at boot with no error and no event, and you reach for the snapshot.

So the decision has to run without re-entering LSA. The secret stays keyed by SID and DPAPI-encrypted, for the credential provider. On top of that, StoreSecret also writes two tiny indexes under a locked-down key: one keyed by the RID of the account, one by its name. Just markers, no secret. The hot path does a single registry read, which is served by the kernel's configuration manager and not by LSA's auth logic, so it is safe to call from here.

Added to store.h:

C++
    // Hot-path enrollment checks for code that runs INSIDE lsass. Each is a
    // single registry read: no DPAPI decrypt and no account-name or SID lookup,
    // so nothing calls back into LSA and the logon path cannot deadlock.
    // Neither allocates: a caller in lsass must not risk std::bad_alloc.
    //
    // Three outcomes, because a caller that VETOES must not read a failed read
    // as "not enrolled" - that is the one wrong answer that lets an enrolled
    // account through. A missing index key is No (nothing indexed on this
    // machine at all); any other read error is Unknown.
    enum class Enrollment { No, Yes, Unknown };

    // EnrollmentByRid is the one to use whenever the caller has the account's
    // RID from the SAM (the MSV1_0 sub-authentication filter gets it in
    // USER_ALL_INFORMATION). A RID survives a rename and the SAM never hands
    // out a RID twice, so this index can neither miss a renamed account nor
    // match a different, re-created one.
    Enrollment EnrollmentByRid(DWORD rid);

    // IsEnrolledByRid is EnrollmentByRid(rid) == Yes, so it reads every failure
    // as "not enrolled". Only for callers that do not veto.
    bool IsEnrolledByRid(DWORD rid);

    // EnrollmentByName is only for callers that have nothing but the name a
    // client typed (the authentication package). `name` is counted, not
    // null-terminated, and is normalized into a fixed buffer here.
    //
    // It is weaker than the RID check and fails OPEN in one case: after an
    // enrolled account is renamed, the index still holds the old name, so the
    // new name reads as "not enrolled" until `enroll /reindex` runs. A
    // re-created account with an old name reads as enrolled (more
    // restrictive). Prefer EnrollmentByRid wherever the RID is available.
    Enrollment EnrollmentByName(const WCHAR* name, SIZE_T cch);

The reads have their own file, store_index.cpp. It's the only part of the store that the two DLLs in lsass link. store.cpp, with DPAPI and the account lookups, stays in LogonUI and enroll.exe. My first version had the reads in store.cpp too, so both DLLs carried DPAPI and TOTP code into lsass without ever calling it. The registry paths are in storekeys.h, so both files use the same ones.

storekeys.h:

C++
#pragma once
// Registry layout of the 2FA store. Internal to store.cpp and store_index.cpp.
#include <windows.h>

namespace tac
{
    namespace keys
    {
        // Secrets: one REG_BINARY value per SID, DPAPI-protected.
        static const wchar_t kSecrets[] = L"SOFTWARE\\TheAdminCafe\\2FA";
        // Replay and lockout state: one UserState per SID.
        static const wchar_t kState[]   = L"SOFTWARE\\TheAdminCafe\\2FA\\State";
        // Enrollment indexes for the LSA hot path (presence only, no secret).
        static const wchar_t kNames[]   = L"SOFTWARE\\TheAdminCafe\\2FA\\Names";
        static const wchar_t kRids[]    = L"SOFTWARE\\TheAdminCafe\\2FA\\Rids";

        // UNLEN + 1. Nothing the SAM stores comes close.
        static const SIZE_T kMaxNameCch = 257;
    }
}

store_index.cpp:

C++
// The enrollment-index reads that run INSIDE lsass: the sub-authentication
// filter and the authentication package link this file and nothing else from
// the store. No DPAPI, no TOTP, no name or SID lookup, no heap and no CRT of
// our own - see lsasafe.h for why each of those matters in lsass.
//
// Everything that writes the indexes, or needs DPAPI, lives in store.cpp and
// only ever runs in LogonUI or enroll.exe.

#include "store.h"
#include "storekeys.h"

#pragma comment(lib, "advapi32.lib")

namespace tac
{
    bool NormalizeUserInto(const WCHAR* user, SIZE_T cch, WCHAR* out, SIZE_T outCap)
    {
        if (!user || !out || outCap == 0)
            return false;
        out[0] = L'\0';

        // Stop at an embedded NUL: nothing after it belongs to the name.
        SIZE_T len = 0;
        while (len < cch && user[len] != L'\0')
            ++len;

        // Keep only what follows the last backslash.
        SIZE_T start = 0;
        for (SIZE_T i = 0; i < len; ++i)
            if (user[i] == L'\\')
                start = i + 1;

        const SIZE_T bare = len - start;
        if (bare == 0 || bare >= outCap)
            return false;

        // LOCALE_INVARIANT, so "JÖRG" and "jörg" fold the same way on every
        // machine. Plain towlower only ever folded ASCII, which made the name
        // index miss non-ASCII names.
        const int written = LCMapStringW(LOCALE_INVARIANT, LCMAP_LOWERCASE,
                                         user + start, static_cast<int>(bare),
                                         out, static_cast<int>(outCap - 1));
        if (written > 0 && static_cast<SIZE_T>(written) < outCap)
        {
            out[written] = L'\0';
            return true;
        }

        // NLS unavailable or the mapping did not fit: fold ASCII only, which
        // is what every name used to get.
        for (SIZE_T i = 0; i < bare; ++i)
        {
            const WCHAR c = user[start + i];
            out[i] = (c >= L'A' && c <= L'Z') ? static_cast<WCHAR>(c - L'A' + L'a') : c;
        }
        out[bare] = L'\0';
        return true;
    }

    // The RID as the decimal value name of the Rids index, without the CRT.
    // This runs inside lsass, where swprintf_s on an overflow would end the
    // process. A DWORD has at most 10 digits, so out[12] always fits.
    static void RidToValueName(DWORD rid, WCHAR (&out)[12])
    {
        WCHAR digits[10];
        int n = 0;
        do
        {
            digits[n++] = static_cast<WCHAR>(L'0' + rid % 10);
            rid /= 10;
        } while (rid != 0 && n < 10);

        int i = 0;
        while (n > 0)
            out[i++] = digits[--n];
        out[i] = L'\0';                   // i <= 10, so this is in bounds
    }

    // One registry read of an index key, with the three outcomes a vetoing
    // caller needs.
    static Enrollment QueryIndex(const wchar_t* path, const WCHAR* value)
    {
        HKEY hKey = nullptr;
        LSTATUS status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hKey);
        if (status == ERROR_FILE_NOT_FOUND)
            return Enrollment::No;          // no index on this machine at all
        if (status != ERROR_SUCCESS)
            return Enrollment::Unknown;

        status = RegQueryValueExW(hKey, value, nullptr, nullptr, nullptr, nullptr);
        RegCloseKey(hKey);

        if (status == ERROR_SUCCESS)
            return Enrollment::Yes;
        if (status == ERROR_FILE_NOT_FOUND)
            return Enrollment::No;
        // Only a value that is really not there counts as "not enrolled". Any
        // other failure is Unknown: a filter that read it as "not enrolled"
        // would wave an enrolled account through on one unexpected error.
        return Enrollment::Unknown;
    }

    Enrollment EnrollmentByRid(DWORD rid)
    {
        if (rid == 0)
            return Enrollment::No;

        WCHAR value[12];
        RidToValueName(rid, value);
        return QueryIndex(keys::kRids, value);
    }

    bool IsEnrolledByRid(DWORD rid)
    {
        return EnrollmentByRid(rid) == Enrollment::Yes;
    }

    Enrollment EnrollmentByName(const WCHAR* name, SIZE_T cch)
    {
        WCHAR normalized[keys::kMaxNameCch];
        if (!NormalizeUserInto(name, cch, normalized, ARRAYSIZE(normalized)))
            return Enrollment::Unknown;     // unusable name: never claim "No"

        return QueryIndex(keys::kNames, normalized);
    }
}

And StoreSecret in store.cpp writes the indexes first and the secret second. Two small helpers write the markers:

C++
    // Writes a presence flag (REG_DWORD 1) under one of the index keys.
    static bool SetFlag(const wchar_t* path, const std::wstring& value)
    {
        HKEY hKey = nullptr;
        if (OpenProtectedKey(path, &hKey) != ERROR_SUCCESS)
            return false;
        DWORD one = 1;
        bool ok = RegSetValueExW(hKey, value.c_str(), 0, REG_DWORD,
                                 reinterpret_cast<const BYTE*>(&one), sizeof(one)) == ERROR_SUCCESS;
        RegCloseKey(hKey);
        return ok;
    }

    // Writes the RID index and, if the SID still resolves to a name, the name
    // index for one enrolled SID.
    static void WriteIndexes(const std::wstring& sid, bool& ridOk, bool& nameOk)
    {
        ridOk = nameOk = false;

        DWORD rid = 0;
        if (RidFromSidString(sid, rid))
            ridOk = SetFlag(kRids, std::to_wstring(rid));

        std::wstring name;
        if (NameFromSid(sid, name))
            nameOk = SetFlag(kNames, name);
    }

StoreSecret calls them before it touches the secret:

C++
    bool StoreSecret(const std::wstring& sid, const std::string& base32Secret)
    {
        if (!IsSidString(sid))
            return false;

        std::vector<BYTE> blob;
        if (!Protect(base32Secret, blob))
            return false;

        // The indexes the LSA hot path reads come first. If they cannot be
        // written, nothing else is touched, so a re-enrollment that fails
        // leaves the old enrollment working. If the secret then fails, the
        // index entries stay behind: that only makes the LSA packages refuse
        // MORE (network logon of an account without a secret), never less,
        // and `enroll /remove` clears them.
        bool ridOk = false, nameOk = false;
        WriteIndexes(sid, ridOk, nameOk);
        if (!ridOk || !nameOk)
            return false;

        HKEY hKey = nullptr;
        LSTATUS status = OpenProtectedKey(kSecrets, &hKey);
        if (status == ERROR_SUCCESS)
        {
            status = RegSetValueExW(hKey, sid.c_str(), 0, REG_BINARY,
                                    blob.data(), static_cast<DWORD>(blob.size()));
            RegCloseKey(hKey);
        }
        return status == ERROR_SUCCESS;
    }

The order matters. A secret without an index is bad: the tile works, and the LSA part silently thinks the account is not enrolled. My first version wrote the secret first and deleted it again if the index failed. When you enrolled someone again, that destroyed an enrollment that worked. Now the indexes come first. If they can't be written, nothing else is changed and the old enrollment keeps working. If the secret fails after the indexes, the markers stay. That only makes the LSA side refuse more, never less, and enroll.exe /remove deletes them.

Why two indexes? The first version only had the name. Part 1 has a whole chapter on why the secret belongs to the SID, and the name index brought the old weakness back. I wrote that it only fails in the strict direction. That was wrong. If you delete alice and create a new alice, the new account reads as enrolled. Too strict, fine. But if you rename alice to alicia, the index still says alice. Now alicia reads as not enrolled, and her network logons work with the password alone. Too loose.

The filter doesn't need the name at all. MSV1_0 gives it the account record from the SAM, and the RID in there is the last part of the SID. It stays the same after a rename, and the SAM never gives the same RID to a new account. So the filter asks the RID index. That one really is as safe as I thought the name index was. Only the authentication package still reads the name, because it only has what the client typed. There it doesn't matter, as you will see in the next chapter. After a rename, or after an update from the old version, run enroll.exe /reindex once.

Why it can only deny

Now the part that decides how big the project gets. In LsaApLogonUserEx2 you can do two things: deny, or let the logon succeed.

Denying is one line. You return STATUS_ACCOUNT_RESTRICTION and LSA refuses.

Letting a logon succeed is a completely different amount of work. On success your package has to build the whole result: a logon token, a profile buffer, the account SID, the group memberships, everything the real packages spend thousands of lines producing. You do not want to reimplement MSV1_0. And a package that sits transparently in front of MSV1_0 to pass credentials through is exactly the shim that credential-theft tooling uses. MITRE ATT&CK lists it under T1556, the same entry as the malicious credential provider from Part 1. I am not going to write that.

So the package only ever denies or declines. The deny is STATUS_ACCOUNT_RESTRICTION, with the reason in SubStatus. The decline is STATUS_INVALID_LOGON_TYPE, and that one is easy to misread. It means "this package does not handle this logon", and LSA doesn't retry it against MSV1_0. A caller that selected us by package id and gets this back has its logon fail right there.

My first version declined with STATUS_NOT_IMPLEMENTED. That one isn't on the list of values this function may return, and inside lsass I don't want to find out what LSA does with an answer it doesn't expect.

ap.cpp:

C++
#include "ap.h"
#include "lsasafe.h"
#include "store.h"

#pragma comment(lib, "advapi32.lib")

// NTSTATUS values we return. They live in ntstatus.h, which clashes with
// windows.h, so we define the handful we need. Every one of these is listed in
// the documentation of LSA_AP_LOGON_USER_EX2 as a value this callback may
// return - STATUS_NOT_IMPLEMENTED, which this package used to decline with,
// is not.
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS             ((NTSTATUS)0x00000000L)
#endif
#ifndef STATUS_ACCOUNT_RESTRICTION
#define STATUS_ACCOUNT_RESTRICTION ((NTSTATUS)0xC000006EL)  // "account not allowed to log on here/now"
#endif
#ifndef STATUS_INVALID_LOGON_TYPE
#define STATUS_INVALID_LOGON_TYPE  ((NTSTATUS)0xC000010BL)
#endif
#ifndef STATUS_INVALID_WORKSTATION
#define STATUS_INVALID_WORKSTATION ((NTSTATUS)0xC0000070L)
#endif
#ifndef STATUS_NOT_IMPLEMENTED
#define STATUS_NOT_IMPLEMENTED     ((NTSTATUS)0xC0000002L)
#endif
#ifndef STATUS_INVALID_PARAMETER
#define STATUS_INVALID_PARAMETER   ((NTSTATUS)0xC000000DL)
#endif
#ifndef STATUS_NO_MEMORY
#define STATUS_NO_MEMORY           ((NTSTATUS)0xC0000017L)
#endif

// Every export below runs inside lsass.exe, so the rules from lsasafe.h apply:
// no heap of our own and no CRT on the logon path, and SEH rather than C++
// try/catch, because under /EHsc a catch (...) does not catch the access
// violation a bad pointer from the caller would cause. The only allocations
// here come from the LSA heap, through the dispatch table, because LSA asks
// for the account name that way and frees it itself.

// Kerberos message types we recognise in a submit buffer.
#ifndef KerbInteractiveLogon
#define KerbInteractiveLogon        2
#endif
#ifndef KerbWorkstationUnlockLogon
#define KerbWorkstationUnlockLogon  7
#endif

namespace
{
    PLSA_DISPATCH_TABLE g_lsa = nullptr;
    ULONG               g_packageId = 0;

    // UNLEN + 1.
    const SIZE_T kApNameCch = 257;

    // Logging from inside lsass. OutputDebugStringW is the channel you
    // actually read under a kernel debugger. ReportEvent is best-effort on top,
    // guarded so a logging failure can never affect a logon. We never log a
    // password or a code, only metadata.
    void ApLog(WORD type, DWORD id, const WCHAR* text)
    {
        WCHAR debug[320];
        tac::Buf d(debug, ARRAYSIZE(debug));
        d.Str(L"[Doppio-AP] ");
        d.Str(text);
        d.Str(L"\n");
        OutputDebugStringW(debug);

        HANDLE h = RegisterEventSourceW(nullptr, L"TheAdminCafe 2FA");
        if (h)
        {
            LPCWSTR s[1] = { text };
            ReportEventW(h, type, 0, id, nullptr, 1, 0, s, nullptr);
            DeregisterEventSource(h);
        }
    }

    bool IsNonInteractive(SECURITY_LOGON_TYPE t)
    {
        switch (t)
        {
        case Network:            // 3
        case Batch:              // 4
        case Service:            // 5
        case NetworkCleartext:   // 8
        case NewCredentials:     // 9
            return true;
        default:
            return false;
        }
    }

    const wchar_t* LogonTypeName(SECURITY_LOGON_TYPE t)
    {
        switch (t)
        {
        case Interactive:       return L"Interactive";
        case Network:           return L"Network";
        case Batch:             return L"Batch";
        case Service:           return L"Service";
        case Unlock:            return L"Unlock";
        case NetworkCleartext:  return L"NetworkCleartext";
        case NewCredentials:    return L"NewCredentials";
        case RemoteInteractive: return L"RemoteInteractive";
        case CachedInteractive: return L"CachedInteractive";
        default:                return L"Other";
        }
    }

    // A UNICODE_STRING inside the submit buffer has a Buffer field that is not
    // a pointer we may follow. Two forms reach us:
    //
    //   * an address in the CLIENT process. LSA hands us ClientBufferBase, the
    //     address the buffer had there, so the difference is the offset into
    //     our copy.
    //   * a plain offset from the start of the submit buffer. That is how
    //     Winlogon and LogonUI pack a KERB_INTERACTIVE_UNLOCK_LOGON - see
    //     KerbInteractiveUnlockLogonPack in Microsoft's credential provider
    //     sample, whose comment says the members "are not actually pointers
    //     but byte offsets into the overall buffer". The old code only knew
    //     the first form and read a packed buffer as an empty name.
    //
    // Everything is bounds-checked against the submit buffer. Anything off
    // copies nothing and the caller fails safe. Writes into a caller buffer:
    // no heap, no CRT.
    bool ReadClientString(const UNICODE_STRING& us,
                          const void* submitBase, const void* clientBase, ULONG submitSize,
                          WCHAR* out, SIZE_T outCap, SIZE_T& outCch)
    {
        outCch = 0;
        if (outCap)
            out[0] = L'\0';

        if (!submitBase || !outCap || !us.Buffer || us.Length == 0 ||
            (us.Length % sizeof(WCHAR)) != 0)
            return false;

        const ULONG_PTR p    = reinterpret_cast<ULONG_PTR>(us.Buffer);
        const ULONG_PTR base = reinterpret_cast<ULONG_PTR>(clientBase);

        ULONG_PTR off = 0;
        if (clientBase && p >= base && (p - base) <= submitSize)
            off = p - base;                 // client address, relocated
        else if (p < submitSize)
            off = p;                        // already an offset
        else
            return false;

        if ((off % sizeof(WCHAR)) != 0 || us.Length > submitSize - off)
            return false;

        const WCHAR* s = reinterpret_cast<const WCHAR*>(
            static_cast<const BYTE*>(submitBase) + off);

        SIZE_T cch = us.Length / sizeof(WCHAR);
        if (cch > outCap - 1)
            cch = outCap - 1;

        SIZE_T n = 0;
        while (n < cch && s[n] != L'\0')
        {
            out[n] = s[n];
            ++n;
        }
        out[n] = L'\0';
        outCch = n;
        return n > 0;
    }

    // What the decision produced. A plain struct with fixed buffers, so the
    // __try frame in the export holds nothing that needs unwinding.
    struct Decision
    {
        bool             deny;
        bool             haveName;
        tac::Enrollment  enrolled;
        WCHAR            name[kApNameCch];
        SIZE_T           nameCch;
    };

    // The account check. We read ONLY the user name from the submit buffer
    // (never the password field) and ask the store, with a single registry
    // read, whether that name is enrolled. EnrollmentByName does no DPAPI and
    // no LSA name/SID lookup, so it is safe on the logon path, and it does not
    // allocate.
    //
    // The name is what the CLIENT typed, and the name index is not updated by
    // a rename (see store.h), so this check is weaker than the RID check in
    // the sub-authentication filter. It does not matter here - this package
    // never lets a logon through either way (see ap.h) - but do not copy it
    // into anything that does.
    void Decide(SECURITY_LOGON_TYPE logonType, PVOID submit, ULONG size, PVOID clientBase,
                Decision& d)
    {
        d.deny     = false;
        d.haveName = false;
        d.enrolled = tac::Enrollment::No;
        d.name[0]  = L'\0';
        d.nameCch  = 0;

        // The name first, for every logon type: LSA writes AccountName into
        // the audit record whatever we decide.
        if (!submit || size < sizeof(KERB_INTERACTIVE_LOGON))
            return;

        auto* k = static_cast<const KERB_INTERACTIVE_LOGON*>(submit);
        if (k->MessageType != KerbInteractiveLogon &&
            k->MessageType != KerbWorkstationUnlockLogon)
            return;

        d.haveName = ReadClientString(k->UserName, submit, clientBase, size,
                                      d.name, ARRAYSIZE(d.name), d.nameCch);

        if (!IsNonInteractive(logonType))
            return;                         // the tile already asked for a code
        if (!d.haveName)
            return;

        d.enrolled = tac::EnrollmentByName(d.name, d.nameCch);

        // Yes and Unknown both deny. "Could not tell" must never come out as
        // "not enrolled" - the same rule the sub-authentication filter follows.
        d.deny = d.enrolled != tac::Enrollment::No;
    }

    // LSA puts this in the audit record and frees it itself, so the account
    // name has to come from the LSA heap. The documentation of
    // LSA_AP_LOGON_USER_EX2 says it "must always be returned regardless of the
    // success or failure of the call"; this package used to leave it null.
    PUNICODE_STRING AllocAccountName(const WCHAR* name, SIZE_T cch)
    {
        if (!g_lsa || !g_lsa->AllocateLsaHeap || !g_lsa->FreeLsaHeap)
            return nullptr;
        if (cch > kApNameCch - 1)
            cch = kApNameCch - 1;

        auto* us = static_cast<PUNICODE_STRING>(
            g_lsa->AllocateLsaHeap(sizeof(UNICODE_STRING)));
        if (!us)
            return nullptr;

        const USHORT cb = static_cast<USHORT>(cch * sizeof(WCHAR));
        WCHAR* buf = static_cast<WCHAR*>(g_lsa->AllocateLsaHeap(cb + sizeof(WCHAR)));
        if (!buf)
        {
            g_lsa->FreeLsaHeap(us);
            return nullptr;
        }

        for (SIZE_T i = 0; i < cch; ++i)
            buf[i] = name[i];
        buf[cch] = L'\0';

        us->Length        = cb;
        us->MaximumLength = static_cast<USHORT>(cb + sizeof(WCHAR));
        us->Buffer        = buf;
        return us;
    }
}

NTSTATUS NTAPI LsaApInitializePackage(
    ULONG AuthenticationPackageId,
    PLSA_DISPATCH_TABLE LsaDispatchTable,
    PLSA_STRING /*Database*/,
    PLSA_STRING /*Confidentiality*/,
    PLSA_STRING* AuthenticationPackageName)
{
    if (!LsaDispatchTable || !AuthenticationPackageName)
        return STATUS_INVALID_PARAMETER;
    *AuthenticationPackageName = nullptr;

    g_lsa       = LsaDispatchTable;
    g_packageId = AuthenticationPackageId;

    static const char kName[] = "TacAuthPackage";
    const USHORT len = sizeof(kName) - 1;

    char* buf = static_cast<char*>(g_lsa->AllocateLsaHeap(len + 1));
    if (!buf)
        return STATUS_NO_MEMORY;
    memcpy(buf, kName, len + 1);

    LSA_STRING* name = static_cast<LSA_STRING*>(g_lsa->AllocateLsaHeap(sizeof(LSA_STRING)));
    if (!name)
    {
        g_lsa->FreeLsaHeap(buf);
        return STATUS_NO_MEMORY;
    }
    name->Length        = len;
    name->MaximumLength = len + 1;
    name->Buffer        = buf;
    *AuthenticationPackageName = name;

    // LSA loads authentication packages while it starts, before the Eventlog
    // service is running, so event 200 normally goes nowhere at boot. The
    // [Doppio-AP] debugger line is the one you can rely on here.
    WCHAR text[160];
    tac::Buf b(text, ARRAYSIZE(text));
    b.Str(L"LSA authentication package loaded (id ");
    b.U64(AuthenticationPackageId);
    b.Str(L").");
    ApLog(EVENTLOG_INFORMATION_TYPE, 200, text);

    return STATUS_SUCCESS;
}

// We only ever DENY or decline here; we never mint a token. The deny path
// returns STATUS_ACCOUNT_RESTRICTION with the reason in SubStatus. Otherwise we
// return STATUS_INVALID_LOGON_TYPE to say "this package does not handle this
// logon". Note: a caller that selects this package by id has its logon fail
// here either way; it is not transparently retried against MSV1_0. Standard
// network/batch logons do not address this package at all - that is what the
// sub-authentication filter (subauth.cpp) is for. See the article, "deny is
// easy, success is hard".
NTSTATUS NTAPI LsaApLogonUserEx2(
    PLSA_CLIENT_REQUEST /*ClientRequest*/,
    SECURITY_LOGON_TYPE LogonType,
    PVOID ProtocolSubmitBuffer,
    PVOID ClientBufferBase,
    ULONG SubmitBufferSize,
    PVOID* ProfileBuffer,
    PULONG ProfileBufferSize,
    PLUID /*LogonId*/,
    PNTSTATUS SubStatus,
    PLSA_TOKEN_INFORMATION_TYPE /*TokenInformationType*/,
    PVOID* /*TokenInformation*/,
    PUNICODE_STRING* AccountName,
    PUNICODE_STRING* AuthenticatingAuthority,
    PUNICODE_STRING* MachineName,
    PSECPKG_PRIMARY_CRED /*PrimaryCredentials*/,
    PSECPKG_SUPPLEMENTAL_CRED_ARRAY* CachedCredentials)
{
    if (ProfileBuffer)            *ProfileBuffer = nullptr;
    if (ProfileBufferSize)        *ProfileBufferSize = 0;
    if (SubStatus)                *SubStatus = STATUS_SUCCESS;
    if (AccountName)              *AccountName = nullptr;
    if (AuthenticatingAuthority)  *AuthenticatingAuthority = nullptr;
    if (MachineName)              *MachineName = nullptr;
    if (CachedCredentials)        *CachedCredentials = nullptr;

    Decision d = {};
    bool faulted = false;

    // A bad pointer in the submit buffer would otherwise take lsass down with
    // it, and with it the machine. Nothing in Decide allocates, so there is no
    // state to unwind.
    __try
    {
        Decide(LogonType, ProtocolSubmitBuffer, SubmitBufferSize, ClientBufferBase, d);
    }
    __except (tac::LsaDecisionExceptionFilter(GetExceptionCode()))
    {
        faulted    = true;
        d.deny     = IsNonInteractive(LogonType);   // fail closed
        d.haveName = false;
        d.nameCch  = 0;
        d.name[0]  = L'\0';
    }

    WCHAR text[320];
    tac::Buf b(text, ARRAYSIZE(text));

    NTSTATUS status;
    if (d.deny)
    {
        b.Str(L"Denied a ");
        b.Str(LogonTypeName(LogonType));
        b.Str(L" logon for '");
        b.Str(d.haveName ? d.name : L"?");
        b.Str(faulted ? L"' after an exception while deciding."
                      : (d.enrolled == tac::Enrollment::Unknown
                             ? L"': the enrollment index could not be read."
                             : L"': an enrolled account. This path has no second factor."));
        ApLog(EVENTLOG_WARNING_TYPE, 201, text);

        if (SubStatus) *SubStatus = STATUS_INVALID_WORKSTATION;
        status = STATUS_ACCOUNT_RESTRICTION;
    }
    else
    {
        // Not "passed on": nothing is forwarded anywhere. The caller asked for
        // this package, and this package never builds a token, so the logon
        // fails.
        b.Str(L"Declined a ");
        b.Str(LogonTypeName(LogonType));
        b.Str(L" logon addressed to this package. It fails; this package never "
              L"builds a token.");
        ApLog(EVENTLOG_INFORMATION_TYPE, 202, text);

        status = STATUS_INVALID_LOGON_TYPE;
    }

    // Always, success or failure: LSA writes it to the audit record and frees
    // it. A name we could not read is reported as "-" rather than left null.
    if (AccountName)
        *AccountName = d.haveName ? AllocAccountName(d.name, d.nameCch)
                                  : AllocAccountName(L"-", 1);

    return status;
}

static NTSTATUS CallStub(PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength,
                         PNTSTATUS ProtocolStatus)
{
    if (ProtocolReturnBuffer) *ProtocolReturnBuffer = nullptr;
    if (ReturnBufferLength)   *ReturnBufferLength = 0;
    if (ProtocolStatus)       *ProtocolStatus = STATUS_NOT_IMPLEMENTED;
    return STATUS_SUCCESS;
}

NTSTATUS NTAPI LsaApCallPackage(PLSA_CLIENT_REQUEST, PVOID, PVOID, ULONG,
                                PVOID* rb, PULONG rl, PNTSTATUS ps)
{ return CallStub(rb, rl, ps); }

NTSTATUS NTAPI LsaApCallPackageUntrusted(PLSA_CLIENT_REQUEST, PVOID, PVOID, ULONG,
                                         PVOID* rb, PULONG rl, PNTSTATUS ps)
{ return CallStub(rb, rl, ps); }

NTSTATUS NTAPI LsaApCallPackagePassthrough(PLSA_CLIENT_REQUEST, PVOID, PVOID, ULONG,
                                           PVOID* rb, PULONG rl, PNTSTATUS ps)
{ return CallStub(rb, rl, ps); }

VOID NTAPI LsaApLogonTerminated(PLUID /*LogonId*/)
{
}

A few details in the code:

  • All the out parameters are set at the top, before any decision. If LSA reads an uninitialised pointer because some path forgot to set it, you do not get a clean failure, you get a crash in lsass.
  • The account name always goes back to LSA. The documentation says AccountName "must always be returned regardless of the success or failure of the call", because LSA writes it into the audit record. My first version left it null. Now it comes from the LSA heap, also for logons the package declines, and it's - if the name couldn't be read. LSA frees it.
  • ReadClientString first checks that the offset is inside the buffer and only then us.Length > submitSize - off. The order matters. The other way around, submitSize - off would underflow on an out-of-range offset and the check would pass.
  • Decide only parses two message types. For an unknown one there is no name, so the logon is declined rather than denied. Unknown input has to fail in the harmless direction.
  • If the name index can't be read, the package counts the account as enrolled and denies. EnrollmentByName has the same three answers as the RID read in the filter. Here that only changes the status code, because both fail. But it's the same rule in both DLLs now, and nobody copies the weaker one by accident.
  • AllocateLsaHeap is LSA's allocator from the dispatch table, not new. The package name you hand back belongs to LSA afterwards. If the second allocation fails, the first one has to be freed with FreeLsaHeap. Normally you wouldn't bother with that, but here you have to.
  • ApLog writes to OutputDebugStringW first and the event log second. The event log is best effort. LSA loads the package before the event log service runs, so event 200 hardly ever shows up. The debugger line is the one you can rely on.
  • The package follows the same rules as the filter. My first version built the name and the log lines with std::wstring and caught every C++ exception at the export. Those are two of the three mistakes the filter had, see the details after subauth.cpp. A catch (...) doesn't catch an access violation under /EHsc, and a bad pointer in the submit buffer is exactly what would cause one. Now the package uses fixed buffers and Buf from lsasafe.h, and Decide runs behind __try/__except. After a fault a non-interactive logon is denied.
  • The log line for the decline says what really happens: "Declined ... It fails". My first version said "Passed a ... logon to the normal packages", which is exactly the misreading the paragraph above warns about.

lsasafe.h, which both DLLs use:

C++
#pragma once
//
// Helpers for code that runs INSIDE lsass.exe (the authentication package in
// ap.cpp and the sub-authentication filter in subauth.cpp). The three rules,
// learned the hard way in Part 3 (Ristretto):
//
//   * No heap and no CRT of our own on the decision path. std::wstring can
//     throw std::bad_alloc; swprintf_s calls the invalid-parameter handler on
//     overflow, and the default handler ends the process - here lsass, which
//     is a bugcheck. Build log lines with Buf (it cuts instead) and format
//     numbers without the CRT. (Windows APIs we call - the registry,
//     OutputDebugString, the event log - allocate inside Windows; that is
//     theirs to get right, and none of them throws into our code.)
//   * SEH, not C++ try/catch. With /EHsc a catch (...) does not catch an
//     access violation, and a bad pointer from the caller is the failure that
//     actually matters here. The decision runs behind one __except whose
//     filter is LsaDecisionExceptionFilter.
//
// Both files shared private copies of this before; keeping one copy means a
// fix lands in both at once.

#include <windows.h>

namespace tac
{
    // Bounded, CRT-free wide-string builder. Never writes past `cap`, always
    // null-terminates, and simply stops appending when full (no overflow, no
    // invalid-parameter handler, nothing that could end lsass).
    class Buf
    {
    public:
        Buf(WCHAR* p, SIZE_T cap) : p_(p), cap_(cap), n_(0)
        {
            if (cap_) p_[0] = L'\0';
        }

        void Str(const WCHAR* s)
        {
            if (!s) return;
            while (*s && n_ + 1 < cap_) p_[n_++] = *s++;
            if (cap_) p_[n_] = L'\0';
        }

        void U64(ULONGLONG v)
        {
            WCHAR t[21];
            int i = 0;
            do { t[i++] = (WCHAR)(L'0' + (ULONG)(v % 10)); v /= 10; } while (v && i < 20);
            while (i > 0 && n_ + 1 < cap_) p_[n_++] = t[--i];
            if (cap_) p_[n_] = L'\0';
        }

    private:
        WCHAR* p_;
        SIZE_T cap_;
        SIZE_T n_;
    };

    // Which exceptions the __except around a decision swallows. A stack
    // overflow is not ours to survive: the guard page is gone by the time we
    // run. Everything else here means a bad pointer from the caller, and on
    // that one a dead lsass is the worse outcome, so it is caught and the
    // caller fails closed.
    inline LONG LsaDecisionExceptionFilter(DWORD code)
    {
        switch (code)
        {
        case EXCEPTION_STACK_OVERFLOW:
        case EXCEPTION_NONCONTINUABLE_EXCEPTION:
            return EXCEPTION_CONTINUE_SEARCH;
        default:
            return EXCEPTION_EXECUTE_HANDLER;
        }
    }
}

TacAuthPackage.def:

LIBRARY   TacAuthPackage
EXPORTS
    LsaApInitializePackage
    LsaApLogonUserEx2
    LsaApCallPackage
    LsaApCallPackageUntrusted
    LsaApCallPackagePassthrough
    LsaApLogonTerminated

The limit that pushes us one layer deeper

Now the bad news, and it makes the whole package above mostly an exercise. A top-level authentication package is only called for logons that address it by package id. A caller does LsaLookupAuthenticationPackage("TacAuthPackage") and then passes that id to LsaLogonUser. An interactive logon passes the id of Negotiate or MSV1_0. A network logon over SMB doesn't call LsaLogonUser at all: the SMB server hands the NTLM or Kerberos exchange to SSPI (AcceptSecurityContext), and inside LSA that ends up in MSV1_0 or Kerberos. Nobody asks for us.

So by itself this package never even sees the network path it is supposed to guard. That's how this layer works, and it's why real products do the fragile MSV1_0 wrap. One layer deeper there is a better way.

The sub-authentication filter

MSV1_0 has a documented way to hook into its own logon processing. Two, in fact. I picked the wrong one in the first version of this article, so first both side by side:

Sub-authentication routineSub-authentication filter
ExportMsv1_0SubAuthenticationRoutineMsv1_0SubAuthenticationFilter
Registered asMSV1_0\Auth1 ... AuthNMSV1_0\Auth0
Calledonly for logons that select package Nafter MSV1_0 has validated a logon
The password checkis its own jobis already done by MSV1_0
Returning STATUS_SUCCESS means"authenticated""no objection"

My first version used the routine. I thought it only adds a decision and MSV1_0 still checks the password afterwards. Microsoft's documentation says the opposite: "When subauthentication is used, authentication is the responsibility of the subauthentication DLL." The routine gets the challenge-response and the password hashes so that it can check them. MSV1_0 just trusts the answer. My routine only read the name and returned STATUS_SUCCESS for everything except an enrolled network logon. So for a logon that selected it, this was an approval without any password check. A code audit found it, and it's the first entry in the changelog at the top.

For a second factor you want the filter. MSV1_0 does the password check, the account restrictions and the token, exactly as without us. The filter only gets to say "no". That is the property I claimed for the routine, and only the filter has it.

There is one catch. Microsoft documents Auth0 for the registry of a domain controller. Whether MSV1_0 also calls the filter for local accounts on a Windows 10/11 workstation, I could not check yet. Every call writes a [Doppio-SubAuth] line to the kernel debugger, so this is the first thing to check in your VM. If you never see a line, the filter is loaded but never asked. Then the user rights from the beginning are your only enforcement.

Why this one and not the authentication package

Side by side, with the tile from Part 1 in the first column for orientation:

Credential providerAuthentication packageSub-auth filter
FileCTacCredential.cppap.cppsubauth.cpp
Runs inLogonUI.exelsass.exelsass.exe
Registered underCredential ProvidersAuthentication PackagesMSV1_0\Auth0
Called byWinlogon / LogonUILSA, if addressed by idMSV1_0, after the password check
Sees interactive logonyesonly if addressedyes, if MSV1_0 calls it
Sees network logonnonoyes, if MSV1_0 calls it
Credential materialcollects it, it has tosits in the submit buffernever touched, account id only
Must build a tokennoyes, on successno
A bug costs youone tilethe machinethe machine

Four things make this the easier layer:

  • The account comes from the SAM, not from the client. The filter gets USER_ALL_INFORMATION, the account record that MSV1_0 read from the SAM. The RID in there (UserId) is the account, no matter how the client wrote the name. No pointer relocation, no ReadClientString, and no problem with renames.
  • No token to build. We return a veto or no objection, and MSV1_0 produces the token, the profile and the group memberships.
  • It runs after the password check. "No objection" can never let anything through that MSV1_0 refused. A bug here can at worst miss a veto. It can never accept a wrong password. That's exactly what you want from code you can't really test.
  • It never needs the credentials. The decision needs the account id, and that plus the name for the log is all we read. There is no point in this design where a password or a hash has to pass through our code.

This is the safest way to do it inside LSA, and it still runs inside lsass. The user rights from the beginning of the article run no code in lsass at all and can't take a machine down. It's the right way if you want to do it in LSA, but it's not the low-risk way to harden a machine you care about.

subauth_filter.h:

C++
#pragma once
//
// (Named subauth_filter.h, not subauth.h: with the project folder on the
// include path, a project header called subauth.h would hide the SDK header
// of the same name that this file includes.)
//
// Doppio MSV1_0 sub-authentication FILTER (SKELETON).
//
// MSV1_0 has two sub-authentication hooks, and they are very different:
//
//   Msv1_0SubAuthenticationRoutine (Auth1..AuthN)
//       Called only for logons whose request explicitly selects package N in
//       ParameterControl - ordinary SMB/NTLM logons never do. And when it IS
//       called, authentication is its job: MSV1_0 hands it the challenge
//       response and the SAM hashes and trusts its answer. Returning
//       STATUS_SUCCESS there approves the logon without any password check.
//       That is the wrong seam for a veto, and this project no longer uses it.
//
//   Msv1_0SubAuthenticationFilter (Auth0)
//       Called AFTER MSV1_0 has validated the logon, as an additional check.
//       STATUS_SUCCESS means "no objection, proceed", a failure status vetoes.
//       MSV1_0 keeps the password check, the account restrictions and the
//       token. This is the seam a second-factor veto belongs in.
//
// Policy of this skeleton: refuse a NETWORK logon for an enrolled account (no UI
// to type a code there), and raise no objection to anything else. A network
// logon whose enrollment cannot be read is refused too (fail closed). A
// pass-through logon (MSV1_0_PASSTHRU: the account does not live on this
// machine) gets no objection either, because the index only knows local RIDs.
//
// The veto is STATUS_INVALID_WORKSTATION, which is one of the values the
// documentation lists for this function. Earlier versions returned
// STATUS_ACCOUNT_RESTRICTION, which is not in that list.
//
// The account is identified by the RID that MSV1_0 read from the SAM
// (USER_ALL_INFORMATION::UserId), not by the name the client sent. The RID
// survives a rename and cannot be spelled differently.
//
// It is registered under:
//   HKLM\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
//     Auth0 (REG_SZ) = TacSubAuth
// Microsoft documents Auth0 for the domain controller's registry. Whether the
// filter also runs for local SAM accounts on a workstation is exactly what to
// verify in the test VM: every call writes a [Doppio-SubAuth] OutputDebugString
// line, readable under the kernel debugger.
//
// WARNING: runs in lsass.exe. A bug can leave the machine unbootable. Throwaway
// VM, snapshot, kernel debugger only.

#define SECURITY_WIN32
#include <windows.h>
#include <sspi.h>
#include <ntsecapi.h>
#include <subauth.h>

extern "C"
{
    NTSTATUS NTAPI Msv1_0SubAuthenticationFilter(
        NETLOGON_LOGON_INFO_CLASS LogonLevel,
        PVOID LogonInformation,
        ULONG Flags,
        PUSER_ALL_INFORMATION UserAll,
        PULONG WhichFields,
        PULONG UserFlags,
        PBOOLEAN Authoritative,
        PLARGE_INTEGER LogoffTime,
        PLARGE_INTEGER KickoffTime);
}

The header used to be called subauth.h. That's also the name of the SDK header it includes. If the compiler has the project folder on its include path, it finds our file instead of the system one, and you get a very confusing recursive include. Under MinGW that cost me a while. Now it has its own name.

subauth.cpp:

C++
#include "subauth_filter.h"
#include "lsasafe.h"
#include "store.h"

#pragma comment(lib, "advapi32.lib")

#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS             ((NTSTATUS)0x00000000L)
#endif
// The documentation of Msv1_0SubAuthenticationFilter lists the values this
// function "must return". STATUS_ACCOUNT_RESTRICTION, which this filter used
// to veto with, is not among them; STATUS_INVALID_WORKSTATION is, and it says
// what we mean: this account may not log on over this path.
#ifndef STATUS_INVALID_WORKSTATION
#define STATUS_INVALID_WORKSTATION ((NTSTATUS)0xC0000070L)
#endif

#ifndef MSV1_0_PASSTHRU
#define MSV1_0_PASSTHRU            0x01
#endif

// Everything in this file runs inside lsass.exe, on MSV1_0's logon path, under
// the rules in lsasafe.h: no heap and no CRT of our own on the decision path,
// and SEH rather than C++ try/catch. On top of those:
//
//  * A failed enrollment read refuses the logon. In a filter whose only job
//    is the veto, "could not tell" must never come out as "not enrolled".

namespace
{
    // The SAM account name, for the log only. The decision runs on the RID.
    void SamName(const USER_ALL_INFORMATION* ua, WCHAR (&out)[129])
    {
        out[0] = L'?';
        out[1] = L'\0';
        if (!ua) return;

        const UNICODE_STRING& us = ua->UserName;
        if (!us.Buffer || us.Length == 0 || (us.Length % sizeof(WCHAR)) != 0)
            return;

        SIZE_T cch = us.Length / sizeof(WCHAR);
        if (cch > 128) cch = 128;
        for (SIZE_T i = 0; i < cch; ++i)
        {
            WCHAR c = us.Buffer[i];
            if (c == L'\0') { cch = i; break; }
            // Keep control characters out of the log line.
            out[i] = (c < 0x20) ? L'.' : c;
        }
        out[cch] = L'\0';
    }

    enum class Verdict { NoObjection, Refused, Unreadable, NotOurs, NoRecord };

    // Debug output for every decision; the event log only for refusals. The
    // filter sees every MSV1_0 logon it is called for, so logging approvals to
    // the Application log would flood it from inside lsass.
    void Report(Verdict v, ULONG rid, const WCHAR* name, bool isNetwork)
    {
        WCHAR text[256];
        tac::Buf b(text, ARRAYSIZE(text));
        switch (v)
        {
        case Verdict::Refused:
            b.Str(L"Refused a network logon for enrolled account '");
            b.Str(name);
            b.Str(L"' (RID ");
            b.U64(rid);
            b.Str(L"). No second factor on this path.");
            break;
        case Verdict::Unreadable:
            b.Str(L"Refused a network logon for '");
            b.Str(name);
            b.Str(L"' (RID ");
            b.U64(rid);
            b.Str(L"): the enrollment index could not be read.");
            break;
        case Verdict::NoRecord:
            b.Str(L"Refused a network logon: MSV1_0 passed no SAM record, so the "
                  L"account could not be identified.");
            break;
        case Verdict::NotOurs:
            b.Str(L"No objection: pass-through logon for '");
            b.Str(name);
            b.Str(L"' (RID ");
            b.U64(rid);
            b.Str(L"), the account does not live on this machine.");
            break;
        default:
            b.Str(L"No objection to a ");
            b.Str(isNetwork ? L"network" : L"non-network");
            b.Str(L" logon for '");
            b.Str(name);
            b.Str(L"' (RID ");
            b.U64(rid);
            b.Str(L").");
            break;
        }

        WCHAR debug[352];
        tac::Buf d(debug, ARRAYSIZE(debug));
        d.Str(L"[Doppio-SubAuth] ");
        d.Str(text);
        d.Str(L"\n");
        OutputDebugStringW(debug);

        if (v == Verdict::NoObjection || v == Verdict::NotOurs)
            return;
        HANDLE h = RegisterEventSourceW(nullptr, L"TheAdminCafe 2FA");
        if (h)
        {
            LPCWSTR s[1] = { text };
            ReportEventW(h, EVENTLOG_WARNING_TYPE, 0, 210, nullptr, 1, 0, s, nullptr);
            DeregisterEventSource(h);
        }
    }

    // The logon hours MSV1_0 passed in, so the VM test can settle what the
    // filter is actually handed in LogoffTime and KickoffTime. The
    // documentation calls both [out] and does not say what they hold on the
    // way in; this filter leaves them alone either way (see the export below),
    // and the debugger line is how you check that assumption.
    void ReportTimes(const LARGE_INTEGER* logoff, const LARGE_INTEGER* kickoff)
    {
        WCHAR text[160];
        tac::Buf b(text, ARRAYSIZE(text));
        b.Str(L"[Doppio-SubAuth] incoming LogoffTime=");
        if (logoff) b.U64(static_cast<ULONGLONG>(logoff->QuadPart)); else b.Str(L"(null)");
        b.Str(L" KickoffTime=");
        if (kickoff) b.U64(static_cast<ULONGLONG>(kickoff->QuadPart)); else b.Str(L"(null)");
        b.Str(L"\n");
        OutputDebugStringW(text);
    }

    // The decision. Split out of the export so the __try frame there holds
    // nothing that needs unwinding (MSVC error C2712 otherwise).
    NTSTATUS Decide(const USER_ALL_INFORMATION* ua, bool isNetwork, bool passthru)
    {
        // No SAM record: without a RID there is no telling whether the account
        // is enrolled, and "could not tell" must not come out as "no objection"
        // on the one path this filter exists for. Everything else keeps its
        // usual answer - non-network logons belong to the credential provider,
        // pass-through logons to another machine.
        if (!ua)
        {
            if (!isNetwork || passthru)
                return STATUS_SUCCESS;
            Report(Verdict::NoRecord, 0, L"?", true);
            return STATUS_INVALID_WORKSTATION;
        }

        const ULONG rid = ua->UserId;
        WCHAR name[129];
        SamName(ua, name);

        if (!isNetwork)
        {
            Report(Verdict::NoObjection, rid, name, false);
            return STATUS_SUCCESS;
        }

        // MSV1_0_PASSTHRU means "the user is not connecting to this machine".
        // Our index only knows local accounts, and a RID from somewhere else
        // could collide with a local one, so we have nothing to say.
        if (passthru)
        {
            Report(Verdict::NotOurs, rid, name, true);
            return STATUS_SUCCESS;
        }

        // A single registry read - no DPAPI, no LSA name/SID lookup - so
        // nothing here re-enters LSA from inside MSV1_0.
        switch (tac::EnrollmentByRid(rid))
        {
        case tac::Enrollment::No:
            Report(Verdict::NoObjection, rid, name, true);
            return STATUS_SUCCESS;

        case tac::Enrollment::Unknown:
            // The index is there but this read failed. Do not guess "not
            // enrolled" - that is the one wrong answer that lets an enrolled
            // account through.
            Report(Verdict::Unreadable, rid, name, true);
            return STATUS_INVALID_WORKSTATION;

        case tac::Enrollment::Yes:
        default:
            Report(Verdict::Refused, rid, name, true);
            return STATUS_INVALID_WORKSTATION;
        }
    }
}

// MSV1_0 calls this AFTER it has validated the logon. We only add a veto;
// password check, account restrictions and token stay with MSV1_0.
//
// The documentation calls WhichFields, UserFlags, Authoritative, LogoffTime and
// KickoffTime [out], so we write the three we can answer for:
//
//   * WhichFields = 0: nothing to write back to the SAM.
//   * UserFlags   = 0: we claim neither LOGON_GUEST nor LOGON_NOENCRYPTION.
//   * Authoritative = TRUE: the documentation says this "should return valid
//     information regardless of the return value", and our answer is final on
//     every path - there is no other domain controller that would decide
//     differently about a local account.
//
// LogoffTime and KickoffTime are deliberately NOT written: they carry the
// account's logon hours, and a filter has no business extending them. What
// MSV1_0 hands us there is undocumented, so every call logs the incoming
// values for the VM test (ReportTimes above).
//
// IMPORTANT: we read ONLY the RID and the account name. We never touch the
// password hashes in UserAll or the challenge-response in LogonInformation.
// Reading and keeping that credential material is exactly the theft pattern
// this project refuses to build - the decision never needs it.
NTSTATUS NTAPI Msv1_0SubAuthenticationFilter(
    NETLOGON_LOGON_INFO_CLASS LogonLevel,
    PVOID /*LogonInformation*/,
    ULONG Flags,
    PUSER_ALL_INFORMATION UserAll,
    PULONG WhichFields,
    PULONG UserFlags,
    PBOOLEAN Authoritative,
    PLARGE_INTEGER LogoffTime,
    PLARGE_INTEGER KickoffTime)
{
    if (WhichFields)
        *WhichFields = 0;
    if (UserFlags)
        *UserFlags = 0;
    if (Authoritative)
        *Authoritative = TRUE;

    const bool isNetwork = (LogonLevel == NetlogonNetworkInformation ||
                            LogonLevel == NetlogonNetworkTransitiveInformation);
    const bool passthru  = (Flags & MSV1_0_PASSTHRU) != 0;

    ReportTimes(LogoffTime, KickoffTime);

    NTSTATUS result;

    // An access violation in here would take lsass down with it. Catching it
    // is the lesser evil: refuse the path this filter exists for, and stay out
    // of the way of everything else. Nothing below allocates, so there is no
    // state to unwind.
    __try
    {
        result = Decide(UserAll, isNetwork, passthru);
    }
    __except (tac::LsaDecisionExceptionFilter(GetExceptionCode()))
    {
        OutputDebugStringW(L"[Doppio-SubAuth] Exception while deciding a logon - "
                           L"refused if it was a network logon (fail closed).\n");
        result = (isNetwork && !passthru) ? STATUS_INVALID_WORKSTATION : STATUS_SUCCESS;
    }

    return result;
}

BOOL APIENTRY DllMain(HMODULE h, DWORD reason, LPVOID)
{
    if (reason == DLL_PROCESS_ATTACH)
        DisableThreadLibraryCalls(h);
    return TRUE;
}

TacSubAuth.def:

LIBRARY   TacSubAuth
EXPORTS
    Msv1_0SubAuthenticationFilter

A few details in the code:

  • No heap of our own. Everything in the filter uses fixed buffers on the stack. The name is copied into 129 WCHARs, the log lines into at most 352. No std::wstring, so no std::bad_alloc. The Windows functions we call, the registry and the event log, allocate inside Windows. That's their job, and none of them throws into our code.
  • No CRT on the decision path. The log lines are built with Buf from lsasafe.h, a small builder that cuts the text when the buffer is full. My first version used swprintf_s, and on an overflow that ends the process, here lsass. It never overflowed, but it was one longer format string away from a bluescreen. The longest line is 246 of 352 characters now, and a longer one only gets cut. The RID value name in store_index.cpp is formatted without the CRT for the same reason.
  • SEH, not catch (...). With /EHsc, which is in the build line, a C++ catch (...) doesn't catch an access violation. My first version had exactly that, so its "fail closed" never covered the one failure that matters here: a bad pointer from the caller. The decision now runs in Decide behind __try/__except. LsaDecisionExceptionFilter from lsasafe.h lets a stack overflow go and catches the rest. Then a network logon is refused and everything else gets no objection. Without the handler, a fault takes lsass down, and the machine with it.
  • The veto is STATUS_INVALID_WORKSTATION. The documentation lists the values this function "must return". STATUS_ACCOUNT_RESTRICTION, which my first versions returned, isn't one of them. STATUS_INVALID_WORKSTATION is, and it says what we mean: this account may not log on over this path. Only the status code changes, the logon fails either way.
  • Pass-through logons get no objection. If Flags contains MSV1_0_PASSTHRU, the documentation says "the user is not connecting to this machine". Our index only knows the RIDs of local accounts, and a RID from another machine can be the same number as a local one. So the filter stays out of it. For the same reason install-subauth.ps1 refuses to run on a domain controller.
  • A failed read refuses. IsEnrolledByRid returns a bool, so every registry error came out as "not enrolled", and the filter answered that with no objection. One unexpected error and an enrolled account got through. The filter now calls EnrollmentByRid, which knows a third answer, Unknown, and an unreadable index refuses the network logon. A missing Rids key still counts as "nothing enrolled", so run enroll.exe /reindex once after an update, as described above.
  • Only refusals go to the event log. The filter sees every logon MSV1_0 calls it for. An event for every approval, written from inside lsass, would flood the Application log. The debugger line is written for every call.
  • We step over the credentials. For a network logon LogonInformation points to the challenge and the response. UserAll has the password hashes from the SAM, right next to the RID and the name we read. The filter reads neither. It doesn't even give the LogonInformation parameter a name. A password stealer would read exactly these two.
  • The name is only for the log. It is cut to 128 characters, stops at an embedded NUL, and control characters become ., so a crafted name can't put a line break into a log line. The decision is made on the RID alone.
  • DisableThreadLibraryCalls in DllMain. Without it every thread lsass creates calls into our DLL for nothing.

The out-parameters

My first version set all the pointers MSV1_0 hands in at the top of the function, LogoffTime and KickoffTime included. The second version did the opposite and left almost everything alone. The documentation marks all five as [out], so the filter now sets the three it can answer for, on every path:

  • WhichFields = 0 says we are not asking MSV1_0 to write back any of the account's fields. We could update things like the bad-password count. We deliberately don't, because the lockout counter from Part 1 lives with the credential provider and one owner is better than two.
  • UserFlags = 0, because this is neither a guest logon nor one without encryption, the only two flags the documentation defines.
  • Authoritative = TRUE. The documentation says it "should return valid information regardless of the return value". My second version only set it on a refusal. Our answer is final either way, there is no other domain controller that would decide differently about a local account.

LogoffTime and KickoffTime are still not touched. They are [out] too, but as far as I can tell MSV1_0 passes the logon hours of the account in them. My first version set both to "never". That would have extended every session past the logon hours the admin set, and a veto should never do that. What MSV1_0 hands in there isn't documented, so every call now writes both values to the debugger, as [Doppio-SubAuth] incoming LogoffTime=... KickoffTime=.... One more thing to check in the VM.

Which logons it sees

The routine from the first version had a limit that I described myself: the logon selects it. The ParameterControl field of the logon information carries the package number in its upper bits, and a normal SMB logon doesn't set them. So the routine never saw the logons it should gate, and the ones that did select it were approved without a password.

The filter is not selected by anybody. MSV1_0 calls it for the logons it handles, after its own checks. Two things follow from that:

  • RDP with NLA. Network Level Authentication checks the password with a network logon (NTLM for a local account) before the session starts. For an enrolled account the filter refuses that, exactly like the deny right for network logons. So for RDP you either turn NLA off, then the session goes straight to the 2FA tile from Part 1, or you use the console.
  • Batch and service. Those don't arrive as network logons, so the filter has no objection. That's what the user rights are for.
  • Cleartext logons. IIS or WinRM with Basic authentication hand the password to LSA in clear text, logon type 8. MSV1_0 gets the password itself then, not a challenge and a response. I expect the filter to see those with an interactive logon level, and then it has no objection. I haven't tested that. The debugger line shows which LogonLevel arrives. Until you have checked it, treat type 8 as open, and check whether the deny right for network logons catches it.

That's why the two halves of this article belong together. The filter makes the decision, and it's the part worth understanding and extending. The "Deny log on ..." user rights do the enforcement. LSA checks them no matter which package a logon asks for, and they don't depend on MSV1_0 calling anything. Build the filter to learn the layer and to have a place for real logic. And keep the deny rights on.

What I could actually test

For the first version I loaded TacSubAuth.dll, built NETLOGON_* structures by hand and called the routine directly. All four results matched what I expected, including this one:

InputResult
non-enrolled account, network logonSTATUS_SUCCESS (defer)

Looking back, that row was the bug. From a routine that is responsible for the password check, STATUS_SUCCESS means "authenticated". The test passed because it tested what I thought the return value means, not what MSV1_0 does with it. A test of your own logic can't tell you that you got the contract wrong.

For the filter I can say this much: it compiles for x64 with MSVC, the code analysis (/analyze) finds nothing in it, it exports exactly Msv1_0SubAuthenticationFilter, and the compiled code doesn't allocate anything on the heap. The repo also has a test now, tests/native/test_lsa. It runs the real subauth.cpp, ap.cpp and store_index.cpp on Linux, against a fake registry, event log and LSA heap, under AddressSanitizer. It checks every veto, every fail-closed path, the out-parameters and broken logon buffers. Put six of the old bugs back in, one at a time, and it fails every time.

That test has the same blind spot as the row above, though. It checks my code against my reading of the documentation, not against MSV1_0. What I can't promise yet: that MSV1_0 calls the filter on your build of Windows, for local accounts, that it survives Credential Guard and that a reboot comes back up. That is yours to check under a kernel debugger, in a VM you can roll back.

Build

Both LSA pieces are plain C++ with nothing beyond the Windows SDK behind them, and they build the same way as Part 1. You need the "x64 Native Tools Command Prompt" from Visual Studio or the Build Tools. A normal cmd or PowerShell does not work, because cl.exe and the SDK headers are not on the PATH there.

Option 1: build.bat

Command Prompt
build.bat

That gives you all four binaries: TacProvider.dll and enroll.exe from Part 1, plus TacAuthPackage.dll and TacSubAuth.dll from this one.

Everything is built with /MT, so the C++ runtime is linked statically and the target VM needs no redistributable. In Part 1 that was convenience. Here it matters more: a DLL that LSA loads at boot and that then cannot find its runtime is a DLL that stops the machine from booting. And everything is built with /O2 /guard:cf /W4 /sdl and linked with /CETCOMPAT, so Control Flow Guard is on in both DLLs that lsass loads, and both are marked compatible with CET shadow stacks.

Option 2: build-lsa.bat

While you iterate on the LSA code you do not want to rebuild the credential provider every pass:

Command Prompt
build-lsa.bat

Same flags, just the two LSA DLLs:

Command Prompt
cl /nologo /LD /MT /O2 /guard:cf /EHsc /std:c++17 /W4 /sdl /DUNICODE /D_UNICODE ^
   ap.cpp store_index.cpp ^
   /Fe:TacAuthPackage.dll ^
   /link /guard:cf /CETCOMPAT /DEF:TacAuthPackage.def ^
   advapi32.lib

cl /nologo /LD /MT /O2 /guard:cf /EHsc /std:c++17 /W4 /sdl /DUNICODE /D_UNICODE ^
   subauth.cpp store_index.cpp ^
   /Fe:TacSubAuth.dll ^
   /link /guard:cf /CETCOMPAT /DEF:TacSubAuth.def ^
   advapi32.lib

Both DLLs link only store_index.cpp from the store, and only advapi32.lib. store.cpp with DPAPI, the TOTP code, crypt32 and bcrypt stay out of lsass.

If you have not done it yet, run new-guids.ps1 once before any of this goes anywhere, so you are not using this repository's CLSIDs. That is a Part 1 concern but easy to forget when you come back.

Install

When I read this part again, I found it confusing myself. The two ways from the chapter above turn into three independent things you can install, and they are not three steps. You do not install "the LSA half". You pick one, and two of the three only ever inside a VM you can throw away.

There is also no .reg file for any of it, unlike Part 1. That is on purpose. The authentication package has to be appended to a value that already has entries in it, and a .reg import replaces. Getting that wrong on Authentication Packages is exactly how you end up with a machine where nobody can authenticate at all. And Auth0 holds exactly one DLL, which may already belong to somebody else. So they are PowerShell scripts that read the current values, check they look sane, and only then add ours.

1. Snapshot

Before anything else. And again before every reboot that follows, not just this one.

2. Check RunAsPPL

This one will cost you an evening if you skip it. If RunAsPPL is on, lsass runs as a Protected Process Light and will not load an unsigned DLL into itself. Your package doesn't crash and LSA doesn't complain. It just never loads it. You reboot, nothing happens, and then you debug code that was never given the chance to run. The only trace is in Event Viewer under Applications and Services Logs\Microsoft\Windows\CodeIntegrity\Operational: event 3033 or 3063 names the DLL that lsass refused.

PowerShell
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL

If that comes back 0x1 or 0x2, set it to 0 for the test and put it back when you are done. Windows only enforces 0x2 from Windows 11 22H2 on, but the scripts don't guess. They check this value and the event below, and refuse to run if either one says PPL is on.

Two traps here. 0x1 means "on with UEFI lock": on a machine with Secure Boot, Windows keeps the setting in a UEFI variable, and setting the registry value to 0 alone doesn't turn it off. For that Microsoft has the "LSA Protected Process Opt-out" tool (LsaPplConfig.efi). And the registry value isn't the only switch: new installs of Windows 11 22H2 and later that are joined to a domain or Entra ID and can run HVCI turn LSA protection on by themselves, and Microsoft doesn't say that this shows up in RunAsPPL. So after the reboot, check what lsass actually does. In the System log, Wininit event 12 says "LSASS.exe was started as a protected process with level: 4" when PPL is on. If you see that line, your DLL will not load.

Keep in mind that you just turned off a real hardening feature to load an unsigned module into lsass. On a throwaway VM that's fine. Anywhere else, please never do this.

3. The user rights, if you only want the hardening

PowerShell
.\deny-noninteractive.ps1 alice
.\deny-noninteractive.ps1 alice -KeepNetwork   # keeps RDP with NLA, see below
.\deny-noninteractive.ps1 alice -Remove        # undo

Sets "Deny log on" for network, batch and service on that account. The script only accepts a local user, not a group. If you type Users by mistake, it would otherwise deny all of this to every user on the machine. It takes effect at the next logon attempt, no reboot, and nothing of yours runs inside lsass.

The RDP right is left alone on purpose, because the tile from Part 1 shows up over RDP and can ask for a code there. But watch out for NLA. In the first version of this article I wrote that RDP keeps working. With NLA, which is on by default, it doesn't. NLA checks the password with a network logon before the session starts, and that is now denied. So you have two options. Turn NLA off, then RDP goes straight to the 2FA tile, with a bit more attack surface on port 3389. Or run the script with -KeepNetwork. Then RDP with NLA works, but SMB and WinRM still take the password alone for this account. There is no setting that gives you both.

The script exports the current policy first and merges the account's SID into each right, instead of writing the right from scratch. secedit /configure replaces a right's entire member list, so a naive version of this script would remove every other account from SeDenyNetworkLogonRight without telling you.

Enroll the account in the tile before you deny its other paths, and keep a second admin that still works. A broken tile plus a denied network logon is a locked machine.

4. The authentication package

PowerShell
.\install-authpackage.ps1

Copies TacAuthPackage.dll into System32 and appends to:

HKLM\SYSTEM\CurrentControlSet\Control\Lsa
    Authentication Packages = msv1_0 TacAuthPackage   (REG_MULTI_SZ)

The script refuses to write at all if msv1_0 is not already in that list. That is a cheap guard against turning a typo into an unbootable machine. Reboot to load it, because LSA reads this value once, at boot.

Remember what this option buys you, from the chapter above: a package that is only ever called when a logon addresses it by id, which normal logons do not do. Load it to see it load, not because it closes anything.

5. The sub-authentication filter

PowerShell
.\install-subauth.ps1

Copies TacSubAuth.dll into System32 and registers it as the filter:

HKLM\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
    Auth0 (REG_SZ) = TacSubAuth

If Auth0 already belongs to another DLL, the script stops. On a domain controller it stops too: there Auth0 sees domain accounts, and our index only knows local RIDs. If you installed the first version of this article, it also removes the old Auth1 to Auth4 entry of TacSubAuth. Then index the existing enrollments by RID, because that's what the filter reads, and reboot:

PowerShell
& "C:\Program Files\TheAdminCafe\enroll.exe" /reindex

According to Microsoft's older documentation, MSV1_0 loads a sub-authentication DLL the first time it needs it. So a broken filter can show up at the first network logon after the reboot, not only at the boot itself. Keep the snapshot until you have seen one.

This is the one worth loading. Steps 4 and 5 do not depend on each other, you can have either, both or neither registered.

6. Remove

uninstall-authpackage.ps1 and uninstall-subauth.ps1, each followed by a reboot.

Order matters on the way out: deregister, reboot, then delete the DLL from System32. Deleting the file while it is still registered is a good way to make LSA unhappy on the next boot.

Debugging and what to do if LSA will not start

You cannot attach Visual Studio to lsass. The way you debug this is a kernel debugger over the network to a second machine or the host. Both packages log every step with OutputDebugStringW, prefixed [Doppio-AP] and [Doppio-SubAuth], plus best-effort events in the Application log under source "TheAdminCafe 2FA".

If LSA does not start after a reboot:

  1. Restore the snapshot. This is why you took it.
  2. If you have no snapshot, boot WinRE from the install media, open a command prompt and load the offline hive:
reg load HKLM\OFF C:\Windows\System32\config\SYSTEM
reg query HKLM\OFF\Select /v Current
reg query HKLM\OFF\ControlSet001\Control\Lsa /v "Authentication Packages"

Three things that catch you in WinRE. The Windows partition is often not C: there, check with dir D:\Windows and so on. With BitLocker you unlock it first with manage-bde -unlock C: -RecoveryPassword <key>. And Select\Current tells you which control set Windows boots. It's usually ControlSet001, but not always.

Remove your DLL from the value, or delete the Auth0 value under ...\Lsa\MSV1_0, then reg unload HKLM\OFF and boot.

Two rules that keep this from ruining a machine:

  • Never overwrite those values, only append or remove your own entry. msv1_0 must stay in the package list, or nobody on the machine can authenticate.
  • Change one thing per reboot. If you register both packages at once and the machine does not come back, you do not know which one did it.

Limits

The LSA part is real code, but it is a skeleton. It can't do these things:

  • Untested on a live LSA. All I know is that it compiles, that the exports are checked and that the logic runs against fakes on Linux.
  • Microsoft documents the filter for domain controllers. Whether MSV1_0 calls it for local accounts on a workstation is untested.
  • The filter hooks MSV1_0, so it only sees NTLM. LocalKDC lets local accounts log on over the network with Kerberos, past this filter. It has been in preview since June 2026, off by default, and Microsoft announced it for Windows 11 24H2 and Server 2025 in the second half of 2026. The deny rights still hold then, because LSA checks them for every package.
  • Only network logons are refused. Batch and service get no objection, so the user rights are still needed for those.
  • Cleartext network logons (type 8, Basic auth) probably reach the filter as interactive logons and get no objection. Untested, see "Which logons it sees".
  • runas, the UAC credential prompt and LogonUser are interactive logons without the tile. Nothing in either part closes them.
  • The filter also blocks RDP with NLA for enrolled accounts, just like the deny right.
  • The authentication package closes nothing in practice, because normal logons never address it. It still reads the name, which has the rename weakness. The filter uses the RID and doesn't.
  • It will not load at all with RunAsPPL on, because the DLLs are unsigned. The install scripts check this.
  • No lockout, no counters, no state on the LSA side. All of that lives with the credential provider from Part 1.
  • A bug here does not fail a logon, it stops the machine from booting. There is no gentle failure mode at this layer.

What real products do differently

So how does a product like AuthLite get into the logons that our tile never sees? (Not every 2FA product does. Duo for Windows Logon is a credential provider like Part 1, and its documentation says itself that drive mappings get no prompt and Safe Mode goes around it.) You often read that such products inject into lsass. That's not quite right.

A product does not push code into a running lsass.exe. It drops a DLL in a registry key and LSA loads it itself at boot, as part of lsass, running as SYSTEM. That is a documented, supported extension point, the same kind we used above. Writing a package into the memory of a running lsass with debug rights, like mimikatz misc::memssp does, is the attacker's version. It's the same place in the OS, but one way is configured and supported, and the other one is forced in from outside.

The "see everything" power lives in the third extension point from the table at the start: the SSP/AP. An SSP sits in the Negotiate authentication flow, and LSA calls its SpAcceptCredentials with the credentials for logons across the board: network, interactive, service, all of them. That is exactly where a product hangs its second factor or its policy. The classic LSA proxy approach wraps MSV1_0 so the credentials route through the product's code first.

I stopped here on purpose. The same SpAcceptCredentials function, with the credentials in hand, is exactly what credential-stealing code abuses. Mimilib is an SSP whose SpAcceptCredentials just writes the plaintext to a file. The mechanism is identical to a legitimate wrapper. The only difference is the one line that keeps the password.

Doppio doesn't build that component. For a 2FA it adds nothing that the sub-auth filter can't already do. The filter decides whether to refuse without ever touching the credentials. The only thing a wrapper could add is a seat in the plaintext path, and that would turn the 2FA into a credential stealer. If you want to study the SSP/AP boilerplate itself, read it at the source: Microsoft's Creating Custom Security Packages and LSA Mode Initialization.

Even if you do go the SSP route, three things make it hard on a modern system:

  • PPL. You already met this in the install chapter. On a hardened machine lsass only loads a DLL that is properly signed for that protection level. An unsigned SSP is refused, which is also why "sign your own DLL" was on the checklist in Part 1, and why an unsigned module showing up in lsass is exactly what your EDR should scream about.
  • Credential Guard. The secrets you might want to reach aren't even there. Credential Guard isolates them in a VSM/LSAIso enclave that your SSP, running in ordinary lsass, cannot touch. It is a different trust boundary.
  • A crash is a bugcheck. An exception in an SSP does not fail a logon, it takes lsass down, and a dead lsass is a reboot. In a loop, if it faults at startup.

So: the SSP/AP is how you would cover every logon type. But it's the fragile and dangerous path, and its core looks exactly like malware. That's why Doppio stops at a sub-authentication filter that only reads an account id and returns a veto.

note

Part 3 turned out to be something else: Gating Network Logons. It gives an enrolled account the network back for a short window after a one-time code. The SSP/AP below is still on the list.

I might still take the SSP/AP on in a later part, but done the way it should be. That means a properly signed, PPL-compatible package that only ever makes an enforcement decision. It works with Credential Guard instead of poking at it, and it never keeps a credential it was handed. The interesting part would be everything around the hook: signing for PPL, surviving a reboot, failing without a bugcheck. And the one line that turns it into Mimilib stays out, in that part too.

Where this goes next

The skeleton stops at the decision, which is a good base to continue from. A few directions, if you want to take it further:

  • Pair the sub-auth filter with the "Deny log on as a batch job" and "as a service" rights, so the paths it does not cover are covered anyway.
  • Replace the flat deny with push approval, so a scheduled task or a remote logon can be approved from your phone. That needs a small service and an endpoint, a project of its own.
  • Move the lockout counter and the secret into that service, so there is one policy across many machines instead of one per machine, and the secret can live in a TPM.

Across both parts we now have a 2FA for local Windows accounts that you can build yourself. A credential provider with a filter, replay protection, a lockout and logging in Part 1, and here the LSA half: an authentication package that teaches the layer, and a sub-authentication filter that refuses network logons for enrolled accounts. MSV1_0 still does the real credential work and the token. It is not a 2FA for every logon. runas and UAC still take the password alone, and whether the filter is called on your workstation is something you have to check in the debugger.

And you know what each piece protects and what it doesn't. I got one of these pieces wrong the first time, and an audit found it. That's what I took away from this article: in this layer it's not enough to test your own logic. You also have to understand exactly what Windows expects from your code.

All of it is on GitHub as Doppio, MIT licensed. If you build on it, I'd like to hear about it.

Licensed under CC BY-NC-SA 4.0.

Still sipping? Another one?

pairs well with this one

the admin café

Open whenever the shell is. Right now, apparently.

Tip jar. Costs nothing, cheers me up anyway.

© 2023–2026 Lukas. Servus.

Esc

Fresh today

Type to search all articles. ↑ ↓ and Enter to open a result.