This code implements security best practices and protections against common web vulnerabilities.
Application Structure
The secure application demonstrates proper security controls and defensive programming.File Organization
Main Application (app.py)
Imports and Security Modules
Source:secure/app.py:1-8
Security Libraries:
markupsafe.escape- Prevents XSS attackswerkzeug.security- Secure password hashing with bcryptflask_wtf.csrf- CSRF token protectiondotenv- Environment variable management
Configuration
Source:secure/app.py:10-16
Security Improvements:
- Secret key loaded from environment variables
- Not hardcoded or in version control
- CSRF protection enabled globally
- Different keys per environment
Security Headers Middleware
Source:secure/app.py:18-26
HTTP Security Headers:
Prevents MIME type sniffing attacks
Prevents clickjacking attacks
Enables browser’s XSS filter
Forces HTTPS connections for 1 year
Restricts resource loading to same origin
Route: Login (Secure Authentication)
Source:secure/app.py:32-73
- Full Route
- Key Security Features
Security Controls:
- Input Validation - Length and presence checks
- Prepared Statements - Parameterized queries prevent SQL injection
- Password Hashing - Bcrypt with automatic salt
- Generic Error Messages - “Credenciales incorrectas” doesn’t reveal if username exists
- No Debug Output - No query logging or error details
- Session Security - Permanent sessions with secure configuration
Route: Register (Secure User Creation)
Source:secure/app.py:75-122
Security Features:
- Comprehensive Input Validation
- Required field checks
- Username length: 3-50 characters
- Password minimum: 6 characters
- Input trimming with
.strip()
- Secure Password Storage
- Bcrypt hashing via
generate_password_hash() - Automatic salt generation
- Computational cost prevents brute force
- Bcrypt hashing via
- SQL Injection Prevention
- Parameterized queries
- No string concatenation
- Error Handling
- Catches
IntegrityErrorfor duplicate usernames - Generic error messages to users
- Detailed errors only logged server-side
- Catches
Route: Dashboard (XSS Prevention)
Source:secure/app.py:124-137
XSS Prevention:
escape()function sanitizes all HTML special characters<script>becomes<script>(harmless text)- Template uses
{{ message }}without|safefilter - CSP headers provide additional layer of protection
Before and After
Route: Profile (IDOR Prevention)
Source:secure/app.py:139-179
Authorization Controls:
- Authentication Check - Requires active session
- Input Validation - Type checking with
int() - Authorization Logic:
- Users can only view their own profile
- Admins can view any profile
- Unauthorized access blocked with 403
- Data Minimization - Password field excluded from SELECT
- SQL Injection Prevention - Parameterized query
Authorization Flow
Database Module (database.py)
Secure Database Setup
Source:secure/database.py:17-52
Database Security:
- Hashed Passwords - All passwords stored with bcrypt
- Indexes - Performance optimization on username lookups
- Prepared Statements - Even for setup queries
- Unique Constraints - Prevents duplicate usernames
Password Hash Comparison
Environment Configuration
.env File Structure
Generating a Secure Secret Key
Security Best Practices Implemented
SQL Injection Prevention
SQL Injection Prevention
Technique: Parameterized queries (prepared statements)How it works: The database driver separates SQL code from data, preventing injection.
XSS Prevention
XSS Prevention
Techniques:
- HTML Escaping:
escape()function converts special characters - CSP Headers: Restricts inline scripts and external resources
- Proper Template Usage: Avoid
|safefilter unless absolutely necessary
Authentication Security
Authentication Security
Password Security:
- Hashing Algorithm: Bcrypt via Werkzeug
- Automatic Salt: Each password gets unique salt
- Computational Cost: Tunable work factor prevents brute force
Authorization Controls
Authorization Controls
CSRF Protection
CSRF Protection
Implementation: Flask-WTF CSRFProtectIn templates:
Security Headers
Security Headers
Headers Applied:
| Header | Purpose | Value |
|---|---|---|
X-Content-Type-Options | Prevent MIME sniffing | nosniff |
X-Frame-Options | Prevent clickjacking | DENY |
X-XSS-Protection | Enable XSS filter | 1; mode=block |
Strict-Transport-Security | Force HTTPS | max-age=31536000 |
Content-Security-Policy | Control resources | default-src 'self' |
Testing Security Controls
Test SQL Injection Protection
Try the previous SQL injection attack:Expected Result: Login fails with “Credenciales incorrectas”The prepared statement treats the entire input as a string, not SQL code.
Test XSS Protection
Visit:Expected Result: The literal text
<script>alert('XSS')</script> appears on the page (not executed)Test IDOR Protection
Login as regular user, then try to view admin profile:Expected Result: “No tienes permiso para ver este perfil” message
Performance Considerations
Password Hashing Impact: Bcrypt is intentionally slow (computational cost) to prevent brute force attacks. This adds ~100-300ms to login/register operations, which is acceptable for the security benefit.
Database Indexes
username column speeds up login queries significantly:
- Without index: O(n) full table scan
- With index: O(log n) B-tree lookup
Security Checklist
SQL Injection - Parameterized queries everywhere
XSS - HTML escaping and CSP headers
CSRF - Token validation on forms
Authentication - Bcrypt password hashing
Authorization - Role-based access control
IDOR - User ID validation and permission checks
Security Headers - X-Frame-Options, CSP, HSTS
Secret Management - Environment variables
Error Handling - Generic messages to users
Input Validation - Type and length checks
For production deployments, also consider:
- Rate limiting (prevent brute force)
- HTTPS enforcement (TLS/SSL)
- Database encryption at rest
- Audit logging
- Regular security updates
- Penetration testing