Skip to content

Commit 501715a

Browse files
Update secure_software_development_fundamentals.md
Co-authored-by: Ashwin Ramaswami <[email protected]>
1 parent 1d21d66 commit 501715a

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

secure_software_development_fundamentals.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2532,7 +2532,16 @@ If user input doesn't have a valid mapping, reject the input.
25322532
This increases the probability that a change to the program
25332533
will not result in unvalidated input being concatenated into a query,
25342534
or that the problem will be detected before shipping.
2535+
For example, in Python, if you need to write to a user-provided table name, you can do the following:
25352536

2537+
~~~~python
2538+
table_name_untrusted = request.get("table_name") # This is untrusted, don't put this directly in the query!
2539+
table_name_map = {"table1": "db.table1", "table2": "db.table2"}
2540+
table_name = table_name_map[table_name_untrusted]
2541+
con = sqlite3.connect(...)
2542+
cur = con.cursor()
2543+
cur.execute(f"insert into {table_name}(d, ts) values (?, ?)", (today, now)) # This is safe because we know that table_name can only take trusted values from table_name_map
2544+
~~~~
25362545
##### Other Approaches
25372546

25382547
Many programs use object-relational mapping (ORM). This is just a technique to automatically convert data in a relational database into an object in an object-oriented programming language and back; lots of libraries and frameworks will do this for you. This is fine, as long as the ORM is implemented using parameterized statements or something equivalent to them. In practice, any good ORM implementation will do so. So if you are using a respected ORM, you are already doing this. That said, it is common in systems that use ORMs to occasionally need to use SQL queries directly… and when you do, use parameterized statements or prepared statements.

0 commit comments

Comments
 (0)