Search code examples
mysqlstored-proceduresprepared-statementsql-injectiondynamic-sql

Is this MySQL Stored Procedure vulnerable to SQL injection?


I have a MySQL stored procedure that uses Dynamic SQL. We went with Dynamic SQL because we have several tables with similar columns and we're trying to make the code as reusable as possible.

I'm concerned about SQL Injection, but standard attack strings don't seem to work on this. Is this stored procedure susceptible to SQL Injection? If so, is there a better way to write it?

CREATE DEFINER=CURRENT_USER PROCEDURE `sp_lookup`(IN tableName VARCHAR(256))
BEGIN
  SET @sql = CONCAT('SELECT id, name, FROM ', tableName, ' ORDER BY name');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
END

Solution

  • Stored procedure won't add any additional security.

    It does not prevent the SQL injection, you need to use prepared statement.

    Another approach would be to use table white-listing, this means you first check that the table matches one of your existing tables if not do not run the query.