Windows

From Segfault
Jump to navigation Jump to search

Resource Kit Tools

The Resource Kit Tools (Archive) held quite a few commands, usually under %ProgramFiles%\Windows Resource Kits\Tools, nowadays some of these tools should be available on a standard Windows installation.

tasklist

$ tasklist /fi "memusage gt 8192"

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
winlogon.exe                 512 Console                 0     10,140 K
svchost.exe                  980 Console                 0     28,956 K
avguard.exe                 1128 Console                 0      8,740 K
explorer.exe                1160 RDP-Tcp#3               1      8,316 K
firefox.exe                 3772 RDP-Tcp#3               1     54,240 K

Sometimes we want to know which program[1] occupies a certain network port. Running tasklist in a loop with netstat can emulate something like netstat -p in Linux:

@echo off
:loop

echo %time%
for /f "tokens=1-5" %%a ^
  in ('netstat -ano ^| find "10.0.0.3"') ^
do echo "REMOTE %%c PID: %%e" & ^
  tasklist /FO CSV /V /FI "PID eq %%e" /NH & ^
echo.

goto loop

Windows' own netstat has an option to display not only the PIDs but the program name - but it's awfully slow and it needs Administrator privileges:

$ netstat -anob

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       748
  Can not obtain ownership information
  TCP    10.5.13.2:1279         10.5.1.21:22           ESTABLISHED     5336
  [putty.exe]
  [...]

taskkill

Similar to tasklist, there's taskkill to terminate processes:

$ tasklist | find "Job"
JobServer.exe                16224 Services                   0     90,436 K
JobServerChild.exe           21796 Services                   0    127,936 K
JobServerChild.exe           13768 Services                   0    129,164 K
$ taskkill /PID 21796 /PID 13768 /f
SUCCESS: The process with PID 21796 has been terminated.
SUCCESS: The process with PID 13768 has been terminated.

qwinsta, rwinsta

How to query (and terminate) RDP sessions:

$ qwinsta
 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 console                                     0  Conn    wdcon
 rdp-tcp                                 65536  Listen  rdpwd
>rdp-tcp#3         Administrator             1  Active  rdpwd
                   bob                       2  Disc    rdpwd

$ rwinsta 2

disk usage

Without any additional tools, all we have is dir, but that's not really useful, as we cannot print directory names and sizes on the same line:

$ dir /o:s /s "c:\Program Files" | find "bytes" | sort
             75 File(s)     70,783,134 bytes
             81 File(s)      6,992,256 bytes
             88 File(s)        899,425 bytes
             89 File(s)        907,053 bytes
            127 File(s)    119,764,510 bytes
           3291 Dir(s)  77,508,915,200 bytes free
           3647 File(s)  2,336,559,490 bytes

With du this looks a bit better:

$ du -nobanner -v c:\ | sort
Processing...
[...]
  3,676,260  c:\Windows\WinSxS
  3,916,391  c:\Users\dummy
  3,919,139  c:\Users
  5,263,591  c:\Windows\System32
 17,144,086  c:\Windows
Directories:  96243
Files:        340178
Size on disk: 26,900,548,576 bytes
Size:         29,744,207,359 bytes

But PowerShell of course is here to help:[2]

> $totalsize = [long]0
> Get-ChildItem -File -Recurse -Force -ErrorAction SilentlyContinue | % {$totalsize += $_.Length}
> $totalsize / 1024 / 1024 / 1024
55.0684367781505

Systeminfo

To gather system information, use systeminfo or msinfo32.

3rd party programs

Sysinternals Suite

The Sysinternals Suite comes with another set of useful tools:

 $ pslist -m explorer
 Process memory detail for WINXP:
 Name                Pid      VM      WS    Priv Priv Pk   Faults   NonP Page
 explorer           1312  103744   22772   13416   14872    40934     14  107

UnxUtils

unxutils (last updated 2007-03-01) provide GNU utilities for Win32 - a bit of sanity for Win32 systems.

PortQry

PortQry[3] can be used as a #Netcat substitute.

Scan a single port:

PortQry.exe -n alice -p tcp -e 80

Scan several ports:

PortQry.exe -n alice -p tcp -o 80,443

Scan a range:

PortQry.exe -n alice -p tcp -r 512:1024

