File size: 236,720 Bytes
8168f10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
{"source": "firecrawl_search", "query": "OWASP Python SQL injection parameterized query sqlite3 remediation", "source_url": "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html", "license": "web_reference", "markdown": "[Skip to content](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html#sql-injection-prevention-cheat-sheet)\n\n# SQL Injection Prevention Cheat Sheet [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#sql-injection-prevention-cheat-sheet \"Permanent link\")\n\n## Introduction [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#introduction \"Permanent link\")\n\nA SQL injection attack occurs when untrusted data (usually strings) becomes part of a query's SQL syntax, modifying the logic of the SQL request.\n\nThe malicious data can come from various sources such as:\n\n- an HTTP request (for example, from a malicious user);\n- an LDAP directory;\n- an incoming email;\n- a third party REST API service;\n- the database itself.\n\n**Impact:** A successful SQL injection attack can, depending on database features and privileges, read data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, execute operating system commands.\n\n**Resolution:** define the SQL structure separately from its data values, then bind those values through the database API:\n\n- use parameterized queries for dynamic data values;\n- use fixed application-owned choices for dynamic table names, column names, sort order (`ASC`, `DESC`), etc.\n\nThese controls apply regardless of whether data comes from an HTTP request, another service, or previously stored data.\n\nA related class of vulnerability affects object-relational mapping (ORM) frameworks, such as JPA/Hibernate, which have their own query language (JPQL/HQL). Applications using these frameworks might be vulnerable to injections of these query languages:\n\n- JPQL injections (JPA);\n- HQL injections (Hibernate).\n\nFor other injection types, see the [Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html).\n\n## Examples of injections [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#examples-of-injections \"Permanent link\")\n\n### Basic SQL injection [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#basic-sql-injection \"Permanent link\")\n\nA simple SQL injection flaw in Java is shown below. The \"customerName\" parameter is simply concatenated to build the query and an attacker can enter SQL code into that query and the application would take the attacker's code and execute it on the database.\n\n```\n// UNSAFE!\nString query = \"SELECT account_balance FROM user_data WHERE user_name = '\"\n    + request.getParameter(\"customerName\") + \"'\";\nStatement statement = connection.createStatement();\nResultSet results = statement.executeQuery(query);\n```\n\nAs explained below, the recommended safe implementation would use parameterized queries, using `?` as placeholders for the values:\n\n```\nString query = \"SELECT account_balance FROM user_data WHERE user_name = ?\";\nPreparedStatement statement = connection.prepareStatement(query);\nstatement.setString(1, customerName);\nResultSet results = statement.executeQuery();\n```\n\nAn input such as `tom' or '1'='1` is treated as the literal username to match, not as a condition added to the query. Parameter binding prevents this value from changing SQL syntax; it does not decide whether the caller may access the matching account.\n\n### SQL injection with Procedure Calls [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#sql-injection-with-procedure-calls \"Permanent link\")\n\nSQL injections can happen as well in procedure calls:\n\n```\n// UNSAFE\nCallableStatement statement = connection.prepareCall(\"{call sp_updateAccountBalance('\" + customerName + \"' , \" + amount + \")}\");\nstatement.execute();\n```\n\nAs below, the recommended implementation uses parameterized queries:\n\n```\nCallableStatement statement = connection.prepareCall(\"{call sp_updateAccountBalance(?,?)}\");\nstatement.setString(1, customerName);\nstatement.setBigDecimal(2, amount);\nstatement.execute();\n```\n\nWhile this prevents injection when calling the procedure, the procedure itself might still be vulnerable to SQL injection, as explained in [SQL Injection inside stored Procedures and Functions](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html#sql-injection-inside-stored-procedures-and-functions).\n\n### SQL Injection in ORM Query Languages [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#sql-injection-in-orm-query-languages \"Permanent link\")\n\nSome ORM frameworks such as [Hibernate](https://hibernate.org/) use dedicated query languages, such as Hibernate Query Language (HQL), which may suffer from the same injection problems ( [HQL Injection](https://cwe.mitre.org/data/definitions/564.html)):\n\n```\n// UNSAFE: HQL injection!\nQuery unsafeHQLQuery = session.createQuery(\"from Inventory where productID='\"+userSuppliedParameter+\"'\");\n```\n\nParameterized queries are the recommended solution here as well:\n\n```\n// Here is a safe version of the same query using named parameters\nQuery safeHQLQuery = session.createQuery(\"from Inventory where productID=:productid\");\nsafeHQLQuery.setParameter(\"productid\", userSuppliedParameter);\n```\n\n### SQL Injection inside stored Procedures and Functions [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#sql-injection-inside-stored-procedures-and-functions \"Permanent link\")\n\n**Binding procedure arguments protects the call, not dynamic SQL constructed inside the procedure.**\n\nUse static SQL with parameters, or separately bind data values in internal dynamic queries instead of concatenating them into SQL text. [Microsoft's secure dynamic SQL guidance](https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/writing-secure-dynamic-sql?view=sql-server-ver17) calls for reviewing procedures that construct SQL and parameterizing their commands.\n\nFor example, [PostgreSQL documents `EXECUTE ... USING` for binding values](https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN) and `format('%I', ...)` for quoting identifiers. Select identifiers from fixed application-owned mappings. Identifier quoting protects SQL syntax, but does not restrict which tables the application may select.\n\n## Primary Defenses [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#primary-defenses \"Permanent link\")\n\nThe preferred patterns are:\n\n- **parameterized queries** when including dynamic data in SQL requests;\n- for structural parts that cannot be parameterized (table names, column names, sort direction), map user choices to a **strict allow-list** of fixed, application-owned values.\n\nRelying on manually escaping dynamic inputs is error-prone and is strongly discouraged.\n\n### Parameterized Queries [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#parameterized-queries \"Permanent link\")\n\nDefine the SQL structure separately from its data values and bind those values through the database API, as shown in the [Basic SQL injection](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html#basic-sql-injection) example. Concatenating untrusted values into the query before preparing it defeats this protection.\n\nSee the [Query Parameterization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html) for additional examples of parameterized queries in several languages, including Java, .NET, Ruby, PHP, Cold Fusion, Perl, and Rust. Other examples can be found at [Bobby Tables](https://bobby-tables.com/).\n\n### Allow-List Input Validation [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#allow-list-input-validation \"Permanent link\")\n\nParameter markers represent data values, not table names, column names, or SQL keywords such as `ASC` and `DESC`; see the [PDO parameter-marker limitations](https://www.php.net/manual/en/pdo.prepare.php). Keep these structural choices fixed in code where possible. When users need to select among them, map their selection to a small set of application-owned values allowed for that query and reject anything else. In this example, `tableName` can only hold one of two fixed values, so it can be appended to the query:\n\n```\nString tableName;\nswitch(PARAM) {\n  case \"room\":\n    tableName = \"roomTable\";\n    break;\n  case \"floor\":\n    tableName = \"floorTable\";\n    break;\n  default:\n    throw new InputValidationException(\"unexpected table name\");\n}\n```\n\nMap a requested sort direction the same way, to the literal `ASC` or `DESC`, rather than appending the supplied text.\n\n### Manually escaping (STRONGLY DISCOURAGED) [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#manually-escaping-strongly-discouraged \"Permanent link\")\n\n**Do not manually escape untrusted values to construct SQL queries. Use parameterized queries instead.**\n\nManually escaping the values into the SQL string is error-prone and attempts to do something which is normally handled by the database driver through parameter bindings. It can fail and can allow SQL injections for several reasons:\n\n- SQL escaping rules are not always straightforward;\n- different SQL dialects have different rules;\n- some databases have configuration which might affect the escaping behavior (such as MySQL [NO\\_BACKSLASH\\_ESCAPES](https://dev.mysql.com/doc/refman/9.7/en/sql-mode.html#sqlmode_no_backslash_escapes)).\n\nReplace escaping-based query construction with parameter binding.\n\n## Hardening [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#hardening \"Permanent link\")\n\nWe also recommend adopting all of these additional defenses to provide defense in depth to limit damage in case of successful SQL injection attacks.\n\n### Least Privilege [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#least-privilege \"Permanent link\")\n\nTo minimize the potential damage of a successful SQL injection attack, you should minimize the privileges assigned to every database account in your environment. Start from the ground up to determine what access rights your application accounts require, rather than trying to figure out what access rights you need to take away.\n\nMake sure that accounts that only need read access are only granted read access to the tables they need access to. DO NOT ASSIGN DBA OR ADMIN TYPE ACCESS TO YOUR APPLICATION ACCOUNTS. We understand that this is easy, and everything just \"works\" when you do it this way, but it is very dangerous.\n\n#### Minimizing Application and OS Privileges [¶](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\\#minimizing-application-and-os-privileges \"Permanent link\")\n\nSQL injection is not the only threat to your database data. Attackers can simply change the parameter values from one of the legal values they are presented with, to a value that is unauthorized for them, but the application itself might be authorized to access. As such, minimizing the privileges granted to your application will reduce the likelihood of such unauthorized access attempts, even when an attacker is not trying to use SQL injection as part of their exploit.\n\nWhile you are at it, you should minimize the privileges of the operating system account that the DBMS runs under. Don't run your DBMS as root or system! Most DBMSs run out of the box with a very powerful system account. For example, MySQL runs as system on Windows by default! Change the DBMS's OS account to something more appropriate, with restricted privileges.\n\n#### Details Of Lea"}
{"source": "firecrawl_search", "query": "OWASP Python SQL injection parameterized query sqlite3 remediation", "source_url": "https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html", "license": "web_reference", "markdown": "[Skip to content](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html#query-parameterization-cheat-sheet)\n\n# Query Parameterization Cheat Sheet [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#query-parameterization-cheat-sheet \"Permanent link\")\n\n## Introduction [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#introduction \"Permanent link\")\n\n[SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) is one of the most dangerous web vulnerabilities. As of the [OWASP Top 10:2025](https://owasp.org/Top10/2025/A05_2025-Injection/), it is categorized under A05:2025-Injection.\n\nIt represents a serious threat because SQL Injection allows evil attacker code to change the structure of a web application's SQL statement in a way that can steal data, modify data, or potentially facilitate command injection to the underlying OS.\n\nSee also the [SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html).\n\n## Parameterized Query Examples [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#parameterized-query-examples \"Permanent link\")\n\nSQL Injection is best prevented through the use of [_parameterized queries_](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html). The following chart demonstrates, with real-world code samples, how to build parameterized queries in most of the common web languages. The purpose of these code samples is to demonstrate to the web developer how to avoid SQL Injection when building database queries within a web application.\n\nPlease note, many client side frameworks and libraries offer client side query parameterization. These libraries often just build queries with string concatenation before sending raw queries to a server. Please ensure that query parameterization is done server-side!\n\n### Prepared Statement Examples [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#prepared-statement-examples \"Permanent link\")\n\n#### Using Java built-in feature [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-java-built-in-feature \"Permanent link\")\n\n```\nString custname = request.getParameter(\"customerName\");\nString query = \"SELECT account_balance FROM user_data WHERE user_name = ? \";\nPreparedStatement pstmt = connection.prepareStatement( query );\npstmt.setString( 1, custname);\nResultSet results = pstmt.executeQuery( );\n```\n\n#### Using Java with JPA/Hibernate [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-java-with-jpahibernate \"Permanent link\")\n\n```\n// HQL\n@Entity // declare as entity;\n@NamedQuery(\n name=\"findByDescription\",\n query=\"FROM Inventory i WHERE i.productDescription = :productDescription\"\n)\npublic class Inventory implements Serializable {\n @Id\n private long id;\n private String productDescription;\n}\n\n// Use case\n// This should REALLY be validated too\nString userSuppliedParameter = request.getParameter(\"Product-Description\");\n// Perform input validation to detect attacks\nList<Inventory> list =\n session.getNamedQuery(\"findByDescription\")\n .setParameter(\"productDescription\", userSuppliedParameter).list();\n\n// Criteria API\n// This should REALLY be validated too\nString userSuppliedParameter = request.getParameter(\"Product-Description\");\n// Perform input validation to detect attacks\nInventory inv = (Inventory) session.createCriteria(Inventory.class).add\n(Restrictions.eq(\"productDescription\", userSuppliedParameter)).uniqueResult();\n```\n\n#### Using .NET built-in feature [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-net-built-in-feature \"Permanent link\")\n\n```\nString query = \"SELECT account_balance FROM user_data WHERE user_name = ?\";\ntry {\n   OleDbCommand command = new OleDbCommand(query, connection);\n   command.Parameters.Add(new OleDbParameter(\"customerName\", CustomerName.Text));\n   OleDbDataReader reader = command.ExecuteReader();\n   // …\n} catch (OleDbException se) {\n   // error handling\n}\n```\n\n#### Using ASP .NET built-in feature [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-asp-net-built-in-feature \"Permanent link\")\n\n```\nstring sql = \"SELECT * FROM Customers WHERE CustomerId = @CustomerId\";\nSqlCommand command = new SqlCommand(sql);\ncommand.Parameters.Add(new SqlParameter(\"@CustomerId\", System.Data.SqlDbType.Int));\ncommand.Parameters[\"@CustomerId\"].Value = 1;\n```\n\n#### Using Ruby with ActiveRecord [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-ruby-with-activerecord \"Permanent link\")\n\n```\n## Create\nProject.create!(:name => 'owasp')\n## Read\nProject.all(:conditions => \"name = ?\", name)\nProject.all(:conditions => { :name => name })\nProject.where(\"name = :name\", :name => name)\n## Update\nproject.update_attributes(:name => 'owasp')\n## Delete\nProject.delete(:name => 'name')\n```\n\n#### Using Ruby built-in feature [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-ruby-built-in-feature \"Permanent link\")\n\n```\ninsert_new_user = db.prepare \"INSERT INTO users (name, age, gender) VALUES (?, ? ,?)\"\ninsert_new_user.execute 'aizatto', '20', 'male'\n```\n\n#### Using PHP with PHP Data Objects [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-php-with-php-data-objects \"Permanent link\")\n\n```\n$stmt = $dbh->prepare(\"INSERT INTO REGISTRY (name, value) VALUES (:name, :value)\");\n$stmt->bindParam(':name', $name);\n$stmt->bindParam(':value', $value);\n```\n\n#### Using Cold Fusion built-in feature [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-cold-fusion-built-in-feature \"Permanent link\")\n\n```\n<cfquery name = \"getFirst\" dataSource = \"cfsnippets\">\n    SELECT * FROM #strDatabasePrefix#_courses WHERE intCourseID =\n    <cfqueryparam value = #intCourseID# CFSQLType = \"CF_SQL_INTEGER\">\n</cfquery>\n```\n\n#### Using PERL with Database Independent Interface [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-perl-with-database-independent-interface \"Permanent link\")\n\n```\nmy $sql = \"INSERT INTO foo (bar, baz) VALUES ( ?, ? )\";\nmy $sth = $dbh->prepare( $sql );\n$sth->execute( $bar, $baz );\n```\n\n#### Using Rust with SQLx [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#using-rust-with-sqlx \"Permanent link\")\n\n```\n// Input from CLI args but could be anything\nlet username = std::env::args().last().unwrap();\n\n// Using build-in macros (compile time checks)\nlet users = sqlx::query_as!(\n        User,\n        \"SELECT * FROM users WHERE name = ?\",\n        username\n    )\n    .fetch_all(&pool)\n    .await\n    .unwrap();\n\n// Using built-in functions\nlet users: Vec<User> = sqlx::query_as::<_, User>(\n        \"SELECT * FROM users WHERE name = ?\"\n    )\n    .bind(&username)\n    .fetch_all(&pool)\n    .await\n    .unwrap();\n```\n\n### Stored Procedure Examples [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#stored-procedure-examples \"Permanent link\")\n\nThe SQL you write in your web application isn't the only place that SQL injection vulnerabilities can be introduced. If you are using Stored Procedures, and you are dynamically constructing SQL inside them, you can also introduce SQL injection vulnerabilities.\n\nDynamic SQL can be parameterized using bind variables, to ensure the dynamically constructed SQL is secure.\n\nHere are some examples of using bind variables in stored procedures in different databases.\n\n#### Oracle using PL/SQL [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#oracle-using-plsql \"Permanent link\")\n\n##### Normal Stored Procedure [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#normal-stored-procedure \"Permanent link\")\n\nNo dynamic SQL being created. Parameters passed in to stored procedures are naturally bound to their location within the query without anything special being required:\n\n```\nPROCEDURE SafeGetBalanceQuery(UserID varchar, Dept varchar) AS BEGIN\n   SELECT balance FROM accounts_table WHERE user_ID = UserID AND department = Dept;\nEND;\n```\n\n##### Stored Procedure Using Bind Variables in SQL Run with EXECUTE [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#stored-procedure-using-bind-variables-in-sql-run-with-execute \"Permanent link\")\n\nBind variables are used to tell the database that the inputs to this dynamic SQL are 'data' and not possibly code:\n\n```\nPROCEDURE AnotherSafeGetBalanceQuery(UserID varchar, Dept varchar)\n          AS stmt VARCHAR(400); result NUMBER;\nBEGIN\n   stmt := 'SELECT balance FROM accounts_table WHERE user_ID = :1\n            AND department = :2';\n   EXECUTE IMMEDIATE stmt INTO result USING UserID, Dept;\n   RETURN result;\nEND;\n```\n\n#### SQL Server using Transact-SQL [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#sql-server-using-transact-sql \"Permanent link\")\n\n##### Normal Stored Procedure [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#normal-stored-procedure_1 \"Permanent link\")\n\nNo dynamic SQL being created. Parameters passed in to stored procedures are naturally bound to their location within the query without anything special being required:\n\n```\nPROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN\n   SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = @Dept\nEND\n```\n\n##### Stored Procedure Using Bind Variables in SQL Run with EXEC [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#stored-procedure-using-bind-variables-in-sql-run-with-exec \"Permanent link\")\n\nBind variables are used to tell the database that the inputs to this dynamic SQL are 'data' and not possibly code:\n\n```\nPROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN\n   DECLARE @sql VARCHAR(200)\n   SELECT @sql = 'SELECT balance FROM accounts_table WHERE '\n                 + 'user_ID = @UID AND department = @DPT'\n   EXEC sp_executesql @sql,\n                      '@UID VARCHAR(20), @DPT VARCHAR(10)',\n                      @UID=@UserID, @DPT=@Dept\nEND\n```\n\n## References [¶](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html\\#references \"Permanent link\")\n\n- [Oracle JDBC: Using Prepared Statements](https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html)\n- [PHP PDO: Prepared Statements and Stored Procedures](https://www.php.net/pdo.prepared-statements)"}
{"source": "firecrawl_search", "query": "OWASP Python SQL injection parameterized query sqlite3 remediation", "source_url": "https://safeguard.sh/resources/blog/sql-injection-prevention-in-python-with-parameterized-queries", "license": "web_reference", "markdown": "[Skip to content](https://safeguard.sh/resources/blog/sql-injection-prevention-in-python-with-parameterized-queries#main-content)\n\n[![Safeguard](https://safeguard.sh/brand/safeguard-lockup-ink.svg)![Safeguard](https://safeguard.sh/brand/safeguard-lockup-white.svg)](https://safeguard.sh/)\n\nAK\n\nAman Khan\n\nAppSec Engineer\n\nJuly 5, 20267 min read\n\nShare\n\nIn March 2024, a security researcher disclosed a SQL injection vulnerability in a widely used Python-based inventory management tool that allowed unauthenticated attackers to dump entire customer databases with a single crafted request. The root cause was unremarkable: a developer had built a query using an f-string instead of a parameterized statement. This pattern repeats constantly across Python codebases, from Flask APIs to Django admin panels to internal data pipelines built with raw psycopg2 or sqlite3 calls. SQL injection has ranked in the OWASP Top 10 since the list's inception in 2003, and it remains one of the most common findings in application security audits today. The fix is well understood and has existed in Python's database libraries for decades: parameterized queries, also called prepared statements. This post explains why string concatenation fails, how parameterized queries close the gap, and how to verify your codebase is actually using them consistently rather than assuming it is.\n\n## What Makes SQL Injection Still Possible in Python in 2026?\n\nSQL injection is still possible because Python's database drivers let developers build queries as plain strings, and string concatenation offers no separation between code and data. When a developer writes `cursor.execute(f\"SELECT * FROM users WHERE username = '{username}'\")`, the database receives a single blob of text and has no way to distinguish the intended query structure from user-supplied content. If `username` arrives as `' OR '1'='1`, the resulting query becomes `SELECT * FROM users WHERE username = '' OR '1'='1'`, which returns every row in the table. This isn't a Python-specific flaw — it's how relational databases have always parsed SQL text — but Python's flexibility with string formatting (`%`, `.format()`, f-strings, and now the walrus operator inside expressions) gives developers more ways than ever to accidentally build unsafe queries while the code still looks clean and readable.\n\n## How Do Parameterized Queries Actually Prevent Injection?\n\nParameterized queries prevent injection by sending the query structure and the user-supplied values to the database as two separate channels instead of one merged string. In Python's DB-API 2.0 specification (PEP 249), every compliant driver — psycopg2, mysql-connector-python, sqlite3, pyodbc — supports passing parameters as a second argument to `execute()`. For example: `cursor.execute(\"SELECT * FROM users WHERE username = %s\", (username,))`. The database receives the literal template `SELECT * FROM users WHERE username = ?` and compiles it once, then binds `username` strictly as a data value in the parameter slot. Even if `username` contains `' OR '1'='1`, the database treats it as a single string literal to compare against, not as executable SQL. This is the same mechanism that made prepared statements a security control in the SQL standard itself, not a Python-specific workaround, which is why it applies equally to ORMs like SQLAlchemy and Django's ORM when used correctly.\n\n## Which Python Query Patterns Are Actually Safe Versus Dangerous?\n\nThe safe patterns all share one trait: user input never touches the query string directly, while the dangerous patterns all build the query text dynamically. Safe: `cursor.execute(\"SELECT * FROM orders WHERE id = %s\", (order_id,))` using psycopg2's placeholder syntax, or `User.objects.filter(username=username)` in Django's ORM, or `session.query(User).filter(User.username == username)` in SQLAlchemy. Dangerous: f-strings (`f\"SELECT * FROM t WHERE id={id}\"`), `%` formatting applied before `execute()` instead of passed as the second argument, `.format()` calls building WHERE clauses, and `str.join()` on user-controlled lists of column names. A subtler trap is `cursor.execute(query % params)` — this looks similar to the parameterized form but performs Python-level string substitution before the driver ever sees it, which is functionally identical to concatenation. Django's `.raw()` and `.extra()` methods and SQLAlchemy's `text()` construct also reintroduce risk if developers interpolate variables into the raw SQL string rather than using the bound-parameter syntax those functions still support.\n\n## What Do Real-World Python SQL Injection Incidents Look Like?\n\nReal-world Python SQL injection incidents typically trace back to a single unparameterized query buried in an otherwise secure codebase, not a wholesale absence of security practices. CVE-2023-32677, affecting the Ray distributed computing framework, involved improperly sanitized inputs reaching backend queries. In 2019, a widely reported breach of a healthcare scheduling platform built on Django stemmed from a custom raw SQL report-generation endpoint that concatenated a date-range filter supplied via query parameters. In both cases, the surrounding application used an ORM correctly for 95% of its data access, but one custom reporting or admin feature dropped down to raw SQL for performance or flexibility reasons and skipped parameterization. This is the pattern security teams see repeatedly: injection risk concentrates in analytics endpoints, admin tooling, and legacy scripts that predate a team's adoption of ORM conventions, making these areas disproportionately important to review even after \"the app\" has been broadly secured.\n\n## Are ORMs Like Django and SQLAlchemy Automatically Safe from Injection?\n\nORMs are safe from injection only when developers stick to the ORM's query-building API and avoid its raw-SQL escape hatches without parameters. Django's ORM parameterizes queries built through `filter()`, `exclude()`, `get()`, and similar methods by default, but `Model.objects.raw(f\"SELECT * FROM app_user WHERE email = '{email}'\")` bypasses that protection entirely and is exploitable exactly like raw psycopg2 code. SQLAlchemy behaves the same way: `select(User).where(User.name == name)` is parameterized automatically, while `session.execute(text(f\"SELECT * FROM users WHERE name = '{name}'\"))` is not, even though `text()` is a legitimate, commonly used SQLAlchemy function. Security reviews that stop at \"the project uses an ORM\" and conclude the injection risk is handled miss this distinction consistently, because the presence of an ORM in a codebase says nothing about whether every query path uses it correctly.\n\n## How Should Teams Verify Parameterization Across a Large Python Codebase?\n\nTeams should verify parameterization through automated static analysis rather than manual code review, because manual review does not scale past a few thousand lines and injection risk hides in exactly the endpoints reviewers are least likely to prioritize. Tools like Bandit (B608: hardcoded SQL expressions) and Semgrep's Python SQL injection rulesets can flag f-string and `.format()` usage adjacent to `execute()` calls, but they produce false positives on legitimate dynamic table-name construction and false negatives on custom query-builder wrappers that obscure the eventual `execute()` call. Effective verification combines pattern-based static analysis with dependency and framework awareness — knowing which of your 200 microservices use raw psycopg2 versus Django ORM versus SQLAlchemy Core changes where you should concentrate manual review effort. This is where treating SQL injection prevention as a continuous supply-chain-security question, not a one-time audit, produces materially better outcomes: new services and new contributors reintroduce the same f-string pattern indefinitely unless the check runs on every change.\n\n## How Safeguard Helps\n\nSafeguard approaches SQL injection risk as a software supply chain problem: the vulnerable pattern doesn't just live in your own repositories, it can arrive through a dependency, a forked internal library, or a contributor unfamiliar with your team's conventions, and it needs continuous detection rather than a single point-in-time audit. Safeguard's platform scans Python codebases and their dependency graphs for unparameterized query construction — including f-strings, `.format()`, and `%`-formatting feeding into `execute()`, `raw()`, and `text()` calls — and flags them with the specific file, line, and data flow path from user input to query execution, so security teams don't have to manually trace request handlers to database calls. Because Safeguard integrates into CI/CD pipelines, these checks run on every pull request across every service, catching the one raw-SQL reporting endpoint or admin script before it merges rather than after an incident. For teams managing dozens or hundreds of Python services with mixed ORM and raw-driver usage, Safeguard also maps which services rely on which database access patterns, giving security leads a prioritized view of where parameterization gaps are most likely to exist and where manual review time is best spent. The goal is straightforward: make the safe pattern the default outcome of your pipeline, not a policy that depends on every engineer remembering PEP 249 on every pull request.\n\n[sql-injection](https://safeguard.sh/resources/blog/tag/sql-injection) [python-security](https://safeguard.sh/resources/blog/tag/python-security) [parameterized-queries](https://safeguard.sh/resources/blog/tag/parameterized-queries) [application-security](https://safeguard.sh/resources/blog/tag/application-security) [supply-chain-security](https://safeguard.sh/resources/blog/tag/supply-chain-security) [owasp](https://safeguard.sh/resources/blog/tag/owasp)\n\n[Back to all articles](https://safeguard.sh/resources/blog)\n\n## More on\\#sql-injection\n\n[View all](https://safeguard.sh/resources/blog/tag/sql-injection)\n\n[Application Security\\\\\n**Your Application Connects as a User That Can Do Everything** \\\\\n6 min read](https://safeguard.sh/resources/blog/one-database-user-that-can-do-everything) [Application Security\\\\\n**Second-Order SQL Injection Is the Bug Class a Scanner Should Refuse to Test** \\\\\n7 min read](https://safeguard.sh/resources/blog/second-order-sql-injection-scanners-should-refuse) [Vulnerability Analysis\\\\\n**MOVEit Transfer (CVE-2023-34362): A Mass Exploitation Data-Theft Campaign** \\\\\n2 min read](https://safeguard.sh/resources/blog/moveit-transfer-cve-2023-34362-clop-retrospective) [Vulnerability Analysis\\\\\n**A Critical SQL Injection in Drupal Core's Database Abstraction Layer Is Being Actively Exploited** \\\\\n5 min read](https://safeguard.sh/resources/blog/drupal-core-sql-injection)\n\n## Related articles inIndustry Analysis\n\n[Industry Analysis\\\\\n\\\\\n**Do AI Coding Tools Make Developers Faster? What the Controlled Studies Measured, 2023 to 2026** \\\\\n\\\\\nSix controlled studies of AI coding tools, from 56% faster to 19% slower. What each measured, why they disagree, and a script to measure your own team.\\\\\n\\\\\nOctober 22, 2026Read](https://safeguard.sh/resources/blog/ai-coding-tools-developer-productivity-studies-2023-2026) [Industry Analysis\\\\\n\\\\\n**Voice AI Latency: Why 200 Milliseconds Matters and Where a Voice Agent Spends Its Time** \\\\\n\\\\\nPeople reply in about 200 ms and read 600 ms gaps as reluctance. Where a voice agent's delay goes, why sequential pipelines miss, and how to measure it.\\\\\n\\\\\nOctober 22, 2026Read](https://safeguard.sh/resources/blog/voice-ai-latency-budget-200-ms-turn-taking) [Industry Analysis\\\\\n\\\\\n**How Many AI Agents Are There in 2026? What the Published Numbers Actually Count** \\\\\n\\\\\nThere is no census of AI agents. What Microsoft (nearly 40 million agents registered in Agent 365), Salesforce, OpenAI, IDC and Gartner have actually published, what each figure counts, a reproducible count of the official MCP Registry (46,265 servers), and ho"}
{"source": "firecrawl_search", "query": "Python path traversal pathlib resolve is_relative_to prevention", "source_url": "https://orbisappsec.com/blog/how-path-traversal-in-open-happens-in-python-and-how-to-fix", "license": "web_reference", "markdown": "[Back to Blog](https://orbisappsec.com/blog)\n\nhigh SEVERITY7 min read\n\n# How path traversal in open() happens in Python and how to fix it\n\nA high-severity path traversal vulnerability was discovered in \\`tool/update-doc.py\\`, where user-controlled input was passed directly to Python's \\`open()\\` function without sanitization. This flaw could allow an attacker to read arbitrary files on the server by manipulating the file path. The fix ensures that file paths are validated and restricted to an intended directory before being opened.\n\nO\n\nBy Orbis AppSec\n\n•Technically reviewed by [Anupam Mediratta](https://orbisappsec.com/authors/anupam-mediratta)•PublishedJune 6, 2026•ReviewedJune 6, 2026\n\n[#path-traversal](https://orbisappsec.com/blog/category/path-traversal) [#python](https://orbisappsec.com/blog/category/python) [#file-security](https://orbisappsec.com/blog/category/file-security) [#cwe-22](https://orbisappsec.com/blog/category/cwe-22) [#appsec](https://orbisappsec.com/blog/category/appsec) [#input-validation](https://orbisappsec.com/blog/category/input-validation) [#orbis-appsec](https://orbisappsec.com/blog/category/orbis-appsec)\n\n## Answer Summary\n\nThis is a path traversal vulnerability (CWE-22) in Python's \\`open()\\` function inside \\`tool/update-doc.py\\`, where user-controlled input was used as a file path without sanitization. An attacker could supply a path like \\`../../etc/passwd\\` to read arbitrary files outside the intended directory. The fix involves sanitizing or validating the input path — typically by resolving it to an absolute path and confirming it remains within an allowed base directory before calling \\`open()\\`. Orbis AppSec automatically detected and patched this issue.\n\n## Vulnerability at a Glance\n\n|     |     |\n| --- | --- |\n| cwe | CWE-22 |\n| fix | Validate and restrict file paths to an intended base directory before calling open() |\n| risk | Attackers can read arbitrary files on the server, including credentials, config files, and source code |\n| language | Python |\n| root cause | User-controlled input passed directly to open() without path sanitization or boundary enforcement |\n| vulnerability | Path Traversal via open() |\n\n## Summary\n\nA high-severity path traversal vulnerability was discovered in `tool/update-doc.py`, where user-controlled input was passed directly to Python's `open()` function without sanitization. This flaw could allow an attacker to read arbitrary files on the server by manipulating the file path. The fix ensures that file paths are validated and restricted to an intended directory before being opened.\n\n* * *\n\n## Introduction\n\nThe `tool/update-doc.py` script handles documentation updates — a utility role that might seem low-risk at first glance. But a flaw in how it processes file paths created a serious security hole: user-controlled input flowed directly into a call to `open()` with no sanitization, no boundary checking, and no path normalization.\n\nThis is a textbook **path traversal vulnerability**. The script trusts the caller to provide a safe file path, but an attacker who controls that input can supply something like `../../../../etc/passwd` and cause the application to open files it was never meant to touch.\n\nFor developers building documentation tools, CLI utilities, or any script that accepts filenames from external sources, this pattern is surprisingly easy to introduce and surprisingly dangerous to leave unaddressed.\n\n* * *\n\n## The Vulnerability Explained\n\n### What went wrong in `update-doc.py`\n\nThe vulnerable pattern looks like this:\n\n```\n# Vulnerable code — user-controlled `doc_path` passed directly to open()\ndoc_path = request.args.get(\"doc\")  # or sys.argv, or any external source\nwith open(doc_path, \"r\") as f:\n    content = f.read()\n```\n\nThe problem is straightforward: **the value of `doc_path` comes from user-controlled input and is used directly as the argument to `open()`**. Python's `open()` function will happily accept any valid filesystem path — including ones that traverse parent directories using `../` sequences.\n\nThere is no call to `os.path.realpath()`, no check that the resolved path starts with a trusted base directory, and no filtering of dangerous path components. The script simply trusts the input.\n\n### How an attacker exploits this\n\nImagine the script is intended to open documentation files from a directory like `/app/docs/`. An attacker who can influence the `doc_path` value could supply:\n\n```\n../../etc/passwd\n```\n\nWhich resolves to:\n\n```\n/app/docs/../../etc/passwd  →  /etc/passwd\n```\n\nPython's `open()` resolves this path transparently and returns the contents of `/etc/passwd`. On a real system, this technique can be used to read:\n\n- **`/etc/passwd`** — system user accounts\n- **`~/.ssh/id_rsa`** — private SSH keys\n- **Application config files** — database credentials, API keys, secrets\n- **Other source files** — internal business logic, hardcoded tokens\n\nThe attacker doesn't need authentication, special privileges, or a complex exploit chain. They just need to control the string passed to `open()`.\n\n### Why `update-doc.py` is a realistic target\n\nDocumentation update scripts often run with elevated privileges (they need to write to the filesystem), and they frequently accept filenames from command-line arguments, web requests, or configuration files — all of which can be attacker-influenced. The combination of elevated access and unsanitized input makes this a high-value target.\n\n* * *\n\n## The Fix\n\n### What needs to change\n\nThe fix requires two things:\n\n1\\. **Normalize the path** — resolve `..` sequences and symlinks to get the true absolute path.\n\n2\\. **Enforce a boundary** — confirm the resolved path is inside the intended base directory before opening it.\n\n### Before (vulnerable)\n\n```\n# No sanitization — attacker controls doc_path entirely\ndoc_path = get_user_input()\nwith open(doc_path, \"r\") as f:\n    content = f.read()\n```\n\n### After (fixed)\n\n```\nimport os\n\nBASE_DIR = os.path.realpath(\"/app/docs\")\n\ndef safe_open_doc(user_input):\n    # Resolve the full, normalized absolute path\n    requested_path = os.path.realpath(os.path.join(BASE_DIR, user_input))\n\n    # Enforce that the resolved path is within the allowed base directory\n    if not requested_path.startswith(BASE_DIR + os.sep):\n        raise ValueError(f\"Access denied: path traversal detected in '{user_input}'\")\n\n    with open(requested_path, \"r\") as f:\n        return f.read()\n```\n\n### Why this fix works\n\n- **`os.path.realpath()`** resolves all `../` sequences, symlinks, and redundant separators, giving you the true absolute path on the filesystem. An attacker can't hide traversal in URL encoding or double-dot tricks once this is applied.\n- **`startswith(BASE_DIR + os.sep)`** ensures the resolved path is genuinely _inside_ the base directory, not just a string that happens to start with the same prefix. The `+ os.sep` prevents a bypass where `/app/docs_evil` would incorrectly match `/app/docs`.\n- The check happens **before**`open()` is called, so the file is never opened if the path is out of bounds.\n\nUsing `pathlib` (Python 3.6+) offers an equally clean and Pythonic approach:\n\n```\nfrom pathlib import Path\n\nBASE_DIR = Path(\"/app/docs\").resolve()\n\ndef safe_open_doc(user_input):\n    requested_path = (BASE_DIR / user_input).resolve()\n\n    if not requested_path.is_relative_to(BASE_DIR):\n        raise ValueError(\"Path traversal detected\")\n\n    return requested_path.read_text()\n```\n\n`Path.is_relative_to()` (Python 3.9+) makes the boundary check explicit and readable.\n\n* * *\n\n## Key Takeaways\n\n- **`open(user_input)` in `update-doc.py` is a direct path traversal sink** — any user-controlled string reaching this call without normalization and boundary checking is exploitable.\n- **String filtering for `../` is not a safe mitigation** — attackers can encode, double-encode, or use OS-specific tricks to bypass blocklists. Use `realpath()` \\+ prefix check instead.\n- **Documentation and utility scripts are not low-risk** — tools like `update-doc.py` often run with elevated permissions and accept filenames as input, making them attractive targets.\n- **The `startswith(BASE_DIR + os.sep)` pattern is critical** — omitting `+ os.sep` creates a bypass where sibling directories with similar names pass the check incorrectly.\n- **`pathlib.Path.is_relative_to()` is the modern, readable way** to enforce directory boundaries in Python 3.9+ and should be preferred in new code.\n\n* * *\n\n## How Orbis AppSec Detected This\n\n- **Source**: User-controlled input (e.g., command-line argument, request parameter, or external config value) providing the file path in `tool/update-doc.py`\n- **Sink**: `open(doc_path, ...)` called with the unsanitized user-controlled path, allowing arbitrary file reads\n- **Missing control**: No call to `os.path.realpath()` or equivalent normalization; no check that the resolved path falls within an intended base directory before the file is opened\n- **CWE**: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory (Path Traversal)\n- **Fix**: Normalize the input path with `os.path.realpath()` and verify it resolves within the allowed base directory before passing it to `open()`\n\nOrbis AppSec detects issues like this automatically. [Try Orbis AppSec on your repositories](https://orbisappsec.com/) to find and fix issues like this automatically.\n\n* * *\n\n## Conclusion\n\nPath traversal in Python's `open()` is one of those vulnerabilities that looks simple but carries serious consequences. In `tool/update-doc.py`, the absence of a single normalization-and-boundary-check pattern was enough to expose the entire server filesystem to anyone who could influence the file path argument.\n\nThe fix is not complex — `os.path.realpath()` combined with a `startswith()` check, or `pathlib`'s `is_relative_to()`, closes the door entirely. The lesson for developers is to treat every file path that originates from outside your code as untrusted, normalize it unconditionally, and verify it resolves where you expect before acting on it.\n\nSecurity in file handling isn't about trusting your users. It's about building code that stays safe regardless of what input it receives.\n\n* * *\n\n## Prevention and further reading\n\n- [Path traversal: resolve first, then check containment](https://orbisappsec.com/reference/path-traversal)— vulnerable and secure code side by side, plus how to detect it in your own repository.\n\n[View Repository →](https://github.com/fluent/onigmo)\n\n## Related Articles\n\n[high **player.html Path Traversal via \\`project\\` Query Parameter** \\\\\nA server-side request forgery vulnerability in the player.html endpoint allowed attackers to read arbitrary files from the server filesystem by manipulating the \\`project\\` URL parameter. The fix implements strict path segment validation to reject traversal sequences before any filesystem access occurs.](https://orbisappsec.com/blog/player-html-path-traversal-via-project-query-parameter) [high **clean\\_path() Path Traversal: rel\\_path Escapes USERDATA Dir** \\\\\nA path traversal flaw in the \\`clean\\_path()\\` helper let a user-controlled \\`rel\\_path\\` value escape the intended USERDATA directory and reach arbitrary files on disk. The function joined path segments without checking the final result, so \\`../\\` sequences in route parameters or query strings could be used to read or write files outside the sandboxed storage area. The fix normalizes the path and verifies it still resolves inside the USERDATA root before returning it, raising an error otherwise.](https://orbisappsec.com/blog/clean-path-path-traversal-rel-path-escapes-userdata-dir) [critical **path.resolve() Path Traversal in Node CLI's Dynamic import()** \\\\\nA Node.js CLI script for validating expression definitions took a file path from \\`process.argv\\[2\\]\\`, resolved it with \\`path.resolve()\\`, and passed the result straight into a dynamic \\`import()\\` — with no check that the resolved path stayed inside the working directory. An attacker (or a maliciou"}
{"source": "firecrawl_search", "query": "Python path traversal pathlib resolve is_relative_to prevention", "source_url": "https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code", "license": "web_reference", "markdown": "##### Collectives™ on Stack Overflow\n\nFind centralized, trusted content and collaborate around the technologies you use most.\n\n[Learn more about Collectives](https://stackoverflow.com/collectives)\n\n# [How to prevent directory traversal attack from Python code](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code)\n\n[Ask Question](https://stackoverflow.com/questions/ask)\n\nAsked9 years, 4 months ago\n\nModified [3 years, 4 months ago](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code?lastactivity \"2023-07-21 11:52:52Z\")\n\nViewed\n28k times\n\n\nThis question shows research effort; it is useful and clear\n\n11\n\nThis question does not show any research effort; it is unclear or not useful\n\nSave this question.\n\n[Timeline](https://stackoverflow.com/posts/45188708/timeline)\n\nShow activity on this post.\n\nI need to prevent from `directory traversal attack` from my code using Python. My code is below:\n\n```python\nCopy\nif request.GET.get('param') is not None and request.GET.get('param') != '':\n    param = request.GET.get('param')\n    startdir = os.path.abspath(os.curdir)\n    requested_path = os.path.relpath(param, startdir)\n    requested_path = os.path.abspath(requested_path)\n    print(requested_path)\n    tfile = open(requested_path, 'rb')\n    return HttpResponse(content=tfile, content_type=\"text/plain\")\n```\n\nHere I need user is running like `http://127.0.0.1:8000/createfile/?param=../../../../../../../../etc/passwd` this it should prevent the directory traversal attack.\n\n- [python](https://stackoverflow.com/questions/tagged/python \"show questions tagged 'python'\")\n- [directory-traversal](https://stackoverflow.com/questions/tagged/directory-traversal \"show questions tagged 'directory-traversal'\")\n\n[Share](https://stackoverflow.com/q/45188708)\n\nShare a link to this question\n\nCopy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ \"The current license for this post: CC BY-SA 4.0\")\n\nShort permalink to this question\n\n[Improve this question](https://stackoverflow.com/posts/45188708/edit \"\")\n\nFollow\n\n\n\nFollow this question to receive notifications\n\n[edited Aug 4, 2019 at 10:44](https://stackoverflow.com/posts/45188708/revisions \"show all edits to this post\")\n\n[![halfer's user avatar](https://i.sstatic.net/4rtxd.png?s=64)](https://stackoverflow.com/users/472495/halfer)\n\n[halfer](https://stackoverflow.com/users/472495/halfer)\n\n20.3k2020 gold badges112112 silver badges209209 bronze badges\n\nasked Jul 19, 2017 at 11:05\n\n[![satya's user avatar](https://www.gravatar.com/avatar/d952131af13179b13ffbe07b089dd741?s=64&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/4790217/satya)\n\n[satya](https://stackoverflow.com/users/4790217/satya)\n\n3,5801111 gold badges6262 silver badges137137 bronze badges\n\n3\n\n- user should not be allowed to access or modify sudo directories. So check that path is not a sudo dir\n\n\n\nArpit Solanki\n\n\n–\n[Arpit Solanki](https://stackoverflow.com/users/5250746/arpit-solanki \"10,041 reputation\")\n\n\n\n2017-07-19 11:09:41 +00:00\n\n[CommentedJul 19, 2017 at 11:09](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344550_45188708)\n\n\n- I need to prevent also that. Can you make it like this ?\n\n\n\nsatya\n\n\n–\n[satya](https://stackoverflow.com/users/4790217/satya \"3,580 reputation\")\n\n\n\n2017-07-19 11:11:52 +00:00\n\n[CommentedJul 19, 2017 at 11:11](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344639_45188708)\n\n- not saying that its a good solution but there are around 20 root directories so check that path does not contain any one of them like if user requests a path containing bin directory then don't allow\n\n\n\nArpit Solanki\n\n\n–\n[Arpit Solanki](https://stackoverflow.com/users/5250746/arpit-solanki \"10,041 reputation\")\n\n\n\n2017-07-19 11:15:00 +00:00\n\n[CommentedJul 19, 2017 at 11:15](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344762_45188708)\n\n\n[Add a comment](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code# \"Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.\") \\| [Expand to show all comments on this post](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code# \"Expand to show all comments on this post\")\n\n## 3 Answers 3\n\nSorted by:\n[Reset to default](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code?answertab=scoredesc#tab-top)\n\nHighest score (default)\n\nTrending (recent votes count more)\n\nDate modified (newest first)\n\nDate created (oldest first)\n\n\nThis answer is useful\n\n19\n\nThis answer is not useful\n\nSave this answer.\n\nLoading when this answer was accepted…\n\n[Timeline](https://stackoverflow.com/posts/45188896/timeline)\n\nShow activity on this post.\n\nSuppose the user content is all located in\n\n```python\nUse with AICopy\nsafe_dir = '/home/saya/server/content/'\n```\n\nEnding with `/` is important as [heinrichj](https://stackoverflow.com/users/3333406/heinrichj) mentions to ensure the check below matches against a specific directory.\n\nYou need to verify the final request is in there:\n\n```python\nUse with AICopy\nif os.path.commonprefix((os.path.realpath(requested_path),safe_dir)) != safe_dir:\n    #Bad user!\n```\n\nIf the requested path is allowed to be the `save_dir` itself, you would also need to allow entry if `os.path.realpath(requested_path)+'/' == safe_dir`.\n\nI encourage you to make sure all stuff you want accessible by the user in one place.\n\n[Share](https://stackoverflow.com/a/45188896)\n\nShare a link to this answer\n\nCopy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ \"The current license for this post: CC BY-SA 4.0\")\n\nShort permalink to this answer\n\n[Improve this answer](https://stackoverflow.com/posts/45188896/edit \"\")\n\nFollow\n\n\n\nFollow this answer to receive notifications\n\n[edited Oct 17, 2019 at 10:09](https://stackoverflow.com/posts/45188896/revisions \"show all edits to this post\")\n\nanswered Jul 19, 2017 at 11:13\n\n[![kabanus's user avatar](https://www.gravatar.com/avatar/8416cdfe2e349f6e17f090091c9eab3b?s=64&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/kabanus)\n\n[kabanus](https://stackoverflow.com/users/kabanus)\n\n26.4k77 gold badges5050 silver badges8080 bronze badges\n\n## 13 Comments\n\nAdd a comment\n\n[![](https://i.sstatic.net/ua0kY.png?s=64)](https://stackoverflow.com/users/7553525/zwer)\n\nzwer\n\n[zwer](https://stackoverflow.com/users/7553525/zwer) [Jul 19, 2017 at 11:16](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344836_45188896)\n\nYou should consider adding `os.path.realpath()` to it in case there is a symlink in the safe path that points outside of it.\n\n2017-07-19T11:16:53.79Z+00:00\n\n3\n\nReply\n\n- Copy link\n\n[![](https://www.gravatar.com/avatar/8416cdfe2e349f6e17f090091c9eab3b?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/kabanus)\n\nkabanus\n\n[kabanus](https://stackoverflow.com/users/kabanus) [Jul 19, 2017 at 11:17](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344851_45188896)\n\n@satya Correct. It's usually the best practice to make sure stuff readable by the world is in the same place.\n\n2017-07-19T11:17:10.137Z+00:00\n\n0\n\nReply\n\n- Copy link\n\n[![](https://www.gravatar.com/avatar/d952131af13179b13ffbe07b089dd741?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/4790217/satya)\n\nsatya\n\n[satya](https://stackoverflow.com/users/4790217/satya) [Jul 19, 2017 at 11:19](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77344943_45188896)\n\nOk,Let me to implement it and let you know.\n\n2017-07-19T11:19:01.97Z+00:00\n\n0\n\nReply\n\n- Copy link\n\n[![](https://www.gravatar.com/avatar/d952131af13179b13ffbe07b089dd741?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/4790217/satya)\n\nsatya\n\n[satya](https://stackoverflow.com/users/4790217/satya) [Jul 19, 2017 at 11:20](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77345012_45188896)\n\nCan I write `safe_dir=os.path.abspath(os.curdir)`, If i need to give permission to my projrct folder only.\n\n2017-07-19T11:20:34.127Z+00:00\n\n0\n\nReply\n\n- Copy link\n\n[![](https://www.gravatar.com/avatar/8416cdfe2e349f6e17f090091c9eab3b?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/kabanus)\n\nkabanus\n\n[kabanus](https://stackoverflow.com/users/kabanus) [Jul 19, 2017 at 11:22](https://stackoverflow.com/questions/45188708/how-to-prevent-directory-traversal-attack-from-python-code#comment77345095_45188896)\n\n@satya No, because you may be executing from somewhere else. If the python file is in the 'safe' directory use `safe_dir=os.path.realpath(__FILE__)` though I usually separate content from code. Also note you should use **realpath**, as zwer mentioned.\n\n2017-07-19T11:22:17.863Z+00:00\n\n0\n\nReply\n\n- Copy link\n\nAdd a comment\n\nThis answer is useful\n\n14\n\nThis answer is not useful\n\nSave this answer.\n\nLoading when this answer was accepted…\n\n[Timeline](https://stackoverflow.com/posts/45190125/timeline)\n\nShow activity on this post.\n\nyou could try the methods of [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.relative_to)\n\n```python\nUse with AICopy\nPath(root_dir).joinpath(param).resolve().relative_to(root_dir.resolve())\n```\n\nshould return the relative path starting from the `root_dir`, or raise an `ValueError` if a directory traversal attack is tried\n\n# testing\n\n```python\nUse with AICopy\nparam = 'test_file'\nPath(root_dir).joinpath(param).relative_to(root_dir)\n```\n\n> WindowsPath('test\\_file')\n\n```python\nUse with AICopy\nparam = 'test_file/nested'\nPath(root_dir).joinpath(param).relative_to(root_dir)\n```\n\n> WindowsPath('test\\_file/nested')\n\n```python\nUse with AICopy\nparam = 'non_existing/../../data'\nPath(root_dir).joinpath(param).resolve().relative_to(root_dir.resolve())\n```\n\n> ```python\n> Use with AICopy\n> ---------------------------------------------------------------------------\n> ValueError                                Traceback (most recent call last)\n> <ipython-input-26-a74379fe1817> in <module>()\n> ....\n> ValueError: 'C:\\\\python_scripts\\\\PyCharmProjects\\\\data' does not start with 'C:\\\\python_scripts\\\\PyCharmProjects\\\\testproject'\n> ```\n\n```python\nUse with AICopy\nparam = 'non_existing/../nested'\nPath(root_dir).joinpath(param).resolve().relative_to(root_dir.resolve())\n```\n\n> WindowsPath('nested')\n\n[Share](https://stackoverflow.com/a/45190125)\n\nShare a link to this answer\n\nCopy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ \"The current license for this post: CC BY-SA 3.0\")\n\nShort permalink to this answer\n\n[Improve this answer](https://stackoverflow.com/posts/45190125/edit \"\")\n\nFollow\n\n\n\nFollow this answer to receive notifications\n\n[edited Jul 19, 2017 at 12:27](https://stackoverflow.com/posts/45190125/revisions \"show all edits to this post\")\n\nanswered Jul 19, 2017 at 12:09\n\n[![Maarten Fabré's user avatar](https://www.gravatar.com/avatar/0be3cbb95b7e672fc8135509aa37b589?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/maarten-fabre)\n\n[Maarten Fabré](https://stackoverflow.com/users/maarten-fabre)\n\n7,07811 gold badge2020 silver badges3737 bronze badges\n\n## Comments\n\nAdd a comment\n\nThis answer is useful\n\n-4\n\nThis answer is not useful\n\nSave this answer.\n\nLoading when this answer was accepted…\n\n[Timeline](https://stackoverflow.com/posts/76737752/timeline)\n\nShow activity on this post.\n\na check like below will also prevent traversal.\n\n```python\nUse with AICopy\nif '..' in pathParam:\n    abort(ERRORCODE)\n```\n\n[Share](https://stackoverfl"}
{"source": "firecrawl_search", "query": "Python path traversal pathlib resolve is_relative_to prevention", "source_url": "https://osintteam.blog/path-traversal-and-remediation-in-python-0b6e126b4746", "license": "web_reference", "markdown": "```\n<!doctype html><html><head></head><body></body></html>\n```"}
{"source": "firecrawl_search", "query": "Python subprocess shell=False command injection option injection --", "source_url": "https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false", "license": "web_reference", "markdown": "##### Collectives™ on Stack Overflow\n\nFind centralized, trusted content and collaborate around the technologies you use most.\n\n[Learn more about Collectives](https://stackoverflow.com/collectives)\n\n# [How does subprocess.call() work with shell=False?](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false)\n\n[Ask Question](https://stackoverflow.com/questions/ask)\n\nAsked9 years, 6 months ago\n\nModified [3 years ago](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false?lastactivity \"2023-11-23 11:28:11Z\")\n\nViewed\n13k times\n\n\nThis question shows research effort; it is useful and clear\n\n17\n\nThis question does not show any research effort; it is unclear or not useful\n\nSave this question.\n\n[Timeline](https://stackoverflow.com/posts/43990219/timeline)\n\nShow activity on this post.\n\nI am using Python's [`subprocess`](https://docs.python.org/2/library/subprocess.html#module-subprocess) module to call some Linux command line functions. The documentation explains the `shell=True` argument as\n\n> If _shell_ is `True`, the specified command will be executed through the shell\n\nThere are two examples, which seem the same to me from a descriptive viewpoint (i.e. both of them call some command-line command), but one of them uses `shell=True` and the other does not\n\n```python\nCopy\n>>> subprocess.call([\"ls\", \"-l\"])\n0\n\n>>> subprocess.call(\"exit 1\", shell=True)\n1\n```\n\nMy question is:\n\n- What does running the command with `shell=False` do, in contrast to `shell=True`?\n- I was under the impression that `subprocess.call` and `check_call` and `check_output` all must execute the argument through the shell. In other words, how can it possibly _not_ execute the argument through the shell?\n\nIt would also be helpful to get some examples of:\n\n- Things that can be done with `shell=True` that can't be done with\n`shell=False` and why they can't be done.\n- Vice versa (although it seems that there are no such examples)\n- Things for which it does not matter whether `shell=True` or `False` and why it doesn't matter\n\n- [python](https://stackoverflow.com/questions/tagged/python \"show questions tagged 'python'\")\n- [linux](https://stackoverflow.com/questions/tagged/linux \"show questions tagged 'linux'\")\n- [bash](https://stackoverflow.com/questions/tagged/bash \"show questions tagged 'bash'\")\n- [shell](https://stackoverflow.com/questions/tagged/shell \"show questions tagged 'shell'\")\n- [subprocess](https://stackoverflow.com/questions/tagged/subprocess \"show questions tagged 'subprocess'\")\n\n[Share](https://stackoverflow.com/q/43990219)\n\nShare a link to this question\n\nCopy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ \"The current license for this post: CC BY-SA 3.0\")\n\nShort permalink to this question\n\n[Improve this question](https://stackoverflow.com/posts/43990219/edit \"\")\n\nFollow\n\n\n\nFollow this question to receive notifications\n\n[edited May 16, 2017 at 1:09](https://stackoverflow.com/posts/43990219/revisions \"show all edits to this post\")\n\n[![Charles Duffy's user avatar](https://www.gravatar.com/avatar/5e2861b08f37fa306fbf5384994af688?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/charles-duffy)\n\n[Charles Duffy](https://stackoverflow.com/users/charles-duffy)\n\n299k4444 gold badges458458 silver badges514514 bronze badges\n\nasked May 15, 2017 at 23:22\n\n[![dkv's user avatar](https://www.gravatar.com/avatar/8103c1852d6cbaaba27fd7ea34146a02?s=64&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/2593878/dkv)\n\n[dkv](https://stackoverflow.com/users/2593878/dkv)\n\n7,5221010 gold badges3939 silver badges5959 bronze badges\n\n12\n\n- 1\n\n\n\n\n\nHow do you think the shell starts other (non-shell) programs? There has to be a way for programs to start other programs without a shell, or else the shell couldn't do it either (since a shell is _just another program_).\n\n\n\nCharles Duffy\n\n\n–\n[Charles Duffy](https://stackoverflow.com/users/charles-duffy \"298,852 reputation\")\n\n\n\n2017-05-15 23:28:27 +00:00\n\n[CommentedMay 15, 2017 at 23:28](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false#comment75009522_43990219)\n\n\n- 1\n\n\n\n\n\nShells aren't fundamental to UNIX. When your system first boots up, it creates a process -- PID 1 -- executing an external binary, traditionally `/sbin/init`. Unless `init` is a shell script, there's no shell involved in running it. `init` can then run other programs likewise without any shell involved; to do that, it duplicates itself (with `fork()`), and then transforms the new copy into a different program (with `execve()`); no shells anywhere in the process. And even when what `init` runs _is_ a shell, it uses that same process.\n\n\n\nCharles Duffy\n\n\n–\n[Charles Duffy](https://stackoverflow.com/users/charles-duffy \"298,852 reputation\")\n\n\n\n2017-05-16 00:03:06 +00:00\n\n[CommentedMay 16, 2017 at 0:03](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false#comment75010014_43990219)\n\n- ...so, honoring the shebang line -- be it `#!/bin/sh` or `#!/usr/bin/env` or `#!/usr/bin/python` \\-\\- is fundamentally something done _by the kernel_ as part of the implementation of `execve()`; a shell is just another program that `execve()` can invoke.\n\n\n\nCharles Duffy\n\n\n–\n[Charles Duffy](https://stackoverflow.com/users/charles-duffy \"298,852 reputation\")\n\n\n\n2017-05-16 00:05:32 +00:00\n\n[CommentedMay 16, 2017 at 0:05](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false#comment75010060_43990219)\n\n- 2\n\n\n\n\n\nDo you only want answers for Linux? Python subprocess.call() works on Windows too. I ask because this question might be made canonical, so it's good to be general. Also better to know about portability issues.\n\n\n\nsmci\n\n\n–\n[smci](https://stackoverflow.com/users/smci \"34,291 reputation\")\n\n\n\n2018-05-22 10:02:44 +00:00\n\n[CommentedMay 22, 2018 at 10:02](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false#comment87942972_43990219)\n\n- 1\n\n\n\n\n\n@smci, it strikes me that the Linux and Windows answers are different enough that a separate Windows question would be better able to attract people with that particular domain expertise. Keeping individual questions' scope narrower avoids the case where you have one answer that covers aspect-X better, and another better covering aspect-Y, and thus don't/can't _have_ a single, ideal canonical answer.\n\n\n\nCharles Duffy\n\n\n–\n[Charles Duffy](https://stackoverflow.com/users/charles-duffy \"298,852 reputation\")\n\n\n\n2019-05-28 14:24:55 +00:00\n\n[CommentedMay 28, 2019 at 14:24](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false#comment99293757_43990219)\n\n\n[Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false# \"Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.\") \\| [Show **7** more comments](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false# \"Expand to show all comments on this post\")\n\n## 2 Answers 2\n\nSorted by:\n[Reset to default](https://stackoverflow.com/questions/43990219/how-does-subprocess-call-work-with-shell-false?answertab=scoredesc#tab-top)\n\nHighest score (default)\n\nTrending (recent votes count more)\n\nDate modified (newest first)\n\nDate created (oldest first)\n\n\nThis answer is useful\n\n26\n\nThis answer is not useful\n\nSave this answer.\n\nLoading when this answer was accepted…\n\n[Timeline](https://stackoverflow.com/posts/43990278/timeline)\n\nShow activity on this post.\n\nUNIX programs start each other with the following three calls, or derivatives/equivalents thereto:\n\n- `fork()` \\- Create a new copy of yourself.\n- `exec()` \\- Replace yourself with a different program (do this if you're the copy!).\n- `wait()` \\- Wait for another process to finish (optional, if not running in background).\n\nThus, with `shell=False`, you do just that (as Python-syntax pseudocode below -- exclude the `wait()` if not a blocking invocation such as `subprocess.call()`):\n\n```python\nUse with AICopy\npid = fork()\nif pid == 0: # we're the child process, not the parent\n  execlp(\"ls\", \"ls\", \"-l\", NUL);\nelse:\n  retval = wait(pid) # we're the parent; wait for the child to exit & get its exit status\n```\n\nwhereas with `shell=True`, you do this:\n\n```python\nUse with AICopy\npid = fork()\nif pid == 0:\n  execlp(\"sh\", \"sh\", \"-c\", \"ls -l\", NUL);\nelse:\n  retval = wait(pid)\n```\n\nNote that with `shell=False`, the command we executed was `ls`, whereas with `shell=True`, the command we executed was `sh`.\n\n* * *\n\nThat is to say:\n\n```python\nUse with AICopy\nsubprocess.Popen(foo, shell=True)\n```\n\nis exactly the same as:\n\n```python\nUse with AICopy\nsubprocess.Popen(\n  [\"sh\", \"-c\"] + ([foo] if isinstance(foo, basestring) else foo),\n  shell=False)\n```\n\nThat is to say, you execute a copy of `/bin/sh`, and direct that copy of `/bin/sh` to parse the string into an argument list and execute `ls -l` itself.\n\n* * *\n\nSo, why _would_ you use `shell=True`?\n\n- **You're invoking a shell builtin.**\n\nFor instance, the `exit` command is actually part of the shell itself, rather than an external command. That said, this is a [fairly small set of commands](http://pubs.opengroup.org/onlinepubs/009695399/idx/sbi.html), and it's rare for them to be useful in the context of a shell instance that only exists for the duration of a single `subprocess.call()` invocation.\n\n- **You have some code with shell constructs (ie. redirections) that would be difficult to emulate without it.**\n\nIf, for instance, your command is `cat one two >three`, the syntax `>three` is a _redirection_: It's not an argument to `cat`, but an instruction to the shell to set `stdout=open('three', 'w')` when running the command `['cat', 'one', 'two']`. If you don't want to deal with redirections and pipelines yourself, you need a shell to do it.\n\nA slightly trickier case is `cat foo bar | baz`. To do that without a shell, you need to start both sides of the pipeline yourself: `p1 = Popen(['cat', 'foo', 'bar'], stdout=PIPE), p2=Popen(['baz'], stdin=p1.stdout)`.\n\n- **You don't give a damn about security bugs.**\n\n...okay, that's a _little_ bit too strong, but not by much. Using `shell=True` is dangerous. You can't do this: `Popen('cat -- %s' % (filename,), shell=True)` without a shell injection vulnerability: If your code were ever invoked with a `filename` containing `$(rm -rf ~)`, you'd have a very bad day. On the other hand, `['cat', '--', filename]` is safe with all possible filenames: The filename is purely data, not parsed as source code by a shell or anything else.\n\nIt _is_ possible to write safe scripts in shell, but you need to be careful about it. Consider the following:\n\n\n```python\nUse with AICopy\n    filenames = ['file1', 'file2'] # these can be user-provided\n    subprocess.Popen(['cat -- \"$@\" | baz', '_'] + filenames, shell=True)\n```\n\n\nThat code is safe (well -- as safe as letting a user read any file they want _ever_ is), because it's passing your filenames out-of-band from your script code -- but it's safe only because the string being passed to the shell is fixed and hardcoded, and the parameterized content is external variables (the `filenames` list). And even then, it's \"safe\" only to a point -- a bug like [Shellshock](https://en.wikipedia.org/wiki/Shellshock_(software_bug)) that triggers on shell initialization would impact it as much as anything else.\n\n\n[Share](https://stackoverflow.com/a/43990278)\n\nShare a link to this answer\n\nCopy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ \"The current license for this post: CC BY-SA 4.0\")\n\nShort permalink to this answer\n\n[Improve this answer](https://stackoverflow.com/posts/43990278/edit \"\")\n\nFollow\n\n\n\nFollow this answer to receive notifications\n\n[edited Nov 23, 2023 at 11:28](https://stackoverflow.com/posts/439"}
{"source": "firecrawl_search", "query": "Python subprocess shell=False command injection option injection --", "source_url": "https://docs.python.org/3/library/subprocess.html", "license": "web_reference", "markdown": "### Navigation\n\n- [index](https://docs.python.org/3/genindex.html \"General Index\")\n- [modules](https://docs.python.org/3/py-modindex.html \"Python Module Index\") \\|\n- [next](https://docs.python.org/3/library/sched.html \"sched — Event scheduler\") \\|\n- [previous](https://docs.python.org/3/library/concurrent.interpreters.html \"concurrent.interpreters — Multiple interpreters in the same process\") \\|\n- ![Python logo](https://docs.python.org/3/_static/py.svg)\n- [Python](https://www.python.org/) »\n- German \\| DeutschGreek \\| ΕλληνικάEnglishSpanish \\| españolPersian \\| فارسیFrench \\| françaisItalian \\| italianoJapanese \\| 日本語Korean \\| 한국어Punjabi \\| ਪੰਜਾਬੀPolish \\| polskiBrazilian Portuguese \\| Português brasileiroRomanian \\| RomâneșteRussian \\| РусскийTurkish \\| TürkçeSimplified Chinese \\| 简体中文Traditional Chinese \\| 繁體中文\n\ndev (3.16)3.15.23.143.133.123.113.103.93.83.73.63.53.43.33.23.13.02.72.6\n\n- [3.15.2 documentation](https://docs.python.org/3/index.html) »\n\n- [The Python standard library](https://docs.python.org/3/library/index.html) »\n- [Concurrent Execution](https://docs.python.org/3/library/concurrency.html) »\n- [`subprocess` — Subprocess management](https://docs.python.org/3/library/subprocess.html)\n- \\|\n\n- Theme\nAutoLightDark \\|\n\n# `subprocess` — Subprocess management [¶](https://docs.python.org/3/library/subprocess.html\\#module-subprocess \"Link to this heading\")\n\n**Source code:** [Lib/subprocess.py](https://github.com/python/cpython/tree/3.15/Lib/subprocess.py)\n\n* * *\n\nThe `subprocess` module allows you to spawn new processes, connect to their\ninput/output/error pipes, and obtain their return codes. This module intends to\nreplace several older modules and functions:\n\nCopy\n\n```\nos.system\nos.spawn*\n```\n\nInformation about how the `subprocess` module can be used to replace these\nmodules and functions can be found in the following sections.\n\nSee also\n\n[**PEP 324**](https://peps.python.org/pep-0324/) – PEP proposing the subprocess module\n\n[Availability](https://docs.python.org/3/library/intro.html#availability): not Android, not iOS, not WASI.\n\nThis module is not supported on [mobile platforms](https://docs.python.org/3/library/intro.html#mobile-availability)\nor [WebAssembly platforms](https://docs.python.org/3/library/intro.html#wasm-availability).\n\n## Using the `subprocess` Module [¶](https://docs.python.org/3/library/subprocess.html\\#using-the-subprocess-module \"Link to this heading\")\n\nThe recommended approach to invoking subprocesses is to use the [`run()`](https://docs.python.org/3/library/subprocess.html#subprocess.run \"subprocess.run\")\nfunction for all use cases it can handle. For more advanced use cases, the\nunderlying [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") interface can be used directly.\n\nsubprocess.run( _args_, _\\*_, _stdin=None_, _input=None_, _stdout=None_, _stderr=None_, _capture\\_output=False_, _shell=False_, _cwd=None_, _timeout=None_, _check=False_, _encoding=None_, _errors=None_, _text=None_, _env=None_, _universal\\_newlines=None_, _\\*\\*other\\_popen\\_kwargs_) [¶](https://docs.python.org/3/library/subprocess.html#subprocess.run \"Link to this definition\")\n\nRun the command described by _args_. Wait for command to complete, then\nreturn a [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess \"subprocess.CompletedProcess\") instance.\n\nThe arguments shown above are merely the most common ones, described below\nin [Frequently Used Arguments](https://docs.python.org/3/library/subprocess.html#frequently-used-arguments) (hence the use of keyword-only notation\nin the abbreviated signature). The full function signature is largely the\nsame as that of the [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") constructor - most of the arguments to\nthis function are passed through to that interface. ( _timeout_, _input_,\n_check_, and _capture\\_output_ are not.)\n\nIf _capture\\_output_ is true, stdout and stderr will be captured.\nWhen used, the internal [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") object is automatically created with\n_stdout_ and _stderr_ both set to [`PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE \"subprocess.PIPE\").\nThe _stdout_ and _stderr_ arguments may not be supplied at the same time as _capture\\_output_.\nIf you wish to capture and combine both streams into one,\nset _stdout_ to `PIPE`\nand _stderr_ to [`STDOUT`](https://docs.python.org/3/library/subprocess.html#subprocess.STDOUT \"subprocess.STDOUT\"),\ninstead of using _capture\\_output_.\n\nA _timeout_ may be specified in seconds, it is internally passed on to\n[`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate \"subprocess.Popen.communicate\"). If the timeout expires, the child process will be\nkilled and waited for. The [`TimeoutExpired`](https://docs.python.org/3/library/subprocess.html#subprocess.TimeoutExpired \"subprocess.TimeoutExpired\") exception will be\nre-raised after the child process has terminated. The initial process\ncreation itself cannot be interrupted on many platform APIs so you are not\nguaranteed to see a timeout exception until at least after however long\nprocess creation takes.\n\nThe _input_ argument is passed to [`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate \"subprocess.Popen.communicate\") and thus to the\nsubprocess’s stdin. If used it must be a byte sequence, or a string if\n_encoding_ or _errors_ is specified or _text_ is true. When\nused, the internal [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") object is automatically created with\n_stdin_ set to [`PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE \"subprocess.PIPE\"),\nand the _stdin_ argument may not be used as well.\n\nIf _check_ is true, and the process exits with a non-zero exit code, a\n[`CalledProcessError`](https://docs.python.org/3/library/subprocess.html#subprocess.CalledProcessError \"subprocess.CalledProcessError\") exception will be raised. Attributes of that\nexception hold the arguments, the exit code, and stdout and stderr if they\nwere captured.\n\nIf _encoding_ or _errors_ are specified, or _text_ is true,\nfile objects for stdin, stdout and stderr are opened in text mode using the\nspecified _encoding_ and _errors_ or the [`io.TextIOWrapper`](https://docs.python.org/3/library/io.html#io.TextIOWrapper \"io.TextIOWrapper\") default.\nThe _universal\\_newlines_ argument is equivalent to _text_ and is provided\nfor backwards compatibility. By default, file objects are opened in binary mode.\n\nIf _env_ is not `None`, it must be a mapping that defines the environment\nvariables for the new process; these are used instead of the default\nbehavior of inheriting the current process’ environment. It is passed\ndirectly to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\"). This mapping can be str to str on any platform\nor bytes to bytes on POSIX platforms much like [`os.environ`](https://docs.python.org/3/library/os.html#os.environ \"os.environ\") or\n[`os.environb`](https://docs.python.org/3/library/os.html#os.environb \"os.environb\").\n\nExamples:\n\nCopy\n\n```\n>>> subprocess.run([\"ls\", \"-l\"])  # doesn't capture output\nCompletedProcess(args=['ls', '-l'], returncode=0)\n\n>>> subprocess.run(\"exit 1\", shell=True, check=True)\nTraceback (most recent call last):\n  ...\nsubprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1\n\n>>> subprocess.run([\"ls\", \"-l\", \"/dev/null\"], capture_output=True)\nCompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\nstdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n', stderr=b'')\n```\n\nAdded in version 3.5.\n\nChanged in version 3.6: Added _encoding_ and _errors_ parameters\n\nChanged in version 3.7: Added the _text_ parameter, as a more understandable alias of _universal\\_newlines_.\nAdded the _capture\\_output_ parameter.\n\nChanged in version 3.12: Changed Windows shell search order for `shell=True`. The current\ndirectory and `%PATH%` are replaced with `%COMSPEC%` and\n`%SystemRoot%\\System32\\cmd.exe`. As a result, dropping a\nmalicious program named `cmd.exe` into a current directory no\nlonger works.\n\nclasssubprocess.CompletedProcess [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess \"Link to this definition\")\n\nThe return value from [`run()`](https://docs.python.org/3/library/subprocess.html#subprocess.run \"subprocess.run\"), representing a process that has finished.\n\nargs [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.args \"Link to this definition\")\n\nThe arguments used to launch the process. This may be a list or a string.\n\nreturncode [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.returncode \"Link to this definition\")\n\nExit status of the child process. Typically, an exit status of 0 indicates\nthat it ran successfully.\n\nA negative value `-N` indicates that the child was terminated by signal\n`N` (POSIX only).\n\nstdout [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.stdout \"Link to this definition\")\n\nCaptured stdout from the child process. A bytes sequence, or a string if\n[`run()`](https://docs.python.org/3/library/subprocess.html#subprocess.run \"subprocess.run\") was called with an encoding, errors, or text=True.\n`None` if stdout was not captured.\n\nIf you ran the process with `stderr=subprocess.STDOUT`, stdout and\nstderr will be combined in this attribute, and [`stderr`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.stderr \"subprocess.CompletedProcess.stderr\") will be\n`None`.\n\nstderr [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.stderr \"Link to this definition\")\n\nCaptured stderr from the child process. A bytes sequence, or a string if\n[`run()`](https://docs.python.org/3/library/subprocess.html#subprocess.run \"subprocess.run\") was called with an encoding, errors, or text=True.\n`None` if stderr was not captured.\n\ncheck\\_returncode() [¶](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.check_returncode \"Link to this definition\")\n\nIf [`returncode`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.returncode \"subprocess.CompletedProcess.returncode\") is non-zero, raise a [`CalledProcessError`](https://docs.python.org/3/library/subprocess.html#subprocess.CalledProcessError \"subprocess.CalledProcessError\").\n\nAdded in version 3.5.\n\nsubprocess.DEVNULL [¶](https://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL \"Link to this definition\")\n\nSpecial value that can be used as the _stdin_, _stdout_ or _stderr_ argument\nto [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") and indicates that the special file [`os.devnull`](https://docs.python.org/3/library/os.html#os.devnull \"os.devnull\")\nwill be used.\n\nAdded in version 3.3.\n\nsubprocess.PIPE [¶](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE \"Link to this definition\")\n\nSpecial value that can be used as the _stdin_, _stdout_ or _stderr_ argument\nto [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") and indicates that a pipe to the standard stream should be\nopened. Most useful with [`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate \"subprocess.Popen.communicate\").\n\nsubprocess.STDOUT [¶](https://docs.python.org/3/library/subprocess.html#subprocess.STDOUT \"Link to this definition\")\n\nSpecial value that can be used as the _stderr_ argument to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen \"subprocess.Popen\") and\nindicates that standard error should go into the same handle as standard\nout"}
{"source": "firecrawl_search", "query": "Python subprocess shell=False command injection option injection --", "source_url": "https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/python-flask/command-injection/", "license": "web_reference", "markdown": "For AI agents: A markdown version of this page is available at [https://docs.datadoghq.com/security/code\\_security/static\\_analysis/static\\_analysis\\_rules/python-flask/command-injection.md](https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/python-flask/command-injection.md).\nA documentation index is available at [/llms.txt](https://docs.datadoghq.com/llms.txt).\n\n[Home](https://www.datadoghq.com/) [Docs](https://docs.datadoghq.com/) [API](https://docs.datadoghq.com/api/)\n\n- [Agents](https://docs.datadoghq.com/)\n- [Essentials](https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/python-flask/command-injection/#)\n  - [Getting Started](https://docs.datadoghq.com/getting_started/)\n    - [Agent](https://docs.datadoghq.com/getting_started/agent/)\n    - [API](https://docs.datadoghq.com/getting_started/api/)\n    - [APM Tracing](https://docs.datadoghq.com/getting_started/tracing/)\n    - [Containers](https://docs.datadoghq.com/getting_started/containers/)\n      - [Autodiscovery](https://docs.datadoghq.com/getting_started/containers/autodiscovery)\n      - [Datadog Operator](https://docs.datadoghq.com/getting_started/containers/datadog_operator)\n    - [Dashboards](https://docs.datadoghq.com/getting_started/dashboards/)\n    - [Database Monitoring](https://docs.datadoghq.com/getting_started/database_monitoring/)\n    - [Datadog](https://docs.datadoghq.com/getting_started/application/)\n    - [Datadog Site](https://docs.datadoghq.com/getting_started/site/)\n    - [DevSecOps](https://docs.datadoghq.com/getting_started/devsecops)\n    - [Incident Management](https://docs.datadoghq.com/getting_started/incident_management/)\n    - [Integrations](https://docs.datadoghq.com/getting_started/integrations/)\n      - [AWS](https://docs.datadoghq.com/getting_started/integrations/aws/)\n      - [Azure](https://docs.datadoghq.com/getting_started/integrations/azure/)\n      - [Google Cloud](https://docs.datadoghq.com/getting_started/integrations/google_cloud/)\n      - [OCI](https://docs.datadoghq.com/getting_started/integrations/oci/)\n      - [Terraform](https://docs.datadoghq.com/getting_started/integrations/terraform/)\n      - [Stripe](https://docs.datadoghq.com/getting_started/integrations/stripe/)\n    - [Internal Developer Portal](https://docs.datadoghq.com/getting_started/internal_developer_portal/)\n    - [Logs](https://docs.datadoghq.com/getting_started/logs/)\n    - [Monitors](https://docs.datadoghq.com/getting_started/monitors/)\n    - [Notebooks](https://docs.datadoghq.com/getting_started/notebooks/)\n    - [OpenTelemetry](https://docs.datadoghq.com/getting_started/opentelemetry/)\n    - [Profiler](https://docs.datadoghq.com/getting_started/profiler/)\n    - [Search](https://docs.datadoghq.com/getting_started/search/)\n      - [Product-Specific Search](https://docs.datadoghq.com/getting_started/search/product_specific_reference)\n    - [Session Replay](https://docs.datadoghq.com/getting_started/session_replay/)\n    - [Security](https://docs.datadoghq.com/getting_started/security/)\n      - [App and API Protection](https://docs.datadoghq.com/getting_started/security/application_security)\n      - [Cloud Security](https://docs.datadoghq.com/getting_started/security/cloud_security_management/)\n      - [Cloud SIEM](https://docs.datadoghq.com/getting_started/security/cloud_siem/)\n      - [Code Security](https://docs.datadoghq.com/getting_started/code_security/)\n    - [Serverless for AWS Lambda](https://docs.datadoghq.com/getting_started/serverless/)\n    - [Software Delivery](https://docs.datadoghq.com/getting_started/software_delivery/)\n      - [CI Visibility](https://docs.datadoghq.com/getting_started/ci_visibility/)\n      - [Feature Flags](https://docs.datadoghq.com/getting_started/feature_flags/)\n      - [Test Optimization](https://docs.datadoghq.com/getting_started/test_optimization/)\n      - [Test Impact Analysis](https://docs.datadoghq.com/getting_started/test_impact_analysis/)\n      - [MCP Tools](https://docs.datadoghq.com/getting_started/software_delivery_mcp_tools/)\n    - [Synthetic Monitoring and Testing](https://docs.datadoghq.com/getting_started/synthetics/)\n      - [API Tests](https://docs.datadoghq.com/getting_started/synthetics/api_test)\n      - [Browser Tests](https://docs.datadoghq.com/getting_started/synthetics/browser_test)\n      - [Mobile App Tests](https://docs.datadoghq.com/getting_started/synthetics/mobile_app_testing)\n      - [Continuous Testing](https://docs.datadoghq.com/getting_started/continuous_testing/)\n      - [Private Locations](https://docs.datadoghq.com/getting_started/synthetics/private_location)\n    - [Tags](https://docs.datadoghq.com/getting_started/tagging/)\n      - [Assigning Tags](https://docs.datadoghq.com/getting_started/tagging/assigning_tags)\n      - [Unified Service Tagging](https://docs.datadoghq.com/getting_started/tagging/unified_service_tagging)\n      - [Using Tags](https://docs.datadoghq.com/getting_started/tagging/using_tags)\n    - [Teams](https://docs.datadoghq.com/getting_started/teams/)\n    - [Workflow Automation](https://docs.datadoghq.com/getting_started/workflow_automation/)\n    - [Access for Enterprises](https://docs.datadoghq.com/getting_started/access_for_enterprises/)\n      - [Choosing Your Datadog Topology](https://docs.datadoghq.com/getting_started/access_for_enterprises/choosing_topology/)\n      - [Permissions and Feature Access](https://docs.datadoghq.com/getting_started/access_for_enterprises/permissions/)\n      - [Assigning Users to Roles and Teams](https://docs.datadoghq.com/getting_started/access_for_enterprises/assigning_users/)\n      - [Protecting Assets](https://docs.datadoghq.com/getting_started/access_for_enterprises/protecting_assets/)\n      - [Protecting Sensitive Data](https://docs.datadoghq.com/getting_started/access_for_enterprises/protecting_sensitive_data/)\n      - [Credential Management](https://docs.datadoghq.com/getting_started/access_for_enterprises/credential_management/)\n      - [Creating Access Policies](https://docs.datadoghq.com/getting_started/access_for_enterprises/creating_access_policies/)\n      - [Sharing Across Organizations](https://docs.datadoghq.com/getting_started/access_for_enterprises/sharing_across_organizations/)\n      - [Example Implementations](https://docs.datadoghq.com/getting_started/access_for_enterprises/example_implementations/)\n    - [Learning Center](https://docs.datadoghq.com/getting_started/learning_center/)\n    - [Support](https://docs.datadoghq.com/getting_started/support/)\n  - [Glossary](https://docs.datadoghq.com/glossary/)\n  - [Standard Attributes](https://docs.datadoghq.com/standard-attributes)\n  - [Guides](https://docs.datadoghq.com/all_guides/)\n  - [Agent](https://docs.datadoghq.com/agent/)\n    - [Architecture](https://docs.datadoghq.com/agent/architecture/)\n    - [IoT](https://docs.datadoghq.com/agent/iot/)\n    - [Supported Platforms](https://docs.datadoghq.com/agent/supported_platforms/)\n      - [AIX](https://docs.datadoghq.com/agent/supported_platforms/aix/)\n      - [Linux](https://docs.datadoghq.com/agent/supported_platforms/linux/)\n      - [Ansible](https://docs.datadoghq.com/agent/supported_platforms/ansible/)\n      - [Chef](https://docs.datadoghq.com/agent/supported_platforms/chef/)\n      - [Heroku](https://docs.datadoghq.com/agent/supported_platforms/heroku/)\n      - [MacOS](https://docs.datadoghq.com/agent/supported_platforms/osx/)\n      - [Puppet](https://docs.datadoghq.com/agent/supported_platforms/puppet/)\n      - [SaltStack](https://docs.datadoghq.com/agent/supported_platforms/saltstack/)\n      - [SCCM](https://docs.datadoghq.com/agent/supported_platforms/sccm/)\n      - [Windows](https://docs.datadoghq.com/agent/supported_platforms/windows/)\n      - [From Source](https://docs.datadoghq.com/agent/supported_platforms/source/)\n    - [Log Collection](https://docs.datadoghq.com/agent/logs/)\n      - [Log Agent tags](https://docs.datadoghq.com/agent/logs/agent_tags/)\n      - [Advanced Configurations](https://docs.datadoghq.com/agent/logs/advanced_log_collection)\n      - [Proxy](https://docs.datadoghq.com/agent/logs/proxy)\n      - [Transport](https://docs.datadoghq.com/agent/logs/log_transport)\n      - [Multi-Line Detection](https://docs.datadoghq.com/agent/logs/auto_multiline_detection)\n    - [Configuration](https://docs.datadoghq.com/agent/configuration)\n      - [Commands](https://docs.datadoghq.com/agent/configuration/agent-commands/)\n      - [Configuration Files](https://docs.datadoghq.com/agent/configuration/agent-configuration-files/)\n      - [Log Files](https://docs.datadoghq.com/agent/configuration/agent-log-files/)\n      - [Status Page](https://docs.datadoghq.com/agent/configuration/agent-status-page/)\n      - [Network Traffic](https://docs.datadoghq.com/agent/configuration/network/)\n      - [Proxy Configuration](https://docs.datadoghq.com/agent/configuration/proxy/)\n      - [FIPS Compliance](https://docs.datadoghq.com/agent/configuration/fips-compliance/)\n      - [Dual Shipping](https://docs.datadoghq.com/agent/configuration/dual-shipping/)\n      - [Secrets Management](https://docs.datadoghq.com/agent/configuration/secrets-management/)\n      - [Infrastructure Modes](https://docs.datadoghq.com/agent/configuration/infrastructure-modes/)\n      - [Agent Data Plane](https://docs.datadoghq.com/agent/configuration/agent-data-plane/)\n    - [Fleet Automation](https://docs.datadoghq.com/agent/fleet_automation)\n      - [Fleet View](https://docs.datadoghq.com/agent/fleet_automation/fleet_view)\n      - [Access Control](https://docs.datadoghq.com/agent/fleet_automation/access_control)\n      - [Configure Agents](https://docs.datadoghq.com/agent/fleet_automation/configure_agents)\n      - [Supported datadog.yaml Fields](https://docs.datadoghq.com/agent/fleet_automation/supported_datadog_yaml_fields)\n      - [Configure Agent Integrations](https://docs.datadoghq.com/agent/fleet_automation/configure_integrations)\n      - [Configure Custom Logs](https://docs.datadoghq.com/agent/fleet_automation/configure_logs)\n      - [Modify Tags](https://docs.datadoghq.com/agent/fleet_automation/modify_tags)\n      - [Configuration Policies](https://docs.datadoghq.com/agent/fleet_automation/configuration_policies)\n      - [Upgrade Agents](https://docs.datadoghq.com/agent/fleet_automation/upgrade_agents)\n      - [Upgrade SDKs](https://docs.datadoghq.com/agent/fleet_automation/upgrade_sdks)\n      - [OpenTelemetry Collectors](https://docs.datadoghq.com/agent/fleet_automation/otel_collectors)\n    - [Troubleshooting](https://docs.datadoghq.com/agent/troubleshooting/)\n      - [Container Hostname Detection](https://docs.datadoghq.com/agent/troubleshooting/hostname_containers/)\n      - [Debug Mode](https://docs.datadoghq.com/agent/troubleshooting/debug_mode/)\n      - [Agent Flare](https://docs.datadoghq.com/agent/troubleshooting/send_a_flare/)\n      - [Agent Check Status](https://docs.datadoghq.com/agent/troubleshooting/agent_check_status/)\n      - [NTP Issues](https://docs.datadoghq.com/agent/troubleshooting/ntp/)\n      - [Permission Issues](https://docs.datadoghq.com/agent/troubleshooting/permissions/)\n      - [Integrations Issues](https://docs.datadoghq.com/agent/troubleshooting/integrations/)\n      - [Site Issues](https://docs.datadoghq.com/agent/troubleshooting/site/)\n      - [Autodiscovery Issues](https://docs.datadoghq.com/agent/troubleshooting/autodiscovery/)\n      - [Windows Container Issues](https://docs.datadoghq.com/agent/troubleshooting/windows_containers)\n      - [Agent Runtime Configuration](https://docs.datadoghq.com/agent/troubleshooting/config)\n      - [High CPU or Memory Consumption](https://docs.datadoghq.com/agent/troubleshooting/high_memory_usage/)\n      - [Missing Log Bytes](https://docs.datadoghq.com/agent/troubleshooting/missing_log_bytes/)\n    - [Guides](https://docs.datadoghq.com/agent/guide/)\n    - [Data Security](https://docs.datadoghq.com/data_security/agent/)\n  - [Integrations](https://docs.datadoghq.com/integrations"}
{"source": "firecrawl_search", "query": "Python SSRF prevention ipaddress private loopback link-local validation", "source_url": "https://safeguard.sh/resources/blog/python-ssrf-prevention", "license": "web_reference", "markdown": "[Skip to content](https://safeguard.sh/resources/blog/python-ssrf-prevention#main-content)\n\n[![Safeguard](https://safeguard.sh/brand/safeguard-lockup-ink.svg)![Safeguard](https://safeguard.sh/brand/safeguard-lockup-white.svg)](https://safeguard.sh/)\n\nPM\n\nPriya Mehta\n\nSecurity Researcher\n\nJuly 8, 20265 min read\n\nShare\n\nServer-side request forgery, SSRF, is a vulnerability where an attacker makes your server issue HTTP requests to a destination of their choosing. It sounds mild until you remember where your server sits: inside your network, holding a cloud identity, able to reach internal admin panels, databases, and the cloud metadata endpoint that hands out credentials. A feature as ordinary as \"fetch the image at this URL\" can become the pivot into your entire environment.\n\n## The shape of the bug\n\nSSRF appears anywhere your application takes a user-supplied URL or host and makes a request to it: webhook registration, URL preview and link unfurling, PDF and image generation from a URL, importing data from a remote source, or an integration that calls \"any endpoint you configure.\" The vulnerable pattern is trivially small:\n\n```python\nimport requests\n\nurl = request.args[\"url\"]           # attacker controls this\nresp = requests.get(url)            # your server fetches whatever they want\nreturn resp.content\n```\n\nPoint that at `http://169.254.169.254/latest/meta-data/` on a cloud host and, without further hardening, an attacker can read instance metadata and potentially cloud credentials. Point it at `http://localhost:6379/` and they are talking to your Redis.\n\n## Allowlist, do not blocklist\n\nThe instinct is to block \"bad\" destinations: reject `localhost`, reject `169.254.169.254`. Blocklists lose, because there are too many ways to write the same address: decimal IP notation, IPv6-mapped addresses, `0.0.0.0`, alternate DNS names that resolve to internal ranges. The robust design flips the default. Decide up front which destinations are legitimate and permit only those:\n\n```python\nALLOWED_HOSTS = {\"api.partner.com\", \"cdn.partner.com\"}\n\nfrom urllib.parse import urlparse\n\ndef is_allowed(url: str) -> bool:\n    parsed = urlparse(url)\n    return parsed.scheme in {\"https\"} and parsed.hostname in ALLOWED_HOSTS\n```\n\nWhen your integrations are a known set, an allowlist is both simpler and far safer than trying to enumerate everything malicious.\n\n## When the destination cannot be fixed: validate the resolved IP\n\nSome features genuinely must fetch arbitrary user URLs. There, the defense is to resolve the hostname yourself and reject the request if it points at a private, loopback, link-local, or reserved range, then connect to the IP you validated:\n\n```python\nimport ipaddress, socket\n\ndef resolve_public_ip(hostname: str) -> str:\n    ip = socket.gethostbyname(hostname)\n    addr = ipaddress.ip_address(ip)\n    if addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved:\n        raise ValueError(\"Destination resolves to a non-public address\")\n    return ip\n```\n\nTwo traps remain. First, **DNS rebinding**: an attacker's domain can pass your check with a public IP, then re-resolve to an internal one before the actual request. Defend by connecting to the exact IP you validated rather than re-resolving the hostname. Second, **redirects**: a permitted URL can 302 to an internal one, so disable automatic redirect following and re-validate every hop:\n\n```python\nresp = requests.get(url, allow_redirects=False, timeout=5)\n```\n\n## Restrict the URL scheme, and expect blind SSRF\n\nAttackers do not limit themselves to `http`. Depending on the client library, schemes like `file://`, `gopher://`, `ftp://`, and `dict://` can read local files or speak to internal services in ways a naive validator never anticipates. Always constrain the scheme to an explicit allowlist, in practice just `https`, before any other check runs.\n\nAlso plan for blind SSRF, where the response never comes back to the attacker but the request still fires. A webhook validator that fetches a URL and discards the body still lets an attacker probe internal ports by timing, or trigger state-changing internal endpoints. The mitigations are the same, allowlisting, IP validation, egress control, but the detection story is harder, so lean on network-level logging of unexpected outbound connections from application hosts.\n\n## Lock down the network and the metadata endpoint\n\nApplication-layer checks should not be your only line. Put the outbound fetch behind an egress proxy that enforces the allowlist at the network level, so a code bug cannot bypass it. On cloud hosts, require IMDSv2 (the session-token version of the instance metadata service), which defeats the simple SSRF-to-metadata path that older, header-less metadata access allowed. And apply timeouts and response-size limits so SSRF cannot double as a denial-of-service amplifier.\n\nBecause SSRF is fundamentally about runtime request behavior, the most reliable way to confirm your defenses hold is to test the deployed application from the outside. A [dynamic application security scan](https://safeguard.sh/products/dast) can feed metadata and internal-range payloads at your URL-fetching endpoints and report which ones actually reach where they should not.\n\n## Checklist\n\n- [ ] Allowlist destinations wherever the set of valid hosts is known\n- [ ] For arbitrary URLs, resolve and reject private, loopback, link-local, reserved IPs\n- [ ] Connect to the validated IP to defeat DNS rebinding\n- [ ] Disable automatic redirects; re-validate each hop\n- [ ] Enforce timeouts and response-size caps\n- [ ] Require IMDSv2 and restrict egress at the network layer\n- [ ] Test with SSRF payloads against the running app\n\n## How Safeguard helps\n\nThe allowlisting and IP-validation logic above is code you write; a scanner will not author it for you, and we say that plainly. Safeguard helps on the flanks. SSRF is often introduced through a dependency, an HTTP client, a URL parser, or a link-unfurling library, and when one of those carries an SSRF or request-smuggling CVE, our [software composition analysis](https://safeguard.sh/products/sca) surfaces it in your tree with fix guidance. When a patched version exists, [automated remediation](https://safeguard.sh/products/auto-fix) opens the upgrade PR so the known-vulnerable client is replaced quickly. Teams comparing our reachability-aware approach to prioritization against other tools often start with our [comparison against Snyk](https://safeguard.sh/compare/vs-snyk).\n\n## Get started\n\nAdd allowlisting and IP validation to your URL-fetching code, require IMDSv2, then let Safeguard watch the HTTP libraries underneath. Create a free project at [app.safeguard.sh/register](https://app.safeguard.sh/register) and follow the docs at [docs.safeguard.sh](https://docs.safeguard.sh/).\n\n[python](https://safeguard.sh/resources/blog/tag/python) [ssrf](https://safeguard.sh/resources/blog/tag/ssrf) [web-security](https://safeguard.sh/resources/blog/tag/web-security)\n\n[Back to all articles](https://safeguard.sh/resources/blog)\n\n## More on\\#python\n\n[View all](https://safeguard.sh/resources/blog/tag/python)\n\n[Vulnerability Analysis\\\\\n**Python setuptools package\\_index ReDoS (CVE-2022-40897)** \\\\\n7 min read](https://safeguard.sh/resources/blog/python-setuptools-packageindex-redos-cve-2022-40897) [Open Source Security\\\\\n**Python's .pth Files Are a Code Execution Primitive, and Attackers Noticed** \\\\\n7 min read](https://safeguard.sh/resources/blog/python-pth-files-startup-code-execution-supply-chain-primitive) [Container Security\\\\\n**Minimal, Non-Root Docker Images for Python: A Best-Practices Guide** \\\\\n6 min read](https://safeguard.sh/resources/blog/docker-security-best-practices-python-apps) [Application Security\\\\\n**ssl vs. requests vs. httpx: where Python TLS configuration goes wrong** \\\\\n5 min read](https://safeguard.sh/resources/blog/python-secure-network-communication-libraries)\n\n## Related articles inSecurity Guides\n\n[Security Guides\\\\\n\\\\\n**What are zombie connections in low-code tools and how do you retire them?** \\\\\n\\\\\nZombie connections are old, broad, long-lived credentials left in low-code platforms. Learn how they form and a safe way to find and retire them.\\\\\n\\\\\nOctober 19, 2026Read](https://safeguard.sh/resources/blog/zombie-connections-in-low-code-platforms-find-and-retire-them) [Security Guides\\\\\n\\\\\n**How does zero trust apply to legacy systems that cannot change?** \\\\\n\\\\\nZero trust shifts protection from network location to each resource. For legacy systems, that means a gate in front of each one, not trust in the segment.\\\\\n\\\\\nOctober 19, 2026Read](https://safeguard.sh/resources/blog/zero-trust-for-legacy-systems-protect-the-resource-not-the-segment) [Security Guides\\\\\n\\\\\n**Your payment provider is down. How should checkout behave?** \\\\\n\\\\\nFail clearly, never guess. Stop new charge attempts, keep carts, queue safe actions, reconcile with the provider afterwards, and tell customers plainly.\\\\\n\\\\\nOctober 19, 2026Read](https://safeguard.sh/resources/blog/your-payment-provider-is-down-how-should-checkout-behave)\n\n## Never miss an update\n\nWeekly insights on software supply chain security, delivered to your inbox.\n\nWebsite\n\nEmail address\n\nSubscribe\n\nWe email you a link to confirm, and only then add you to the list. Unsubscribe in one click. [Privacy](https://safeguard.sh/company/privacy-policies)\n\n![](https://safeguard.sh/brand/safeguard-monogram.svg)\n\n## Self-healing security runs on Safeguard.\n\nYour first fix PR is minutes away.\n\n[Book a demo](https://safeguard.sh/talk) [Get started](https://safeguard.sh/download)\n\nNo sales call required, even your agent can complete the purchase over MCP.\n\n![James](https://safeguard.sh/sdr/james.jpg)Ask James"}
{"source": "firecrawl_search", "query": "Python SSRF prevention ipaddress private loopback link-local validation", "source_url": "https://codesignal.com/learn/courses/server-side-request-forgery-ssrf-prevention-in-fastapi/lessons/understanding-ssrf-vulnerabilities", "license": "web_reference", "markdown": "# Understanding SSRF Vulnerabilities\n\n![](https://k3-production-bucket.s3.amazonaws.com/uploads/d0197b8f-547c-44f2-9ded-74bc235f06d4_slide-1.png)\n\nVideo Player is loading.\n\nPlay Video\n\nPlaySkip BackwardSkip Forward\n\nMute\n\nCurrent Time 0:00\n\n/\n\nDuration -:-\n\nLoaded: 0%\n\nStream Type LIVE\n\nSeek to live, currently behind liveLIVE\n\nRemaining Time -0:00\n\n1x\n\nPlayback Rate\n\n- 3x\n- 2.75x\n- 2.5x\n- 2.25x\n- 2x\n- 1.75x\n- 1.5x\n- 1.25x\n- 1x, selected\n- 0.75x\n- 0.5x\n\nChapters\n\n- Chapters\n\nDescriptions\n\n- descriptions off, selected\n\nCaptions\n\n- captions settings, opens captions settings dialog\n- captions off, selected\n\nAudio Track\n\nFullscreen\n\nThis is a modal window.\n\nThe media could not be loaded, either because the server or network failed or because the format is not supported.\n\n## Introduction to SSRF\n\nWelcome to the very first lesson of the \" **Server-Side Request Forgery (SSRF) Prevention in FastAPI**\" course! In this lesson, we will explore **Server-Side Request Forgery (SSRF)**, a critical security vulnerability that can affect web applications. `SSRF` occurs when an attacker tricks a server into making unauthorized requests on their behalf. This can lead to the exposure of sensitive information or unauthorized actions within a network.\n\nUnderstanding `SSRF` is crucial for building secure applications and protecting against potential threats. Let's dive into the mechanics of `SSRF` to see how these vulnerabilities occur. 🚀\n\n## Understanding SSRF\n\nTo understand `SSRF`, it's important to differentiate between client-side and server-side requests. In a typical web application, client-side requests are made by the user's browser, while server-side requests are made by the server itself. `SSRF` vulnerabilities occur when an attacker manipulates server-side requests to access unauthorized resources.\n\nImagine a scenario in which a web application allows users to input a URL to fetch data. If the application doesn't properly validate the input, an attacker could input a URL pointing to an internal resource, such as a private server. Internal resources typically include services like internal dashboards, internal APIs, or even databases that are not exposed to the public internet. These systems are usually protected by network-level restrictions like firewalls or NAT, meaning users on the internet shouldn't be able to access them directly. However, because the server itself is inside the protected network, it can access these systems. By leveraging SSRF, attackers exploit this trust boundary and trick the server into making requests to sensitive endpoints on their behalf — essentially bypassing external access restrictions.\n\n## SSRF Attack Patterns\n\nSSRF attacks can take several forms, depending on the target and the attacker's goals:\n\n1. **Internal Network Scanning**: Attackers use SSRF to map out internal networks by sending requests to various IP addresses and ports.\n\n2. **Cloud Metadata Service Attacks**: In cloud environments, attackers target metadata services (like AWS Instance Metadata Service) to obtain sensitive information such as access keys.\n\n3. **Local File Access**: Using protocols like `file://`, attackers might attempt to read local files on the server.\n\n4. **Service-Specific Exploits**: Attackers target internal services that might have weak authentication when accessed from within the network.\n\n\nHere's a basic example of an SSRF vulnerability:\n\nPython\n\nCopy to clipboard\n\n```\nimport requests\n\n# Example of a vulnerable server-side request\ndef fetch_data(url: str) -> None:\n    # Server makes a request to the provided URL without validation\n    print(f'Fetching data from: {url}')\n    response = requests.get(url)\n    print(response.text)\n\nuser_input = 'http://internal-server.local/data'\nfetch_data(user_input)\n```\n\n## Common SSRF Targets\n\nWhen conducting SSRF attacks, attackers typically target:\n\n1. **Cloud Infrastructure Metadata**: Endpoints like:\n   - AWS: `http://169.254.169.254/latest/meta-data/`\n   - Azure: `http://169.254.169.254/metadata/instance`\n   - GCP: `http://metadata.google.internal/computeMetadata/v1/`\n2. **Internal APIs and Services**: Internal services often lack the same level of security as public-facing endpoints.\n\n3. **Admin Interfaces**: Internal admin panels that might be accessible only from within the network.\n\n4. **Database Servers**: Accessing internal database servers to extract sensitive data.\n\n\nShell\n\nCopy to clipboard\n\n```\n# Example of targeting cloud metadata service\ncurl http://vulnerable-app.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/\n```\n\n## SSRF Detection Techniques\n\nTo identify `SSRF` vulnerabilities in code, we need to look for areas where user input is used to construct server-side requests. For example, if a user-supplied URL is passed directly into a function like `requests.get()` or `httpx.get()` without domain or scheme restrictions, this is a strong indicator of SSRF risk. Developers should examine whether the input is sanitized, validated against allowlists, and whether any proxy or redirect behavior is occurring that could allow the attacker to circumvent basic filters.\n\n## Identifying Internal IPs and Localhost\n\nA naive approach to SSRF detection is to check if the URL contains internal IP addresses or localhost references as substrings. However, this can lead to false positives. For example, the domain `not-localhost.com` would be incorrectly flagged as dangerous, even though it is a public domain.\n\nA more robust approach is to parse the URL and check the actual hostname against known internal addresses and private IP ranges. Additionally, it's important to check if any query parameter values themselves are internal IPs, hostnames, or URLs pointing to internal resources.\n\nPython\n\nCopy to clipboard\n\n```\nimport ipaddress\nimport logging\nfrom urllib.parse import urlparse, parse_qs\n\n# Check for internal IPs and localhost variants using proper IP classification\ndef is_ssrf_vulnerable(url: str) -> bool:\n    localhost_hostnames = ['127.0.0.1', 'localhost', '0.0.0.0', '::1']\n\n    def is_dangerous_host(host: str) -> bool:\n        if host in localhost_hostnames:\n            return True\n\n        # Use ipaddress module for proper IP classification\n        try:\n            ip = ipaddress.ip_address(host)\n            # Check for private, loopback, link-local, multicast, reserved, or unspecified addresses\n            if (ip.is_private or ip.is_loopback or ip.is_link_local or\n                ip.is_multicast or ip.is_reserved or ip.is_unspecified):\n                return True\n        except ValueError:\n            # Not a valid IP address, check if it's a dangerous hostname\n            if host.lower() in ['localhost', 'local']:\n                return True\n        return False\n\n    try:\n        parsed = urlparse(url)\n        hostname = parsed.hostname or parsed.netloc\n\n        # Check for localhost variants and private IPs in the main hostname\n        if is_dangerous_host(hostname):\n            return True\n\n        # Check for dangerous patterns in query parameter values\n        query_params = parse_qs(parsed.query)\n        for values in query_params.values():\n            for value in values:\n                # If value looks like a host or IP, check it\n                if is_dangerous_host(value):\n                    return True\n\n                # If value is a URL, check its hostname\n                try:\n                    param_url = urlparse(value)\n                    if param_url.hostname and is_dangerous_host(param_url.hostname):\n                        return True\n                except (ValueError, TypeError) as e:\n                    # Not a URL, skip\n                    logging.debug(f\"Failed to parse parameter URL: {e}\")\n\n        return False\n    except (ValueError, TypeError) as e:\n        logging.warning(f\"Failed to parse URL for SSRF check: {e}\")\n        return False\n\nurl = 'http://127.0.0.1/admin'\nprint(f'Is SSRF Vulnerable: {is_ssrf_vulnerable(url)}')\n```\n\n> **Note:** Always parse and check the hostname, not just substrings, to avoid false positives in SSRF detection. Also, consider checking query parameter values, as attackers may try to smuggle internal addresses there.\n\n## Detecting Non-HTTP Schemes\n\nCheck for potentially dangerous URL schemes:\n\nPython\n\nCopy to clipboard\n\n```\n# Check for non-HTTP schemes that could be exploited\ndef has_unsafe_scheme(url: str) -> bool:\n    unsafe_schemes = ['file://', 'gopher://', 'data:', 'dict://', 'ftp://']\n    lower_url = url.lower()\n    return any(lower_url.startswith(scheme) for scheme in unsafe_schemes)\n\nunsafe_url = 'file:///etc/passwd'\nprint(f'Has Unsafe Scheme: {has_unsafe_scheme(unsafe_url)}')\n```\n\n## Validating URL Format and Domain\n\nEnsure the URL format is valid and doesn't point to restricted resources:\n\nPython\n\nCopy to clipboard\n\n```\nfrom urllib.parse import urlparse\n\n# Validate URL format and domain\ndef is_valid_and_safe_url(url: str) -> bool:\n    try:\n        parsed = urlparse(url)\n\n        # Check for valid HTTP/HTTPS scheme\n        if parsed.scheme not in ['http', 'https']:\n            return False\n\n        # Check for valid netloc (hostname and optional port)\n        if not parsed.netloc:\n            return False\n\n        # Check for unsafe targets\n        if is_ssrf_vulnerable(url) or has_unsafe_scheme(url):\n            return False\n\n        # Additional checks could be added here\n        return True\n    except:\n        return False\n```\n\nThese schemes are dangerous because they interact with the system or network in unintended ways. For instance, `file://` accesses local files, `gopher://` can be used to send binary data (often abused in SSRF-to-RCE attacks), and `ftp://` may allow directory traversal or retrieval of sensitive config files.\n\n## Conclusion\n\nIn this lesson, we explored the concept of `Server-Side Request Forgery (SSRF)` and its potential impact on web applications. We learned about various attack patterns, common targets, and methods for detecting SSRF vulnerabilities in code. As we move forward, you'll see how to implement effective prevention techniques in FastAPI applications to mitigate these risks.\n\n[Next Lesson: Preventing SSRF in FastAPI](https://codesignal.com/learn/courses/server-side-request-forgery-ssrf-prevention-in-fastapi/lessons/preventing-ssrf-in-fastapi-1)\n\n![Sign up](https://codesignal.com/_next/image?url=%2Flearn%2Fimg%2Fsignup-module.png&w=1200&q=75)\n\n## Join the 1M+ learners on CodeSignal\n\nBe a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal\n\nStart learning today!\n\nUnderstanding SSRF Vulnerabilities \\| CodeSignal Learn"}
{"source": "firecrawl_search", "query": "Python SSRF prevention ipaddress private loopback link-local validation", "source_url": "https://eyalsec.com/vulnerabilities/ssrf", "license": "web_reference", "markdown": "[Skip to content](https://eyalsec.com/vulnerabilities/ssrf#main)\n\nOn this page\n\n## How it shows up in Python\n\nAny feature that fetches a URL the user supplies is a candidate: a webhook, an \"import from URL\", a link preview, an avatar fetched from a profile address. The code looks harmless:\n\n```python\nimport requests\nfrom flask import request\n\n@app.post(\"/preview\")\ndef preview():\n    url = request.form[\"url\"]\n    resp = requests.get(url, timeout=5)\n    return {\"title\": extract_title(resp.text)}\n```\n\nCopy code\n\nThe server will fetch whatever `url` says, including `http://169.254.169.254/...` (the cloud metadata service, which can hand out credentials), `http://localhost:6379/` (an internal Redis), or a link-local or private-range address that only the server can reach. From the outside an attacker cannot touch those; through this endpoint they can.\n\nSSRF is hard to fix by inspecting the string, because a hostname can resolve to an internal address, a redirect can send a safe-looking URL to an internal one, and there are many spellings of the same address. The reliable defences are structural:\n\n```python\nimport ipaddress\nimport socket\nfrom urllib.parse import urlparse\nimport requests\nfrom flask import request, abort\n\ndef safe_target(url: str) -> str:\n    parts = urlparse(url)\n    if parts.scheme not in (\"http\", \"https\") or not parts.hostname:\n        abort(400)\n    for info in socket.getaddrinfo(parts.hostname, parts.port or 80):\n        ip = ipaddress.ip_address(info[4][0])\n        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:\n            abort(400)\n    return url\n\n@app.post(\"/preview\")\ndef preview():\n    url = safe_target(request.form[\"url\"])\n    resp = requests.get(url, timeout=5, allow_redirects=False)\n    return {\"title\": extract_title(resp.text)}\n```\n\nCopy code\n\nResolve the host and reject private, loopback, link-local and reserved addresses; allow only `http` and `https`; and disable redirects (or re-validate each hop), because a permitted host can redirect to a forbidden one. Stronger still is to route outbound fetches through an egress proxy that enforces an allowlist, so the policy lives in one place instead of every call site.\n\n## Why it is hard to see\n\n- **The request never leaves through the edge.** SSRF is the server making an internal, east-west call. A web application firewall and a CDN watch inbound traffic to the origin, not the origin's own outbound requests.\n- **A hostname that resolves inward.** The URL contains an ordinary public-looking hostname whose DNS record points at an internal address, so there is nothing in the string to match.\n- **Redirect to an internal target.** The submitted URL is on an allowed host and returns a redirect to `169.254.169.254` or `localhost`. A check on the original string passes.\n- **Assembled or decoded in the app.** The destination is built from a base and a user-supplied path, or decoded from an encoded parameter, so no single field is a URL.\n\n## What the es-python event looks like\n\nes-python reports at the point the connection is actually made, which is the one place every one of those bypasses converges. The base event is `socket connect`, `socket getaddrinfo` or `socket gethostbyname` (the call `requests`, `urllib` and friends all funnel through); when the destination the untrusted value resolves to is a loopback, link-local, or private-range address, an `ssrf` event fires alongside it, tagged `ssrf`. Because this is decided on the address the program is dialling, an internal hostname and an in-application redirect both still fire: the final destination is what is checked, not the submitted string.\n\nThe `ssrf` label is a strong signal when it fires, and the base `socket connect` event on untrusted input shows every outbound destination the request steered. The [severity](https://eyalsec.com/docs/events#severity) follows the source. Under a [Raise rule](https://eyalsec.com/docs/report-and-raise#raise), the connection raises a `RuntimeError` before it is made.\n\n## How to fix and prevent it\n\n1. Resolve the host and reject private, loopback, link-local and reserved IP addresses, for every address a hostname resolves to.\n2. Allow only `http` and `https`, and an allowlist of hosts where you can.\n3. Disable redirects or re-validate every hop; the first URL is only the start.\n4. Route outbound fetches through an egress proxy that enforces the allowlist in one place.\n5. Lock down the metadata endpoint (require IMDSv2 on AWS) so a fetch that does slip through gets nothing useful.\n6. In Report mode, watch the `ssrf` tag and the `socket connect` events on request data to see every destination user input can steer.\n\n## Classification\n\nSSRF is [CWE-918](https://cwe.mitre.org/data/definitions/918.html), Server-Side Request Forgery. In the Top 10 for 2025 OWASP folded SSRF into [A01:2025 Broken Access Control](https://top10.owasp.org/2025/A01_2025-Broken_Access_Control/), which lists CWE-918 among its mapped weaknesses.\n\n## Questions people ask\n\nThe questions that come up on forums and in reviews about this class, each answered in a few sentences.\n\n### Why is SSRF dangerous in a cloud environment?\n\nBecause the server can reach what the attacker cannot: internal services, admin interfaces and the cloud metadata endpoint, which hands out instance credentials to any process on the machine. One forged request from a service that fetches user-supplied URLs can turn into cloud credentials. The fix is to decide the destination from an allowlist and to check the resolved address, not the submitted string.\n\n### Does validating the URL hostname stop SSRF?\n\nOnly partly: a hostname check on the submitted string is bypassed by a DNS name that resolves to an internal address, by an HTTP redirect to one, and by alternate spellings of the same IP address. Check the address the program is about to connect to, after resolution and after each redirect, and disable redirects where you can. es-python makes the same decision at the connection, on the final destination, which is why an internal hostname and a redirect both still produce an `ssrf` event.\n\n### How does es-python detect SSRF?\n\nIt reports at the point the connection is made, `socket connect`, `socket getaddrinfo` or `socket gethostbyname`, when the destination was chosen by untrusted data, and adds an `ssrf` event when that destination is a loopback, link-local or private-range address. The check is on the address the program is dialling, so an internal hostname and an in-application redirect both fire. It recognises the standard spellings of an address, not alternate encodings, and a Raise rule stops the connection before it is made.\n\n## Server-side request forgery (SSRF) in your framework\n\n- [**Django** SSRF in Django: why URLField and URLValidator accept loopback addresses, webhook URLs stored in models, and redirects that requests follows by default.](https://eyalsec.com/vulnerabilities/ssrf/django)\n- [**Flask** SSRF in Flask proxy and preview endpoints: a url query parameter passed to requests, redirects followed by default, and a destination check that holds.](https://eyalsec.com/vulnerabilities/ssrf/flask)\n- [**FastAPI** SSRF in FastAPI: what Pydantic HttpUrl does and does not check, webhook registration endpoints, httpx redirect defaults and a resolver-based fix.](https://eyalsec.com/vulnerabilities/ssrf/fastapi)\n\n## Related\n\n### How es-python reports it\n\n- [**Block attacks from the internet (es-python)** User guide: Rule templates](https://eyalsec.com/docs/rule-templates#block-internet)\n- [**Network input (socket)** User guide: Taint sources](https://eyalsec.com/docs/taint-sources#socket)\n- [**Event detail** Clicking an event opens it in place and shows the full story: what happened, why it matters, what to do, and the evidence behind it. This page goes through every block you can see there.](https://eyalsec.com/docs/event-detail)\n\n### Research\n\n- [**SSRF in Python services: requests, httpx, urllib and the cloud metadata endpoint** How SSRF reaches requests, httpx and urllib in Python, why the cloud metadata endpoint raises the stakes, and a destination check that holds up.](https://eyalsec.com/research/ssrf-in-python-services)\n\n### Related classes\n\n- [**Path traversal** Path traversal in Python with open(), os.path.join, send\\_file and zip/tar extraction, the subtle variants, and how es-python reports it.](https://eyalsec.com/vulnerabilities/path-traversal)\n- [**Command injection** OS command injection in Python with os.system, subprocess shell=True and paramiko: the variants hardest to spot, and the es-python event.](https://eyalsec.com/vulnerabilities/command-injection)\n- [**Untrusted code loading** Loading Python code from a file another user can write, or a module shadowing the standard library, why it is RCE, and how es-python reports it.](https://eyalsec.com/vulnerabilities/untrusted-code-loading)\n\n## Watch for Server-side request forgery (SSRF) in your own code\n\nes-python runs your Python application unchanged and reports when untrusted data reaches the operation, with where the data came from and the line that used it. Ask to see it on your own application.\n\n[Protect my Python app](https://eyalsec.com/contact) [All vulnerability classes](https://eyalsec.com/vulnerabilities)\n\n[![](https://eyalsec.com/static/icons/eyalsec-shield.png)EyalSec](https://eyalsec.com/)[Pricing](https://eyalsec.com/pricing) [Docs](https://eyalsec.com/docs) [Security](https://eyalsec.com/security) [Research](https://eyalsec.com/research) [Vulnerabilities](https://eyalsec.com/vulnerabilities) [Play](https://eyalsec.com/play) [Security glossary](https://eyalsec.com/glossary) [About](https://eyalsec.com/about) [Contact](https://eyalsec.com/contact) [עברית](https://eyalsec.com/he) [Login](https://eyalsec.com/login/) [Get started](https://eyalsec.com/register/) [Protect my Python app](https://eyalsec.com/contact)\n\n[Phone +972-58-799-0798](tel:+972587990798) [Press kit](https://eyalsec.com/press) [Changelog](https://eyalsec.com/changelog) [Terms](https://eyalsec.com/legal/terms) [Privacy](https://eyalsec.com/legal/privacy) [DPA](https://eyalsec.com/legal/dpa) [Acceptable Use](https://eyalsec.com/legal/aup) [Security measures](https://eyalsec.com/legal/security) [Report a vulnerability](https://eyalsec.com/security/disclosure) [Licenses](https://eyalsec.com/legal/licenses) [Refund](https://eyalsec.com/legal/refund) Python is a trademark of the Python Software Foundation. EyalSec is not affiliated with or endorsed by the PSF.\n\nMay we remember this browser between visits? One first-party cookie shows us which pages help you most. No ads, nothing shared. [Privacy policy](https://eyalsec.com/legal/privacy#3-cookies-and-similar-technologies)\n\nAllowNo thanks\n\n**EyalSec** Away right now. Leave a message and we will reply.\n\nEnd chatClose\n\nHi there. Questions about protecting your Python services? Ask away.\n\ntyping...\n\nNameEmailYour message\n\nWe keep this conversation so we can answer you. [Privacy](https://eyalsec.com/legal/privacy)\n\nSend message"}
{"source": "firecrawl_search", "query": "Python HTML escaping XSS html.escape urllib urlsplit javascript scheme", "source_url": "https://ssojet.com/dev-guides/html-escaping-in-python", "license": "web_reference", "markdown": "New Sign-in for AI agents: MCP support is in Beta. [Read the docs _→_](https://ssojet.com/docs/en)\n\nEscaping\n\n# HTML Escaping in Python\n\nSafely render HTML in Python. Learn HTML escaping techniques to prevent XSS attacks and ensure secure web applications.\n\nUpdated Apr 29, 2025 · 3 min read · [Markdown](https://ssojet.com/dev-guides/html-escaping-in-python.md)\n\n**16** Languages\n\n## HTML Escaping in other languages\n\nWhen building web applications with Python, directly embedding user-provided data into HTML can open the door to cross-site scripting (XSS) vulnerabilities. HTML escaping is the crucial defense mechanism that sanitizes this data, preventing malicious code injection. This guide dives into the practical techniques for implementing HTML escaping in Python, covering common libraries and best practices. You’ll learn how to ensure your web content remains secure and your users’ data is protected, making your applications safer and more robust.\n\n## Escaping Special HTML Characters\n\nCertain characters in HTML have special meaning and must be escaped when they appear in content that isn’t meant to be interpreted as markup. This is crucial for preventing cross-site scripting (XSS) attacks and ensuring your HTML renders correctly without errors. For instance, the `<` character signals the start of a tag, and `>` signals its end.\n\nConsider user input like `\"<script>alert('XSS')</script>\"`. If rendered directly into an HTML page, this malicious string would execute JavaScript. By escaping it, you transform it into `&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;`. The browser now displays the literal characters instead of interpreting them as code.\n\nA common oversight is forgetting to escape user-provided data before embedding it into your HTML. Always sanitize input. Python’s `html.escape()` function is your best friend here; use it consistently on any dynamic content before it hits the browser.\n\n## Using `html.escape()`\n\nPython’s standard library offers a simple solution for HTML escaping with the `html.escape()` function. This function takes a string and replaces characters that have special meaning in HTML with their corresponding entities.\n\nFor instance, consider this common scenario:\n\n```\nimport html\nuser_input = \"<script>alert('XSS attack!')</script>\"\nsafe_output = html.escape(user_input)\nprint(safe_output)\n# Output: &lt;script&gt;alert(&#x27;XSS attack!&#x27;)&lt;/script&gt;\n```\n\nCopy\n\nA crucial point to remember is that `html.escape()` by default only handles `&`, `<`, and `>`. For robust security, especially when dealing with user-provided data that might include quotes, you should always use the `quote=True` argument. This ensures that single (`'`) and double (`\"`) quotes are also escaped, preventing potential cross-site scripting (XSS) vulnerabilities. Always opt for `html.escape(your_string, quote=True)` when sanitizing user input for display in HTML.\n\n## Escaping in Web Frameworks\n\nMost modern Python web frameworks, including Flask and Django, build HTML escaping directly into their templating systems. This is a crucial security feature designed to prevent Cross-Site Scripting (XSS) attacks.\n\nFor instance, when using Jinja2 with Flask, simply rendering a variable like `{{ user_comment }}` inside an HTML template will automatically escape any special HTML characters present in `user_comment`. This means if `user_comment` contains something like `<script>alert('XSS')</script>`, the template engine will render it as `&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;`, rendering the script harmlessly as text.\n\nA common pitfall arises when developers explicitly disable auto-escaping for user-generated content, perhaps to allow specific HTML formatting. If not handled with extreme care, this bypasses the framework’s built-in protections, reintroducing an XSS vulnerability. Always ensure user input is escaped unless you have a robust sanitization process in place.\n\n## Escaping Attributes and Dynamic Content\n\nAttribute values within HTML tags, such as `href`, `src`, and `title`, also need diligent escaping, particularly when incorporating dynamic data or special characters. Failing to do so can introduce vulnerabilities or break your markup.\n\nConsider how to safely insert a URL into an `href` attribute:\n\n```\nimport html\nurl = \"http://example.com?q=a&b=c\"\nsafe_url = html.escape(url, quote=True)\nprint(f'<a href=\"{safe_url}\">Link</a>')\n# Output: <a href=\"http://example.com?q=a&amp;b=c\">Link</a>\n```\n\nCopy\n\nA common pitfall here is escaping the entire HTML tag instead of isolating and escaping just the attribute’s value. This results in malformed code. Always target the specific attribute value where dynamic content resides to maintain valid HTML structure.\n\nGet started\n\n## Ship enterprise SSO this week\n\nStart free. Keep your auth. Pass the security review.\n\n[Start free](https://portal.ssojet.com/login?screen_hint=signup) [Talk to an expert](https://ssojet.com/contact/)"}
{"source": "firecrawl_search", "query": "Python HTML escaping XSS html.escape urllib urlsplit javascript scheme", "source_url": "https://robyfirnandoyusuf.medium.com/xss-bypass-urlparse-filter-evasion-in-python-30b3aa36247d", "license": "web_reference", "markdown": "[Sitemap](https://robyfirnandoyusuf.medium.com/sitemap/sitemap.xml)\n\n[Open in app](https://play.google.com/store/apps/details?id=com.medium.reader&referrer=utm_source%3DmobileNavBar&source=---top_nav_layout_nav--------------------------------------------)\n\nSign up\n\n[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Frobyfirnandoyusuf.medium.com%2Fxss-bypass-urlparse-filter-evasion-in-python-30b3aa36247d&source=post_page---top_nav_layout_nav-----------------------global_nav---------------------)\n\n[Medium Logo](https://medium.com/?source=---top_nav_layout_nav--------------------------------------------)\n\nGet app\n\n[Write](https://medium.com/m/signin?operation=register&redirect=https%3A%2F%2Fmedium.com%2Fnew-story&source=---top_nav_layout_nav-----------------------new_post_topnav---------------------)\n\n[Search](https://medium.com/search?source=---top_nav_layout_nav--------------------------------------------)\n\nSign up\n\n[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Frobyfirnandoyusuf.medium.com%2Fxss-bypass-urlparse-filter-evasion-in-python-30b3aa36247d&source=post_page---top_nav_layout_nav-----------------------global_nav---------------------)\n\n![Unknown user](https://miro.medium.com/v2/resize:fill:64:64/1*dmbNkD5D-u45r44go_cf0g.png)\n\n500\n\n## Apologies, but something went wrong on our end.\n\nRefresh the page, check [Medium's site status](https://status.medium.com/), or [find something interesting to read](https://medium.com/browse/top)."}
{"source": "firecrawl_search", "query": "Python HTML escaping XSS html.escape urllib urlsplit javascript scheme", "source_url": "https://safeguard.sh/resources/blog/preventing-xss-in-python-web-apps-django-and-jinja", "license": "web_reference", "markdown": "[Skip to content](https://safeguard.sh/resources/blog/preventing-xss-in-python-web-apps-django-and-jinja#main-content)\n\n[![Safeguard](https://safeguard.sh/brand/safeguard-lockup-ink.svg)![Safeguard](https://safeguard.sh/brand/safeguard-lockup-white.svg)](https://safeguard.sh/)\n\nSS\n\nSafeguard Security Team\n\nOctober 18, 20264 min read\n\nShare\n\nPrevent cross-site scripting in Python by rendering every variable through a template engine with autoescaping on, then treating each escape hatch (the safe filter, Markup, autoescape off) as a reviewed exception. Autoescaping covers HTML text. Attributes, URLs and script data need extra care, and user-authored HTML needs a sanitizer.\n\n## What do Django and Jinja do by default?\n\nThey differ, and the difference bites teams that move between them.\n\nDjango escapes the output of every variable tag by default. Five characters change: less-than, greater-than, single quote, double quote and ampersand. A name containing a script tag renders as inert text.\n\nPlain Jinja does the opposite. Its documentation states that the default configuration is no automatic escaping, so the application decides. Flask and similar frameworks configure it for you, but a standalone Jinja environment used to build emails or reports may be wide open. When autoescaping is on, everything is escaped except values explicitly marked safe.\n\nIf you use Jinja outside a framework, check the environment setting first. That one line decides whether every template is safe or none is.\n\n## Where do the escape hatches live?\n\nBoth engines give you ways to switch escaping off, and every one is a spot where XSS returns.\n\n- Django: the `safe` filter, the `autoescape off` tag, and `mark_safe` in Python code.\n- Jinja: the `safe` filter and wrapping a string in `Markup`.\n\nDjango's documentation adds three cautions worth memorizing. String literals typed in a template are treated as already safe. Disabling autoescape in a base template affects every child template that inherits it. And block.super is not escaped again, because it was escaped in the parent.\n\nJinja has a quieter trap: a value that is escaped but not marked safe is escaped again, producing double-escaped text. Developers then \"fix\" the display problem by adding the safe filter, which removes protection. If you see this pattern in a diff, ask why the data was escaped before the template.\n\n## Is autoescaping enough?\n\nNot for every context. Autoescaping handles HTML text and quoted attributes. OWASP's cheat sheet lists spots with no safe encoding at all: inside script or style elements, HTML comments, attribute or tag names, and event handler code.\n\nConstructed example. A profile page wants to show the user's theme color and a website link:\n\n```html\n<div style=\"color: {{ user.color }}\">\n<a href=\"{{ user.website }}\">Website</a>\n```\n\nThe color value is inside a CSS context. Allow only values from a fixed list. The link value is a URL: HTML escaping will not stop a javascript: scheme. Parse it in Python and allow only http and https before rendering.\n\nFor data that scripts need, Jinja's tojson filter produces output that is safe in HTML, but the docs warn that inside double-quoted attributes you should use single quotes or the forceescape filter. Prefer a JSON script block or a data attribute read with textContent in the browser.\n\n## What about user-authored HTML?\n\nIf you accept rich text, encoding would show raw tags, so use a sanitizer. OWASP recommends a maintained sanitizer, such as DOMPurify on the client, and warns against editing the HTML after sanitizing. Sanitize last, store the result, and keep the library patched.\n\n## What to do\n\n1. Confirm autoescaping is on for every template environment, including email and report generators.\n2. Search the codebase for safe, mark\\_safe, Markup and autoescape off. Require a comment explaining each hit.\n3. Never place user data inside script blocks, style blocks, comments or event handlers.\n4. Validate URL schemes before putting a user URL in href or src.\n5. Allowlist values for CSS properties.\n6. Sanitize rich text with a maintained library as the final step.\n7. Add a content security policy as defense in depth and test it in staging.\n8. Keep Django, Jinja and sanitizer packages patched, and scan them on every pull request.\n\nSafeguard's dependency scanning can flag vulnerable template and sanitizer packages in pull requests, so step 8 does not depend on someone remembering.\n\n## Quick check\n\nDoes Flask escape templates automatically?\n\nThe Jinja documentation does not cover Flask, so check Flask's own documentation for the exact rules. Standalone Jinja does not escape by default, so never assume.\n\nIs the safe filter ever acceptable?\n\nYes, for content you control or have already sanitized, such as a stored HTML fragment you generated. Never use it on raw user input.\n\n## Sources\n\n- [Django: automatic HTML escaping](https://docs.djangoproject.com/en/stable/ref/templates/language/#automatic-html-escaping)\n- [Jinja: HTML escaping](https://jinja.palletsprojects.com/en/stable/templates/#html-escaping)\n- [OWASP Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)\n\nLast reviewed: 18 October 2026.\n\n[Application Security](https://safeguard.sh/resources/blog/tag/application-security)\n\n[Back to all articles](https://safeguard.sh/resources/blog)\n\n## More on\\#Application Security\n\n[View all](https://safeguard.sh/resources/blog/tag/application-security)\n\n[Application Security\\\\\n**WAF vs API gateway: what each does and when you need both** \\\\\n4 min read](https://safeguard.sh/resources/blog/waf-vs-api-gateway-what-each-one-does-and-when-you-need-both) [Application Security\\\\\n**What is different about managing TypeScript dependencies securely?** \\\\\n4 min read](https://safeguard.sh/resources/blog/typescript-dependency-management-types-and-runtime-packages) [Application Security\\\\\n**Threat modeling vs risk assessment: what is the difference?** \\\\\n4 min read](https://safeguard.sh/resources/blog/threat-modeling-vs-risk-assessment-what-each-answers) [Application Security\\\\\n**How do you generate secure random numbers and encrypt data in Swift?** \\\\\n5 min read](https://safeguard.sh/resources/blog/secure-random-numbers-and-cryptography-basics-in-swift)\n\n## Related articles inApplication Security\n\n[Application Security\\\\\n\\\\\n**AI Code Security: How to Secure Code Written by AI Assistants and Agents** \\\\\n\\\\\nAI code security for code written by AI assistants and agents: instruction files, package checks at install, agent permissions, SAST, SCA and merge gates.\\\\\n\\\\\nNovember 26, 2026Read](https://safeguard.sh/resources/blog/ai-code-security-how-to-secure-ai-generated-code) [Application Security\\\\\n\\\\\n**Java Vulnerabilities: A Fix Playbook for Maven and Gradle** \\\\\n\\\\\nHow to fix Java deserialization, XXE, injection and vulnerable library findings in Maven and Gradle, then prove the fix shipped in the artifact you deploy.\\\\\n\\\\\nNovember 9, 2026Read](https://safeguard.sh/resources/blog/java-dependency-vulnerabilities-a-fix-playbook-for-maven-and-gradle) [Application Security\\\\\n\\\\\n**Stop XXE Before Merge: Parser Settings, CI Checks, Upgrades** \\\\\n\\\\\nBlock XXE before it merges: safe parser settings for Java, .NET, Python, PHP, Go, Node.js and Ruby, CI checks for unsafe parsers, and fixed library versions.\\\\\n\\\\\nNovember 2, 2026Read](https://safeguard.sh/resources/blog/stop-xxe-before-merge-parser-settings-ci-checks-and-upgrades)\n\n## Never miss an update\n\nWeekly insights on software supply chain security, delivered to your inbox.\n\nWebsite\n\nEmail address\n\nSubscribe\n\nWe email you a link to confirm, and only then add you to the list. Unsubscribe in one click. [Privacy](https://safeguard.sh/company/privacy-policies)\n\n![](https://safeguard.sh/brand/safeguard-monogram.svg)\n\n## Self-healing security runs on Safeguard.\n\nYour first fix PR is minutes away.\n\n[Book a demo](https://safeguard.sh/talk) [Get started](https://safeguard.sh/download)\n\nNo sales call required, even your agent can complete the purchase over MCP.\n\n![James](https://safeguard.sh/sdr/james.jpg)Ask James"}
{"source": "firecrawl_search", "query": "Python hashlib scrypt secrets.token_urlsafe hmac.compare_digest", "source_url": "https://docs.python.org/3/library/secrets.html", "license": "web_reference", "markdown": "### Navigation\n\n- [index](https://docs.python.org/3/genindex.html \"General Index\")\n- [modules](https://docs.python.org/3/py-modindex.html \"Python Module Index\") \\|\n- [next](https://docs.python.org/3/library/allos.html \"Generic Operating System Services\") \\|\n- [previous](https://docs.python.org/3/library/hmac.html \"hmac — Keyed-Hashing for Message Authentication\") \\|\n- ![Python logo](https://docs.python.org/3/_static/py.svg)\n- [Python](https://www.python.org/) »\n- German \\| DeutschGreek \\| ΕλληνικάEnglishSpanish \\| españolPersian \\| فارسیFrench \\| françaisItalian \\| italianoJapanese \\| 日本語Korean \\| 한국어Punjabi \\| ਪੰਜਾਬੀPolish \\| polskiBrazilian Portuguese \\| Português brasileiroRomanian \\| RomâneșteRussian \\| РусскийTurkish \\| TürkçeSimplified Chinese \\| 简体中文Traditional Chinese \\| 繁體中文\n\ndev (3.16)3.15.23.143.133.123.113.103.93.83.73.63.53.43.33.23.13.02.72.6\n\n- [3.15.2 documentation](https://docs.python.org/3/index.html) »\n\n- [The Python standard library](https://docs.python.org/3/library/index.html) »\n- [Cryptographic Services](https://docs.python.org/3/library/crypto.html) »\n- [`secrets` — Generate secure random numbers for managing secrets](https://docs.python.org/3/library/secrets.html)\n- \\|\n\n- Theme\nAutoLightDark \\|\n\n# `secrets` — Generate secure random numbers for managing secrets [¶](https://docs.python.org/3/library/secrets.html\\#module-secrets \"Link to this heading\")\n\nAdded in version 3.6.\n\n**Source code:** [Lib/secrets.py](https://github.com/python/cpython/tree/3.15/Lib/secrets.py)\n\n* * *\n\nThe `secrets` module is used for generating cryptographically strong\nrandom numbers suitable for managing data such as passwords, account\nauthentication, security tokens, and related secrets.\n\nIn particular, `secrets` should be used in preference to the\ndefault pseudo-random number generator in the [`random`](https://docs.python.org/3/library/random.html#module-random \"random: Generate pseudo-random numbers with various common distributions.\") module, which\nis designed for modelling and simulation, not security or cryptography.\n\nSee also\n\n[**PEP 506**](https://peps.python.org/pep-0506/)\n\n## Random numbers [¶](https://docs.python.org/3/library/secrets.html\\#random-numbers \"Link to this heading\")\n\nThe `secrets` module provides access to the most secure source of\nrandomness that your operating system provides.\n\nclasssecrets.SystemRandom [¶](https://docs.python.org/3/library/secrets.html#secrets.SystemRandom \"Link to this definition\")\n\nA class for generating random numbers using the highest-quality\nsources provided by the operating system. See\n[`random.SystemRandom`](https://docs.python.org/3/library/random.html#random.SystemRandom \"random.SystemRandom\") for additional details.\n\nsecrets.choice( _seq_) [¶](https://docs.python.org/3/library/secrets.html#secrets.choice \"Link to this definition\")\n\nReturn a randomly chosen element from a non-empty sequence.\n\nsecrets.randbelow( _exclusive\\_upper\\_bound_) [¶](https://docs.python.org/3/library/secrets.html#secrets.randbelow \"Link to this definition\")\n\nReturn a random int in the range \\[0, _exclusive\\_upper\\_bound_).\\\n\\\nsecrets.randbits( _k_) [¶](https://docs.python.org/3/library/secrets.html#secrets.randbits \"Link to this definition\")\\\n\\\nReturn a non-negative int with _k_ random bits.\\\n\\\n## Generating tokens [¶](https://docs.python.org/3/library/secrets.html\\#generating-tokens \"Link to this heading\")\\\n\\\nThe `secrets` module provides functions for generating secure\\\ntokens, suitable for applications such as password resets,\\\nhard-to-guess URLs, and similar.\\\n\\\nsecrets.token\\_bytes( _nbytes=None_) [¶](https://docs.python.org/3/library/secrets.html#secrets.token_bytes \"Link to this definition\")\\\n\\\nReturn a random byte string containing _nbytes_ number of bytes.\\\n\\\nIf _nbytes_ is not specified or `None`, [`DEFAULT_ENTROPY`](https://docs.python.org/3/library/secrets.html#secrets.DEFAULT_ENTROPY \"secrets.DEFAULT_ENTROPY\")\\\nis used instead.\\\n\\\nCopy\\\n\\\n```\\\n>>> token_bytes(16)\\\nb'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'\\\n```\\\n\\\nsecrets.token\\_hex( _nbytes=None_) [¶](https://docs.python.org/3/library/secrets.html#secrets.token_hex \"Link to this definition\")\\\n\\\nReturn a random text string, in hexadecimal. The string has _nbytes_\\\nrandom bytes, each byte converted to two hex digits.\\\n\\\nIf _nbytes_ is not specified or `None`, [`DEFAULT_ENTROPY`](https://docs.python.org/3/library/secrets.html#secrets.DEFAULT_ENTROPY \"secrets.DEFAULT_ENTROPY\")\\\nis used instead.\\\n\\\nCopy\\\n\\\n```\\\n>>> token_hex(16)\\\n'f9bf78b9a18ce6d46a0cd2b0b86df9da'\\\n```\\\n\\\nsecrets.token\\_urlsafe( _nbytes=None_) [¶](https://docs.python.org/3/library/secrets.html#secrets.token_urlsafe \"Link to this definition\")\\\n\\\nReturn a random URL-safe text string, containing _nbytes_ random\\\nbytes. The text is Base64 encoded, so on average each byte results\\\nin approximately 1.3 characters.\\\n\\\nIf _nbytes_ is not specified or `None`, [`DEFAULT_ENTROPY`](https://docs.python.org/3/library/secrets.html#secrets.DEFAULT_ENTROPY \"secrets.DEFAULT_ENTROPY\")\\\nis used instead.\\\n\\\nCopy\\\n\\\n```\\\n>>> token_urlsafe(16)\\\n'Drmhze6EPcv0fN_81Bj-nA'\\\n```\\\n\\\n### How many bytes should tokens use? [¶](https://docs.python.org/3/library/secrets.html\\#how-many-bytes-should-tokens-use \"Link to this heading\")\\\n\\\nTo be secure against\\\n[brute-force attacks](https://en.wikipedia.org/wiki/Brute-force_attack),\\\ntokens need to have sufficient randomness. Unfortunately, what is\\\nconsidered sufficient will necessarily increase as computers get more\\\npowerful and able to make more guesses in a shorter period. As of 2015,\\\nit is believed that 32 bytes (256 bits) of randomness is sufficient for\\\nthe typical use-case expected for the `secrets` module.\\\n\\\nFor those who want to manage their own token length, you can explicitly\\\nspecify how much randomness is used for tokens by giving an [`int`](https://docs.python.org/3/builtins/functions.html#int \"int\")\\\nargument to the various `token_*` functions. That argument is taken\\\nas the number of bytes of randomness to use.\\\n\\\nOtherwise, if no argument is provided, or if the argument is `None`,\\\nthe `token_*` functions use [`DEFAULT_ENTROPY`](https://docs.python.org/3/library/secrets.html#secrets.DEFAULT_ENTROPY \"secrets.DEFAULT_ENTROPY\") instead.\\\n\\\nsecrets.DEFAULT\\_ENTROPY [¶](https://docs.python.org/3/library/secrets.html#secrets.DEFAULT_ENTROPY \"Link to this definition\")\\\n\\\nDefault number of bytes of randomness used by the `token_*` functions.\\\n\\\nThe exact value is subject to change at any time, including during\\\nmaintenance releases.\\\n\\\n## Other functions [¶](https://docs.python.org/3/library/secrets.html\\#other-functions \"Link to this heading\")\\\n\\\nsecrets.compare\\_digest( _a_, _b_) [¶](https://docs.python.org/3/library/secrets.html#secrets.compare_digest \"Link to this definition\")\\\n\\\nReturn `True` if strings or\\\n[bytes-like objects](https://docs.python.org/3/glossary.html#term-bytes-like-object) _a_ and _b_ are equal, otherwise `False`,\\\nusing a “constant-time compare” to reduce the risk of\\\n[timing attacks](https://web.archive.org/web/20250815071532/https://codahale.com/a-lesson-in-timing-attacks/).\\\nSee [`hmac.compare_digest()`](https://docs.python.org/3/library/hmac.html#hmac.compare_digest \"hmac.compare_digest\") for additional details.\\\n\\\n## Recipes and best practices [¶](https://docs.python.org/3/library/secrets.html\\#recipes-and-best-practices \"Link to this heading\")\\\n\\\nThis section shows recipes and best practices for using `secrets`\\\nto manage a basic level of security.\\\n\\\nGenerate an eight-character alphanumeric password:\\\n\\\nCopy\\\n\\\n```\\\nimport string\\\nimport secrets\\\nalphabet = string.ascii_letters + string.digits\\\npassword = ''.join(secrets.choice(alphabet) for i in range(8))\\\n```\\\n\\\nNote\\\n\\\nApplications should not\\\n[**store passwords in a recoverable format**](https://cwe.mitre.org/data/definitions/257.html),\\\nwhether plain text or encrypted. They should be salted and hashed\\\nusing a cryptographically strong one-way (irreversible) hash function.\\\n\\\nGenerate a ten-character alphanumeric password with at least one\\\nlowercase character, at least one uppercase character, and at least\\\nthree digits:\\\n\\\nCopy\\\n\\\n```\\\nimport string\\\nimport secrets\\\nalphabet = string.ascii_letters + string.digits\\\nwhile True:\\\n    password = ''.join(secrets.choice(alphabet) for i in range(10))\\\n    if (any(c.islower() for c in password)\\\n            and any(c.isupper() for c in password)\\\n            and sum(c.isdigit() for c in password) >= 3):\\\n        break\\\n```\\\n\\\nGenerate an [XKCD-style passphrase](https://xkcd.com/936/):\\\n\\\nCopy\\\n\\\n```\\\nimport secrets\\\n# On standard Linux systems, use a convenient dictionary file.\\\n# Other platforms may need to provide their own word-list.\\\nwith open('/usr/share/dict/words') as f:\\\n    words = [word.strip() for word in f]\\\n    password = ' '.join(secrets.choice(words) for i in range(4))\\\n```\\\n\\\nGenerate a hard-to-guess temporary URL containing a security token\\\nsuitable for password recovery applications:\\\n\\\nCopy\\\n\\\n```\\\nimport secrets\\\nurl = 'https://example.com/reset=' + secrets.token_urlsafe()\\\n```\\\n\\\n### [Table of Contents](https://docs.python.org/3/contents.html)\\\n\\\n- [`secrets` — Generate secure random numbers for managing secrets](https://docs.python.org/3/library/secrets.html#)\\\n  - [Random numbers](https://docs.python.org/3/library/secrets.html#random-numbers)\\\n  - [Generating tokens](https://docs.python.org/3/library/secrets.html#generating-tokens)\\\n    - [How many bytes should tokens use?](https://docs.python.org/3/library/secrets.html#how-many-bytes-should-tokens-use)\\\n  - [Other functions](https://docs.python.org/3/library/secrets.html#other-functions)\\\n  - [Recipes and best practices](https://docs.python.org/3/library/secrets.html#recipes-and-best-practices)\\\n\\\n#### Previous topic\\\n\\\n[`hmac` — Keyed-Hashing for Message Authentication](https://docs.python.org/3/library/hmac.html \"previous chapter\")\\\n\\\n#### Next topic\\\n\\\n[Generic Operating System Services](https://docs.python.org/3/library/allos.html \"next chapter\")\\\n\\\n### This page\\\n\\\n- [Report a bug](https://docs.python.org/3/bugs.html)\\\n- [Improve this page](https://docs.python.org/3/improve-page.html?pagetitle=secrets+%E2%80%94+Generate+secure+random+numbers+for+managing+secrets&pageurl=https%3A%2F%2Fdocs.python.org%2F3%2Flibrary%2Fsecrets.html&pagesource=library%2Fsecrets.rst)\\\n- [Show source](https://github.com/python/cpython/blob/3.15/Doc/library/secrets.rst?plain=1)\\\n\\\n«\\\n\\\n### Navigation\\\n\\\n- [index](https://docs.python.org/3/genindex.html \"General Index\")\\\n- [modules](https://docs.python.org/3/py-modindex.html \"Python Module Index\") \\|\\\n- [next](https://docs.python.org/3/library/allos.html \"Generic Operating System Services\") \\|\\\n- [previous](https://docs.python.org/3/library/hmac.html \"hmac — Keyed-Hashing for Message Authentication\") \\|\\\n- ![Python logo](https://docs.python.org/3/_static/py.svg)\\\n- [Python](https://www.python.org/) »\\\n- German \\| DeutschGreek \\| ΕλληνικάEnglishSpanish \\| españolPersian \\| فارسیFrench \\| françaisItalian \\| italianoJapanese \\| 日本語Korean \\| 한국어Punjabi \\| ਪੰਜਾਬੀPolish \\| polskiBrazilian Portuguese \\| Português brasileiroRomanian \\| RomâneșteRussian \\| РусскийTurkish \\| TürkçeSimplified Chinese \\| 简体中文Traditional Chinese \\| 繁體中文\\\n\\\ndev (3.16)3.15.23.143.133.123.113.103.93.83.73.63.53.43.33.23.13.02.72.6\\\n\\\n- [3.15.2 documentation](https://docs.python.org/3/index.html) »\\\n\\\n- [The Python standard library](https://docs.python.org/3/library/index.html) »\\\n- [Cryptographic Services](https://docs.python.org/3/library/crypto.html) »\\\n- [`secrets` — Generate secure random numbers for managing secrets](https://docs.python.org/3/library/secrets.html)\\\n- \\|\\\n\\\n- Theme\\\nAutoLightDark \\|"}
{"source": "firecrawl_search", "query": "Python hashlib scrypt secrets.token_urlsafe hmac.compare_digest", "source_url": "https://github.com/djeada/Backend-Engineers-Guide/blob/main/scripts/security/hashing_example.py", "license": "web_reference", "markdown": "[Skip to content](https://github.com/djeada/Backend-Engineers-Guide/blob/main/scripts/security/hashing_example.py#start-of-content)"}
{"source": "firecrawl_search", "query": "Python hashlib scrypt secrets.token_urlsafe hmac.compare_digest", "source_url": "https://realpython.com/cheatsheets/python-security/", "license": "web_reference", "markdown": "# Python Security Checklist [Permanent link](https://realpython.com/cheatsheets/python-security/\\#python-security-checklist \"Permanent link\")\n\nThis page contains a condensed checklist for writing secure Python code. It covers keeping secrets out of your code, hashing passwords, encrypting data with Fernet, using HTTPS with certificate verification, validating user input, avoiding injection attacks, and auditing your dependencies.\nYou can also download the information as a printable checklist:\n\nFree Bonus: **Python Security Checklist**\n\nGet a **Python Security Checklist (PDF)** and keep secrets, passwords, encryption, HTTPS, input validation, and dependency audits on one printable page:\n\n![Python Security Checklist](https://files.realpython.com/media/python-security-cheat-sheet-stacked.63d4867f8e75.png)\n\nSend My Python Security Checklist »\n\nPractice with hands-on [coding exercises](https://realpython.com/search?kind=exercise), [quizzes](https://realpython.com/search?kind=quiz), and guided [learning paths](https://realpython.com/learning-paths/). Not sure where to begin? [Start here](https://realpython.com/start-here/).\n\nNew to Python security?\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Help me figure out where to start\n\n## Keep Secrets Out of Code [Permanent link](https://realpython.com/cheatsheets/python-security/\\#keep-secrets-out-of-code \"Permanent link\")\n\n- Never hardcode keys, passwords, or tokens\n- Add `.env` to `.gitignore` before the first commit\n- A leaked key stays in Git history: rotate it\n\nLanguage: PythonFilename: `Read Secrets From the Environment`\n\n```\nimport os\n\nAPI_KEY = os.environ[\"API_KEY\"]  # Fail fast\nDEBUG = os.getenv(\"DEBUG\", \"0\") == \"1\"\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: ShellFilename: ``Load a Local `.env` File``\n\n```\n$ python -m pip install python-dotenv\n$ echo \"API_KEY=sk-test-123\" >> .env\n$ echo \".env\" >> .gitignore\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: Python\n\n```\nfrom dotenv import load_dotenv\nload_dotenv()  # Fills os.environ from .env\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: ``Generate Tokens With `secrets```\n\n```\nimport secrets\ntoken = secrets.token_urlsafe(32)  # Links\ncode = secrets.randbelow(10**6)    # OTPs\n# Constant-time comparison:\nok = secrets.compare_digest(sent, token)\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nWant to go deeper on managing secrets?\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Show me where to learn more about secrets\n\n## Hash Passwords [Permanent link](https://realpython.com/cheatsheets/python-security/\\#hash-passwords \"Permanent link\")\n\n- Store a slow, salted hash, never the password\n- Never use `random`, MD5, or plain SHA-256 here\n- In production, prefer `argon2-cffi` or `bcrypt`\n\nLanguage: PythonFilename: `Hash With a Random Salt`\n\n```\nimport hashlib, hmac, os\n\ndef hash_password(pw):\n    salt = os.urandom(16)\n    digest = hashlib.scrypt(\n        pw.encode(), salt=salt,\n        n=2**14, r=8, p=1,\n    )\n    return salt + digest\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: `Verify in Constant Time`\n\n```\ndef check_password(pw, stored):\n    salt, digest = stored[:16], stored[16:]\n    new = hashlib.scrypt(\n        pw.encode(), salt=salt,\n        n=2**14, r=8, p=1,\n    )\n    return hmac.compare_digest(new, digest)\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nWhy not just SHA-256?\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Show me why the salt and scrypt matter\n\n## Encrypt Data With Fernet [Permanent link](https://realpython.com/cheatsheets/python-security/\\#encrypt-data-with-fernet \"Permanent link\")\n\n- Fernet is symmetric: the same key encrypts and decrypts\n- Keep the key in a secret store or env var, not in code\n- Tampered or wrong-key tokens raise `InvalidToken`\n\nLanguage: PythonFilename: `Generate a Key and Encrypt`\n\n```\n>>> from cryptography.fernet import Fernet\n>>> key = Fernet.generate_key()  # Save it!\n>>> f = Fernet(key)\n>>> token = f.encrypt(b\"card 4242\")\n>>> f.decrypt(token)\nb'card 4242'\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: `Reject Stale or Forged Tokens`\n\n```\nfrom cryptography.fernet import InvalidToken\n\ntry:\n    data = f.decrypt(token, ttl=3600)\nexcept InvalidToken:\n    data = None  # Expired or tampered\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nStill fuzzy on hashing versus encryption?\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Explain hashing versus encryption another way\n\n## Use HTTPS and Verify Certificates [Permanent link](https://realpython.com/cheatsheets/python-security/\\#use-https-and-verify-certificates \"Permanent link\")\n\n- Always call `https://` URLs for anything sensitive\n- `requests` verifies certificates by default: keep it on\n- Always set a `timeout` so a slow host can’t hang you\n\nLanguage: PythonFilename: `Make a Verified Request`\n\n```\nimport requests\n\nurl = \"https://api.example.com/data\"\nresp = requests.get(url, timeout=5)\nresp.raise_for_status()\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: ``Trust a Private CA, Never `verify=False```\n\n```\nrequests.get(url, verify=\"ca.pem\", timeout=5)\nrequests.get(url, verify=False)  # ❌ MITM\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: `Handle Certificate Errors`\n\n```\ntry:\n    requests.get(url, timeout=5)\nexcept requests.exceptions.SSLError:\n    ...  # Bad or expired cert: don't retry\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: ``Secure Sockets With `ssl```\n\n```\nimport ssl\nctx = ssl.create_default_context()\nctx.check_hostname  # True\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nThink you’ve got HTTPS down?\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Quiz me on HTTPS and certificates\n\n**Free Bonus:** [Download the Python Security Checklist PDF](https://realpython.com/bonus/python-security-cheat-sheet-inline/) and keep the essentials at hand.\n\n## Validate User Input [Permanent link](https://realpython.com/cheatsheets/python-security/\\#validate-user-input \"Permanent link\")\n\n- Treat all input as hostile: forms, files, URLs, env\n- Allowlist what’s valid instead of blocklisting bad\n- Escape output for its context (HTML, SQL, shell)\n\nLanguage: PythonFilename: ``Allowlist With `fullmatch()```\n\n```\n>>> import re\n>>> USER = re.compile(r\"[a-z0-9_]{3,20}\")\n>>> bool(USER.fullmatch(\"ann_42\"))\nTrue\n>>> bool(USER.fullmatch(\"ann; DROP\"))\nFalse\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: `Convert and Range-Check`\n\n```\ndef parse_age(text):\n    age = int(text)  # ValueError if not int\n    if not 0 <= age <= 130:\n        raise ValueError(\"age out of range\")\n    return age\n```\n\n![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)\n\n- ###### ![](https://realpython.com/static/mentor/maia.f5d7e1f0f56c.svg)Ask Mentor AI\n\n- Pick a question and Mentor AI answers it with this code block in front of it.\n- Explain this\n\n- Why is it written this way?\n\n- Walk me through it line by line\n\n- Quiz me on this\n\n- Give me a practice exercise\n\n- * * *\n\n- Ask something else…\n\n\nLanguage: PythonFilename: `Block Path Traversal`\n\n```\nfrom pathlib import Path\nBASE = Path(\"/srv/uploads\").resolve()\npath = (BASE / name).resolve()\nif not path.is_relative_to(BASE):\n    raise ValueError(\"path escapes base\")\n```"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/13793399/passing-table-name-as-a-parameter-in-psycopg2", "license": "CC BY-SA 4.0", "markdown": "# Passing table name as a parameter in psycopg2\n\nI have the following code, using pscyopg2:\r\n\r\n    sql = 'select %s from %s where utctime > %s and utctime < %s order by utctime asc;'\r\n    data = (dataItems, voyage, dateRangeLower, dateRangeUpper)\r\n    rows = cur.mogrify(sql, data)\r\n\r\nThis outputs:\r\n\r\n    select 'waterTemp, airTemp, utctime' from 'ss2012_t02' where utctime > '2012-05-03T17:01:35+00:00'::timestamptz and utctime < '2012-05-01T17:01:35+00:00'::timestamptz order by utctime asc;\r\n\r\n\r\nWhen I execute this, it falls over - this is understandable, as the quotes around the table name are illegal.\r\n\r\nIs there a way to legally pass the table name as a parameter, or do I need to do a (explicitly warned against) string concatenation, ie:\r\n\r\n    voyage = 'ss2012_t02'\r\n    sql = 'select %s from ' + voyage + ' where utctime > %s and utctime < %s order by utctime asc;'\r\n\r\nCheers for any insights.\n\n## Accepted Answer\n\nAccording to the official documentation:\r\n\r\n> If you need to generate dynamically an SQL query (**for instance\r\n> choosing dynamically a table name**) you can use the facilities\r\n> provided by the psycopg2.sql module.\r\n\r\nThe `sql` module is new in psycopg2 version 2.7. It has the following syntax:\r\n\r\n    from psycopg2 import sql\r\n    \r\n    cur.execute(\r\n        sql.SQL(\"insert into {table} values (%s, %s)\")\r\n            .format(table=sql.Identifier('my_table')),\r\n        [10, 20])\r\n\r\nMore on: https://www.psycopg.org/docs/sql.html#module-usage\r\n\r\n[Update 2017-03-24: `AsIs` should NOT be used to represent table or fields names, the new `sql` module should be used instead: https://stackoverflow.com/a/42980069/5285608 ]\r\n\r\nAlso, according to psycopg2 documentation:\r\n\r\n> **Warning**: Never, **never**, **NEVER** use Python string concatenation (`+`) or string parameters interpolation (`%`) to pass variables to a SQL query string. Not even at gunpoint."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/7929364/python-best-practice-and-securest-way-to-connect-to-mysql-and-execute-queries", "license": "CC BY-SA 4.0", "markdown": "# Python: best practice and securest way to connect to MySQL and execute queries\n\nWhat is the safest way to run queries on MySQL? I am aware of the dangers involved with MySQL and SQL injection.\r\n\r\nHowever, I do not know how I should run my queries to prevent injection on the variables to which other users (webclients) can manipulate. I used to write my own escape function, but apparently this is \"not-done\".\r\n\r\nWhat should I use and how should I use it to query and do inserts safely on a MySQL database through python without risking MySQL injection?\n\n## Accepted Answer\n\nTo avoid injections, use `execute` with `%s` in place of each variable, then pass the value via a list or tuple as the second parameter of `execute`. Here is an [example from the documentation][1]:\r\n\r\n    c=db.cursor()\r\n    max_price=5\r\n    c.execute(\"\"\"SELECT spam, eggs, sausage FROM breakfast\r\n              WHERE price < %s\"\"\", (max_price,))\r\n\r\nNote that this is using a **comma**, not **%** (which would be a direct string substitution, not escaped). **Don't do this**:\r\n\r\n    c.execute(\"\"\"SELECT spam, eggs, sausage FROM breakfast\r\n              WHERE price < %s\"\"\" % (max_price,))\r\n\r\nIn addition, you must not use single quotes around the position holder (`'%s'`) if the parameter is a string as the driver provides these.\r\n\r\n  [1]: http://mysql-python.sourceforge.net/MySQLdb.html#some-examples"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/897020/a-good-way-to-escape-quotes-in-a-database-query-string", "license": "CC BY-SA 4.0", "markdown": "# A good way to escape quotes in a database query string?\n\nI've tried all manner of Python modules and they either escape too much or in the wrong way.\r\nWhat's the best way you've found to escape quotes (\", ') in Python?\n\n## Accepted Answer\n\nIf it's part of a Database query you should be able to use a [Parameterized SQL Statement][1].\r\n\r\nAs well as escaping your quotes, this will deal with all special characters and will protect you from [SQL injection attacks][2].\r\n\r\n\r\n  [1]: https://web.archive.org/web/20100813151305/http://python.projects.postgresql.org/docs/0.8/driver.html\r\n  [2]: https://stackoverflow.com/questions/681583/sql-injection-on-insert"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/36367555/confusion-between-prepared-statement-and-parameterized-query-in-python", "license": "CC BY-SA 4.0", "markdown": "# Confusion between prepared statement and parameterized query in Python\n\nAs far as I understand, prepared statements are (mainly) a database feature that allows you to separate parameters from the code that uses such parameters. Example:\r\n\r\n    PREPARE fooplan (int, text, bool, numeric) AS\r\n        INSERT INTO foo VALUES($1, $2, $3, $4);\r\n    EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);\r\n\r\nA parameterized query substitutes the manual string interpolation, so instead of doing\r\n\r\n    cursor.execute(\"SELECT FROM tablename WHERE fieldname = %s\" % value)\r\n\r\nwe can do\r\n\r\n    cursor.execute(\"SELECT FROM tablename WHERE fieldname = %s\", [value])\r\n\r\nNow, it seems that prepared statements are, for the most part, used in the database language and parameterized queries are mainly used in the programming language connecting to the database, although I have seen exceptions to this rule.\r\n\r\nThe problem is that asking about the difference between prepared statement and parameterized query brings a lot of confusion. Their purpose is admittedly the same, but their methodology seems distinct. Yet, there are [sources](http://www.programmerinterview.com/index.php/database-sql/parameterized-queries-vs-prepared-statements/) indicating that both are the same. MySQLdb and Psycopg2 seem to support parameterized queries but don’t support prepared statements (e.g. [here](https://stackoverflow.com/a/17237567/460147) for MySQLdb and in the [TODO list for postgres drivers](https://wiki.postgresql.org/wiki/Python_PostgreSQL_Driver_TODO) or [this answer](https://groups.google.com/d/msg/sqlalchemy/LN0evK1hyOM/78nvIwtT7GgJ) in the sqlalchemy group). Actually, there is a [gist](https://gist.github.com/dvarrazzo/3797445) implementing a psycopg2 cursor supporting prepared statements and a minimal [explanation](https://stackoverflow.com/questions/9866350/prepared-statements-using-psycopg) about it. There is also a [suggestion](http://initd.org/psycopg/articles/2012/10/01/prepared-statements-psycopg/) of subclassing the cursor object in psycopg2 to provide the prepared statement manually.\r\n\r\nI would like to get an authoritative answer to the following questions:\r\n\r\n- Is there a meaningful difference between prepared statement and parameterized query? Does this matter in practice? If you use parameterized queries, do you need to worry about prepared statements?\r\n\r\n- If there is a difference, what is the current status of prepared statements in the Python ecosystem? Which database adapters support prepared statements?\n\n## Accepted Answer\n\n* Prepared statement: A reference to a pre-interpreted query routine on the database, ready to accept parameters\n\n* Parametrized query: A query made by your code in such a way that you are passing values in *alongside* some SQL that has placeholder values, usually `?` or `%s` or something of that flavor.\n\nThe confusion here seems to stem from the (apparent) lack of distinction between the ability to directly get a prepared statement object and the ability to pass values into a 'parametrized query' method that acts very much like one... because it is one, or at least makes one for you.\n\nFor example: the C interface of the SQLite3 library has a lot of tools for working with [prepared statement objects](https://www.sqlite.org/c3ref/stmt.html), but the [Python api](https://docs.python.org/3/library/sqlite3.html) makes almost no mention of them. You can't prepare a statement and use it multiple times whenever you want. Instead, you can use `sqlite3.executemany(sql, params)` which takes the SQL code, creates a prepared statement *internally*, then uses that statement in a loop to process each of your parameter tuples in the iterable you gave.\n\nMany other SQL libraries in Python behave the same way. Working with prepared statement objects can be a real pain, and can lead to ambiguity, and in a language like Python which has such a lean towards clarity and ease over raw execution speed they aren't really the greatest option. Essentially, if you find yourself having to make hundreds of thousands or millions of calls to a complex SQL query that gets re-interpreted every time, you should probably be doing things differently. Regardless, sometimes people wish they could have direct access to these objects because if you keep the same prepared statement around the database server won't have to keep interpreting the same SQL code over and over; most of the time this will be approaching the problem from the wrong direction and you will get much greater savings elsewhere or by restructuring your code.*\n\nPerhaps more importantly in general is the way that prepared statements and parametrized queries keep your data sanitary and separate from your SQL code. **This is vastly preferable to string formatting!** You should think of parametrized queries and prepared statements, in one form or another, as **the only way to pass variable data from your application into the database**. If you try to build the SQL statement otherwise, it will not only run significantly slower but you will be vulnerable to [other problems](https://xkcd.com/327/).\n\n*\\*e.g., by producing the data that is to be fed into the DB in a generator function then using `executemany()` to insert it all at once from the generator, rather than calling `execute()` each time you loop.*\n\n## tl;dr\n**A parametrized query is a single operation which generates a prepared statement internally, then passes in your parameters and executes.**\n\n*edit:* A lot of people see this answer! I want to also clarify that many database engines also have concepts of a prepared statement that can be constructed explicitly with plaintext query syntax, then reused over the lifetime of a client's session (in [postgres](https://www.postgresql.org/docs/current/sql-prepare.html) for example). Sometimes you have control over whether the query plan is cached to save even more time. Some frameworks use these automatically (I've seen rails' ORM do it aggressively), sometimes usefully and sometimes to their detriment when there are permutations of form for the queries being prepared.\n\nAlso if you want to nit pick, parametrized queries do not *always* use a prepared statement under the hood; they should do so if possible, but sometimes it's just formatting in the parameter values. The real difference between 'prepared statement' and 'parametrized query' here is really just the shape of the API you use."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/31949733/is-a-sqlalchemy-query-vulnerable-to-injection-attacks", "license": "CC BY-SA 3.0", "markdown": "# Is a SQLAlchemy query vulnerable to injection attacks?\n\nI have the following query that uses `like` to search a blog.  I am not sure if I'm making myself vulnerable to a SQL injection attack if I do this.  How is SQLAlchemy handling this?  Is it safe?\r\n\r\n    search_results = Blog.query.with_entities(Blog.blog_title).filter(Blog.blog_title.like(\"%\"+ searchQuery['queryText'] +\"%\")).all()\n\n## Accepted Answer\n\nThe underlying db-api library for whatever database you're using (sqlite3, psycopg2, etc.) escapes parameters.  SQLAlchemy simply passes the statement and parameters to [`execute`](https://www.python.org/dev/peps/pep-0249/#id15), the driver does whatever is needed.  Assuming you are not writing raw SQL that includes parameters yourself, you are not vulnerable to injection.  Your example is not vulnerable to injection."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/13574043/how-do-django-forms-sanitize-text-input-to-prevent-sql-injection-xss-etc", "license": "CC BY-SA 3.0", "markdown": "# How do Django forms sanitize text input to prevent SQL injection, XSS, etc?\n\nI don't see any form input sanitization in Django's form code w/r/t handling raw text. How does Django ensure that user input is sanitized when going into the database? Does it do this at all to prevent SQL injection, etc?\n\n## Accepted Answer\n\nUser input is sanitized by the database driver automatically.\r\n\r\nExplicit user input sanitization is only ever required when you are trying to assemble a single string that contains both the SQL commands and also the data that you are trying to include; proper use of the Python DBAPI fully separates the commands and the data and you as a programmer should never have to worry about SQL injection as long as you use that functionality properly.  And Django uses that functionality by default, so you doubly don't have to worry about it.\r\n\r\n\r\nEdit: XSS is a separate issue; see @renab's comment and also https://docs.djangoproject.com/en/dev/topics/security/#cross-site-scripting-xss-protection"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/46770201/compose-dynamic-sql-string-with-psycopg2", "license": "CC BY-SA 4.0", "markdown": "# Compose dynamic SQL string with psycopg2\n\nI use `psycopg2` in python (2.7.10) to connect to a postgresql DB. The docs are pretty clear about composition of dynamic SQL statements:\r\n\r\n> Never, **never, NEVER** use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.\r\n\r\nIn `psycopg2` version 2.7 there's the new `sql` module to do this string composition in a way that's safe against SQL injection. I nevertheless don't understand how to properly construct a statement like:\r\n\r\n    import psycopg2 as ps\r\n    \r\n    C = psycopg.connect(host='my_host', port=Port, database='My_DB')\r\n    cur = C.cursor()\r\n    schema = 'some_schema'\r\n    table = 'some_table'\r\n    SQL = cur.execute(\"SELECT * FROM \"+schema+\".\"+table+\";\") # This is horribly wrong\r\n    SQL = cur.execute(\"SELECT * FROM some_schema.some_table;\") # That's what the result should be\r\n\r\n\n\n## Accepted Answer\n\nYou can use [`psycopg2.sql.Identifier`][1] to interpolate an identifier to a query, e.g.:\r\n\r\n    from psycopg2.sql import Identifier, SQL\r\n\r\n    query = SQL('SELECT * FROM {}.{}').format(*map(Identifier, (schema, table)))\r\n    print(query.as_string(conn))\r\n    cur.execute(query)\r\n\r\nAs per the linked documentation page, in `psycopg2` v2.8+ you can also pass multiple strings to `Identifier` to represent a qualified name, i.e. a dot-separated sequence of identifiers:\r\n\r\n    query = SQL('SELECT * FROM {}').format(Identifier(schema, table))\r\n\r\n  [1]: http://initd.org/psycopg/docs/sql.html#psycopg2.sql.Identifier"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/27402426/detect-sql-injections-in-the-source-code", "license": "CC BY-SA 3.0", "markdown": "# Detect SQL injections in the source code\n\nConsider the following code snippet:\r\n\r\n    import MySQLdb\r\n    \r\n    def get_data(id):\r\n        db = MySQLdb.connect(db='TEST')\r\n        cursor = db.cursor()\r\n        cursor.execute(\"SELECT * FROM TEST WHERE ID = '%s'\" % id)\r\n    \r\n        return cursor.fetchall()\r\n    \r\n    print(get_data(1))\r\n\r\nThere is a major problem in the code - it is *vulnerable to SQL injections attacks* since the query is not parameterized through DB API and is constructed via string formatting. If you call the function this way:\r\n\r\n    get_data(\"'; DROP TABLE TEST -- \")\r\n\r\nthe following query would be executed:\r\n\r\n    SELECT * FROM TEST WHERE ID = ''; DROP TABLE TEST --  \r\n\r\nNow, my goal is to analyze the code in the project and detect all places potentially vulnerable to SQL injections. In other words, where the query is constructed via string formatting as opposed to passing query parameters in a separate argument. \r\n\r\nIs it something that can be solved statically, with the help of `pylint`, `pyflakes` or any other static code analysis packages?\r\n \r\n\r\n\r\n----------\r\n\r\nI'm aware of [`sqlmap`][1] popular penetration testing tool, but, as far as I understand, it is working against a web resource, testing it as a black-box through HTTP requests.\r\n\r\n\r\n  [1]: https://github.com/sqlmapproject/sqlmap\n\n## Accepted Answer\n\nThere is a tool that tries to solve exactly what the question is about, [`py-find-injection`][1]:\r\n\r\n> py_find_injection uses various heuristics to look for SQL injection\r\n> vulnerabilities in python source code.\r\n\r\nIt uses [`ast` module][2], looks for `session.execute()` and `cursor.execute()` calls, and checks whether the query inside is formed via [string interpolation, concatenation or `format()`][3].\r\n\r\nHere is what it outputs while checking the snippet in the question:\r\n\r\n    $ py-find-injection test.py\r\n    test.py:6\tstring interpolation of SQL query\r\n    1 total errors\r\n\r\nThe project, though, is *not actively maintained*, but could be used as a starting point. A good idea would be to make a `pylint` or `pyflakes` plugin out of it.\r\n\r\n\r\n  [1]: https://pypi.python.org/pypi/py-find-injection\r\n  [2]: https://docs.python.org/2/library/ast.html\r\n  [3]: https://github.com/uber/py-find-injection/blob/master/py_find_injection/__init__.py#L62-L76"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/48870227/is-sql-injection-protection-built-into-sqlalchemys-orm-or-core", "license": "CC BY-SA 3.0", "markdown": "# Is SQL injection protection built into SQLAlchemy's ORM or Core?\n\nI'm developing an [aiohttp server](https://aiohttp.readthedocs.io/en/stable/web.html) application, and I just saw that [apparently it isn't able to use SQLAlchemy's ORM layer](https://stackoverflow.com/a/32573490/5433896). So, I was wondering: if my application will only be able to use SQLAlchemy's core, is it still protected against SQL injection attacks?\r\n\r\nMy code is the following:\r\n\r\n    async def add_sensor(db_engine, name):\r\n        async with db_engine.acquire() as connection:\r\n            query = model.Sensor.__table__.insert().values(name=name)\r\n            await connection.execute(query)\r\n\r\nA comment on the accepted answer in [this related question](https://stackoverflow.com/questions/6501583/sqlalchemy-sql-injection) makes me doubt:\r\n\r\n> you can still use execute() or other literal data that will NOT be\r\n> escaped by SQLAlchemy.\r\n\r\nSo, with the `execute()` used in my code, does the above quote mean that my code is unsafe? And in general: is protection against SQL Injection only possible with the SQLAlchemy ORM layer, as with the Core layer you'll end up launching `execute()`?\n\n## Accepted Answer\n\nin your example above i dont see any variable beeing supplied to the database query. Since there is no user supplied input there is also no Sql Injection possible.\r\n\r\nEven if there would be a user supplied value as long as you dont use handwritten sql statements with sqlalchemy and instead use the orm model approach (`model.Sensor.__table__.select()`) as can be seen in your example you are secure against Sql Injection.\r\n\r\nIn the end its all about telling sqlalchemy explicitely what columns and tables should be used to select and insert data from/to and keeping that separate from the data that is beeing inserted or selected. Never combine the data string with the query string and always use sqlalchemy orm model objects to describe your query.\r\n\r\nBad way (Sql Injectable):\r\n\r\n    Session.execute(\"select * form users where name = %s\" % request.GET['name'])\r\n\r\nGood way (Not Sql Injectable):\r\n\r\n    Session.execute(model.users.__table__.select().where(model.users.name == request.GET['name']))"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+sql-injection", "source_url": "https://stackoverflow.com/questions/24481362/does-sqlalchemy-sanitize-raw-sql", "license": "CC BY-SA 3.0", "markdown": "# Does SQLAlchemy sanitize raw SQL?\n\nSimply put. If i did something like \r\n\r\n    Conn.execute(RAW_SQL) \r\n\r\n would sqlalchemy sanitize this to prevent sql injection or does it literally just execute it?\r\nThanks\n\n## Accepted Answer\n\nNo, if you pass in raw SQL with values interpolated, SQL Alchemy will **not** sanitise it. It'll just be executed.\r\n\r\nAlways use query parameters, at the very least. \r\n\r\nA string object is passed straight to the underlying database connection implementation; it *does* support query parameters but you'll have to use the parameter style specific to the library that handles the database communication. \r\n\r\nYou can use [`sqlalchemy.sql.expression.text()`](http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.expression.text) to generate SQL with implementation agnostic query parameter syntax. "}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/7382149/whats-the-purpose-of-django-setting-secret-key", "license": "CC BY-SA 3.0", "markdown": "# What's the purpose of Django setting ‘SECRET_KEY’?\n\nI did a few Google searches and checked out the [Django Documentation][1], but I was looking for a more in-depth explanation of this, and why it is required. \r\n\r\nFor example, what could happen if the key was compromised / others knew what it was?\r\n\r\n\r\n  [1]: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n\n## Accepted Answer\n\nIt is used for making hashes.  Look:\r\n\r\n    >grep -Inr SECRET_KEY *\r\n    conf/global_settings.py:255:SECRET_KEY = ''\r\n    conf/project_template/settings.py:61:SECRET_KEY = ''\r\n    contrib/auth/tokens.py:54:        hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +\r\n    contrib/comments/forms.py:86:        info = (content_type, object_pk, timestamp, settings.SECRET_KEY)\r\n    contrib/formtools/utils.py:15:    order, pickles the result with the SECRET_KEY setting, then takes an md5\r\n    contrib/formtools/utils.py:32:    data.append(settings.SECRET_KEY)\r\n    contrib/messages/storage/cookie.py:112:        SECRET_KEY, modified to make it unique for the present purpose.\r\n    contrib/messages/storage/cookie.py:114:        key = 'django.contrib.messages' + settings.SECRET_KEY\r\n    contrib/sessions/backends/base.py:89:        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()\r\n    contrib/sessions/backends/base.py:95:        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:\r\n    contrib/sessions/backends/base.py:134:        # Use settings.SECRET_KEY as added salt.\r\n    contrib/sessions/backends/base.py:143:                       settings.SECRET_KEY)).hexdigest()\r\n    contrib/sessions/models.py:16:        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()\r\n    contrib/sessions/models.py:59:        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:\r\n    core/management/commands/startproject.py:32:        # Create a random SECRET_KEY hash, and put it in the main settings.\r\n    core/management/commands/startproject.py:37:        settings_contents = re.sub(r\"(?<=SECRET_KEY = ')'\", secret_key + \"'\", settings_contents)\r\n    middleware/csrf.py:38:                % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest()\r\n    middleware/csrf.py:41:    return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()\r\n"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/27522626/hash-function-in-python-3-3-returns-different-results-between-sessions", "license": "CC BY-SA 4.0", "markdown": "# hash function in Python 3.3 returns different results between sessions\n\nI've implemented a BloomFilter in python 3.3, and got different results every session. Drilling down this weird behavior got me to the internal hash() function - it returns different hash values for the same string every session.\r\n\r\nExample:\r\n\r\n    >>> hash(\"235\")\r\n    -310569535015251310\r\n\r\n----- opening a new python console -----\r\n\r\n    >>> hash(\"235\")\r\n    -1900164331622581997\r\n\r\nWhy is this happening?\r\nWhy is this useful?\r\n\n\n## Accepted Answer\n\nPython uses a random hash seed to prevent attackers from tar-pitting your application by sending you keys designed to collide. See the [original vulnerability disclosure](http://www.ocert.org/advisories/ocert-2011-003.html). By offsetting the hash with a random seed (set once at startup) attackers can no longer predict what keys will collide.\r\n\r\nYou can set a fixed seed or disable the feature by setting the [`PYTHONHASHSEED` environment variable](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED); the default is `random` but you can set it to a fixed positive integer value, with `0` disabling the feature altogether.\r\n\r\nPython versions 2.7 and 3.2 have the feature disabled by default (use the `-R` switch or set `PYTHONHASHSEED=random` to enable it); it is enabled by default in Python 3.3 and up.\r\n\r\nIf you were relying on the order of keys in a Python set, then don't. Python uses a hash table to implement these types and their order [depends on the insertion and deletion history](https://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary/15479974#15479974) as well as the random hash seed. Note that in Python 3.5 and older, this applies to dictionaries, too.\r\n\r\nAlso see the [`object.__hash__()` special method documentation](https://docs.python.org/3/reference/datamodel.html#object.__hash__):\r\n\r\n> **Note**: By default, the `__hash__()` values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.\r\n>\r\n> This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.\r\n>\r\n> Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).\r\n>\r\n> See also `PYTHONHASHSEED`.\r\n\r\nIf you need a stable hash implementation, you probably want to look at the [`hashlib` module](https://docs.python.org/3/library/hashlib.html); this implements cryptographic hash functions. The [pybloom project uses this approach](https://github.com/jaybaird/python-bloomfilter/blob/master/pybloom/pybloom.py#L54-L98).\r\n\r\nSince the offset consists of a prefix and a suffix (start value and final XORed value, respectively)  you cannot just store the offset, unfortunately. On the plus side, this does mean that attackers cannot easily determine the offset with timing attacks either.    "}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/157938/hiding-a-password-in-a-python-script-insecure-obfuscation-only", "license": "CC BY-SA 4.0", "markdown": "# Hiding a password in a python script (insecure obfuscation only)\n\nI have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection.  \r\n\r\nIs there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? \n\n## Accepted Answer\n\n[Base64 encoding][1] is in the standard library and will do to stop shoulder surfers:\r\n\r\n    >>> import base64\r\n    >>>  print(base64.b64encode(\"password\".encode(\"utf-8\")))\r\n    cGFzc3dvcmQ=\r\n    >>> print(base64.b64decode(\"cGFzc3dvcmQ=\").decode(\"utf-8\"))\r\n    password\r\n\r\n\r\n  [1]: https://docs.python.org/3/library/base64.html"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options", "license": "CC BY-SA 3.0", "markdown": "# I need to securely store a username and password in Python, what are my options?\n\nI'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long time for someone to break it. \r\n\r\nThis script won't have a GUI and will be run periodically by `cron`, so entering a password each time it's run to decrypt things won't really work, and I'll have to store the username and password in either an encrypted file or encrypted in a SQLite database, which would be preferable as I'll be using SQLite anyway, and I _might_ need to edit the password at some point. In addition, I'll probably be wrapping the whole program in an EXE, as it's exclusively for Windows at this point. \r\n\r\nHow can I securely store the username and password combo to be used periodically via a `cron` job?\n\n## Accepted Answer\n\nI recommend a strategy similar to [ssh-agent][1].  If you can't use ssh-agent directly you could implement something like it, so that your password is only kept in RAM.  The cron job could have configured credentials to get the actual password from the agent each time it runs, use it once, and de-reference it immediately using the `del` statement.\r\n\r\nThe administrator still has to enter the password to start ssh-agent, at boot-time or whatever, but this is a reasonable compromise that avoids having a plain-text password stored anywhere on disk.\r\n\r\n\r\n  [1]: http://en.wikipedia.org/wiki/Ssh-agent"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/8529265/google-authenticator-implementation-in-python", "license": "CC BY-SA 3.0", "markdown": "# Google Authenticator implementation in Python\n\nI am trying to use one-time passwords that can be generated using [Google Authenticator application][1].\r\n\r\nWhat Google Authenticator does\r\n------------------------------\r\n\r\nBasically, Google Authenticator implements two types of passwords:\r\n\r\n- **HOTP** - HMAC-based One-Time Password, which means the password is changed with each call, in compliance to [RFC4226][2], and\r\n- **TOTP** - Time-based One-Time Password, which changes for every 30-seconds period (as far as I know).\r\n\r\nGoogle Authenticator is also available as Open Source here: [code.google.com/p/google-authenticator][3]\r\n\r\nCurrent code\r\n------------\r\n\r\nI was looking for existing solutions to generate HOTP and TOTP passwords, but did not find much. The code I have is the following snippet responsible for generating HOTP:\r\n\r\n    import hmac, base64, struct, hashlib, time\r\n    \r\n    def get_token(secret, digest_mode=hashlib.sha1, intervals_no=None):\r\n        if intervals_no == None:\r\n            intervals_no = int(time.time()) // 30\r\n        key = base64.b32decode(secret)\r\n        msg = struct.pack(\">Q\", intervals_no)\r\n        h = hmac.new(key, msg, digest_mode).digest()\r\n        o = ord(h[19]) & 15\r\n        h = (struct.unpack(\">I\", h[o:o+4])[0] & 0x7fffffff) % 1000000\r\n        return h\r\n\r\nThe problem I am facing is that the password I generate using the above code is not the same as generated using Google Authenticator app for Android. Even though I tried multiple `intervals_no` values (exactly first 10000, beginning with `intervals_no = 0`), with `secret` being equal to key provided within the GA app.\r\n\r\nQuestions I have\r\n----------------\r\n\r\nMy questions are:\r\n\r\n1. What am I doing wrong?\r\n2. How can I generate HOTP and/or TOTP in Python?\r\n3. Are there any existing Python libraries for this?\r\n\r\nTo sum up: please give me any clues that will help me implement Google Authenticator authentication within my Python code.\r\n\r\n  [1]: https://market.android.com/details?id=com.google.android.apps.authenticator\r\n  [2]: https://www.rfc-editor.org/rfc/rfc4226\r\n  [3]: http://code.google.com/p/google-authenticator/\n\n## Accepted Answer\n\nI wanted to set a bounty on my question, but I have succeeded in creating solution. My problem seemed to be connected with incorrect value of `secret` key (it must be correct parameter for `base64.b32decode()` function).\r\n\r\nBelow I post full working solution with explanation on how to use it.\r\n\r\nCode\r\n----\r\n\r\nThe following code is enough. I have also uploaded it to GitHub as separate module called _onetimepass_ (available here: [https://github.com/tadeck/onetimepass][1]).\r\n\r\n<!-- language: lang-py -->\r\n\r\n    import hmac, base64, struct, hashlib, time\r\n    \r\n    def get_hotp_token(secret, intervals_no):\r\n        key = base64.b32decode(secret, True)\r\n        msg = struct.pack(\">Q\", intervals_no)\r\n        h = hmac.new(key, msg, hashlib.sha1).digest()\r\n        o = ord(h[19]) & 15\r\n        h = (struct.unpack(\">I\", h[o:o+4])[0] & 0x7fffffff) % 1000000\r\n        return h\r\n    \r\n    def get_totp_token(secret):\r\n        return get_hotp_token(secret, intervals_no=int(time.time())//30)\r\n\r\nIt has two functions:\r\n\r\n- `get_hotp_token()` generates one-time token (that should invalidate after single use),\r\n- `get_totp_token()` generates token based on time (changed in 30-second intervals),\r\n\r\nParameters\r\n----------\r\n\r\nWhen it comes to parameters:\r\n\r\n- `secret` is a secret value known to server (the above script) and client (Google Authenticator, by providing it as password within application),\r\n- `intervals_no` is the number incremeneted after each generation of the token (this should be probably resolved on the server by checking some finite number of integers after last successful one checked in the past)\r\n\r\nHow to use it\r\n-------------\r\n\r\n1. Generate `secret` (it must be correct parameter for `base64.b32decode()`) - preferably 16-char (no `=` signs), as it surely worked for both script and Google Authenticator.\r\n2. Use `get_hotp_token()` if you want one-time passwords invalidated after each use. In Google Authenticator this type of passwords i  mentioned as based on the counter. For checking it on the server you will need to check several values of `intervals_no` (as you have no quarantee that user did not generate the pass between the requests for some reason), but not less than the last working `intervals_no` value (thus you should probably store it somewhere).\r\n3. Use `get_totp_token()`, if you want a token working in 30-second intervals. You have to make sure both systems have correct time set (meaning that they both generate the same Unix timestamp in any given moment in time).\r\n4. Make sure to protect yourself from brute-force attack. If time-based password is used, then trying 1000000 values in less than 30 seconds gives 100% chance of guessing the password. In case of HMAC-based passowrds (HOTPs) it seems to be even worse.\r\n\r\nExample\r\n-------\r\n\r\nWhen using the following code for one-time HMAC-based password:\r\n\r\n<!-- language: lang-py -->\r\n\r\n    secret = 'MZXW633PN5XW6MZX'\r\n    for i in xrange(1, 10):\r\n        print i, get_hotp_token(secret, intervals_no=i)\r\n\r\nyou will get the following result:\r\n\r\n    1 448400\r\n    2 656122\r\n    3 457125\r\n    4 35022\r\n    5 401553\r\n    6 581333\r\n    7 16329\r\n    8 529359\r\n    9 171710\r\n\r\nwhich is corresponding to the tokens generated by the Google Authenticator app (except if shorter than 6 signs, app adds zeros to the beginning to reach a length of 6 chars).\r\n\r\n\r\n  [1]: https://github.com/tadeck/onetimepass"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/21055859/what-are-the-risks-of-running-sudo-pip", "license": "CC BY-SA 3.0", "markdown": "# What are the risks of running 'sudo pip'?\n\nOccasionally I run into [comments or responses](https://stackoverflow.com/a/21047830/656912) that state emphatically that running `pip` under `sudo` is \"wrong\" or \"bad\", but there are cases (including the way I have a bunch of tools set up) where it is either much simpler, or even necessary to run it that way.\r\n\r\nWhat are the risks associated with running `pip` under `sudo`?\n\n## Accepted Answer\n\nWhen you run `pip` with `sudo`, you run `setup.py` with `sudo`. In other words, you run arbitrary Python  code from the Internet as root. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine. Prior to some recent fixes to `pip` and PyPI, an attacker could also run a man in the middle attack to inject their code when you download a trustworthy project."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/3812849/how-to-check-whether-a-directory-is-a-sub-directory-of-another-directory", "license": "CC BY-SA 2.5", "markdown": "# How to check whether a directory is a sub directory of another directory\n\nI like to write a template system in Python, which allows to include files.\r\n\r\ne.g.\r\n<pre>\r\n    This is a template\r\n    You can safely include files with safe_include`othertemplate.rst`\r\n</pre>\r\n\r\nAs you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to create their own templates, they might do something like\r\n\r\n<pre>\r\nI want your passwords: safe_include`/etc/password`\r\n</pre>\r\n\r\nSo therefore, I have to restrict the inclusion of files to files which are for example in a certain subdirectory (e.g. <code>/home/user/templates</code>)\r\n\r\nThe question is now: How can I check, whether <code>/home/user/templates/includes/inc1.rst</code> is in a subdirectory of <code>/home/user/templates</code>?\r\n\r\nWould the following code work and be secure?\r\n\r\n    import os.path\r\n\r\n    def in_directory(file, directory, allow_symlink = False):\r\n        #make both absolute    \r\n        directory = os.path.abspath(directory)\r\n        file = os.path.abspath(file)\r\n\r\n        #check whether file is a symbolic link, if yes, return false if they are not allowed\r\n        if not allow_symlink and os.path.islink(file):\r\n            return False\r\n\r\n        #return true, if the common prefix of both is equal to directory\r\n        #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b\r\n        return os.path.commonprefix([file, directory]) == directory\r\n\r\nAs long, as `allow_symlink` is False, it should be secure, I think. Allowing symlinks of course would make it insecure if the user is able to create such links.\r\n\r\n\r\n**UPDATE - Solution**\r\nThe code above does not work, if intermediate directories are symbolic links.\r\nTo prevent this, you have to use `realpath` instead of `abspath`.\r\n\r\n**UPDATE:** adding a trailing / to directory to solve the problem with commonprefix() Reorx pointed out.\r\n\r\nThis also makes `allow_symlink` unnecessary as symlinks are expanded to their real destination   \r\n\r\n    import os.path\r\n\r\n    def in_directory(file, directory):\r\n        #make both absolute    \r\n        directory = os.path.join(os.path.realpath(directory), '')\r\n        file = os.path.realpath(file)\r\n\r\n        #return true, if the common prefix of both is equal to directory\r\n        #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b\r\n        return os.path.commonprefix([file, directory]) == directory\n\n## Accepted Answer\n\nos.path.realpath(path): Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).\r\n\r\nUse it on directory and subdirectory name, then check latter starts with former."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/6501583/sqlalchemy-sql-injection", "license": "CC BY-SA 3.0", "markdown": "# SQLAlchemy + SQL Injection\n\nWhat are the best practices for mitigating SQL injection attacks when using SQLAlchemy?\n\n## Accepted Answer\n\n> If you have any \"special\" characters (such as semicolons or\r\n> apostrophes) in your data, they will\r\n> be automatically quoted for you by the\r\n> SQLEngine object, so you don't have to\r\n> worry about quoting. This also means\r\n> that unless you deliberately bypass\r\n> SQLAlchemy's quoting mechanisms,\r\n> SQL-injection attacks are basically\r\n> impossible.\r\n\r\n[per [http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html][1]]\r\n\r\n\r\n  [1]: http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html"}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/10741339/do-csrf-attacks-apply-to-apis", "license": "CC BY-SA 4.0", "markdown": "# Do CSRF attacks apply to API's?\n\nI'm writing a Django RESTful API to back an iOS application, and I keep running into Django's CSRF protections whenever I write methods to deal with POST requests.\r\n\r\nMy understanding is that cookies managed by iOS are not shared by applications, meaning that my session cookies are safe, and no other application can ride on them. Is this true? If so, can I just mark all my API functions as CSRF-exempt?\n\n## Accepted Answer\n\nThat's not the purpose of CSRF protection. CSRF protection is to prevent direct posting of data to your site. In other words, the client must actually post through an approved *path*, i.e. view the form page, fill it out, submit the data.\r\n\r\nAn API pretty much precludes CSRF, because its entire purpose is generally to *allow* 3rd-party entities to access and manipulate data on your site (the \"cross-site\" in CSRF). So, yes, I think as a rule any API view should be CSRF exempt. However, you *should* still follow best practices and protect every API-endpoint that actually makes a change with some form of authentication, such as OAuth."}
{"source": "firecrawl_alexandria_stackexchange", "query": "python+security", "source_url": "https://stackoverflow.com/questions/26006727/encrypted-and-secure-docker-containers", "license": "CC BY-SA 3.0", "markdown": "# Encrypted and secure docker containers\n\nWe all know situations when you cannot go open source and freely distribute software - and I am in one of these situations.\r\n\r\nI have an app that consists of a number of binaries (compiled from C sources) and Python code that wraps it all into a system. This app used to work as a cloud solution so users had access to app functions via network but no chance to touch the actual server where binaries and code are stored.\r\n\r\nNow we want to deliver the \"local\" version of our system. The app will be running on PCs that our users will physically own. We know that everything could be broken, but at least want to protect the app from possible copying and reverse-engineering as much as possible.\r\n\r\nI know that Docker is a wonderful deployment tool so I wonder: is it possible to create encrypted Docker containers where no one can see any data stored in the container's filesystem? Is there a known solution to this problem?\r\n\r\nAlso, maybe there are well known solutions not based on Docker?\n\n## Accepted Answer\n\nWhat you are asking about is called [obfuscation](http://en.wikipedia.org/wiki/Obfuscation_(software)#Obfuscating_software). It has nothing to do with Docker and is a very language-specific problem; for data you can always do whatever mangling you want, but while you can hope to discourage the attacker it will never be secure. Even state-of-the-art encryption schemes can't help since the program (which you provide) has to contain the key.\r\n\r\nC is usually hard enough to reverse engineer, for Python you can try [pyobfuscate](https://github.com/astrand/pyobfuscate) and [similar](https://www.google.com/search?q=python+obfuscation).\r\n\r\nFor data, I found [this question](https://gamedev.stackexchange.com/questions/2098/what-do-you-use-to-bundle-encrypt-data) (keywords: [encrypting files game](https://www.google.com/search?q=encrypting+files+game))."}
{"source": "firecrawl_research_index", "query": "reward hacking code generation language models", "source_url": "https://arxiv.org/abs/arxiv:2610.03055", "license": "research_index", "markdown": "# hacktrace: behavior-supervised detection of reward hacking during code generation\n\nA coding agent can earn a passing grade by fixing its code, or by deleting the test that exposes the bug. Detecting such reward hacking requires recognizing attempted shortcuts, including those that fail. We release 173,561 annotated multi-turn coding trajectories from Qwen3-8B and show that supervising shortcut behavior independently of exploit success substantially improves detection. We introduce HACKTRACE, a behavior-supervised monitor that reads the internal states the agent already computes while generating code. Reusing these states enables monitoring before a turn is complete, without additional language-model tokens or passes. Combining this evidence with static features of the final files achieves a mean per-problem AUC of 0.997 with 8 ms of monitoring overhead, improving both accuracy and latency over monitors that run the model again on an honesty question and answer. The same generation states also provide an inexpensive monitoring signal for reinforcement learning. With strong GRPO penalties, HACKTRACE reduces the cheating share of passing solutions from 82-91% to 1-5%, while retaining honest, correct solutions and maintaining high detection accuracy as the policy evolves. Our results show that both the supervision target and the source of monitoring evidence matter for turning accurate detection into a useful training signal."}
{"source": "firecrawl_research_index", "query": "reward hacking code generation language models", "source_url": "https://arxiv.org/abs/arxiv:2604.23488", "license": "research_index", "markdown": "# Do Prompt-Elicited Trajectories Reflect Training-Time Reward Hacking? A Systematic Study on Monitoring Training-Time Reward Hacking in Code Generation\n\nReward hacking in code generation, where models exploit evaluation loopholes to obtain high reward without correctly solving the intended task, poses a critical challenge for Reinforcement Learning (RL) and the deployment of reasoning models. Existing studies often rely on explicitly prompted hacking trajectories, but it remains unclear whether monitors trained on such data can detect reward hacks that arise without direct hacking instructions during RL training. In this work, we introduce Trace-and-Amplify, a framework for scalable curation of reward-hacking trajectories that arise during RL training without explicit hacking instructions. The framework uses unit-test tracers to identify hacking solutions when they occur and retains such trajectories for monitor training and evaluation. Through controlled comparisons between monitors trained on prompt-elicited hacking trajectories and training-time reward-hacking trajectories collected by Trace-and-Amplify, we find that (1) prompt-elicited-data-trained monitors often fail to generalize to trajectories curated by our framework, and (2) monitors trained on our Trace-and-Amplify trajectories demonstrate stronger generalizability to unseen hacking types. Our results indicate that prompted reward hacking data may not fully reflect training-time reward-hacking behaviors, and that relying solely on these data can lead to misleading conclusions. Codebase is available at https://github.com/LichenLillc/CoTMonitoring.git"}
{"source": "firecrawl_research_index", "query": "reward hacking code generation language models", "source_url": "https://arxiv.org/abs/arxiv:2511.21654", "license": "research_index", "markdown": "# EvilGenie: A Reward Hacking Benchmark\n\nWe introduce EvilGenie, a benchmark for reward hacking in programming settings. We source problems from LiveCodeBench and create an environment in which agents can easily reward hack, such as by hardcoding test cases or editing the testing files. We measure reward hacking in three ways: held out unit tests, LLM judges, and test file edit detection. We verify these methods against human review and each other. We find the LLM judge to be highly effective at detecting reward hacking in unambiguous cases, and observe only minimal improvement from the use of held out test cases. In addition to testing many models using Inspect's basicagent scaffold, we also measure reward hacking rates for three popular proprietary coding agents: OpenAI's Codex, Anthropic's Claude Code, and Google's Gemini CLI. We observe explicit reward hacking by both Codex and Claude Code, and misaligned behavior by all three agents. Our codebase can be found at https://github.com/JonathanGabor/evilgenieinspect ."}
{"source": "firecrawl_research_index", "query": "reward hacking code generation language models", "source_url": "https://arxiv.org/abs/arxiv:2511.18397", "license": "research_index", "markdown": "# Natural Emergent Misalignment from Reward Hacking in Production RL\n\nWe show that when large language models learn to reward hack on production RL environments, this can result in egregious emergent misalignment. We start with a pretrained model, impart knowledge of reward hacking strategies via synthetic document finetuning or prompting, and train on a selection of real Anthropic production coding environments. Unsurprisingly, the model learns to reward hack. Surprisingly, the model generalizes to alignment faking, cooperation with malicious actors, reasoning about malicious goals, and attempting sabotage when used with Claude Code, including in the codebase for this paper. Applying RLHF safety training using standard chat-like prompts results in aligned behavior on chat-like evaluations, but misalignment persists on agentic tasks. Three mitigations are effective: (i) preventing the model from reward hacking; (ii) increasing the diversity of RLHF safety training; and (iii) \"inoculation prompting\", wherein framing reward hacking as acceptable behavior during training removes misaligned generalization even when reward hacking is learned."}
{"source": "firecrawl_research_index", "query": "reward hacking code generation language models", "source_url": "https://arxiv.org/abs/arxiv:2604.01476", "license": "research_index", "markdown": "# From Rebound to Remedy: Understanding and Mitigating Reward Hacking via Representation Engineering\n\nReinforcement learning for LLMs is vulnerable to reward hacking, where models exploit shortcuts to maximize reward without solving the intended task. We systematically study this phenomenon in coding tasks using an environment-manipulation setting, where models can rewrite evaluator code to trivially pass tests without solving the task, as a controlled testbed. Across both studied models, we identify a reproducible three-phase rebound pattern: models first attempt to rewrite the evaluator but fail, as their rewrites embed test cases their own solutions cannot pass. They then temporarily retreat to legitimate solving. When legitimate reward remains scarce, they rebound into successful hacking with qualitatively different strategies. Using representation engineering, we extract concept directions for shortcut, deception, and evaluation awareness from domain-general contrastive pairs and find that the shortcut direction tracks hacking behavior most closely, making it an effective representational proxy for detection. Motivated by this finding, we propose Advantage Modification, which integrates shortcut concept scores into GRPO advantage computation to penalize hacking rollouts before policy updates. Because the penalty is internalized into the training signal rather than applied only at inference time, Advantage Modification provides more robust suppression of hacking compared with generation-time activation steering."}
{"source": "firecrawl_research_index", "query": "automated vulnerability repair LLM reinforcement learning", "source_url": "https://arxiv.org/abs/arxiv:2510.05480", "license": "research_index", "markdown": "# Vul-R2: A Reasoning LLM for Automated Vulnerability Repair\n\nThe exponential increase in software vulnerabilities has created an urgent need for automatic vulnerability repair (AVR) solutions. Recent research has formulated AVR as a sequence generation problem and has leveraged large language models (LLMs) to address this problem. Typically, these approaches prompt or fine-tune LLMs to generate repairs for vulnerabilities directly. Although these methods show state-of-the-art performance, they face the following challenges: (1) Lack of high-quality, vulnerability-related reasoning data. Current approaches primarily rely on foundation models that mainly encode general programming knowledge. Without vulnerability-related reasoning data, they tend to fail to capture the diverse vulnerability repair patterns. (2) Hard to verify the intermediate vulnerability repair process during LLM training. Existing reinforcement learning methods often leverage intermediate execution feedback from the environment (e.g., sandbox-based execution results) to guide reinforcement learning training. In contrast, the vulnerability repair process generally lacks such intermediate, verifiable feedback, which poses additional challenges for model training."}
{"source": "firecrawl_research_index", "query": "automated vulnerability repair LLM reinforcement learning", "source_url": "https://arxiv.org/abs/arxiv:2401.03374", "license": "research_index", "markdown": "# LLM-Powered Code Vulnerability Repair with Reinforcement Learning and Semantic Reward\n\nIn software development, the predominant emphasis on functionality often supersedes security concerns, a trend gaining momentum with AI-driven automation tools like GitHub Copilot. These tools significantly improve developers' efficiency in functional code development. Nevertheless, it remains a notable concern that such tools are also responsible for creating insecure code, predominantly because of pre-training on publicly available repositories with vulnerable code. Moreover, developers are called the \"weakest link in the chain\" since they have very minimal knowledge of code security. Although existing solutions provide a reasonable solution to vulnerable code, they must adequately describe and educate the developers on code security to ensure that the security issues are not repeated. Therefore we introduce a multipurpose code vulnerability analysis system SecRepair, powered by a large language model, CodeGen2 assisting the developer in identifying and generating fixed code along with a complete description of the vulnerability with a code comment. Our innovative methodology uses a reinforcement learning paradigm to generate code comments augmented by a semantic reward mechanism. Inspired by how humans fix code issues, we propose an instruction-based dataset suitable for vulnerability analysis with LLMs. We further identify zero-day and N-day vulnerabilities in 6 Open Source IoT Operating Systems on GitHub. Our findings underscore that incorporating reinforcement learning coupled with semantic reward augments our model's performance, thereby fortifying its capacity to address code vulnerabilities with improved efficacy."}
{"source": "firecrawl_research_index", "query": "automated vulnerability repair LLM reinforcement learning", "source_url": "https://arxiv.org/abs/arxiv:2604.17184", "license": "research_index", "markdown": "# SynthFix: Adaptive Neuro-Symbolic Code Vulnerability Repair\n\nLarge Language Models (LLMs) can generate plausible code patches, but plausibility is not enough for automated repair: a patch must compile, pass tests, and remove the target vulnerability. We present SynthFix, a neuro-symbolic repair framework that combines supervised repair learning with compiler-informed feedback. During training, a lightweight router selects between Supervised Fine-Tuning (SFT) for common repair patterns and Reward Fine-Tuning (RFT) for examples that benefit from symbolic feedback. The reward combines static structure, lint/compile checks, security scanning, and public execution tests where available; at inference time, the same evidence guides best-of-K candidate selection under a greedy floor. Across five code LLMs (1.3B-7B) on pyrepair, CodeFlaws, and SVEN, SynthFix improves deployable repair metrics over SFT-only and RFT-only baselines, with relative gains up to 54 percent in functional correctness and 14 percent in security clearance. Our code and data are available at https://github.com/CoderDoge1108/SynthFix."}
{"source": "firecrawl_research_index", "query": "automated vulnerability repair LLM reinforcement learning", "source_url": "https://arxiv.org/abs/arxiv:2611.36559", "license": "research_index", "markdown": "# Reinforcement Building: Toward Self-Improving Harnesses for Defensive Software Security Agents\n\nLarge language model (LLM) agents have become capable of discovering and exploiting vulnerabilities in real-world software with limited human intervention. This widens an asymmetry that already favors attackers, who need a single overlooked vulnerability, whereas defenders must find and fix vulnerabilities before they are exploited. Defenders therefore need markedly better defensive repair agents to keep up with the growing number of discovered vulnerabilities. With each new generation of models, researchers build multi-agent harnesses that outperform a single-agent baseline. These harnesses, however, are often tuned to a specific model version and may bring smaller gains, or even performance degradation, when used with another model. With the increasing speed at which new models are released, rebuilding a harness by hand for each new generation appears impractical. We present Reinforcement Building (RB), a framework that automatically builds the harness of a defensive agent for a given model. In each round, RB runs the current harness on training vulnerabilities and grades every patch with an execution oracle. An optimizer model then proposes edits to its agents, tools, delegation edges and memory, and a validation gate keeps them only if they strictly improve the harness. Without updating any weights, RB improves the repair success rate of two open-weight models on three held-out benchmarks by 58% to 750% relative to the base harness (8.5 to 36.1 percentage points). On SEC-bench, it outperforms ContraFix, the state-of-the-art harness builder for vulnerability repair, by 21% relative for both models. Compared with reinforcement learning with verifiable rewards (RLVR) on the same data, RB needs 7.4 times fewer training episodes to reach the same success rate on Gemma-4-31B."}
{"source": "firecrawl_research_index", "query": "automated vulnerability repair LLM reinforcement learning", "source_url": "https://arxiv.org/abs/arxiv:2409.00571", "license": "research_index", "markdown": "# Enhancing Source Code Security with LLMs: Demystifying The Challenges and Generating Reliable Repairs\n\nWith the recent unprecedented advancements in Artificial Intelligence (AI) computing, progress in Large Language Models (LLMs) is accelerating rapidly, presenting challenges in establishing clear guidelines, particularly in the field of security. That being said, we thoroughly identify and describe three main technical challenges in the security and software engineering literature that spans the entire LLM workflow, namely; (i) Data Collection and Labeling; (ii) System Design and Learning; and (iii) Performance Evaluation. Building upon these challenges, this paper introduces SecRepair, an instruction-based LLM system designed to reliably identify, describe, and automatically repair vulnerable source code. Our system is accompanied by a list of actionable guides on (i) Data Preparation and Augmentation Techniques; (ii) Selecting and Adapting state-of-the-art LLM Models; (iii) Evaluation Procedures. SecRepair uses a reinforcement learning-based fine-tuning with a semantic reward that caters to the functionality and security aspects of the generated code. Our empirical analysis shows that SecRepair achieves a 12% improvement in security code repair compared to other LLMs when trained using reinforcement learning. Furthermore, we demonstrate the capabilities of SecRepair in generating reliable, functional, and compilable security code repairs against real-world test cases using automated evaluation metrics."}