SQL Injection & NoSQL Injection

🔥 Vibe Prompt

"Test a login API for SQLi. Show vulnerable vs parameterized query. Then test MongoDB NoSQLi."

import sqlite3, json

# VULNERABLE
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INT, username TEXT, password TEXT)")
conn.execute("INSERT INTO users VALUES (1, 'admin', 'secret123')")

def vulnerable_login(username, password):
    # NEVER do this!
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    print(f"Query: {query}")
    return conn.execute(query).fetchone() is not None

# SQLi attack
print(f"SQLi: {vulnerable_login("admin'--", "anything")}")  # Bypasses auth!

# SAFE: parameterized
safe_query = "SELECT * FROM users WHERE username=? AND password=?"
print(f"Safe: {conn.execute(safe_query, ('admin'"'--", 'anything')).fetchone()}")  # Fails properly

# NoSQL injection (MongoDB)
# Vulnerable: db.users.find({username: req.body.username, password: req.body.password})
# Attack: {"username": "admin", "password": {"$ne": ""}} → matches!

# Safe fix:
# db.users.find({username: req.body.username, password: hash(req.body.password)})

Prevention

| Technique | How | |-----------|-----| | Parameterized Queries | WHERE id = %s | | ORM | SQLAlchemy, Prisma | | Input Validation | Reject special chars in usernames | | Least Privilege | DB user = SELECT only | | WAF | Block SQLi patterns |

Blind SQLi Detection

' OR 1=1 --        # Always true
' AND 1=2 --       # Always false
' AND SLEEP(5) --  # Time-based detection

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials


API 的注入攻擊:不只是 SQL

在 API 滲透測試中,注入攻擊是最常見的漏洞之一。但現代 API 不只是用 SQL——NoSQL(MongoDB)和 GraphQL 也有注入風險。

SQL vs NoSQL Injection

| 類型 | 目標 | 常用工具 | 防護 | |:----|:----|:--------|:----| | SQL Injection | 關聯式資料庫 | ' OR 1=1-- | 參數化查詢 | | NoSQL Injection | MongoDB | {"$gt": ""} | 輸入驗證、型態檢查 | | GraphQL Injection | GraphQL API | 深度查詢、別名 | Depth Limit、Query Cost |

NoSQL Injection 範例

// 正常的登入請求
POST /api/login
{"username": "alice", "password": "123456"}

// NoSQL 注入——繞過密碼驗證
POST /api/login
{"username": "alice", "password": {"$ne": ""}}
// $ne = not equal → 只要密碼不是空字串就通過!

下一章預告:IDOR

注入攻擊繞過的是驗證。下一章的 IDOR(Insecure Direct Object Reference)繞過的是授權——你登入後可以存取別人的資料。

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!