agentleFS
ivangrynenkoivangrynenko/cursorrules/.cursor/rules/python-injection.mdc

cursorrules / rules

Cursor rule88 starsChanged 13 months agoMITView on GitHub

Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03

The file

We split this python-injection.mdc into the rules it gives an agent

11 rules. About 0 are common, 11 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈11

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use parameterized queries (prepared statements) with placeholders:

    line 67
  2. Distinctive:

    Use ORM frameworks when possible (Django ORM, SQLAlchemy)

    line 78
  3. Distinctive:

    Never use shell=True with subprocess functions

    line 82
  4. Distinctive:

    Use shlex.quote() if you must include user input in shell commands

    line 88
  5. Distinctive:

    Consider using safer alternatives like Python libraries instead of shell commands

    line 89
  6. Distinctive:

    Use template auto-escaping (enabled by default in modern frameworks)

    line 92
  7. Distinctive:

    Use os.path.abspath() and os.path.normpath()

    line 114
  8. Distinctive:

    Consider using libraries like Werkzeug's secure_filename()

    line 116
  9. Distinctive:

    Use parameterized queries or query builders

    line 119
  10. Distinctive:

    Avoid using eval() or exec() with user input

    line 128
  11. Distinctive:

    Use sandboxed template engines

    line 129

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
python-injection.mdc
---
description: Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03
globs: *.py, *.ini, *.cfg, *.yml, *.yaml, *.json, *.toml
alwaysApply: false
---
 # Python Injection Security Standards (OWASP A03:2021)

This rule enforces security best practices to prevent injection vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A03.

<rule>
name: python_injection
description: Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03
filters:
  - type: file_extension
    pattern: "\\.(py)$"
  - type: file_path
    pattern: ".*"

