Scan, Identify, and Fix Security Vulnerabilities
扫描、识别和修复安全漏洞
Learn to use Semgrep for static analysis, identify OWASP Top 10 vulnerabilities, and implement security fixes including SQL injection prevention, XSS protection, and secure cryptography.
学习使用Semgrep进行静态分析,识别OWASP十大漏洞,并实施安全修复,包括SQL注入防护、XSS保护和安全加密。
backend/app/routers/notes.py lines 69-92@router.get("/unsafe-search", response_model=list[NoteRead])
def unsafe_search(q: str, db: Session = Depends(get_db)):
sql = text(
f"""
SELECT id, title, content, created_at, updated_at
FROM notes
WHERE title LIKE '%{q}%' OR content LIKE '%{q}%'
ORDER BY created_at DESC
LIMIT 50
"""
)
rows = db.execute(sql).all()
return [NoteRead.model_validate(row) for row in rows]
@router.get("/safe-search", response_model=list[NoteRead])
def safe_search(q: str, db: Session = Depends(get_db)):
"""Search notes using parameterized query to prevent SQL injection."""
from sqlalchemy import bindparam
# Use parameterized query with bindparam - prevents SQL injection
sql = text(
"""
SELECT id, title, content, created_at, updated_at
FROM notes
WHERE title LIKE :search_pattern OR content LIKE :search_pattern
ORDER BY created_at DESC
LIMIT 50
"""
)
search_pattern = f"%{q}%"
rows = db.execute(sql, {"search_pattern": search_pattern}).all()
return [NoteRead.model_validate(row) for row in rows]
backend/app/routers/notes.py lines 95-99@router.get("/debug/hash-md5")
def debug_hash_md5(q: str) -> dict[str, str]:
import hashlib
return {"algo": "md5", "hex": hashlib.md5(q.encode()).hexdigest()}
@router.get("/debug/hash-sha256")
def debug_hash_sha256(q: str, add_salt: bool = False) -> dict[str, str]:
"""Hash input using SHA-256 with optional salt."""
import hashlib
import secrets
if add_salt:
# Generate a cryptographically secure random salt
salt = secrets.token_hex(16)
value = q.encode() + salt.encode()
hex_digest = hashlib.sha256(value).hexdigest()
return {
"algo": "sha256",
"hex": hex_digest,
"salted": True,
"salt": salt,
}
else:
# SHA-256 is much stronger than MD5
hex_digest = hashlib.sha256(q.encode()).hexdigest()
return {"algo": "sha256", "hex": hex_digest, "salted": False}
frontend/app.js line 14async function loadNotes(params = {}) {
const list = document.getElementById('notes');
list.innerHTML = '';
const notes = await fetchJSON('/notes/?' + new URLSearchParams(params));
for (const n of notes) {
const li = document.createElement('li');
li.innerHTML = `${n.title}: ${n.content}`; // ⚠️ XSS vulnerability
list.appendChild(li);
}
}
async function loadNotes(params = {}) {
const list = document.getElementById('notes');
list.innerHTML = '';
const notes = await fetchJSON('/notes/?' + new URLSearchParams(params));
for (const n of notes) {
const li = document.createElement('li');
// Use textContent instead of innerHTML to prevent XSS
const titleSpan = document.createElement('strong');
titleSpan.textContent = n.title; // ✅ Safe - automatic escaping
li.appendChild(titleSpan);
const contentSpan = document.createTextNode(`: ${n.content}`);
li.appendChild(contentSpan);
list.appendChild(li);
}
}
<, >, & are converted to HTML entities (<, >, &).<script>alert('XSS')</script> with innerHTML executes the script. With textContent, it displays literally as text.<、>、&被转换为HTML实体。<script>alert('XSS')</script>,使用innerHTML会执行脚本。使用textContent时,它会按字面显示为文本。
Always use parameterized queries or ORM methods to prevent SQL injection.
始终使用参数化查询或ORM方法来防止SQL注入。
Never trust user input. Always validate, sanitize, and use safe APIs.
永远不要信任用户输入。始终验证、清理并使用安全API。
Use textContent instead of innerHTML for user-generated content.
对用户生成内容使用textContent而非innerHTML。
Use modern algorithms: SHA-256, bcrypt, argon2. Avoid MD5, SHA1.
使用现代算法:SHA-256、bcrypt、argon2。避免MD5、SHA1。
Apply multiple layers of security controls for comprehensive protection.
应用多层安全控制以实现全面保护。
Use Semgrep and SAST tools to catch vulnerabilities early.
使用Semgrep和SAST工具尽早发现漏洞。