API 已經是現代服務的核心,無論是手機 App、前端網站、甚至 IoT,都靠 API 互通。
但這也代表 駭客最愛的攻擊目標,因為只要 API 有一點點漏洞,就可能被利用來竊取資料、注入惡意指令。
人工檢測太慢,因此今天示範如何用 AI Agent 模擬攻擊 + 自動生成防護建議。
"' OR 1=1 --"
→ 測試 SQL Injection<script>alert(1)</script>
→ 測試 XSS{}
→ 測試弱驗證<script>
標籤建立基本的 Express 伺服器,並啟用 express.json()
讓它能解析 JSON body
import express from "express";
const app = express();
app.use(express.json());
這裡刻意留下兩個漏洞:
' OR 1=1 --
時,伺服器會回傳登入成功。<script>
,伺服器會直接輸出。app.post("/api/login", (req, res) => {
const { username, password } = req.body;
// 模擬 SQL Injection 風險 (直接拼接字串,錯誤示範)
if (username === "admin" && password === "' OR 1=1 --") {
return res.json({ message: "登入成功 (SQLi 模擬)" });
}
// 模擬 XSS 風險 (回應未做轉義)
if (username && username.includes("<script>")) {
return res.send(`<h1>歡迎 ${username}</h1>`);
}
res.status(401).json({ error: "登入失敗" });
});
啟動在本機 3000 port,給後續的 agent.js
測試使用
app.listen(3000, () => {
console.log("測試 API 伺服器已啟動 ");
});
指定測試目標,就是剛剛建立的 /api/login
const apiUrl = "http://localhost:3000/api/login";
const payloads = [
{ username: "admin", password: "' OR 1=1 --" }, // SQL Injection
{ username: "<script>alert(1)</script>", password: "123" } // XSS
];
async function attackApi(payload) {
const res = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
const text = await res.text();
return { payload, status: res.status, response: text };
}
async function detectVulnerabilities(results) {
const prompt = `
你是一個資安檢測 Agent,請分析以下 API 回應結果,指出可能的弱點:
${JSON.stringify(results, null, 2)}
請輸出「弱點類型 / 偵測結果」的列表。
`;
const r = await model.generateContent(prompt);
return r.response.text();
}
async function generateAdvice(detection) {
const prompt = `
根據以下檢測結果,請提供對應的防護建議:
${detection}
請用表格形式輸出 (弱點類型 / 建議措施)。
`;
const r = await model.generateContent(prompt);
return r.response.text();
}
(async () => {
console.log("開始模擬攻擊 API:", apiUrl);
// 1. 發送攻擊
const attackResults = [];
for (const p of payloads) {
const result = await attackApi(p);
attackResults.push(result);
}
// 2. 偵測漏洞
const detection = await detectVulnerabilities(attackResults);
console.log("檢測結果:\n", detection);
// 3. 生成防護建議
const advice = await generateAdvice(detection);
console.log("防護建議:\n", advice);
})();