Using 'where..in' inside store procedure with prepared statements (Safe Way) - mysql

Im trying to secure my store procedure to avoid SQL Injection attacks using prepared
statements. with the guide that mentioned here :
"https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html"
mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql> SET #a = 3;
mysql> SET #b = 4;
mysql> EXECUTE stmt1 USING #a, #b;
+------------+
| hypotenuse |
+------------+
| 5 |
+------------+
mysql> DEALLOCATE PREPARE stmt1;
I have no problem with passing parameter one by one.
Now if i have to pass array of item to SP from java and use 'where..in' , what is the best
approach ?
I can use something like this :
SET #somestring = '1,3,18,25';
SET #s=CONCAT("
SELECT * FROM city
WHERE id IN (",#somestring,");");
PREPARE stmt FROM #s;
EXECUTE stmt;
Dont know if is it secure enough for injection , since i guess its not checking parameter
one by one while it not use "USING #a, #b".

You cannot pass an array to your stored procedure, because MySQL doesn't support arrays. Your string '1,3,18,25' is a string that happens to contain commas. This is not an array.
Interpolating an unknown string into a dynamic SQL statement is SQL injection, full stop. You can't be sure it does not contain special characters that would change the syntax of the dynamic SQL query, so it's not safe.
The safest way to use variables in dynamic SQL statements is by using query parameters. But there's a couple of problems: I assume your string with comma-separated numbers may have a variable number of numbers, and you must support that.
Query parameters can only be used for individual scalar values. One parameter per value:
WHERE id IN (?, ?, ?, ?)
The syntax for EXECUTE stmt USING ... supports a variable number of arguments, but not a dynamic number of arguments. You must code the arguments as fixed in your code, and the arguments must be individual user-defined variables (the type with the # sigil). There's no good way to convert a string of comma-separated values into a like number of individual variables. It's possible to extract substrings in a loop, but that's a lot of code.
And it still wouldn't help because you'd have to find a way to pass a dynamic number of arguments to EXECUTE ... USING.
A common workaround for MySQL users is to use FIND_IN_SET(). This allows you to match a column to a comma-separated string of values.
WHERE FIND_IN_SET(id, '1,3,18,25') > 0
So you could pass your string as a single parameter to a prepared statement:
SET #somestring = '1,3,18,25';
SET #s='SELECT * FROM city WHERE FIND_IN_SET(id, ?)';
PREPARE stmt FROM #s;
EXECUTE stmt USING #somestring;
In fact, you don't even need to use PREPARE & EXECUTE for this. You can use MySQL variables in a query directly.
SELECT * FROM city WHERE FIND_IN_SET(id, #somestring);
This is safe, because the variable does not cause SQL injection. The query has already been parsed at the time you create the stored procedure, so there's no way the content of the variable can affect the syntax of the query, which is what we're trying to avoid.
This is safe ... but it's not optimized. By using FIND_IN_SET(), the query cannot use an index to search for the values in your string. It will be forced to do a table-scan. Probably not what you want.
So what are the options for solutions?
You could check the input string to make sure it has only digits and commas, and abort if not.
IF #somestring NOT REGEXP '^([[:digit:]]+,)*[[:digit:]]+$' THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = 'Invalid input, please use only comma-separated integers';
FI
Once you confirm that the string is safe, then you can safely interpolate it into the query string, as in your example with CONCAT().
My preferred solution is to stop using MySQL stored procedures. I hardly ever use them, because virtually every other programming interface for MySQL is easier to code.

Related

Changing Dynamic Table name in Query based on week number [duplicate]

I want to use variable in table name position like:
SELECT * FROM #targetTableName
However it makes error.
Is there any way to use variables in table name place in MySQL?
There are two reasons the query you show doesn't work.
Userd-defined variables interpolated into a query are treated as if you had use a string literal, not an identifier. The query you show would be like:
SELECT * FROM 'mytable'
That is of course not correct syntax. You can't select from a string literal.
Table names (and any other identifers) must be fixed at the time the query is parsed. So you can't make a query that names a table using a parameter, an expression, a subquery, or anything else. The table identifier must be plain and fixed before any data is read.
If you need to use a variable table name, you have to do it with dynamic SQL. That is, the whole query must be a string, which you can format any way you want it. Then parse that string as SQL at runtime.
Dynamic SQL is common. This is the way virtually all SQL is run from applications. If you use Java or Python or PHP or Go or any other language, you're probably using dynamic SQL.
If you run the query in a stored procedure, you have to use PREPARE and EXECUTE, after concatenating your variable into a string to format the query:
SET #sql = CONCAT('SELECT * FROM `', #targetTableName, '`');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

How to dynamically set value in mysql query from an object?

I am trying to have an abstract method that can handle any update to a particular table. I want this to pull and set dynamically without using any additional code logic.
I know of a few ways to accomplish this, either using addition code logic or just refining the query to be more explicit.
let result = await db.query(`UPDATE media SET ? WHERE product_id=?;`, [[data.variant_id], productId]);
return result;
}
I would like to have the set value be, in this case, variant_id=.
I don't know of a way to accomplish this in the query itself other than setting the value prior to the query
You missed the column name
let result = await db.query('UPDATE media SET your_column_name = ?
WHERE product_id=?;',
[[data.variant_id], productId]);
and don't use backtics for sql string use single quote instead .. In mysql backtics are used for composite column name and column name containing reserved word
Use the prepare statement for Mysql dynamic update fields
set #stmt = concat ("UPDATE media SET variant_id=",data," WHERE product_id=",productId," ;");
prepare resultset from #stmt;
execute resultset;
deallocate prepare resultset;

MySql prepare statement - is it possible to parametrize column name or function name?

Lets say that I want to write a procedure allowing me to call certain function on certain column, for example:
call foo('min','age') -> SELECT min(age) FROM table;
I want my procedure to be safe from sql injection, therefore, I'm willing to use prepared statements and parametrize the input
SET #var = "SELECT ?(?) FROM table;"
PREPARE x FROM #var;
EXECUTE x USING a, b;
Where a and b are input parameters, function and column, respectively.
However, it doesnt seem to be possible - InnoDB keeps throwing an error whenever I want to execute this statement.
Is it possible to solve this this way, or I need to resort to whitelisting?
EDIT:
Full code:
create procedure test(in func varchar(20), in col varchar(20))
begin
set #f = func;
set #c = col;
set #sql = "select ?(?) from table;";
prepare x from #sql;
execute x using #f, #c;
end;
calling:
call test('min','age');
Full error:
[42000][1064] You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near '(?) from table' at line 1
You cannot parametrize column/table/function name/alias. As, PREPARE statement only allow "values" part of the SQL query to be used as parameters. Function/Table/Column name/alias are used to determine the validity of the SQL statement; and thus cannot be changed during run-time execution. Changing it at execution time would potentially alter whether the SQL statement was valid.
You can think of it as compiling a code; hence the compiler must know all the function/class name(s) etc for creating a valid executable (yes, we can do dynamic classes, but that is rare). On the other hand, we can change input "values" to the program, but generally cannot change the operations to be done on the input data.
Also, MySQL server would consider the parameters as literals, and apply quotes around them, before using them in query execution.
Now, in your case, you can still use the function name as parameter for Stored procedure, and generate the query string using that. But you cannot use it as a parameter for the query itself.
delimiter $$
create procedure test(in func varchar(20), in col varchar(20))
begin
set #c = col;
-- use concat function to generate the query string using func parameter
set #sql = concat('select ', func, '(?) from table');
-- prepare the statement
prepare stmt from #sql;
-- execute
execute x using #c;
-- don't forget to deallocate the prepared statement
deallocate prepare stmt;
end$$
delimiter ;
I came across this while writing a mySQL query builder plugin. My solution was to prefix column and function names with a "?" character (the user can change the character in the plugin preferences).
The code that builds the prepared statement looks for values that begin with "?" and inserts the subsequent column/function name into the query inline instead of as prepared statement values.

Is possible to interpret and operation on string using a mathematical function in MySQL?

I want to select the final value of a string (for example '3+4') using a SELECT. I want to know if exists a function or a way in MySQL.
Example:
SELECT ('4+1*3') as VALUE;
The result is:
VALUE
7
You can do this in three steps:
Combine query into a single string
Create a prepared statement from this string
Execute said statement
Something like this:
SET #query = CONCAT('SELECT (', '4+1*3', ') AS VALUE');
PREPARE stmt FROM #query;
EXECUTE stmt;
Note that this does not merely evaluate mathematical expressions. A malicious user could insert pretty much anything into the query here, so you are open to the worst of sql injection attacks unless you carefully sanitize the string you paste into the query to only allow mathematical expressions.
Note that I can think of no application where this kind of operation would be useful. I'd say if you have to evaluate arbitrary strings, you're probably better of doing so in application code, not in the database.

Escape string on server side

I have a stored procedure in a database that accepts string arguments that are inserted directly into a query. I have client-side code to escape the inputs, but that doesn't stop anyone with permission to execute that procedure with bad arguments and inject SQL.
Current implementation is something like this:
CREATE PROCEDURE grantPermissionSuffix (perm VARCHAR(30), target VARCHAR(30), id VARCHAR(8), host VARCHAR(45), suffix VARCHAR(45))
BEGIN
SET #setPermissionCmd = CONCAT('GRANT ', perm, ' ON ', target, ' TO ''', id, '''#''', host, ''' ', suffix, ';');
PREPARE setPermissionStmt FROM #setPermissionCmd;
EXECUTE setPermissionStmt;
DEALLOCATE PREPARE setPermissionStmt;
FLUSH PRIVILEGES;
END
Clearly this is a recipe for disaster. How can I prevent an injection opportunity? Is there a standard SQL function to escape input? Is there one for MySQL? Is there another way to get the same result without extra client-side code?
My fear is that the only solution will be client-side prepared statements, which is not an option at this time. I need all the logic to be handled on a server, requiring clients to only call this procedure (I don't want to have to grant users permission to modify tables/permissions directly, only to handle it with procedures they're allowed to execute).
You can prepare statements with ? placeholders for variables and later EXECUTE USING the variables, just like in client-side prepared statements, at least according to the manual. I'm not sure how well this would work when substituting table names, though, but this is limited by prepare rules, so if it doesn't work in server-side, it wouldn't work on client-side either.
UPDATE:
Apparently, mysql doesn't recognize ? placeholders in prepared GRANT query. In that case, you'll have to take care of it manually. Some tips are in that answer - namely, using ` (backtick) to escape identifiers and using a whitelist for keywords - that way, you also gain fine-grain control on what you do allow in your procedure.
I would add that for your specific purposes it might be better to select from information_schema and mysql tables to control that, for example, db and table passed to you actually exist. You can use prepared statements with placeholders for that, so it's safe. Something like this will check db and table:
PREPARE mystat FROM 'SELECT count(*) into #res FROM INFORMATION_SCHEMA.TABLES WHERE upper(TABLE_SCHEMA)=UPPER(?) and UPPER(TABLE_NAME)=UPPER(?)';
set #db = 'mydb'; --these two are params to your procedure
set #table = 'mytable';
set #res = 0;
execute mystat using #db, #table;
select #res; --if it's still 0, then no db/table exists, possibly an attack is happening.
Checking user and host can be done like that, too, using mysql.users table instead. For the rest of params, you'll have to build a whitelist.
Yet another way I see is to check for allowed characters using a regular expression - there's REGEXP command for that. For example, you can control that your procedure parameter has only alphabetic uppercase with if #var REGEXP '^[A-z]+$'. To my knowledge, it's impossible to perform an SQL injection using only A-z.