Why should you not use CONCAT() for static string literals?

我们两清 提交于 2019-12-23 21:13:22

问题


So you have

$sql = "SELECT * FROM `table` WHERE `some_text_field` LIKE CONCAT('%', ?, '%')";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST['badies_code']));

And looking at another question i found that this causes a security concern, but why?

I found this question, a downvoted answer and an upvoted comment that is why i ask

The comment said

This is not the correct way to do this. You should not use CONCAT() for three static string literals, as it opens you up to a specific type of SQL injection (i forget the name). – Theodore R. Smith

PHP PDO prepared statement -- mysql LIKE query


回答1:


I think what @TheodoreR.Smith may have meant is the so called Lateral SQL Injection in Oracle Database[1][2].

It works by changing environment variables holding format information such as NLS_DATE_FORMAT, or NLS_NUMERIC_CHARACTERS, which are then used in a stored procedure that builds and executes a statement dynamically (this is where string concatenation is used, denoted by the || operators):

CREATE OR REPLACE PROCEDURE date_proc IS
    stmt VARCHAR2(200);
    v_date DATE := SYSDATE;
BEGIN
    stmt := 'select object_name from all_objects where created = ''' || v_date || '''';
    EXECUTE IMMEDIATE stmt;
END;

Here SYSDATE returns the current date in the format specified in NLS_DATE_FORMAT. Although the procedure has no parameter, changing the date format to something like ' or 1=1--:

ALTER SESSION SET NLS_DATE_FORMAT = ''' or 1=1--'

The resulting statement is:

select object_name from all_objects where created = '' or 1=1--'

This environment variable manipulation is specific to Oracle Database. And again, it can be mitigated using prepared statements:

CREATE OR REPLACE PROCEDURE date_proc IS
    stmt VARCHAR2(200);
    v_date DATE := SYSDATE;
BEGIN
    stmt := 'select object_name from all_objects where created = :date';
    EXEC SQL PREPARE prepared_stmt FROM :stmt;
    EXEC SQL EXECUTE prepared_stmt USING :v_date;
end;

I’m not aware that MySQL is prone to this kind of environment variable manipulation.

However, building statements dynamically without proper processing is prone to SQL injections, no matter whether it happens in the application or in the database. So using prepared statements in stored procedures is mandatory as well.




回答2:


It would be quite a complex task to remember the name of injection that doesn't exist.

There is nothing wrong in using concat() with prepared statement.



来源:https://stackoverflow.com/questions/22740375/why-should-you-not-use-concat-for-static-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!