Windows

From Segfault
Jump to: navigation, search

Windows Server 2003 Resource Kit Tools

The Resource Kit Tools hold quite a few commands, usually under %ProgramFiles%\Windows Resource Kits\Tools:

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 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 needs Administrator privileges:

$ netstat -anb

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

diskuse

WINXP# diskuse /v /u:Administrator /n:3 /s "c:\Program Files"
DiskUse                   Version 1.3

Scanning Path c:\Program 
Resolving Names.
Sorting.

User: WINXP\Administrator
Space Used: 184571495
   12283904 : 03/29/2010 : c:\Program Files\Google\Picasa3\setup.exe
   19875328 : 11/08/2009 : c:\Program Files\Avira\AntiVir Desktop\vbase000.vdf
   19875328 : 11/08/2009 : c:\Program Files\Avira\AntiVir Desktop\vbase000.vdf

ntrights

TODO

oh

NOTE:

 The system global flag 'maintain object type lists' is not enabled
 for this system. Please use 'oh +otl' to enable it and then reboot.

Find all open handles:

WINXP# oh -p 0 | qgrep -e "Documents and Settings"
[...]
000007A0 cmd.exe        File           000c \Documents and Settings\Administrator
000004B8 oh.exe         File           000c \Documents and Settings\Administrator
000000A8 qgrep.exe      File           000c \Documents and Settings\Administrator
0000050C qgrep.exe      File           000c \Documents and Settings\Administrator

pmon

A top like utility:

WINXP# pmon
 Memory:  523796K Avail: 321572K  PageFlts:    12 InRam Kernel: 1400K P:17292K
 Commit: 215472K/ 172892K Limit: 621464K Peak: 355364K  Pool N: 4604K P:17640K

                Mem  Mem   Page   Flts Commit  Usage   Pri  Hnd Thd  Image
CPU  CpuTime  Usage Diff   Faults Diff Charge NonP Page     Cnt Cnt  Name

              55160    8  1086984    2                             File Cache
96  43:43:53     28    0        0    0      0    0    0  0    0  1 Idle Process
 0   0:26:06    236    0     3238    0     28    0    0  8  239 44 System
 0   0:00:00    400    0      239    0    156    0    6 11   26  2 smss.exe

qgrep

qgrep actually understands a few regular expressions:

WINXP# tasklist | qgrep -v "K$"

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============

WINXP# tasklist | qgrep  "^s"
smss.exe                     424 Console                 0        400 K
services.exe                 556 Console                 0      5,428 K
svchost.exe                  772 Console                 0      5,600 K
svchost.exe                  816 Console                 0      4,248 K
svchost.exe                  932 Console                 0      3,932 K
svchost.exe                  948 Console                 0      3,168 K
svchost.exe                  980 Console                 0     28,656 K
sched.exe                   1036 Console                 0        768 K

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[1] 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 -c c:

TODO: find out if these tools zero the unused space or if they overwrite with random data.

Directories that are safe to delete

Windows saves a lot of things to disk, never deleting them. So %SystemRoot% grows and grows and sometimes we need to free up some space, quickly:

Screen Lock, Hibernation, Standby

To lock the screen:

rundll32.exe user32.dll,LockWorkStation

To put the system into hibernation or standby:

rundll32.exe powrprof.dll,SetSuspendState

Use Powercfg.cpl to check if hibernation is enabled: if it is, the system will go into hibernation, otherwise the system will go into standby.

One can also click on the taskbar, hit ALT+F4 and a popup window appears to choose from standby, hibernate, restart and shutdown. If hibernate is not listed, try pressing H to force hibernation.

Suspend to RAM

Suspend to RAM (STR) can be possible if the hardware supports it:

Multiple TerminalServer Sessions

This should work immediately, w/o restarting the machine:

 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\fSingleSessionPerUser = 0x0  (DWORD)

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" ...

Telnet

Server

It's 2012 and Windows still comes w/o a SSH server installed. Being in a trusted environment, let's use Telnet then:

  1. Go to Control PanelProgram & FeaturesTurn Windows Features on or off
  2. Enable "Telnet Server"
  3. Enable "Telnet" via services.msc
  4. Start "Telnet" (e.g. net start Telnet)

Client

In some later Windows versions, even the telnet client is disabled, for whatever reasons. Here's how to enable[2] the client again in Windows 7 or Windows 8:

  1. Open Control PanelPrograms and FeaturesTurn Windows features on or off
  2. Enable "Telnet Client" in "Windows Features"
  3. Click OK


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[3].

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:[4]

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.

Sudo

TBD

Control Panels

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

Environment variables

<source lang=dos>

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

</source>

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[5]
  • disable system protection (which will in effect delete the system's shadow copies[6])


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[7] until Windows XP and Windows Server 2003, we can use certutil[8] 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[9] to point to the correct path again:

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

With that, the GRUB menu was restored.

See also

Links



References