Monday, April 21, 2008

Unlocking XP/2003 without passwords

The winlogon secure desktop is really just another desktop on winsta0, and I came across a utility - RemoteUnlock.exe - which injects itself as a thread in the console winlogon process of a remote machine and switches from the secure winlogon desktop to the logged on user’s winsta0\default desktop.

This allows you to skip the SAS process requiring the account password of the currently logged on user, and just shows the desktop, allowing full console interaction as the logged on user.

This doesn't really have very many practical uses, but the concept is great and I thought I would share the utility I came across plus some additional thoughts on the topic.

The utility and source code:

I've previously toyed with creating a command shell on a remote winlogon desktop, which can be done with the following command:
- psexec /s \\%computer% cmd /c c:\windows\temp\psexec /accepteula /x /d /s cmd

After another discussion regarding secure passwords with PowerShell, I was curious just what might be possible from the Winlogon desktop.

One thing led to another, and after trying unsuccessfully using a PowerShell script run from a command shell on the Winlogon desktop (using psexec) calling GetProcessWindowStation/UnlockWindowStation (an undocumented API, presumably unlocking a window station) and OpenDesktop/SwitchDesktop , I came across a reference to UnlockWindowStation which mentioned that this would only work when running as part of winlogon.exe, explaining why the PowerShell script did nothing.

I then successfully tested remoteunlock.exe running from one XPSP2 workstation against another. RemoteUnlock uses switchdesktop which doesn’t actually unlock the desktop, I was going to recompile and try unlockwindowstation, but I don’t have Visual Studio. It would also be interesting to modify this to work with TS winlogon processes, rather than only the interactive console (I presume you could similarly ‘unlock’ an in-use TS session).

As an aside, below is the PowerShell script calling APIs through VB.Net embedded code, which doesn’t work in this case but it's still a valid example of how to call APIs from PowerShell (which I essentially just copied from

$provider = new-object Microsoft.VisualBasic.VBCodeProvider
$params = new-object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$refs = "System.dll","Microsoft.VisualBasic.dll"

$txtCode = @'
Class FindProcessWinStation
    Declare Auto Function GetProcWinStation Lib “user32.dll” Alias "GetProcessWindowStation" () As Integer
    Declare Auto Function UnlockWinStation Lib “user32.dll” Alias "UnlockWindowStation" (ByVal WinSta As Integer) As Integer
    Declare Auto Function OpenWinStation Lib “user32.dll” Alias "OpenWindowStation" (ByVal lpszWinSta As String, ByVal fInherit as Boolean, ByVal ACCESS_MASK as Integer) As Integer
    Declare Auto Function OpenDesktop Lib “user32.dll” Alias "OpenDesktop" (ByVal lpszDesktop As String, ByVal dwFlags as Integer, ByVal fInherit as Boolean, ByVal ACCESS_MASK as Integer) As Integer
    Declare Auto Function SwitchDesktop Lib “user32.dll” Alias "SwitchDesktop" (ByVal hDesktop As Integer) As Integer
    Function Main()
        main = GetProcWinStation()
'        UnlockWinStation(main)
'        main = OpenWinStation("winsta0\\desktop", True, 895)
        main = OpenDesktop("Default", 0, True, 256)

    End Function
end class

$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("FindProcessWinStation")
$r = $i.main()

write-host $r

Wayne's World of IT (WWoIT), Copyright 2008 Wayne Martin.


Nathan Hartley said...

I found your post while researching a way to create a desktop lock/unlock Powershell script.

I first wrote a single script to lock the computer using a run dll call [1] and then wait as long as the screen saver was running [2]. The only problem is when a screen saver is not running it simply switches desktops as you mention in your article.

I was wondering if you could point me in the right direction to detect when a workstation is locked/switched to the default desktop.


[1] rundll32.exe "user32.dll,GetProcessWindowStation"

$ScreenSaverPath = (get-item "HKCU:\control panel\desktop\").GetValue("scrnsave.exe")
while ([boolean] (get-process | where-object {$_.Path -like $ScreenSaverPath})) {
Sleep .5

Wayne Martin said...

Hi Nathan,

The OpenInputDesktop function also provides a handle to the current desktop receiving user input, which I assume would be either winlogon or default, depending on whether workstation was locked or not.

You could try using my example example and run EnumDesktops and OpenInputDesktop. I have no idea whether this will work, you'd have to try.

Some other information:

I also noticed while looking with procexp.exe that when the winlogon desktop is active (which I saw with psexec /x /i /s procexp.exe), it creates another handle to the \default desktop in the winlogon process, and when the desktop is unlocked and control returns to \default the handle is destroyed.

The win32_process WMI class has information that inclues the sessionID, and this might provide some of the info you want. For example, you can see the winlogon process and it's associated session, indicating the session that winsta0\winlogon is using. And when I ran it against a machine I was RDP'ing into, I could see that logon.scr was running in the same session ID as winlogon.
wmic path win32_process get name,sessionid

Query.exe enumerates sessions (query is a windows server 2003 utility)
query.exe session

I also saw a reference to a command-line utility called objdir.exe in the vista wdk to enumerate winstations, but it doesn't seem to return anything more than the GUI winobj.exe equivalent. I found this utility in the 2003 DDK:
in the called 'TOOL_otherx_FILE_5' (rename to objdir.exe if you don't want to install the DDK).

There's a TS API called RpcWinStationQueryInformation that has a property called WinStationLockedState

I hope this gives you something more to go on.

Derek Ogle said...

I have do have Visual Studio and tried recompiling it with UnlockWindowStation but nothing changed. In case you are interested here is the code I added.

HWINSTA wdesk = 0;
wdesk = GetProcessWindowStation();
HINSTANCE hGetProcIDDLL = LoadLibraryA("user32.dll");
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"UnlockWindowStation");
typedef int (__stdcall * pICFUNC)(HWINSTA winSta);
pICFUNC UnlockWindows;
UnlockWindows = pICFUNC(lpfnGetProcessID);

Also there is a Visual Studio express edition which is free and has practically the same functionality as the full version.

All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 13 years, and I know just about enough to realise that I don’t know very much.