user1700840
user1700840

Reputation: 451

Is this string replacement enough against SQL injection attacks?

I'm trying to evaluate a sort of customized CMS. The protection the devoloper used against SQL attacks is:

 str_replace("'", "\'", $_POST[$variable]);

Is this good enough, or there're ways to exploit this to inject SQL code?

PS: I know the standard way is using mysql_real_escape_string(), but I'm trying to get an idea of the general quality of the code.

Upvotes: 3

Views: 1457

Answers (3)

Moe Tsao
Moe Tsao

Reputation: 1054

No. Throw in some UTF8 character and this would either garble the code or be escaped.

Use mysqli / PDO or if you must, use mysql_real_escape_string.

Upvotes: 8

bobince
bobince

Reputation: 536359

str_replace("'", "\'", $_POST[$variable]);

Yes this is vulnerable.

Trivially, the backslash is not escaped, so you can break out of a string literal using a backslash to mask a quote: hello\' OR 1 -- -> 'hello\\' OR 1 --'.

Nulls are also not escaped and may cause problems.

Also if East Asian charsets are in use, a multibyte sequence may be used to mask the quote. (Note this is NOT the case for UTF-8, as UTF-8 does not allow ' as a trailing byte.)

Also this escaping format is only suitable for MySQL. If any other database is used, or the ANSI-compliant string literal option is used in MySQL, then it will be ineffective, as the standard escape is to double the quote, not backslash.

The code is useless. At best it shows someone is aware that SQL injection exists, but it exhibits no real understanding of the actual problem.

Upvotes: 6

Jared
Jared

Reputation: 12524

SQL Injections can come in many forms.

If there was a query that performs a where clause on a numeric field (think PIN Number) it could easily be injected.

Something harmless looking for a match on the user entered number:

SELECT * FROM table
WHERE ID = 1

Could turn in to something that always matches

SELECT * FROM table
WHERE ID = 1 OR 1 = 1

Using the vendor specific escape functions or prepared statements is the way to go.

Upvotes: 1

Related Questions