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

推荐订阅源

博客园 - 三生石上(FineUI控件)
Blog — PlanetScale
Blog — PlanetScale
B
Blog
GbyAI
GbyAI
爱范儿
爱范儿
月光博客
月光博客
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
腾讯CDC
MyScale Blog
MyScale Blog
V
Visual Studio Blog
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

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
A Flask Vulnerability Walkthrough
Bettina Lige · 2026-05-27 · via DEV Community

Machine Problem 3
Group Members: Deen, Ligero, Torres

Web applications, even simple ones, can carry serious security flaws that are easy to miss during development. In this article, I'll walk through five vulnerabilities I identified and patched in a small Flask/SQLite app featuring a login page and a user posts feed. The fixes are straightforward, but the impact of leaving them unaddressed can be severe.

Stack: Python, Flask, SQLite3
Vulnerabilities covered: SQL Injection, Cross-Site Request Forgery (CSRF), Cross-Site Scripting (XSS), Insecure Cookie Attributes

Finding 1: SQL Injection — Login Bypass

Severity: Critical
Affected file: app.pylogin() POST handler

The Problem

The login query was built by directly concatenating raw form input into a SQL string:

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

Enter fullscreen mode Exit fullscreen mode

This means an attacker can inject SQL syntax into the username field to manipulate the query entirely. Entering the following bypasses authentication without a valid password:

Username:  ' OR '1'='1' --
Password:  anything

Enter fullscreen mode Exit fullscreen mode

The resulting query becomes:

SELECT id FROM users WHERE username = '' OR '1'='1' --' AND password = '...'

Enter fullscreen mode Exit fullscreen mode

The -- comments out the password check, and '1'='1' is always true — so the query returns the first user in the database.

The Fix

Replace string concatenation with parameterised queries. The ? placeholder lets the database driver handle escaping safely:

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

Enter fullscreen mode Exit fullscreen mode

User input can no longer alter the SQL structure, no matter what it contains.

Finding 2: SQL Injection — Session Token Queries

Severity: High
Affected file: app.pylogin(), home(), posts(), logout() handlers

The Problem

Every route that authenticates the user reads a session token from a cookie and concatenates it directly into SQL. Since cookies can be freely modified by the client, a crafted value like:

' OR '1'='1

Enter fullscreen mode Exit fullscreen mode

...could manipulate those queries — for example, turning a targeted DELETE in logout() into one that wipes every session in the database.

The Fix

Same as Finding 1 — parameterised queries everywhere the cookie value touches SQL:

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"),)
)

Enter fullscreen mode Exit fullscreen mode

Finding 3: Cross-Site Request Forgery (CSRF)

Severity: High
Affected files: app.pyposts() handler; home.html, login.html

The Problem

Neither the /login nor the /posts endpoint verified that form submissions came from the app itself. A malicious site can host a hidden form that POSTs to the app — and since the browser automatically attaches the session cookie, the server has no way to tell the request wasn't intentional.

<!-- Hosted on attacker's site -->
<form method="POST" action="http://localhost:5000/posts" id="f">
  <input type="hidden" name="message" value="CSRF attack!">
</form>
<script>document.getElementById('f').submit();</script>

Enter fullscreen mode Exit fullscreen mode

Any logged-in user who visits that page gets a post created on their account silently.

The Fix

Implement the Synchronizer Token Pattern — a server-generated secret token embedded in every form and validated on every POST:

def get_csrf_token():
    if "csrf_token" not in session:
        session["csrf_token"] = secrets.token_hex(32)
    return session["csrf_token"]

def validate_csrf(token):
    return token and token == session.get("csrf_token")

Enter fullscreen mode Exit fullscreen mode

Add the hidden field to every form in the templates:

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

Enter fullscreen mode Exit fullscreen mode

Requests that arrive without a matching token are rejected. Since the token lives in the server-side session, an attacker's site has no way to obtain it.

Finding 4: Stored Cross-Site Scripting (XSS)

Severity: High
Affected file: templates/home.html

The Problem

Posts were rendered using Jinja2's | safe filter:

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

Enter fullscreen mode Exit fullscreen mode

This explicitly disables HTML escaping, so any HTML or JavaScript stored in the database gets executed directly in the browser. Submitting this as a post:

<script>alert("XSS: " + document.cookie)</script>

Enter fullscreen mode Exit fullscreen mode

...causes the script to run for every user who loads the home page, potentially leaking their session cookie to an attacker.

The Fix

Remove the | safe filter:

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

Enter fullscreen mode Exit fullscreen mode

Jinja2 escapes HTML by default. Characters like <, >, and " become their entity equivalents (&lt;, &gt;, &quot;), so stored scripts display as plain text instead of executing.

Finding 5: Insecure Session Cookie Attributes

Severity: Medium
Affected file: app.pylogin() POST handler

The Problem

The session cookie was set without HttpOnly or SameSite attributes. Without HttpOnly, JavaScript can read the cookie — which means the XSS above could steal the session token directly via document.cookie. Without SameSite, the cookie is sent freely on cross-site requests, weakening CSRF defenses.

The Fix

Set both attributes when creating the cookie:

response.set_cookie(
    "session_token", token,
    httponly=True,   # JS cannot read the cookie
    samesite="Lax"   # Not sent on cross-site POSTs
)

Enter fullscreen mode Exit fullscreen mode

HttpOnly cuts off the cookie-theft XSS vector entirely. SameSite=Lax adds a browser-level CSRF layer on top of the token check.

Set both attributes when creating the cookie:

response.set_cookie(
    "session_token", token,
    httponly=True,   # JS cannot read the cookie
    samesite="Lax"   # Not sent on cross-site POSTs
)

Enter fullscreen mode Exit fullscreen mode

HttpOnly cuts off the cookie-theft XSS vector entirely. SameSite=Lax adds a browser-level CSRF layer on top of the token check.