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
為什麼要學SQL 與 NoSQL 注入攻擊?
SQL 與 NoSQL 注入攻擊 是 api-security-pentest 課程的核心章節之一。
在真實世界中
SQL 與 NoSQL 注入攻擊 並不是課本上的理論——它在真實的軟體開發中頻繁出現。無論你是正在接案、準備面試,還是想要提升自己的技術深度,理解這個主題都能讓你直接受益。
你將從本章獲得
- 🎯 完整的知識體系:從核心原理到實作細節,條理分明
- 💻 可運行的程式碼:每段程式碼都是完整的,可直接執行
- 🔍 除錯技巧:常見錯誤的分析與解決方案
- 🚀 下一步指引:學完後該往哪個方向繼續深入
銜接下一章
本章為你建立了 SQL 與 NoSQL 注入攻擊 的完整知識基礎。下一章將在此基礎上,帶你探索更進階的真實世界應用場景——你將學會如何將本章所學應用到更複雜的問題中。