actions:
  - type: enforce
    conditions:
      # Pattern 1: SQL Injection - String concatenation in SQL queries
      - pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*\\s*[\\+%]|cursor\\.(execute|executemany)\\([^,]+\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*"
        message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string concatenation."
        
      # Pattern 2: SQL Injection - String formatting in SQL queries
      - pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*%[^\"']*[\"']\\s*%\\s*|cursor\\.(execute|executemany)\\([\"'][^\"']*{[^\"']*}[\"']\\.format"
        message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string formatting."
        
      # Pattern 3: Command Injection - Shell command execution with user input
      - pattern: "(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*format\\(|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*f['\"]"
        message: "Potential command injection vulnerability. Never use string concatenation or formatting with shell commands. Use subprocess with shell=False and pass arguments as a list."
        
      # Pattern 4: Command Injection - Shell=True in subprocess
      - pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*shell\\s*=\\s*True"
        message: "Using shell=True with subprocess functions is dangerous and can lead to command injection. Use shell=False (default) and pass arguments as a list."
        
      # Pattern 5: XSS - Unescaped template variables
      - pattern: "\\{\\{\\s*[^|]*\\s*\\}\\}|\\{\\%\\s*autoescape\\s+off\\s*\\%\\}"
        message: "Potential XSS vulnerability. Ensure all template variables are properly escaped. Avoid using 'autoescape off' in templates."
        
      # Pattern 6: XSS - Unsafe HTML rendering in Flask/Django
      - pattern: "render_template\\([^)]*\\)|render\\([^)]*\\)|mark_safe\\([^)]*\\)|safe\\s*\\|"
        message: "Potential XSS vulnerability. Ensure all user-supplied data is properly escaped before rendering in templates."
        
      # Pattern 7: Path Traversal - Unsafe file operations
      - pattern: "open\\([^)]*\\+|open\\([^)]*format\\(|open\\([^)]*f['\"]"
        message: "Potential path traversal vulnerability. Validate and sanitize file paths before opening files. Consider using os.path.abspath and os.path.normpath."
        
      # Pattern 8: LDAP Injection - Unsafe LDAP queries
      - pattern: "ldap\\.search\\([^)]*\\+|ldap\\.search\\([^)]*format\\(|ldap\\.search\\([^)]*f['\"]"
        message: "Potential LDAP injection vulnerability. Use proper LDAP escaping for user-supplied input in LDAP queries."
        
      # Pattern 9: NoSQL Injection - Unsafe MongoDB queries
      - pattern: "find\\(\\{[^}]*\\+|find\\(\\{[^}]*format\\(|find\\(\\{[^}]*f['\"]"
        message: "Potential NoSQL injection vulnerability. Use parameterized queries or proper escaping for MongoDB queries."
        
      # Pattern 10: Template Injection - Unsafe template rendering
      - pattern: "Template\\([^)]*\\)\\.(render|substitute)\\(|eval\\([^)]*\\)|exec\\([^)]*\\)"
        message: "Potential template injection or code injection vulnerability. Avoid using eval() or exec() with user input, and ensure template variables are properly validated."

  - type: suggest
    message: |
      **Python Injection Prevention Best Practices:**
      
      1. **SQL Injection Prevention:**
         - Use parameterized queries (prepared statements) with placeholders:
           ```python
           # Safe SQL query with parameters
           cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
           
           # Django ORM (safe by default)
           User.objects.filter(username=username, password=password)
           
           # SQLAlchemy (safe by default)
           session.query(User).filter(User.username == username, User.password == password)
           ```
         - Use ORM frameworks when possible (Django ORM, SQLAlchemy)
         - Apply proper input validation and sanitization
      
      2. **Command Injection Prevention:**
         - Never use shell=True with subprocess functions
         - Pass command arguments as a list, not a string:
           ```python
           # Safe command execution
           subprocess.run(["ls", "-l", user_dir], shell=False)
           ```
         - Use shlex.quote() if you must include user input in shell commands
         - Consider using safer alternatives like Python libraries instead of shell commands
      
      3. **XSS Prevention:**
         - Use template auto-escaping (enabled by default in modern frameworks)
         - Explicitly escape user input before rendering:
           ```python
           # Django
           from django.utils.html import escape
           safe_data = escape(user_input)
           
           # Flask/Jinja2
           from markupsafe import escape
           safe_data = escape(user_input)
           ```
         - Use Content-Security-Policy headers
         - Validate input against allowlists
      
      4. **Path Traversal Prevention:**
         - Validate and sanitize file paths:
           ```python
           import os
           safe_path = os.path.normpath(os.path.join(safe_base_dir, user_filename))
           if not safe_path.startswith(safe_base_dir):
               raise ValueError("Invalid path")
           ```
         - Use os.path.abspath() and os.path.normpath()
         - Implement proper access controls
         - Consider using libraries like Werkzeug's secure_filename()
      
      5. **NoSQL Injection Prevention:**
         - Use parameterized queries or query builders
         - Validate input against schemas
         - Apply proper type checking
           ```python
           # Safe MongoDB query
           collection.find({"username": username, "status": "active"})
           ```
      
      6. **Template Injection Prevention:**
         - Avoid using eval() or exec() with user input
         - Use sandboxed template engines
         - Limit template functionality to what's necessary
         - Apply proper input validation

  - type: validate
    conditions:
      # Check 1: Safe SQL queries
      - pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\(|cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\[|Model\\.objects\\.filter\\(|session\\.query\\("
        message: "Using parameterized queries or ORM for database access."
      
      # Check 2: Safe command execution
      - pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\(\\[[^\\]]*\\]"
        message: "Using subprocess with arguments as a list (safe pattern)."
      
      # Check 3: Proper input validation
      - pattern: "validate|sanitize|clean|escape|is_valid\\(|validators\\."
        message: "Implementing input validation or sanitization."
      
      # Check 4: Safe file operations
      - pattern: "os\\.path\\.join|os\\.path\\.abspath|os\\.path\\.normpath|secure_filename"
        message: "Using safe file path handling techniques."

metadata:
  priority: high
  version: 1.0
  tags:
    - security
    - python
    - injection
    - sql-injection
    - xss
    - command-injection
    - owasp
    - language:python
    - framework:django
    - framework:flask
    - framework:fastapi
    - category:security
    - subcategory:injection
    - standard:owasp-top10
    - risk:a03-injection
  references:
    - "https://owasp.org/Top10/A03_2021-Injection/"
    - "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"
    - "https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"
    - "https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"
    - "https://docs.python.org/3/library/subprocess.html"
    - "https://docs.djangoproject.com/en/stable/topics/security/"
    - "https://flask.palletsprojects.com/en/latest/security/"
</rule>

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.