github.com
2026-05-16 β Modular split for both architectures, MRU policy change, redirect/help fixes
Both source trees split into focused modules. x64 was split first (15.05.2026); x86 was migrated to the same shape on 16.05.2026 so both trees mirror each other. The old
~90 KB main.asmon each side is nowcli.asm,help.asm,relay.asm,install.asm,strutil.asm,process.asm,token.asm,window.asm, and a slimmain.asm. Compiled binary sizes are unchanged β every byte that used to be inmain.asmis still in the final image, just in a different translation unit. Non-admincmdt -cli <cmd> >> out.txtnow works. A temp-file relay inrelay.asmbridges the UAC handle-inheritance gap: the non-admin parent creates a temp file, passes its path as-outfile <path>to the elevated child, waits for the child to finish writing to it, then streams the file to its ownSTD_OUTPUT_HANDLE(which cmd.exe wired up for the redirect). Two bugs surfaced while implementing this βSHELLEXECUTEINFOW.hProcesswas being read at the wrong offset on x64 (+96 instead of +104), andAttachConsolewas silently overwriting inherited redirect handles withCONOUT$. Both are fixed.cmdt -help(and all six other spellings) works in every shell. The help check now runs beforeIsUserAnAdmin()so the usage banner reaches the original console / redirect target without going through UAC. The output API is selected byGetFileTypeβWriteConsoleWfor a real console,WriteFilefor a file or pipe. After writing to a console, a fake VK_RETURN is posted to stdin so cmd.exe redraws its prompt instead of leaving the cursor idle. MRU dropdown no longer pre-selects the last command at startup.CB_SETCURSEL 0βCB_SETCURSEL -1+SetWindowTextW("")on bothLoadMRUandSaveMRU. History still works (click the dropdown arrow), but the edit field starts empty so the user doesn't accidentally re-run the previous command.
CMDT β Run as TrustedInstaller

