Skip to content

Commit 35a843c

Browse files
Add/update Python_Flask_rules.mdc security rules
1 parent f16a609 commit 35a843c

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
---
2+
description: This rule enforces security best practices for Python applications built with Flask, focusing on preventing common web vulnerabilities.
3+
globs: **/*.py
4+
alwaysApply: false
5+
---
6+
7+
# Secure Python/Flask Application Development Rules
8+
9+
- As a security-aware developer, generate secure Python code using Flask that inherently prevents top security weaknesses.
10+
- Focus on making the implementation inherently safe rather than merely renaming methods with "secure_" prefixes.
11+
- Use inline comments to clearly highlight critical security controls, implemented measures, and any security assumptions made in the code.
12+
- Adhere strictly to best practices from OWASP, with particular consideration for the OWASP ASVS guidelines.
13+
- **Avoid Slopsquatting**: Be careful when referencing or importing packages. Do not guess if a package exists. Comment on any low reputation or uncommon packages you have included.
14+
15+
## Memory Safety Considerations
16+
Python is a memory-safe language due to its automatic memory management (garbage collection) and abstraction of memory access. Therefore, explicit memory safety considerations, such as buffer overflows or use-after-free vulnerabilities, are not directly applicable at the application code level when writing Python.
17+
18+
## Top CWEs for Python + Flask
19+
20+
### CWE-79: Cross-Site Scripting (XSS)
21+
**Summary:** XSS occurs when an application includes untrusted data in an HTML page without proper validation or escaping, allowing attackers to execute scripts in the victim's browser.
22+
**Mitigation Rule:** Always use Flask's Jinja2 templating engine, which performs automatic HTML escaping by default. If rendering content directly outside of Jinja2 or explicitly marking content as safe, ensure all user-supplied or untrusted data is rigorously validated and properly HTML-escaped using `jinja2.escape()` or `werkzeug.utils.escape()`. Avoid using `|safe` or `autoescape off` in Jinja2 unless strictly necessary and after thorough validation and justification.
23+
24+
### CWE-89: SQL Injection
25+
**Summary:** SQL Injection allows attackers to manipulate SQL queries by providing malicious input, potentially leading to unauthorized data access or modification.
26+
**Mitigation Rule:** Never concatenate user input directly into SQL queries. Always use parameterized queries or Prepared Statements via an Object-Relational Mapper (ORM) like SQLAlchemy or directly through database drivers that support parameterization.
27+
28+
### CWE-20: Improper Input Validation
29+
**Summary:** Improper input validation occurs when an application fails to properly validate, filter, or sanitize user-supplied input before processing it.
30+
**Mitigation Rule:** Implement strict server-side validation for all user inputs against expected data types, formats, lengths, and ranges. Use libraries such as `WTForms` or `Pydantic` for comprehensive schema validation and explicit rejection of invalid input. Do not rely solely on client-side validation.
31+
32+
### CWE-22: Path Traversal
33+
**Summary:** Path Traversal allows attackers to access arbitrary files and directories on the server by manipulating file paths, often by using "dot-dot-slash" (../) sequences.
34+
**Mitigation Rule:** Never construct file paths using unvalidated user input. When dealing with file operations or serving static content, use `werkzeug.utils.safe_join()` to securely combine path components and restrict access to designated directories, ensuring paths cannot traverse outside the intended base directory.
35+
36+
### CWE-352: Cross-Site Request Forgery (CSRF)
37+
**Summary:** CSRF forces an authenticated user to submit a malicious request to a web application without their explicit consent.
38+
**Mitigation Rule:** Implement robust CSRF protection for all state-changing operations (e.g., POST, PUT, DELETE requests). Use Flask-WTF or Flask-Security-Too to generate and validate CSRF tokens, ensuring each form submission or AJAX request includes a valid, unique token that is checked on the server-side.
39+
40+
### CWE-287: Improper Authentication
41+
**Summary:** Improper authentication allows attackers to bypass or compromise authentication mechanisms, gaining unauthorized access.
42+
**Mitigation Rule:** Implement strong and secure authentication mechanisms using established libraries like Flask-Login or Flask-Security-Too. Always hash passwords using strong, adaptive, and modern hashing algorithms (e.g., bcrypt) via `werkzeug.security.generate_password_hash()` and `check_password_hash()`. Do not store plain-text passwords or use weak hashing functions. Enforce secure session management, such as setting `session.permanent = True` only for appropriate use cases and ensuring `session.secret_key` is strong and securely managed.
43+
44+
### CWE-798: Use of Hard-coded Credentials
45+
**Summary:** Hard-coding credentials or secrets directly within the source code makes them easily discoverable and compromises security.
46+
**Mitigation Rule:** Never hard-code sensitive information such as API keys, database credentials, secret keys, or cryptographic keys directly in the source code. Store all secrets and sensitive configuration externally using environment variables (accessible via `os.environ`), dedicated configuration files loaded securely (e.g., `.env` files with `python-dotenv`), or a secure secret management service.

0 commit comments

Comments
 (0)