In MySQL is a prepared statement inside a stored procedure safe from SQL injection? See example below. The get_info stored procedure is passed a table name (pTbl) and the where clause (pWhere). pWhere can have many AND’s (e.g. fld1=”a” AND fld2=”b” AND …). It’s probably not the best way to do it but I need to have dynamic sql.
CREATE PROCEDURE get_info(pTbl VARCHAR(10), pWhere TEXT)
BEGIN
SET @uSQL = CONCAT('SELECT info FROM ',pTbl,' WHERE ',pWhere);
PREPARE ps FROM @uSQL;
EXECUTE ps;
END$$
I tried calling the stored procedure like below using MySQL Query Browser but only got an error back saying I have a syntax error in my SQL.
CALL get_info('tbl','1=1;SELECT * FROM information_schema.TABLES;');
If it helps any the stored procedure is being called from PHP using PDO like below. $tbl is a $_SESSION variable and $whr is a $_GET variable.
$s=$c->prepare("CALL get_info(?,?)");
$s->execute(array($tbl,$whr));
Is this stored procedure safe? If not, how would I inject it? Does it make a difference if I inject from MySQL Query Browser vs from a web page? Thanks…
Any time you interpolate a value into a statement there’s the possibility of injection. The procedure is vulnerable. The only general limitation with injection in SQL procedures and functions is that
PREPAREworks on a single statement. In this specific case, that the injected text is after aWHEREclause in aSELECTbasically limits attacks to sub-selects,UNION, calling procedures and functions (tricky but potentially very dangerous), and dumping to files (if the definer ofget_infohas theFILEprivilege).As an example, try: