Windows Administration: Difference between revisions

From miki
Jump to navigation Jump to search
 
(28 intermediate revisions by the same user not shown)
Line 17: Line 17:


Other useful config tools:
Other useful config tools:
* DOSHere<br/>Open a cmd prompt by right clicking on any directory in windows explorer
;DOSHere: Open a cmd prompt by right clicking on any directory in windows explorer


== Device Management ==
== Device Management ==
Line 23: Line 23:
Open a '''cmd.exe''' console:
Open a '''cmd.exe''' console:
<source lang="winbatch">
<source lang="winbatch">
> set devmgr_show_nonpresent_devices=1
set devmgr_show_nonpresent_devices=1
> devmgmt.msc
devmgmt.msc
</source>
</source>
In the ''Device Management Console'', select '''show hidden devices'''. Unused devices are grayed out.
In the ''Device Management Console'', select '''show hidden devices'''. Unused devices are grayed out.


== Disk Management ==
== Convert Logical Drive Letter to PhysicalDrive ==
=== Convert Logical Drive Letter to PhysicalDrive ===


The following C program illustrates what Win32 API to use to convert a logical drive letter like C: to the corresponding ''PhysicalDrive'' specification.
The following C program illustrates what Win32 API to use to convert a logical drive letter like C: to the corresponding ''PhysicalDrive'' specification.
Line 81: Line 82:
</source>
</source>


=== SSD Configuration ===
== Patch file version resource ==
Optimization after ssd installation [http:///www.disk-partition.com/kb/tips-ssd-optimization-windows7-1.html]:
Some windows file have a specific resource record that stores release information on that specific file (like file version, company name, etc ). One can see this record by using the ''NT Explorer'' &rarr; '''right click''' &rarr; '''properties''' &rarr; '''Version''' panel.
* Enable '''AHCI''' in BIOS

* Verify TRIM is enabled: The following command must return <tt>0</tt>
It is quite easy to change the content of this record by using an ''Hex Editor'' such as ''UltraEdit''. Just look for either of the hex string below in the file:
fsutil behavior query disabledeletenotify
<source lang="c">
* Check partition alignment (done in Linux).
560053005F00560045005200530049004F004E005F0049004E0046004F00 // V.S._.V.E.R.S.I.O.N._.I.N.F.O.
* Turn off disk indexing (Disk &rarr; properties &rarr; uncheck Allow files on this drive to have contents indexed in addition to file properties).
460069006C006500560065007200730069006F006E // F.i.l.e.V.e.r.s.i.o.n.
* Turn off defragmentation (Disk &rarr; Tools; &rarr; Defragment now... &rarr; Configure schedule... &rarr; Uncheck Run on a schedule (recommended)).
</source>
* Turn off system protection (Computer &rarr; Properties &rarr; System protection &rarr; Configure... &rarr; Turn off system protection).
Note that the version number (''file version'') given at the top of the ''Version'' panel is actually coded in hex. The example below gives a file version '''1.2.3.4'''.
* Disable prefetch (<code>regedit</code> &rarr; go to <code>HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters</code>)
<source lang="c">
** Set <code>EnablePrefetcher</code> to 0 (was 3).
xx xx xx xx xx xx xx xx xx xx 56 00 53 00 5F 00 // xxxxxxxxxxV.S._.
** Set <code>EnableSuperfetch</code> to 0 (was 3).
56 00 45 00 52 00 53 00 49 00 4F 00 4E 00 5F 00 // V.E.R.S.I.O.N._.
** Go to <code>services.msc</code>, and disable service ''SuperFetch''.
49 00 4E 00 46 00 4F 00 xx xx xx xx xx xx xx xx // I.N.F.O.xxxxxxxx
* (no change to GUI boot)
xx xx xx xx 02 00 01 00 04 00 03 00 xx xx xx xx // xxxx........xxxx
</source>

== Shutting Down / Locking ==

Using '''rundll32.exe''' (see [http://it.slashdot.org/story/09/09/28/1512211/Schneier-On-Un-Authentication?from=rss]):
<source lang="winbatch">
rundll32.exe user32.dll,LockWorkStation
</source>

Another one:
<source lang="winbatch">
rundll32.exe shell32.dll,SHExitWindowsEx [0|1|2|4|8]
:: 0: logoff, 1: shut down, 2: reboot, 4: forced shutdown, 8: powers down the machine
</source>


== Regedit ==
== Regedit ==
Line 188: Line 175:
</source>
</source>


=== Wireless network ===
== Rename / Delete locked files using Registry ==
This uses a registry data called '''<tt>PendingFileRenameOperations</tt>''' in key '''<tt>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]</tt>'''. This data is a '''REG_MULTI_SZ'''. The syntax is as follows:
<pre>
\??\source file
!\??\target file
</pre>
To delete a file, target file must be the null string, i.e. '''00 00'''. For instance the registry file below can be used to delete a file named '''<tt>c:\TEMP\Kill-ME.eXe</tt>'''.
<source lang="reg">
REGEDIT4


References: [http://www.informit.com/articles/article.aspx?p=1597099], [http://www.windowscentral.com/how-manage-wireless-networks-using-command-prompt-windows-10]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]

"PendingFileRenameOperations"=hex(7):5C,3F,3F,5C,63,3A,5C,54,45,4D,50,5C,4B,69,6C,6C,2D,4D,45,2E,65,58,65,00,00,00
<source lang=winbatch>
netsh wlan show profiles # Show list of available profiles
netsh wlan show all # Show details
netsh wlan export profile folder="PATH_TO_FOLDER" name=PROFILENAME # Export profiles with folder/name
netsh wlan export profile # Export all profiles

# More advanced
Netsh WLAN show drivers
Netsh WLAN show wirelesscapabilities
Netsh WLAN show interfaces
Netsh WLAN show profile name="Profile_Name" key=clear

# Troubleshoot
Netsh WLAN show WLANreport # Generate troubleshoot report (html)
</source>
</source>
Another way is to use the windows program '''reg.exe'''.


== Tips ==
== Tips / How-tos ==
=== Re-Enable Hibernate Option (Vista) ===
=== Re-Enable Hibernate Option (Vista) ===
On Vista, Hibernation is disabled after running the disk cleanup wizard and removing the hibernate files. To re-enable (see [http://www.howtogeek.com/howto/windows-vista/re-enable-hibernate-option-in-windows-vista/]):
On Vista, Hibernation is disabled after running the disk cleanup wizard and removing the hibernate files. To re-enable (see [http://www.howtogeek.com/howto/windows-vista/re-enable-hibernate-option-in-windows-vista/]):
Line 227: Line 219:
</source>
</source>


== Open Issue ==
=== Patch file version data ===
Some windows file have a specific record that stores release information on that specific file (like file version, company name, etc ). One can see this record by using the ''NT Explorer'' &rarr; '''right click''' &rarr; '''properties''' &rarr; '''Version''' panel. It is quite easy to change the content of this record by using an ''Hex Editor'' such as ''UltraEdit''. Just look for either of the hex string below in the file:
=== Reduce volume size after updates and service packs ===
<source lang="c">
Particularly true for Windows Vsta. Ideas:
560053005F00560045005200530049004F004E005F0049004E0046004F00 // V.S._.V.E.R.S.I.O.N._.I.N.F.O.
* Can we use '''[[Windows Reference|sysprep]]''' tool?
460069006C006500560065007200730069006F006E // F.i.l.e.V.e.r.s.i.o.n.
</source>
Note that the version number (''file version'') given at the top of the ''Version'' panel is actually coded in hex. The example below gives a file version '''1.2.3.4'''.
<source lang="c">
xx xx xx xx xx xx xx xx xx xx 56 00 53 00 5F 00 // xxxxxxxxxxV.S._.
56 00 45 00 52 00 53 00 49 00 4F 00 4E 00 5F 00 // V.E.R.S.I.O.N._.
49 00 4E 00 46 00 4F 00 xx xx xx xx xx xx xx xx // I.N.F.O.xxxxxxxx
xx xx xx xx 02 00 01 00 04 00 03 00 xx xx xx xx // xxxx........xxxx
</source>


=== Shut down / lock windows from command-line ===
== Troubleshoot ==


Using '''rundll32.exe''' (see [http://it.slashdot.org/story/09/09/28/1512211/Schneier-On-Un-Authentication?from=rss]):
=== Windows 7 Boot Issues ===
<source lang="winbatch">
rundll32.exe user32.dll,LockWorkStation
</source>


Another one:
The new Microsoft's flagship OS come with new features in boot, and now has '''plenty''' of different ways to fail at boot, each time with very cryptic and unhelpful messages. It is very easy to get these insulting messages for instance when you change your harddisk, or restore your Windows 7 backup in a different machine (possibly a virtual one). Here I list all the issues I encountered, and how I did solve them.
<source lang="winbatch">
rundll32.exe shell32.dll,SHExitWindowsEx [0|1|2|4|8]
:: 0: logoff, 1: shut down, 2: reboot, 4: forced shutdown, 8: powers down the machine
</source>


=== Rename / Delete locked files using Registry ===
;TOOLS &mdash; bootrec
This uses a registry data called '''<tt>PendingFileRenameOperations</tt>''' in key '''<tt>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]</tt>'''. This data is a '''REG_MULTI_SZ'''. The syntax is as follows:
Use '''BootRec''' to fix issues in the following items [http://support.microsoft.com/kb/927392]:
<pre>
* A master boot record (MBR)
\??\source file
* A boot sector
!\??\target file
* A Boot Configuration Data (BCD) store
</pre>
To delete a file, target file must be the null string, i.e. '''00 00'''. For instance the registry file below can be used to delete a file named '''<tt>c:\TEMP\Kill-ME.eXe</tt>'''.
<source lang="reg">
REGEDIT4


[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]
Simply boot Windows Recovery CD, and type at prompt:
"PendingFileRenameOperations"=hex(7):5C,3F,3F,5C,63,3A,5C,54,45,4D,50,5C,4B,69,6C,6C,2D,4D,45,2E,65,58,65,00,00,00
<source lang=bash>
bootrec
</source>
</source>
Another way is to use the windows program '''reg.exe'''.


=== Reset (temporarily) Administrator password from Linux ===
; ERROR &mdash; Corrupted / Missing Master Boot Record (MBR)
* Install package {{deb|chntpw}} (from ''universe'')
Typical error messages when the MBR is absent / corrupted:
* Edit {{file|.../Windows/System32/config/SAM}} file:
<source lang=text>
cd .../Windows/System32/config
Missing operating system
chntpw -l SAM # List available users
Error loading operating system
chntpw -u SysAdmin SAM # Edit user 'SysAdmin'
Invalid partition table
* Don't forget to umount Windows partition.
MBR Error 1
...
</source>


For the changes to be temporary [http://www.prime-expert.com/articles/a09/temporarily-change-windows-password-and-restore-it-back.php], simply backup the {{file|SAM.*}} files and restore them afterwards.
There are actually 2 possible way for corrupted MBR:
* Corrupted MBR code (detected by BIOS)
* Corrupted Partition Table (detected by MBR code)


To backup the permissions, use the following script (see [[Linux NTFS]] for details):
The actual message may vary depending on the BIOS (corrupted MBR code), or the variant of MBR code installed on the disk. Note that the MBR works fine if GRUB shows up (even in rescue mode).


Solutions:
* Install new MBR - Windows<br/>Boot Windows Recovery CD, and open command prompt
<source lang=bash>
<source lang=bash>
#! /bin/bash
bootrec /fixmbr
for f in SAM*; do
for ACL in ntfs_attrib_be ntfs_acl; do
sudo echo setfattr -h -v $(getfattr -h -e hex -n system.$ACL $f|grep '=' | sed -e 's/^.*=//') -n system.$ACL $f
done
done > restore_acl.sh
chmod a+x restore_acl.sh
</source>
</source>

* Install GRUB
Alternatively, from Windows, use <code>robocopy.exe</code> to copy the file with permissions:
<source lang=bash>
<source lang=winbatch>
TBC
robocopy c:\Windows\System32\config\ c:\Windows\Temp SAM*.*
</source>
* Fix partition table
<source lang=bash>
TBC
</source>
* Set boot partition
<source lang=bash>
TBC
</source>
</source>


=== Export certificate private keys when export option is greyed out ===
; ERROR &mdash; Corrupted / Missing Volume Boot Record (VBR)
TBC


If the option ''export the private key'' is greyed out, this means that private key export is disabled by group policy. There are two options left:
; ERROR &mdash; Corrupted / Missing BOOT.INI
* Use the tool [https://www.isecpartners.com/jailbreak.html Jailbreak]. But ''jailbreak'' does not work on Win7 64-bit.
TBC
* Use the tool [http://blog.gentilkiwi.com/mimikatz mimikatz] (see also [http://stackoverflow.com/questions/3914882/how-to-export-non-exportable-private-key-from-store]). Run the tool (as administrator):
privilege::debug
crypto::cng
crypto::capi
crypto::certificates
crypto::certificates /export
:The {{file|.pfx}} file is encrypted with password <code>mimikatz</code>


;Minikatz
;ERROR &mdash; Corrupted / Missing \bcd Directory
* Background info [https://www.sentinelone.com/cybersecurity-101/mimikatz/ SentinelOne]
Error:
<source lang=bash>
Windows Boot Manager


=== Export certificate private keys (win 10) ===
File: \Windows\system32\winload.exe
{{note|This is still work in progress.}}
Status: 0xc000000e
Source:
Info: The selected entry could not be loaded because the applicationis missing or corrupt
* https://cqureacademy.com/blog/windows-internals/decrypting-sid-protected-pfx-files-without-password
: Some details about SID-protected PFX files. Background knowledge about DPAPI and DPAPI-NG, Doesn't seem relevant here.
* https://stackoverflow.com/questions/51903332/how-to-export-private-key-from-windows-certificate-manager
: Detailed flow on how to export some key material. However, it requires to have an exportable certificate at hand.
:* In Start menu, launch '''Manage computer certificates''' (this is MMC snap-in <code>certlm.msc</code>).
:* Go to '''Certificates - Local Computer -> Personal -> Certificates'''.
:* We see a certificate with same name as computer, and with intended purpose '''Client Authentication'''.
:* Opening it, we note the certificate '''Thumbprint''' string <code>693867F321B5764E324F3FB8C5CBCE03CDA3C2A3</code>
:* We can find this certificate in registry. Start <code>regedit.exe</code>, and go to '''Computer\HKEY_LOCAL_MAGINE\SOFTWARE\Microsoft\MY\Certificates\3078...'''.
:* Copy the keystore using PowerShell
<source lang="powershell">
$a = get-item cert:\LocalMachine\My\693867F321B5764E324F3FB8C5CBCE03CDA3C2A3
$a.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
# 00998a33dbff25a91050b3b1bf9001ef_a5968f4a-5244-4993-830a-363efe3adaed
</source>
</source>
:* We can export the keystore using a console elevated to SYSTEM account.
<source lang="winbatch">
; Create a SYSTEM console (this must be run in Administrative console)
PsExec64.exe -s -i cmd
; Export the file
xcopy /G /H "C:\Users\All Users\Microsoft\Crypto\RSA\MachineKeys\00998a33dbff25a91050b3b1bf9001ef_a5968f4a-5244-4993-830a-363efe3adaed" c:\Temp
</source>
:* ... the flow continues on a VM, trying to patch a working certificate, etc.
* https://blog.nviso.eu/2019/08/28/extracting-certificates-from-the-windows-registry/
: Some details about certificate data found in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates
HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates


;2022-04-22 - Win10 20H2 (19042.1645)
Fix:
* Used with success the tool '''exportrsa''' ([https://github.com/luipir/ExportNotExportablePrivateKey GitHub])
* Boot Windows Recovery Disk, let auto-repair run. You'd likely get another error afterwards (0x0000007B), see below.
* Run in elevated SYSTEM privilege, then run the tool:

<source lang="winbatch">
;ERROR &mdash; BSOD 0x0000007B
; Create a SYSTEM console (this must be run in Administrative console)
Error: BSOD 0x0000007B, followed with error message
PsExec64.exe -s -i cmd
<source lang=text>
; Export the keys
Windows Error Recovery
exportrsa.exe
Windows failed to start. A recent hardware or software change might be the
cause.

[...]

Launch Startup Repair (recommended)
Start Windows Normally

[...]
</source>
</source>
:Be aware that {{file|exportrsa.exe}} is reported as a virus by VirusTotal, and hence better disable all A/V on Win10 before running the tool.
:Example of output:
Skip cert with NO rsa public key for Microsoft ECC TS Root Certificate Authority 2018
Skip cert with NO rsa public key for Microsoft ECC Product Root Certificate Authority 2018
Key for "f92e9a47-1321-4aff-9600-fd7a6dbef186" is a CNG key
Enter password to protect exported cert:
***************
Enter password again:
***************
SUCCESSFULLY exported cert bundle for "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"in file "1.pfx"
Private key for cert "XXXXXXXXXX" is not exportable: 8009000b
Do you really want to export Public/private key for cert "XXXXXXXXXX"
[Y|N] (default N) >>>>
SUCCESSFULLY get private key for "ZAVCWL0136"
Enter password to protect exported cert:
***************
Enter password again:
***************
SUCCESSFULLY exported cert bundle for "ZAVCWL0136"in file "2.pfx"
* Afterwards, the {{file|*.pfx}} files can be imported again to mark the key as exportable, and export it anew with different options.


=== Manage services from the command line ===
This message is indicative that the kernel was not even loaded (no way to launch Safe Mode). It means that the BCD is missing or corrupted.
The following commands may help
sc query
sc query SERVICE
sc queryex SERVICE
sc qc SERVICE
sc config SERVICE start= auto
sc start SERVICE
net start SERVICE


=== Troubleshoot remote desktop connection ===
Fix:
;Guides
* Launch startup repair (or use recovery dvd)
* [https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/troubleshoot/rdp-error-general-troubleshooting RDP error general troubleshooting (Microsoft)].
* Go to command prompt:
:* To view current remote desktop certificate:
<source lang=bash>
::* Open <code>mmc.exe</code>
bcdedit /export C:\BCD_Backup
::* File &rarr; Add or Remove Snap-ins &rarr; certificates, click '''Add'''.
ren C:\boot\BCD bcd.old
::* Select '''computer account''', then '''local computer''', and click '''Ok'''.
bootrec /rebuildbcd
::* Go to Certificates &rarr; Remote Desktop &rarr; Certificates.
</source>
:* <code>gpresult /H c:\gpresult.html</code> to see current group policies.


Some useful links as well:
; ERROR &mdash; Missing drivers
* https://shellgeek.com/how-to-get-certificates-using-powershell/
* Fix missing drivers (BSOD 0x0000007B) &mdash; Still within Windows Recovery CD, start '''regedit''':
* https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certutil
<source lang=reg>
* https://superuser.com/questions/137500/how-can-i-get-a-list-of-installed-certificates-on-windows
Windows Registry Editor Version 5.00
* https://superuser.com/questions/690763/list-installed-personal-certificates-in-batch


TermService was disabled, restarted
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4D36E96A-E325-11CE-BFC1-08002BE10318}\0000]
sc query TermService
"InfPath"="mshdc.inf"
sc qc TermService
"InfSection"="msahci_Inst"
sc config TermService start= auto
"ProviderName"="Microsoft"
sc start TermService
"DriverDateData"=hex:00,80,8c,a3,c5,94,c6,01
UmRdpService, depends on TermService, set on manual on Win10, is disabled here
"DriverDate"="6-21-2006"
sc query UmRdpService
"DriverVersion"="6.1.7600.16385"
sc qc UmRdpService
"MatchingDeviceId"="pci\\cc_010601"
sc config UmRdpService start= demand
"DriverDesc"="Standard AHCI 1.0 Serial ATA Controller"
sc start UmRdpService
"Migrated"=dword:00000001


* ... turns out policy was disabled in domain group. Switching group fixed the issue.
[HKEY_LOCAL_MACHINE\nxl_SYSTEM\ControlSet001\Control\PnP]
"DisableCDDB"=-


== Open Issue ==
[HKEY_LOCAL_MACHINE\nxl_SYSTEM\ControlSet001\services\atapi]
=== Reduce volume size after updates and service packs ===
"Start"=dword:00000000
Particularly true for Windows Vsta. Ideas:
* Can we use '''[[Windows Reference|sysprep]]''' tool?


== Troubleshoot ==
[HKEY_LOCAL_MACHINE\nxl_SYSTEM\ControlSet001\services\msahci]
"Start"=dword:00000000
</source>
* Boot and ***wait*** for all devices to be detected.
* '''DO NOT''' reboot when prompted, but instead start '''regedit''' again:
<source lang=reg>
Windows Registry Editor Version 5.00


=== Windows 7 Boot Issues ===
[HKEY_LOCAL_MACHINE\nxl_SYSTEM\ControlSet001\Control\PnP]
See [[Windows 7 boot troubleshooting]].
"DisableCDDB"=-
</source>


=== Network Connection Folder is Empty ===
=== Network Connection Folder is Empty ===
Line 369: Line 422:


There is no normally no need to restart the computer.
There is no normally no need to restart the computer.

=== The trust relationship between this workstation and the primary domain failed ===

Relevant links:
* How to fix: [http://implbits.com/active-directory/2012/04/13/dont-rejoin-to-fix.html]
* KB on <code>netdom.exe</code> [https://support.microsoft.com/en-us/kb/325850]
* Test relationship with nltest.exe [http://smtp25.blogspot.be/2008/10/nltest-to-see-local-pc-trust-within.html]
* [http://windowsitpro.com/windows-server/nt-gatekeeper-finding-out-where-nt-stores-machine-account-s-credentials NT Gatekeeper: Finding Out Where NT Stores a Machine Account’s Credentials]
* Prevent the problem [http://windowsitpro.com/windows/q-can-password-windows-machine-s-domain-account-expire-just-normal-user-account-s-password-e]

The root cause is a desync between the machine account password on the computer locally (known as a ''local secret'') and the computer's computer account object on the Windows domain controller.
By default, each windows machine changes the local machine account password every 30 days, and replicates this change to the domain controller. The authentication process keeps the current password and previous password. A desync may occur if the machine is reset to a previous state beyond two password changes.

To fix:
Use <code>netdom.exe</code> to resync the machine account passwords[https://support.microsoft.com/en-us/kb/325850] (need special privilege on DC).

To prevent the problem from happening, edit the following keys in <code>HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters</code> [http://windowsitpro.com/windows/q-can-password-windows-machine-s-domain-account-expire-just-normal-user-account-s-password-e]:
* <code>MaximumPasswordAge</code>
* <code>DisablePasswordChange</code>
* <code>ScavengeInterval</code>

=== Remote Desktop Black Screen issue ===
Symptoms:
* Connect via RDP, screen is black.

Cause:
* Likely the persistent bitmap caching [https://superuser.com/a/1174364/268171]

Fix:
* Press {{kb|Ctrl-Alt-END}}, to go to task manager screen. This should display the desktop in most case.

=== Create a console as SYSTEM user ===
* Download and install [https://docs.microsoft.com/en-us/sysinternals/downloads/pstools PsTools]
* Start powershell console with Administrator rights ({{kb|Ctrl-X-A}}.
* Run
<source lang="powershell">
; Create a SYSTEM console (this must be run in Administrative console)
PsExec64.exe -s -i cmd
</source>

Latest revision as of 19:55, 27 April 2022

CMD.EXE

Configuration

  • Enable file / path extension (see help cmd):
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar     <-- 09 (tab)
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar <-- 09 (tab)
  • Command Extension are enabled by default
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions
  • Delayed expansion is not enabled by default:
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion


Other useful config tools:

DOSHere
Open a cmd prompt by right clicking on any directory in windows explorer

Device Management

View and Delete Unused Devices

Open a cmd.exe console:

set devmgr_show_nonpresent_devices=1
devmgmt.msc

In the Device Management Console, select show hidden devices. Unused devices are grayed out.

Disk Management

Convert Logical Drive Letter to PhysicalDrive

The following C program illustrates what Win32 API to use to convert a logical drive letter like C: to the corresponding PhysicalDrive specification.

#include <stdio.h>
#include <w32api/wtypes.h>
#include <w32api/ddk/ntdddisk.h>

int main()
{
    HANDLE hDeviceHandle = NULL;

    char drive[] = {'\\', '\\', '.', '\\', 'A', ':', 0};
    DWORD driveMask = GetLogicalDrives();

    for(int i = 0; i < 26; i++)
    {
        drive[4] = 'A' + i;
        printf("Drive: %s\n", drive);
        hDeviceHandle = CreateFile(drive , 0, 0, NULL,
        OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL);
        if (hDeviceHandle != (HANDLE)-1)
        {
            STORAGE_DEVICE_NUMBER sdn;
            DWORD returned;
            if (DeviceIoControl(
                hDeviceHandle,IOCTL_STORAGE_GET_DEVICE_NUMBER,NULL ,0,&sdn,sizeof(sdn),&returned,NULL));
            {
                printf("\tDevice type: %d number: %d partition: %d\n",sdn.DeviceType,
                sdn.DeviceNumber, sdn.PartitionNumber);
                if(sdn.DeviceType == 7)
                    printf("\t-->\t\\\\.\\PhysicalDrive%d\n",sdn.DeviceNumber);
            }
        }
    }

    return 0;
}

Compile with:

% gcc logicalToPhysicalDrive.cpp

Example of output:

Drive: \\.\C:
        Device type: 7 number: 0 partition: 1
        -->     \\.\PhysicalDrive0

SSD Configuration

Optimization after ssd installation [1]:

  • Enable AHCI in BIOS
  • Verify TRIM is enabled: The following command must return 0
fsutil behavior query disabledeletenotify
  • Check partition alignment (done in Linux).
  • Turn off disk indexing (Disk → properties → uncheck Allow files on this drive to have contents indexed in addition to file properties).
  • Turn off defragmentation (Disk → Tools; → Defragment now... → Configure schedule... → Uncheck Run on a schedule (recommended)).
  • Turn off system protection (Computer → Properties → System protection → Configure... → Turn off system protection).
  • Disable prefetch (regedit → go to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters)
    • Set EnablePrefetcher to 0 (was 3).
    • Set EnableSuperfetch to 0 (was 3).
    • Go to services.msc, and disable service SuperFetch.
  • (no change to GUI boot)

Regedit

Command-line

Using regtool (cygwin):

regtool /s registry_file.reg                     ;Silent merge registry file (no user confirmation)

Using reg.exe (windows):

;Silent merge
regedit /s registry_file.reg                      

;Create a global USER environment variable (persistent)
SET MYROOT="%CD"
echo Setting global USER Environment variable to %MYROOT%
reg add HKCU\environment /v MYROOT /t REG_SZ /d %MYROOT% /f

Regedit .reg File Format

See also Microsoft's reference page, here, here, here and on Wikipedia.

See also regtool chapter on Cygwin page.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\Setup]
@=dword:00000000
"SetupType"=dword:00000000
"CmdLine"="setup -newsetup"
"SystemPrefix"=hex:c5,0b,00,00,00,40,36,02

; Comments are created with a semi-colon

; Delete a value by assigning a minus to it
"SetupType"=-

; Delete a key by preceding the name with a minus sign
[-HKEY_LOCAL_MACHINE\SYSTEM\Setup]

The header line indicates the version and can be either

 Windows Registry Editor Version 5.00   for Windows 2000, Windows XP, and Windows Server 2003
 REGEDIT4                               for Windows 98 and Windows NT 4.0 (but is also accepted in 2000, XP or 2003)

Network

Detect Network Environment Change

The following VBS script can be used to detect automatically when a network cable is connected or disconnected ("network cable unplugged"), as in [2]. Some explanations at [3], and more on [4].

Use MSNdis_StatusMediaDisconnect to detect when a cable is unplugged.

Set colMonitoredEvents = GetObject("winmgmts:root\wmi")._
     ExecNotificationQuery("Select * from MSNdis_StatusMediaConnect")
Do
     Set strLatestEvent = colMonitoredEvents.NextEvent
     WScript.Echo "Connected! Do something here"
     ' enable the line below if you want to exit after the first event.
     ' Exit Do
Loop

Same script a bit improved in order to limit detection to some specific adapter:

Set colMonitoredEvents = GetObject("winmgmts:root\wmi")._
     ExecNotificationQuery("Select * from MSNdis_StatusMediaConnect" _
        & " WHERE InstanceName = '3Com 10/100 Mini PCI Ethernet Adapter'")
Do
     Set strLatestEvent = colMonitoredEvents.NextEvent
     WScript.Echo "Connected! Do something here"
     ' enable the line below if you want to exit after the first event.
     'Exit Do
Loop

Wireless network

References: [5], [6]

netsh wlan show profiles                                              # Show list of available profiles
netsh wlan show all                                                   # Show details
netsh wlan export profile folder="PATH_TO_FOLDER" name=PROFILENAME    # Export profiles with folder/name
netsh wlan export profile                                             # Export all profiles

# More advanced
Netsh WLAN show drivers
Netsh WLAN show wirelesscapabilities
Netsh WLAN show interfaces
Netsh WLAN show profile name="Profile_Name" key=clear

# Troubleshoot
Netsh WLAN show WLANreport                                            # Generate troubleshoot report (html)

Tips / How-tos

Re-Enable Hibernate Option (Vista)

On Vista, Hibernation is disabled after running the disk cleanup wizard and removing the hibernate files. To re-enable (see [7]):

  • Go to the command prompt icon in the Start menu under Accessories and right click the icon: click “Run as administrator”.
  • Paste: “powercfg.exe /hibernate on” and hit Enter and also paste “powercfg -h on” and hit enter just to be safe.
  • Open Control Panel and type in “Hibernate” in the Search.
  • Click “Turn hibernation on or off”
  • Click “Change advance power settings”
  • Scroll to and expand the “Sleep” option.
  • Select “Off” to the “Allow hybrid sleep” option.
  • Scroll to and expand the “Power buttons and lid” option.
  • Select “Hibernate” for the “Sleep button action” option.
  • Select “Hibernate” for the “Start menu power button” option.

Enable Login Verbose Status

Reference: [8]

Windows Registry Editor Version 5.00
 
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"VerboseStatus"=dword:00000001

Patch file version data

Some windows file have a specific record that stores release information on that specific file (like file version, company name, etc ). One can see this record by using the NT Explorerright clickpropertiesVersion panel. It is quite easy to change the content of this record by using an Hex Editor such as UltraEdit. Just look for either of the hex string below in the file:

560053005F00560045005200530049004F004E005F0049004E0046004F00 // V.S._.V.E.R.S.I.O.N._.I.N.F.O.
460069006C006500560065007200730069006F006E                   // F.i.l.e.V.e.r.s.i.o.n.

Note that the version number (file version) given at the top of the Version panel is actually coded in hex. The example below gives a file version 1.2.3.4.

xx xx xx xx xx xx xx xx xx xx 56 00 53 00 5F 00 // xxxxxxxxxxV.S._.
56 00 45 00 52 00 53 00 49 00 4F 00 4E 00 5F 00 // V.E.R.S.I.O.N._.
49 00 4E 00 46 00 4F 00 xx xx xx xx xx xx xx xx // I.N.F.O.xxxxxxxx
xx xx xx xx 02 00 01 00 04 00 03 00 xx xx xx xx // xxxx........xxxx

Shut down / lock windows from command-line

Using rundll32.exe (see [9]):

rundll32.exe user32.dll,LockWorkStation

Another one:

rundll32.exe shell32.dll,SHExitWindowsEx [0|1|2|4|8]
:: 0: logoff, 1: shut down, 2: reboot, 4: forced shutdown, 8: powers down the machine

Rename / Delete locked files using Registry

This uses a registry data called PendingFileRenameOperations in key [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]. This data is a REG_MULTI_SZ. The syntax is as follows:

\??\source file
!\??\target file

To delete a file, target file must be the null string, i.e. 00 00. For instance the registry file below can be used to delete a file named c:\TEMP\Kill-ME.eXe.

REGEDIT4

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager]
"PendingFileRenameOperations"=hex(7):5C,3F,3F,5C,63,3A,5C,54,45,4D,50,5C,4B,69,6C,6C,2D,4D,45,2E,65,58,65,00,00,00

Another way is to use the windows program reg.exe.

Reset (temporarily) Administrator password from Linux

  • Install package chntpw (from universe)
  • Edit .../Windows/System32/config/SAM file:
cd .../Windows/System32/config
chntpw -l SAM                        # List available users
chntpw -u SysAdmin SAM               # Edit user 'SysAdmin'
  • Don't forget to umount Windows partition.

For the changes to be temporary [10], simply backup the SAM.* files and restore them afterwards.

To backup the permissions, use the following script (see Linux NTFS for details):

#! /bin/bash
 
for f in SAM*; do 
  for ACL in ntfs_attrib_be ntfs_acl; do 
    sudo echo setfattr -h -v $(getfattr -h -e hex -n system.$ACL $f|grep '=' | sed -e 's/^.*=//') -n system.$ACL $f
  done
done > restore_acl.sh
chmod a+x restore_acl.sh

Alternatively, from Windows, use robocopy.exe to copy the file with permissions:

robocopy c:\Windows\System32\config\ c:\Windows\Temp SAM*.*

Export certificate private keys when export option is greyed out

If the option export the private key is greyed out, this means that private key export is disabled by group policy. There are two options left:

  • Use the tool Jailbreak. But jailbreak does not work on Win7 64-bit.
  • Use the tool mimikatz (see also [11]). Run the tool (as administrator):
privilege::debug
crypto::cng
crypto::capi
crypto::certificates
crypto::certificates /export
The .pfx file is encrypted with password mimikatz
Minikatz

Export certificate private keys (win 10)

 ✐  This is still work in progress.

Source:

Some details about SID-protected PFX files. Background knowledge about DPAPI and DPAPI-NG, Doesn't seem relevant here.
Detailed flow on how to export some key material. However, it requires to have an exportable certificate at hand.
  • In Start menu, launch Manage computer certificates (this is MMC snap-in certlm.msc).
  • Go to Certificates - Local Computer -> Personal -> Certificates.
  • We see a certificate with same name as computer, and with intended purpose Client Authentication.
  • Opening it, we note the certificate Thumbprint string 693867F321B5764E324F3FB8C5CBCE03CDA3C2A3
  • We can find this certificate in registry. Start regedit.exe, and go to Computer\HKEY_LOCAL_MAGINE\SOFTWARE\Microsoft\MY\Certificates\3078....
  • Copy the keystore using PowerShell
$a = get-item cert:\LocalMachine\My\693867F321B5764E324F3FB8C5CBCE03CDA3C2A3
$a.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
# 00998a33dbff25a91050b3b1bf9001ef_a5968f4a-5244-4993-830a-363efe3adaed
  • We can export the keystore using a console elevated to SYSTEM account.
; Create a SYSTEM console (this must be run in Administrative console)
PsExec64.exe -s -i cmd
; Export the file
xcopy /G /H "C:\Users\All Users\Microsoft\Crypto\RSA\MachineKeys\00998a33dbff25a91050b3b1bf9001ef_a5968f4a-5244-4993-830a-363efe3adaed" c:\Temp
  • ... the flow continues on a VM, trying to patch a working certificate, etc.
Some details about certificate data found in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates
HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates
2022-04-22 - Win10 20H2 (19042.1645)
  • Used with success the tool exportrsa (GitHub)
  • Run in elevated SYSTEM privilege, then run the tool:
; Create a SYSTEM console (this must be run in Administrative console)
PsExec64.exe -s -i cmd
; Export the keys
exportrsa.exe
Be aware that exportrsa.exe is reported as a virus by VirusTotal, and hence better disable all A/V on Win10 before running the tool.
Example of output:
Skip cert with NO rsa public key for Microsoft ECC TS Root Certificate Authority 2018
Skip cert with NO rsa public key for Microsoft ECC Product Root Certificate Authority 2018
Key for "f92e9a47-1321-4aff-9600-fd7a6dbef186" is a CNG key
Enter password to protect exported cert:
***************
Enter password again:
***************
SUCCESSFULLY exported cert bundle for "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"in file "1.pfx"

Private key for cert "XXXXXXXXXX" is not exportable: 8009000b
Do you really want to export Public/private key for cert "XXXXXXXXXX"
[Y|N] (default N) >>>>
SUCCESSFULLY get private key for "ZAVCWL0136"
Enter password to protect exported cert:
***************
Enter password again:
***************
SUCCESSFULLY exported cert bundle for "ZAVCWL0136"in file "2.pfx"
  • Afterwards, the *.pfx files can be imported again to mark the key as exportable, and export it anew with different options.

Manage services from the command line

The following commands may help

sc query
sc query SERVICE
sc queryex SERVICE
sc qc SERVICE
sc config SERVICE start= auto
sc start SERVICE
net start SERVICE

Troubleshoot remote desktop connection

Guides
  • To view current remote desktop certificate:
  • Open mmc.exe
  • File → Add or Remove Snap-ins → certificates, click Add.
  • Select computer account, then local computer, and click Ok.
  • Go to Certificates → Remote Desktop → Certificates.
  • gpresult /H c:\gpresult.html to see current group policies.

Some useful links as well:

TermService     was disabled, restarted
  sc query TermService
  sc qc TermService
  sc config TermService start= auto
  sc start TermService
UmRdpService, depends on TermService, set on manual on Win10, is disabled here
  sc query UmRdpService
  sc qc UmRdpService
  sc config UmRdpService start= demand
  sc start UmRdpService
  • ... turns out policy was disabled in domain group. Switching group fixed the issue.

Open Issue

Reduce volume size after updates and service packs

Particularly true for Windows Vsta. Ideas:

Troubleshoot

Windows 7 Boot Issues

See Windows 7 boot troubleshooting.

Network Connection Folder is Empty

Reference [12]

  • Open registry editor, and go to key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network,
  • Delete the binary value Config,

There is no normally no need to restart the computer.

The trust relationship between this workstation and the primary domain failed

Relevant links:

The root cause is a desync between the machine account password on the computer locally (known as a local secret) and the computer's computer account object on the Windows domain controller. By default, each windows machine changes the local machine account password every 30 days, and replicates this change to the domain controller. The authentication process keeps the current password and previous password. A desync may occur if the machine is reset to a previous state beyond two password changes.

To fix: Use netdom.exe to resync the machine account passwords[17] (need special privilege on DC).

To prevent the problem from happening, edit the following keys in HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters [18]:

  • MaximumPasswordAge
  • DisablePasswordChange
  • ScavengeInterval

Remote Desktop Black Screen issue

Symptoms:

  • Connect via RDP, screen is black.

Cause:

  • Likely the persistent bitmap caching [19]

Fix:

  • Press Ctrl-Alt-END, to go to task manager screen. This should display the desktop in most case.

Create a console as SYSTEM user

  • Download and install PsTools
  • Start powershell console with Administrator rights (Ctrl-X-A.
  • Run
; Create a SYSTEM console (this must be run in Administrative console)
PsExec64.exe -s -i cmd