The entire tool compiles to under 30 KB (x64) and under 25 KB (x86). No C runtime. No frameworks. No external dependencies beyond the Windows kernel and a handful of system DLLs that ship with every Windows installation since Vista.
Why CMDT?
Windows protects critical system files, registry keys, and services with TrustedInstaller ownership. Even a process running as NT AUTHORITY\SYSTEM cannot modify these resources without taking ownership first β a destructive, auditable, and often irreversible operation.
CMDT solves this by spawning processes that natively run as TrustedInstaller, with the full set of 34 security privileges already enabled. No ownership changes needed. No ACL modifications. The process simply is the owner.
Typical use cases
- Replacing or patching protected system binaries (WinSxS, System32)
- Modifying TrustedInstaller-owned registry keys without taking ownership
- Deleting stubborn files locked behind TrustedInstaller ACLs
- Scripted system maintenance where
SYSTEMcontext is insufficient - Debugging and forensics on protected OS components
- Repairing corrupted Windows installations at the deepest level
Architecture
CMDT is a dual-mode binary β a single executable that operates as both a graphical desktop application and a headless command-line tool, selected at runtime based on arguments. This is not two programs stitched together; the same PE binary, the same entry point, and the same token acquisition pipeline serve both modes. The architecture is sometimes called a hybrid subsystem design: the executable uses the Windows subsystem (/subsystem:windows) but dynamically attaches to the parent console when invoked with CLI flags.
Both architectures β x86 (IA-32) and x64 (AMD64) β are built from separate, hand-written assembly source trees. No cross-compilation, no #ifdef macros, no shared C code. Each target is native assembly tuned to its calling convention and register set.
| Binary | Size | Architecture |
|---|---|---|
cmdt_x64.exe |
under 30 KB | x64 / AMD64 |
cmdt_x86.exe |
under 25 KB | x86 / IA-32 |
For comparison, equivalent tools written in C++ or C# typically weigh in at 50β500 KB, pulling in the CRT, .NET runtime, or static libraries. CMDT achieves full feature parity β GUI with MRU history, shortcut resolution, drag-and-drop, DPI awareness, CLI with I/O redirection, Explorer context menu integration, Sticky Keys IFEO hook, Defender exclusion management, UAC self-elevation β in well under 30 KB on x64 and 25 KB on x86. This is possible only because every byte is hand-placed assembly, every API call is direct, and there is zero abstraction overhead.
Features
- Dual-mode operation β GUI and CLI from a single binary, selected at runtime
- UAC self-elevation β automatically prompts for admin rights via
ShellExecuteEx("runas")if not already elevated, forwarding all original command-line arguments to the elevated instance - Explorer context menu integration β
cmdt -installregisters right-click entries for directories, executables, and shortcuts;cmdt -uninstallremoves them - Sticky Keys IFEO hook β
cmdt -shiftinstalls an Image File Execution Options debugger redirect forsethc.exe, so pressing Shift 5 times at the login screen opens a TrustedInstaller command prompt instead of Sticky Keys;cmdt -unshiftreverts to default behavior - Windows Defender exclusions β
-shiftand-unshiftautomatically add or remove process exclusions for the CMDT binary andcmd.exevia WMI (MSFT_MpPreferenceCOM interface on x64, PowerShell on x86), preventing false-positive interference - CLI help that works everywhere β
-h,-help,--help,-?,/?,/h,/helpall print the usage banner; the check runs before UAC self-elevation so output always reaches the original shell β both interactive (cmdt -help) and redirected (cmdt -help > out.txt) work correctly in elevated and non-elevated sessions - CLI output relay β running
cmdt -cli <command>from a non-admin shell correctly delivers stdout/stderr to the caller's redirect target (>> out.txt,| pipe, etc.); a temp-file relay bridges the UAC handle-inheritance gap transparently - All 34 security privileges enabled in the spawned token
- Token caching β 30-second TTL avoids redundant privilege escalation on repeated runs
- MRU history β last 5 commands persisted in the registry, available in a dropdown; edit field starts empty on launch
- Windows shortcut (.lnk) resolution β via COM (
IShellLinkW+IPersistFile), both path and arguments - Drag-and-drop with UIPI bypass β accepts drops from non-elevated Explorer windows
- DPI-aware β PerMonitorV2 via application manifest, sharp rendering on mixed-DPI setups
- Dark mode support β reads
AppsUseLightThemefrom the registry and appliesDWMWA_USE_IMMERSIVE_DARK_MODEviaDwmSetWindowAttribute; title bar updates instantly onWM_SETTINGCHANGEwithout restarting - Mica backdrop β
DWMWA_SYSTEMBACKDROP_TYPE = DWMSBT_MAINWINDOWon Windows 11; the window background is transparent to the Mica layer (no background brush) - Modern visual styles β Common Controls v6 through SxS manifest dependency
- Resilient service startup β retry loop with up to 2-second backoff when TrustedInstaller service is cold
- I/O handle inheritance β CLI mode preserves stdin/stdout/stderr for piping and redirection
- Zero CRT dependency β all string operations (copy, concatenate, compare, length) are hand-written wide-character routines in
strutil.asm - Proper environment block β
CreateEnvironmentBlockgenerates the correct TrustedInstaller environment for the child process
Installation
No installation required. Copy cmdt_x64.exe (or cmdt_x86.exe for 32-bit systems) anywhere on your system. A natural location is C:\Windows\System32 β this is where Microsoft places its own system utilities, and it makes CMDT available from any command prompt without modifying PATH.
CMDT requires Administrator privileges. If launched without elevation, it automatically re-launches itself with a UAC prompt via ShellExecuteEx("runas"), forwarding all original arguments to the elevated instance. No manual "Run as Administrator" is needed.
To register Explorer context menu entries, run:
cmdt -install
This creates right-click menu items for directories, .exe files, and .lnk shortcuts.
Requirements
- Windows 10 / Windows 11 (or Windows Vista+ with reduced feature set)
- Administrator privileges (Run as Administrator)
- TrustedInstaller service present (ships with all desktop and server editions of Windows)
Usage
GUI Mode
Launch cmdt_x64.exe without arguments to open the graphical interface.
cmdt_x64.exe
The window provides:
- ComboBox with dropdown β type a command or select from the MRU history (last 5 commands, persisted across sessions in
HKCU\Software\cmdt); edit field starts empty on launch so you type fresh - Browse... button β opens a file picker filtered to executables (
.exe,.lnk) - Run button β launches the command as TrustedInstaller
- Status bar β displays "Ready", "Launching...", "Process OK", or "Failed"
- Drag-and-drop β drop any
.exeor.lnkfile onto the window; it resolves the target and runs it immediately - Keyboard β
Enterruns the current command,Escapecloses the window
The GUI dynamically relays out on resize. Controls stretch and reposition to fill the available client area.
CLI Mode
Prefix any command with -cli (or --cli or cli) to run headless, inheriting the parent console's standard handles.
cmdt_x64.exe -cli <command>
cmdt_x64.exe -cli -new <command>
cmdt_x64.exe -install
cmdt_x64.exe -uninstall
cmdt_x64.exe -shift
cmdt_x64.exe -unshift
| Switch | Description |
|---|---|
-cli <command> |
Run command as TrustedInstaller, inheriting the current console |
-cli -new <command> |
Run command in a new, separate console window |
-install |
Register Explorer context menu entries under HKCR |
-uninstall |
Remove all CMDT context menu entries |
-shift |
Install Sticky Keys IFEO hook + Defender exclusions |
-unshift |
Remove Sticky Keys IFEO hook + Defender exclusions |
-h, -help, --help, -?, /?, /h, /help |
Display available options |
(no arguments) |
Launch GUI mode |
Basic examples
# Launch an interactive TrustedInstaller command prompt
cmdt_x64.exe -cli cmd
# Open Registry Editor as TrustedInstaller
cmdt_x64.exe -cli regedit.exe
# Run PowerShell as TrustedInstaller
cmdt_x64.exe -cli powershell
# Launch a specific executable with full path
cmdt_x64.exe -cli notepad
I/O redirection β why it matters for scripting
In CLI mode without the -new flag, CMDT inherits the parent process's stdin, stdout, and stderr handles. This means the spawned TrustedInstaller process writes to the same console and the same pipe as the caller. Standard shell redirection works exactly as expected:
cmdt_x64.exe -cli cmd /c whoami > output.txt
cmdt_x64.exe -cli net session >> out.txt
When running from an already-elevated shell, handle inheritance is direct: CMDT simply passes STARTF_USESTDHANDLES with the inherited handles through to the child process via CreateProcessWithTokenW.
When running from a non-admin shell, UAC starts the elevated child in a new process tree with no handle inheritance β the OS security boundary intentionally severs the handle relationship. CMDT bridges this gap with a temp-file relay:
- The non-admin parent creates a unique temp file via
GetTempFileNameW. - It inserts an internal
-outfile <path>token into the argument string and launches an elevated copy of itself viaShellExecuteExW("runas"). - The elevated child opens the temp file with an inheritable
GENERIC_WRITEhandle and uses it as the spawned process'shStdOutput/hStdError. - After the elevated process exits, the non-admin parent opens the temp file, streams its contents to its own
STD_OUTPUT_HANDLE(which cmd.exe wired up before launch β so> file,>> file, and| pipeall work transparently), then deletes the temp file and exits.
The relay is skipped when -new is passed (a detached console has no output to capture), and falls back gracefully to plain UAC self-elevation if temp-file creation fails.
This makes CMDT suitable for unattended automation scripts, batch files, and CI/CD pipelines where capturing TrustedInstaller-level output is necessary:
@echo off
cmdt_x64.exe -cli cmd /c icacls "C:\Windows\servicing" > acl_report.txt
cmdt_x64.exe -cli cmd /c reg query "HKLM\SYSTEM\CurrentControlSet" /s > reg_dump.txt
cmdt_x64.exe -cli cmd /c dir "C:\Windows\WinSxS\*.manifest" /s > manifests.txt
cmdt_x64.exe -cli net session >> audit.txt
Without the relay, these commands would open orphaned console windows and output would be lost. With the relay, even a non-admin shell gets the full output at the redirect target.
The -new flag β detached console
Add -new between the CLI switch and the command to spawn the process with CREATE_NEW_CONSOLE. The child gets its own independent console window:
# Open a new, standalone TrustedInstaller command prompt window
cmdt_x64.exe -cli -new cmd
# Open PowerShell in its own window as TrustedInstaller
cmdt_x64.exe -cli -new powershell
The difference is architectural:
| Aspect | -cli (default) |
-cli -new |
|---|---|---|
| Console | Inherits parent | Creates new window |
| stdout/stderr | Shared with caller | Independent |
| I/O redirection | Works (> file.txt) |
Not applicable |
| Use case | Scripting, automation | Interactive sessions |
| Creation flags | CREATE_UNICODE_ENVIRONMENT |
CREATE_NEW_CONSOLE \| CREATE_UNICODE_ENVIRONMENT |
| STARTUPINFO | STARTF_USESTDHANDLES |
STARTF_USESHOWWINDOW |
Help display
All of the following are recognized help switches and print the usage banner:
cmdt_x64.exe -help
cmdt_x64.exe -h
cmdt_x64.exe --help
cmdt_x64.exe -?
cmdt_x64.exe /?
cmdt_x64.exe /h
cmdt_x64.exe /help
The help check runs before UAC self-elevation. This matters because the elevated process is detached from the original shell's console and redirect targets. By printing usage from the non-elevated process, CMDT stays attached to the launching console β so both interactive display and cmdt -help > out.txt work correctly regardless of elevation state.
Output is routed via GetFileType on the stdout handle: WriteConsoleW for a real console (native UTF-16), WriteFile for a file or pipe (raw UTF-16 LE bytes). This ensures redirected output is never silently dropped. After writing to a real console, a fake VK_RETURN is posted to stdin via WriteConsoleInputW so cmd.exe redraws its prompt immediately.
Shortcut (.lnk) resolution
CMDT transparently resolves Windows shortcuts. If the target path ends with .lnk, the tool initializes COM, instantiates CLSID_ShellLink, loads the shortcut via IPersistFile::Load, and extracts both the target path (IShellLinkW::GetPath) and embedded arguments (IShellLinkW::GetArguments). The resolved target and its arguments are concatenated and passed to CreateProcessWithTokenW.
This works in both GUI and CLI modes, and correctly handles quoted paths with spaces:
# Resolve shortcut and run the target as TrustedInstaller
cmdt_x64.exe -cli "C:\Users\Public\Desktop\Some App.lnk"
# Also works with drag-and-drop in GUI mode
The .lnk extension check is case-insensitive, implemented via a hand-written wide-character comparator that folds ASCII uppercase to lowercase inline.
Context Menu Integration
Running cmdt -install registers four context menu entries under HKEY_CLASSES_ROOT:
| Registry Path | Menu Text | Behavior |
|---|---|---|
Directory\Background\shell\CMDT |
Open CMD as TrustedInstaller | Right-click on desktop or inside any folder |
Directory\shell\CMDT |
Open CMD as TrustedInstaller | Right-click on a folder icon |
exefile\shell\CMDT |
Run as TrustedInstaller | Right-click on any .exe file |
lnkfile\shell\CMDT |
Run as TrustedInstaller | Right-click on any .lnk shortcut |
How it works
- Directory entries execute:
"<exepath>" -cli -new cmd.exe /k cd /d "%V"β this opens a TrustedInstaller command prompt in the selected directory. - File entries execute:
"<exepath>" "%1"β CMDT receives the file path as an argument. For.exefiles, it runs the executable directly. For.lnkshortcuts, it resolves the target via the COMIShellLinkinterface before execution.
Each entry displays a UAC shield icon borrowed from shell32.dll (icon index 104 β the "keys" icon). The binary itself contains no embedded icon resource (no .ico file). This is the same approach Microsoft uses for its own system utilities that reside in System32. Since CMDT is designed to live in System32 by default, it does not need a standalone icon β Explorer resolves the shell32.dll,104 reference at display time.
Removal
cmdt -uninstall
This deletes all eight registry keys (four parent keys + four command subkeys) in leaf-first order, as the Windows registry does not allow deletion of keys that still contain subkeys.
Sticky Keys IFEO Hook
Running cmdt -shift installs a login-screen backdoor that replaces the Sticky Keys accessibility helper (sethc.exe) with a TrustedInstaller command prompt. Running cmdt -unshift reverses the process completely.
How it works
Windows supports Image File Execution Options (IFEO) β a documented registry mechanism under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ that allows attaching a debugger to any executable. When an IFEO Debugger value exists for a given binary, Windows launches the debugger instead of the original program, passing the original path as an argument.
cmdt -shift creates the following registry entry:
| Key | Value | Data |
|---|---|---|
HKLM\...\Image File Execution Options\sethc.exe |
Debugger |
<exepath> -cli -new cmd.exe |
When the user presses Shift five times at the Windows login screen, the OS launches sethc.exe β but the IFEO redirect intercepts this and runs CMDT instead. CMDT then performs its full token acquisition pipeline (SYSTEM impersonation β TrustedInstaller service start β token duplication β privilege enablement) and opens an interactive cmd.exe window running as NT SERVICE\TrustedInstaller.
This provides a pre-login recovery console with the highest privilege level available in Windows β useful for:
- Emergency system repair when the machine cannot be logged into
- Resetting locked-out local accounts via
net user - Fixing corrupted registry hives or group policies that prevent login
- Recovering from ransomware or malware that blocks the desktop
Windows Defender exclusions
Both -shift and -unshift manage Windows Defender process exclusions automatically. This prevents Defender from flagging CMDT or the spawned cmd.exe as suspicious during the IFEO-redirected launch at the login screen, where no user session exists to dismiss alerts.
| Switch | Action |
|---|---|
-shift |
Adds <filename> and cmd.exe as process exclusions |
-unshift |
Removes <filename> and cmd.exe process exclusions |
On x64, exclusions are managed by calling the MSFT_MpPreference WMI class methods (Add / Remove) directly through the COM interface β no PowerShell or child process is spawned. CMDT connects to the ROOT\Microsoft\Windows\Defender WMI namespace, instantiates IWbemServices, and invokes ExecMethod with a SAFEARRAY of BSTR values for the ExclusionProcess property. This approach is faster, produces no visible console window, and has no dependency on the PowerShell execution policy. On x86, the lighter PowerShell-driven Add-MpPreference path is used instead β the WMI hop is a 30+ KB COM marshalling cost that the x86 build trades away for a tighter binary.
Removal
cmdt -unshift
This deletes the Debugger value from the IFEO registry key (leaving the key itself intact, as it may contain other unrelated values) and removes both Defender process exclusions. Normal Sticky Keys behavior is fully restored.
How It Works β Token Inheritance Chain
CMDT performs a multi-stage privilege escalation to obtain a fully privileged TrustedInstaller token. Each stage builds on the previous one, forming an inheritance chain:
Stage 0: UAC Self-Elevation
Before any token work begins, CMDT checks IsUserAnAdmin(). If the process is not running elevated, it re-launches itself via ShellExecuteExW with the "runas" verb, forwarding the original command-line arguments to the new instance. The non-elevated process then exits immediately. This makes CMDT self-elevating β the user never needs to manually "Run as Administrator".
Stage 1: Self-Elevation
The process enables two critical privileges in its own token using AdjustTokenPrivileges:
- SeDebugPrivilege β required to open process handles across security boundaries
- SeImpersonatePrivilege β required to impersonate another user's token
These are available because the process runs as Administrator (elevated).
Stage 2: SYSTEM Impersonation
CMDT locates winlogon.exe by enumerating the process list via CreateToolhelp32Snapshot + Process32FirstW/NextW, using a case-insensitive wide-character comparison (wcscmp_ci) against each entry's szExeFile field. The winlogon.exe process runs as NT AUTHORITY\SYSTEM.
The tool opens winlogon.exe with PROCESS_QUERY_INFORMATION | PROCESS_DUP_HANDLE, extracts its process token with OpenProcessToken, and duplicates it with DuplicateTokenEx at MAXIMUM_ALLOWED access and SecurityImpersonation level. It then calls ImpersonateLoggedOnUser to assume SYSTEM identity on the current thread.
After this stage, the calling thread runs as SYSTEM β necessary to interact with the Service Control Manager and the TrustedInstaller service process.
Stage 3: TrustedInstaller Service Activation
CMDT opens the Service Control Manager and queries the TrustedInstaller service (OpenServiceW with SERVICE_QUERY_STATUS | SERVICE_START).
If the service is stopped, it calls StartServiceW and enters a retry loop: up to 10 iterations with 200 ms sleep intervals (~2 seconds total). Each iteration re-queries the service status via QueryServiceStatusEx. This resilient approach handles slow or heavily loaded machines where a single 200 ms wait would be insufficient.
Once SERVICE_RUNNING is confirmed, the service's Process ID is extracted from the SERVICE_STATUS_PROCESS structure (offset dwProcessId).
Stage 4: Token Duplication
CMDT opens the TrustedInstaller process with PROCESS_QUERY_INFORMATION, extracts its token, and duplicates it via DuplicateTokenEx with MAXIMUM_ALLOWED access. This duplicated token becomes the foundation for the child process.
Stage 5: Full Privilege Enablement
The duplicated token has all 34 Windows security privileges enabled via a loop that calls LookupPrivilegeValueW + AdjustTokenPrivileges for each privilege in the table.
Stage 6: Process Creation
The fully privileged token is passed to CreateProcessWithTokenW. CMDT generates a proper environment block via CreateEnvironmentBlock (keyed to the TrustedInstaller token) and sets the working directory to GetSystemDirectoryW. The spawned process runs natively as TrustedInstaller with all 34 privileges enabled.
Token Caching
The duplicated, fully privileged token is cached in memory with a 30-second TTL (tracked via GetTickCount). Subsequent invocations within the TTL window skip stages 2β5 entirely and reuse the cached token. This dramatically reduces overhead when running multiple commands in sequence β the expensive service startup, process enumeration, and privilege loop execute only once.
Privilege Composition
CMDT enables all 34 Windows security privileges in the spawned token. This is the complete set that exists in the TrustedInstaller token:
| # | Privilege | Description |
|---|---|---|
| 0 | SeAssignPrimaryTokenPrivilege | Replace process-level token |
| 1 | SeBackupPrivilege | Bypass ACLs for read access (backup) |
| 2 | SeRestorePrivilege | Bypass ACLs for write access (restore) |
| 3 | SeDebugPrivilege | Debug any process |
| 4 | SeImpersonatePrivilege | Impersonate a client after authentication |
| 5 | SeTakeOwnershipPrivilege | Take ownership of any securable object |
| 6 | SeLoadDriverPrivilege | Load and unload device drivers |
| 7 | SeSystemEnvironmentPrivilege | Modify firmware environment variables |
| 8 | SeManageVolumePrivilege | Perform volume maintenance tasks |
| 9 | SeSecurityPrivilege | Manage auditing and security log |
| 10 | SeShutdownPrivilege | Shut down the system |
| 11 | SeSystemtimePrivilege | Change the system time |
| 12 | SeTcbPrivilege | Act as part of the operating system |
| 13 | SeIncreaseQuotaPrivilege | Adjust memory quotas for a process |
| 14 | SeAuditPrivilege | Generate security audits |
| 15 | SeChangeNotifyPrivilege | Bypass traverse checking |
| 16 | SeUndockPrivilege | Remove computer from docking station |
| 17 | SeCreateTokenPrivilege | Create a token object |
| 18 | SeLockMemoryPrivilege | Lock pages in memory |
| 19 | SeCreatePagefilePrivilege | Create a pagefile |
| 20 | SeCreatePermanentPrivilege | Create permanent shared objects |
| 21 | SeSystemProfilePrivilege | Profile system performance |
| 22 | SeProfileSingleProcessPrivilege | Profile a single process |
| 23 | SeCreateGlobalPrivilege | Create global objects |
| 24 | SeTimeZonePrivilege | Change the time zone |
| 25 | SeCreateSymbolicLinkPrivilege | Create symbolic links |
| 26 | SeIncreaseBasePriorityPrivilege | Increase scheduling priority |
| 27 | SeRemoteShutdownPrivilege | Force shutdown from a remote system |
| 28 | SeIncreaseWorkingSetPrivilege | Increase a process working set |
| 29 | SeRelabelPrivilege | Modify an object label |
| 30 | SeDelegateSessionUserImpersonatePrivilege | Obtain impersonation token for another user in same session |
| 31 | SeTrustedCredManAccessPrivilege | Access Credential Manager as a trusted caller |
| 32 | SeEnableDelegationPrivilege | Enable computer and user accounts to be trusted for delegation |
| 33 | SeSyncAgentPrivilege | Synchronize directory service data |
Binary-level string decomposition
The privilege names are not stored as complete strings in the binary. Instead, CMDT uses a prefix-suffix decomposition technique that splits every privilege name into three parts:
| Part | Value | Storage |
|---|---|---|
| Prefix | Se |
Single shared constant |
| Middle | e.g. Debug, Backup, TakeOwnership |
Per-privilege unique string |
| Suffix | Privilege |
Single shared constant |
At runtime, the BuildPrivilegeName procedure concatenates these three parts into a temporary buffer before passing the result to LookupPrivilegeValueW. The full name SeDebugPrivilege is assembled in memory but never appears as a contiguous string in the binary image.
This decomposition has two engineering consequences:
-
Size reduction β The prefix (
Se, 4 bytes UTF-16) and suffix (Privilege, 18 bytes UTF-16) are stored once instead of 34 times, saving approximately 750 bytes. In a sub-25 KB binary, that is nearly 3% of the total size. -
Static analysis opacity β Automated scanners and signature-based tools that grep for known privilege strings like
SeDebugPrivilegeorSeTcbPrivilegewill find no matches in the binary. The stringsSeandPrivilegeappear separately, and the middle parts (Debug,Tcb,Backup, etc.) are generic English words that carry no security significance on their own. This is not obfuscation β it is a natural consequence of factoring out common substrings in a size-constrained binary. But the side effect is significant: the binary's static footprint does not betray the scope of privileges it enables.
Manifest and DPI Awareness
CMDT embeds a Win32 application manifest that declares three important capabilities:
PerMonitorV2 DPI Awareness
The manifest declares both the legacy dpiAware=true attribute (for Vistaβ8.1 compatibility) and the modern dpiAwareness=PerMonitorV2 attribute (Windows 10 1703+). On modern systems, this means:
- The window renders at native resolution on every monitor β no bitmap scaling or blurriness
- When dragged between monitors with different DPI settings, the window rescales correctly
- Text, buttons, and controls render sharp on 4K, ultrawide, and mixed-DPI configurations
This is the same DPI awareness model used by modern Windows applications like Explorer, Edge, and Terminal.
Common Controls v6 (Visual Styles)
The manifest declares a Side-by-Side (SxS) dependency on Microsoft.Windows.Common-Controls version 6.0. This activates the modern visual theme for all standard controls β the ComboBox dropdown, buttons, and static labels render with the current Windows theme (Fluent, Aero, or Classic) rather than the legacy Win95 appearance.
Dark Mode and Mica Backdrop
CMDT reads the system app theme preference from the registry at startup and whenever the user changes the Windows color scheme:
HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize
AppsUseLightTheme (DWORD) β 0 = dark, 1 = light
Depending on the value, it calls DwmSetWindowAttribute with two attributes:
| Attribute | Value | Effect |
|---|---|---|
DWMWA_USE_IMMERSIVE_DARK_MODE (20) |
0 or 1 | Dark or light title bar and window frame |
DWMWA_USE_IMMERSIVE_DARK_MODE_OLD (19) |
same | Fallback for Windows 10 builds before 20H1 |
DWMWA_SYSTEMBACKDROP_TYPE (38) |
DWMSBT_MAINWINDOW (2) |
Mica material backdrop |
The Mica backdrop (DWMSBT_MAINWINDOW) applies on Windows 11 regardless of light/dark mode β the material automatically adapts its tint to the system accent color and theme. The window class is registered with no background brush (hbrBackground = NULL), leaving the client area transparent to the Mica layer.
CMDT also listens for WM_SETTINGCHANGE and WM_THEMECHANGED and re-applies both attributes on every theme change. Switching between light and dark mode in Windows Settings updates the CMDT title bar immediately without restarting the application.
The manifest specifies requestedExecutionLevel=asInvoker. CMDT does not rely on the manifest for elevation β instead, it programmatically checks IsUserAnAdmin() at startup and re-launches itself via ShellExecuteExW("runas") if not elevated. This approach allows the same binary to be invoked silently from already-elevated contexts (scripts, scheduled tasks, elevated terminals) without triggering a redundant UAC prompt, while still self-elevating when launched from a standard user session.
MRU (Most Recently Used) History
The GUI maintains a persistent MRU list of the last 5 commands in the Windows registry at HKEY_CURRENT_USER\Software\cmdt. Values are stored as named entries 0 through 4, where 0 is the most recent command.
On startup, LoadMRU reads these values and populates the ComboBox dropdown. After each successful execution, SaveMRU shifts existing entries down (0β1, 1β2, ..., 3β4), deletes the oldest entry, and writes the new command at position 0. Duplicate detection is implicit β the shift operation naturally pushes older duplicates off the end of the list.
Both LoadMRU and SaveMRU deselect the dropdown with CB_SETCURSEL, -1 and clear the edit field with SetWindowTextW(g_hwndEdit, ""), so the GUI never pre-fills the last command β the user has to either pick from the dropdown explicitly or type fresh. This avoids the trap of accidentally re-running a destructive previous command.
The MRU list persists across sessions, reboots, and updates. It is the only state CMDT writes to disk (via the registry).
Drag-and-Drop with UIPI Bypass
CMDT accepts drag-and-drop of .exe and .lnk files. Dropping a file onto the window sets the command text and immediately executes it.
Because CMDT runs elevated (as Administrator), the default Windows behavior is to block drag-and-drop messages from non-elevated processes like Explorer. This is enforced by User Interface Privilege Isolation (UIPI) β a security boundary that prevents lower-integrity processes from sending messages to higher-integrity windows.
CMDT explicitly bypasses this restriction by calling ChangeWindowMessageFilterEx for both WM_DROPFILES and WM_COPYGLOBALDATA on the main window handle. This whitelists these specific messages, allowing drops from standard Explorer windows while maintaining the UIPI boundary for all other message types.
Building from Source
Prerequisites
- Microsoft Macro Assembler β
ml.exe(x86) andml64.exe(x64) from Visual Studio Build Tools - Windows SDK β for
rc.exe(resource compiler), import libraries, and headers - PowerShell β for the build script
Build
.\build.ps1
The build script assembles all source modules for both architectures, compiles the resource file (cmdt.rc) with the manifest, and links against system import libraries only:
kernel32.lib, user32.lib, advapi32.lib, shell32.lib, comdlg32.lib, ole32.lib, gdi32.lib, shlwapi.lib, userenv.lib
No CRT library is linked. The entry point is mainCRTStartup (x64) / start (x86) β these are raw assembly procedures, not CRT initialization stubs.
Output binaries are placed in the bin\ directory.
Project Structure
cmdt_asm/
βββ x64/ # AMD64 assembly sources
β βββ main.asm # Entry point, CLI/GUI dispatch, privilege table
β βββ cli.asm # CLI mode and file-run dispatch, -outfile relay protocol
β βββ help.asm # Usage banner and help-switch recognition
β βββ relay.asm # Non-admin output relay (temp-file bridge over UAC)
β βββ token.asm # Token acquisition, SYSTEM impersonation, service control
β βββ process.asm # CreateProcessWithTokenW wrapper
β βββ install.asm # Context menu registration and Sticky Keys IFEO hook
β βββ window.asm # GUI, MRU, drag-and-drop, .lnk resolution via COM
β βββ strutil.asm # Wide-character string helpers (wcscpy_p, wcscat_p, β¦)
β βββ consts.inc # Windows API constants, control IDs, message codes
β βββ globals.inc # External symbol declarations shared across modules
βββ x86/ # IA-32 assembly sources (parallel structure)
β βββ β¦
βββ bin/ # Compiled binaries
β βββ cmdt_x64.exe # 64-bit binary (<30 KB)
β βββ cmdt_x86.exe # 32-bit binary (<25 KB)
βββ cmdt.rc # Version info resource
βββ cmdt.manifest # Application manifest (DPI, visual styles, execution level)
βββ build.ps1 # Build script (assembles + links both architectures)
βββ README.md # This file (documentation)
Every source file in x64/ has a corresponding counterpart in x86/. The x86 versions use .586 + flat/stdcall MASM syntax with invoke macros; the x64 versions use raw proc frame with explicit SEH prologue/epilogue annotations (.pushreg, .allocstack, .setframe, .endprolog). Both targets share the same .rc and .manifest files.
Both source trees were previously monolithic β a single ~90 KB main.asm on each side that held the entry point, dispatcher, all helpers, the GUI, the context-menu installer, and the Sticky-Keys hook. They have since been split into focused modules of roughly 200β700 lines each, while keeping the compiled binary size unchanged. The split is identical on both architectures, so any reader who learns one tree can navigate the other without re-orientation.
String Operations β No CRT
CMDT implements all necessary string operations as hand-written wide-character (UTF-16LE) assembly routines in strutil.asm. There is no dependency on msvcrt.dll, ucrtbase.dll, or any C runtime:
| Function | Purpose |
|---|---|
wcscpy_p |
Wide string copy |
wcscat_p |
Wide string concatenation |
wcscmp_ci |
Case-insensitive wide string comparison |
wcscmp_token |
Token-prefix comparison (match up to first space) |
wcslen_p |
Wide string length |
skip_spaces |
Skip leading whitespace in command parsing |
DecryptWideStr |
In-place string decryption for obfuscated constants (x64 only) |
All routines are declared PUBLIC in strutil.asm and referenced via EXTRN (x64) or PROTO (x86) in the modules that use them. Each is a tight loop operating on 16-bit words, with inline ASCII case folding for the comparison functions (uppercase AβZ folded to lowercase by adding 32 to the code point).
Verification
After launching a command prompt as TrustedInstaller:
cmdt_x64.exe -cli cmd
Verify the security context:
C:\Windows\System32> whoami
nt service\trustedinstaller
C:\Windows\System32> whoami /priv
All 34 privileges should appear with state Enabled.
Security Considerations
TrustedInstaller is the highest privilege level in Windows β higher than Administrator, higher than SYSTEM. A process running as TrustedInstaller can:
- Modify or delete any file on the system, including protected OS components
- Write to any registry key, including those owned by TrustedInstaller
- Load and unload kernel drivers
- Access and modify the firmware environment (UEFI variables)
- Debug any process, including critical system processes
- Create token objects and impersonate any security principal
Use CMDT with the same caution you would apply to a kernel debugger. Mistakes at this privilege level can render the operating system unbootable.
CMDT requires Administrator privileges to run. It does not bypass UAC β the user must explicitly elevate the process before CMDT can acquire the TrustedInstaller token.
License
MIT License
Copyright (c) 2026 Marek Wesolowski
Author
Marek Wesolowski
- Web: https://kvc.pl
- E-mail: [email protected]
Size Trivia
During early development, the minimal proof-of-concept builds were significantly smaller:
| Variant | Size | Notes |
|---|---|---|
| CLI-only (no GUI, no registry, no manifest) | 4 KB | Bare token acquisition + CreateProcessWithTokenW |
| Hybrid GUI/CLI (no registry, no manifest) | 6 KB | Added window creation, MRU, drag-and-drop |
| Current full build (x86) | <25 KB | Hybrid mode, context menu, UAC self-elevation, manifest, COM .lnk resolution |
| Current full build (x64) | <30 KB | Same feature set, 64-bit calling convention overhead |
The growth from 4β6 KB to the current size (~23 KB on x86, ~29 KB on x64) is almost entirely due to the application manifest (DPI awareness, Common Controls v6, execution level declaration), the context menu registry logic, the Sticky Keys IFEO hook with Defender exclusion management, UAC self-elevation, and the wide-character string constants for registry paths and UI text. The core token acquisition pipeline β the actual "engine" of CMDT β remains remarkably compact.
Written in 100% bare-metal x86/x64 MASM assembly. No frameworks. No runtimes. No compromises.