Skip to content

Conversation

@asadeddin
Copy link

No description provided.


# 4 - SQL Injection via input
elif 'sql' in request.form:
sql = request.form['sql']
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SQL Injection ( 🔴 High ) - The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. View in Corgea ↗

More Details
🎟️Issue Explanation: The code directly takes user input to build an SQL command, risking attackers changing the query to access or damage data. This is called SQL Injection.

- The input "request.form['sql']" is used raw, allowing attackers to insert malicious SQL like "' OR 1=1 --".
- This can modify SQL queries, leading to data leaks, deletion, or unauthorized access.
- Since SQL commands are important and often handle sensitive info, this flaw can cause serious security breaches.

🪄Fix Explanation: The fix replaces directly executing raw SQL from user input with a parameterized, allowlisted set of predefined queries, preventing arbitrary SQL execution and thus mitigating SQL injection risks.
- Replaces `"sql = request.form['sql']"` with `"query_key = request.form['sql']"`, treating input as a key, not raw SQL.
- Introduces `"allowed_queries"`, a dictionary of predefined SQL statements and their parameters, enforcing a whitelist.
- Checks if `"query_key"` exists in `"allowed_queries"`, raising an error for unsupported keys.
- Uses parameterized queries via `"cursor.execute(sql, params)"` to safely insert user-supplied ID, preventing injection.
- Eliminates direct execution of user-supplied SQL, drastically reducing injection attack surface.

💡Important Instructions: Ensure the upstream code always provides valid query keys and validate the id parameter is an integer before processing to avoid type errors.
Suggested change
sql = request.form['sql']
query_key = request.form['sql']
try:
# Execute the user's SQL query
# Execute an allowlisted, parameterized query instead of raw user SQL
allowed_queries = {
'get_all_users': ("SELECT id, username FROM users", ()),
'get_user_by_id': ("SELECT id, username FROM users WHERE id = ?", (int(request.form.get('id', -1)),)),
}
if query_key not in allowed_queries:
raise ValueError("Unsupported query key")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants