Name

DYN-02: Carefully validate any parameter values that might be used to construct dynamic SQL

Synopsis

Whenever you create a dynamic SQL statement based on parameters to a procedure or user inputs, you should always guard carefully against SQL injection (see Chapter 18). SQL injection allows the user to provide fragments of SQL as parameters to your stored programs, potentially subverting the resulting dynamic SQL.

Therefore, you should always carefully validate the inputs to your stored programs if they contribute to your dynamic SQL.

In the previous example, we prevented SQL injection through the careful use of placeholders. Variable binding could not, however, address the potential vulnerability of concatenating in the names of tables and columns.

In the modified version below, we perform a SQL query to confirm that the parameter inputs do, in fact, represent valid table and column names. Once we validate the inputs, we then construct and execute the dynamic SQL:

 CREATE PROCEDURE update_anything_2 (in_table VARCHAR(60), in_where_col VARCHAR(60), in_set_col VARCHAR(60), in_where_val VARCHAR(60), in_set_val VARCHAR(60)) BEGIN DECLARE v_count INT; SELECT COUNT(*) INTO v_count FROM information_schema.columns WHERE table_name=in_table AND column_name IN (in_set_col,in_where_col); IF ( v_count <2 ) THEN SELECT 'Invalid table or column names provided'; ELSE SET @dyn_sql=CONCAT( 'UPDATE ' , in_table , ' SET ' ,in_set_col, ' = ? WHERE ' , in_where_col, ' = ?'); SELECT @dyn_sql; PREPARE ...

Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.