Netcat

Someone was kind enough to upload Netcat for Windows!

$ nc -h
[v1.11 NT www.vulnwatch.org/netcat/]
connect to somewhere:   nc [-options] hostname port[s] [ports] ...
listen for inbound:     nc -l -p port [options] [hostname] [port]
options:
        -d              detach from console, background mode

        -e prog         inbound program to exec [dangerous!!]
        -g gateway      source-routing hop point[s], up to 8
        -G num          source-routing pointer: 4, 8, 12, ...
        -h              this cruft
        -i secs         delay interval for lines sent, ports scanned
        -l              listen mode, for inbound connects
        -L              listen harder, re-listen on socket close
        -n              numeric-only IP addresses, no DNS
        -o file         hex dump of traffic
        -p port         local port number
        -r              randomize local and remote ports
        -s addr         local source address
        -t              answer TELNET negotiation
        -u              UDP mode
        -v              verbose [use twice to be more verbose]
        -w secs         timeout for connects and final net reads
        -z              zero-I/O mode [used for scanning]
port numbers can be individual or ranges: m-n [inclusive]

Wipe

To wipe free space and/or objects, there are several tools available:

cipher.exe will overwrite all free space on the specified drive or directory:

cipher /w:c:

SDelete will do the same:

sdelete -z c:

rinetd

Together with Disable445Feature.zip[4] we can do magic things.

$ type Disable445Feature.ps1
Function Disable445Feature
{
    $netBTParametersPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters"
    IF(Test-Path -Path $netBTParametersPath) {
        Set-ItemProperty -Path $netBTParametersPath -Name "SMBDeviceEnabled" -Value 0
    }
    Set-Service lanmanserver -StartupType Disabled
    Stop-Service lanmanserver -Force
}

Disable445Feature

Once disabled, our local port 445 should be free to be used with rinetd:

$ type config.txt
127.0.0.1 445 10.0.0.1 445

$ rinetd.exe -c config.txt

$ netstat -an | find "445"
 TCP    127.0.0.1:445          0.0.0.0:0              LISTENING

Now shares can be mounted from localhost!

Package Managers

Name Comment
Chocolatey
Ninite
Scoop command line tools mostly
AppGet Superseded[5] by WinGet
Npackd

Filesystem Links

Hardlinks can be created with fsutil:

fsutil hardlink create %systemroot%\foo.exe "%programfiles%\application\this-app.exe"

Symbolic links for directories can be created via junction:

junction %systemroot%\target "%programfiles%\source"

Windows Vista introduced support symbolic links for files and directories via mklink:

runas /user:administrator mklink %systemroot%\target.exe "%programfiles%\source.exe"

Note:

  • Be careful with junctions - when deleting the target directory, the (content of the) source directory is also deleted! That's what you get when hardlinking directories.
  • mklink needs explicit permissions to create symbolic links! Sometimes a dedicated administrator shell is necessary:
$ runas /user:administrator cmd
Enter the password for administrator:
Attempting to start cmd as user "LOCALHOST\administrator" ...

Miscellaneous

Start applications minimized

start /min %systemroot%\system32\taskmgr.exe
takeown /f directory_name /r /d y
icacls directory_name /grant administrators:F /t
 0 - Title text is truncated
 1 - Title text wraps to the next line

Disable system auto restart

After (automatic) updates were installed, the system sometimes needs to be rebooted. To disable the automatic restart, adjust the following registry key:

 HKEY_LOCAL_MACHINE \Software\Policies \Microsoft\Windows \WindowsUpdate\AU
 NoAutoRebootWithLoggedOnUsers=1

To activate this setting, the system has to be rebooted[6].

Note: on this Windows XP SP2 system here, even without rebooting, a normal user was then able to at least cancel the "Please reboot now" screen.

Runas

The basic usage of runas is:

runas /noprofile /user:admin "some\program.exe"

In some Windows versions, the Run as... right-click option is disabled for .bat and .cmd files. To enable those, use the following registry snippet:[7]

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\batfile\shell\runas\command]
@="\"%1\" %*"

[HKEY_CLASSES_ROOT\cmdfile\shell\runas\command]
@="\"%1\" %*"

Note: runas will still ask for a password, namely the password for the specified /user: above. We could create an auxiliary admin user with a different name (and member of the "Administrators" group), but that still is no substitute for SUID or sudo approaches.

Control Panels

 runas /user:Administrator cmd.exe
 
 sysdm.cpl                   # System Properties
 firewall.cpl                # Windows Firewall

Environment variables

PATH=%PATH%;%ProgramFiles%\UnxUtils\usr\local\wbin;%ProgramFiles%\Windows Resource Kits\Tools;%ProgramFiles%\SysinternalsSuite
PROMPT=%COMPUTERNAME%# 
DIRCMD=/a/ogn/p

Allow users to change the system time

It's not really about changing the time but to be able to double-click on the clock in the system tray, so that one can see the calendar.

  • Open secpol.msc (Administrative ToolsLocal Security Policy)
  • Local Policy → User Rights Assignment → Change the System time

Add e.g. "Authenticated Users" to this policy.

Windows NT Logon Screen Background

Set "Wallpaper" to the full name path of the new background image, or set to NULL to disable the background altogether:

 HKEY_USERS\Local Machine\.DEFAULT\Control Panel\Desktop\Wallpaper

This way, logging on via RDP is way faster, because no backgound image has to be transferred.

Disk Management

Shrink Volumes

Trying to shrink a volume only allows us to shrink it by a certain amount, although more (free) disk space would be available. The Application log in the system event viewer shows:

A volume shrink analysis was initiated on volume Windows (C:).
This event log entry details information about the last unmovable file that could limit the maximum number of reclaimable bytes.

Diagnostic details:
- The last unmovable file appears to be: \System Volume Information\[...]
- The last cluster of the file is: 0x788ecaf
- Shrink potential target (LCN address): 0x1a8842b
- The NTFS file flags are: ---AD
- Shrink phase: <analysis>

To find more details about this file please use the 
"fsutil volume querycluster \\?\Volume{d66eabaf-6574-4b9d-ac48-309125edfbc8} 0x788ecaf" command.

To free these unmovable objects we need to:

  • (temporarily) disable the paging file[8]
  • disable system protection (which will in effect delete the system's shadow copies[9])


See also: Q. I'm trying to shrink an NTFS volume, but the shrink value possible is far less than my free space. What's wrong?

Checksums

With fciv only available[10] until Windows XP and Windows Server 2003, we can use certutil[11] to do the job:

$ certutil -hashfile -? | find "algo"
Hash algorithms: MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512

$ certutil -hashfile foo.txt SHA256
SHA256 hash of foo.txt:
4b9d687ac625690fd026ed4b236dad1cac90ef69e7ad256cc42766a065b50026
CertUtil: -hashfile command completed successfully.

Disable Hibernation

From an administrator shell:

powercfg.exe /hibernate off

This will also remove the (large) hiberfil.sys file.

Windows Firewall

We may want to allow some services in our firewall

  • File and Printer Sharing (Echo Request - ICMPv4-In)
  • File and Printer Sharing (Echo Request - ICMPv6-In)
  • Remote Desktop - User Mode (TCP-In)

Fix EFI boot loader

Booted into Windows to apply some firmware updates and it altered the boot order. So Windows would still boot, but the GRUB menu was gone and there was no way to boot into Linux again. Use bcdedit[12] to point to the correct path again:

bcdedit /set {bootmgr} path \EFI\fedora\grubx64.efi

With that, the GRUB menu was restored.

Windows Build

Display the Windows version and build without running Windows, i.e. from a Linux machine:[13][14]

$ iconv -f UTF-16 -t UTF-8 < some.log | grep -Po 'Data.OsBuild.{40}'
Data.OsBuild": 18362, "Data.OsBuildRevision": 476, "

$ hivexget /mnt/disk/Windows/System32/config/SOFTWARE 'Microsoft\Windows NT\CurrentVersion' | egrep -w 'ProductName|CurrentBuild'
"CurrentBuild"="18362"
"ProductName"="Windows 10 Pro"

$ cat /mnt/disk/ProgramData/Microsoft/Diagnosis/osver.txt 
10.0.18362

UTC system time

To configure Windows to use UTC instead of local time[15], a registry key must be set:

reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /d 1 /t REG_QWORD /f

See also

Links

References