smart solution of SQL injection - mysql

These is one keyword confliction issue in the query module of my application,please see if you can tell me a smart solution.
First,In query module,each query condition contains three parts in UI:
1.field name,its value is fixed,e.g origin,finalDest...
2.operator,it is a select list which includes "like","not like","in","not in","=","!="
3.value,this part is input by user.then in back-end,it will assemble the SQL statement according to UI's query criteria,e.g if user type/select following stuff in UI
Field Name Operator Value
origin like CHI
finalDest in SEL
In back-end,it will generate following SQL:
select * from Booking where origin like '%CHI%' and finalDest in ('SEL').
But there is a bug,e.g if user type some of special symbol in "value",e.g "'","_" etc,it will lead to the generated SQL also contain ' or _ ,e.g:
select * from Booking where origin like '%C_HI%' and finalDest in ('S'EL').
you could see as there is special symbol in "where" block,the SQL can't be executed
For this problem,my solution is add escape character "/" in front of the special symbol before executing it,but what i know is just ' or _ that would conflict with the SQL keywords,do you know if there is any others similar symbol that i need to handle or do you guys have any better idea that can avoid the injection
Sorry,forgot told you what language i am using,i am using java,the DB is mysql,i also use hibernate,there are a lot of people said why i didn't use PreparedStatement,this is a little complex,simply speaking,in my company,we had a FW called dynamic query,we pre-defined the SQL fragment in a XML file,then we will assemble the SQL according to the UI pass in criteria with the jxel expression,as the SQL is kinda of pre-defined stuff,i afraid if change to use PreparedStatement,it will involve a lot of change for our FW,so what we care is just on how to fix the SQL injection issue with a simple way.

The code should begin attempting to stop SQL injection on the server side prior to sending any information to the database. I'm not sure what language you are using, but this is normally accomplished by creating a statement that contains bind variables of some sort. In Java, this is a PreparedStatement, other languages contains similar features.
Using bind variables or parameters in a statement will leverage built in protection against SQL injection, which honestly is going to be better than anything you or I write on the database. If your doing any String concatenation on the server side to form a complete SQL statement, this is an indicator of a SQL injection risk.

0 An ASCII NUL (0x00) character.
' A single quote (“'”) character.
" A double quote (“"”) character.
b A backspace character.
n A newline (linefeed) character.
r A carriage return character.
t A tab character.
Z ASCII 26 (Control+Z). See note following the table.
\ A backslash (“\”) character.
% A “%” character. See note following the table.
_ A “_” character. See note following the table
Reference
Stack Similar Question

You should use bind variables in your SQL statement. As already mentioned this is done with PreparedStatements in Java.
To make sure, only valid column names are used, you can validate the input against the database. MySQL provides schema information like columns of each table as part of the INFORMATION_SCHEMA. For further information, check the MySQL documentation:
"The INFORMATION_SCHEMA COLUMNS Table"

Related

Save json_encode string to mysql db

I was save this string to DB
{"form_5_check":"N\u00e1kladov\u00e9 stredisko"}
But in mysql db is this string:
{"form_5_check":"Nu00e1kladovu00e9 stredisko"}
Pls where are "\" lost ? Thanks a lot
MySQL treats the backslash character as an escape character. If you did something like this:
query = "INSERT INTO foo (json) VALUES ('" + json + "');
you have basically three problems:
the single backslash you have will get interpreted as an escape character, not as content; unless the next character is a quote or another backslash, it will have escaped nothing, and silently disappear.
if your json contained any single quotes, and you are lucky, you will get a syntax error, as the quote that was supposed to contain the value will be closed, and gibberish that SQL can't parse follows.
if your json contained any single quotes, and you're not lucky, you're now a victim of SQL injection attack, the most infamous example being XKCD's.
To avoid all that, make sure that your data is properly sanitised before it hits the database. This can be done in two ways:
The manual, and error-prone way includes always remembering to escape any characters that need it any time you insert a string into a query. This differs between databases. Some databases want a backslash before quotes, while some prefer doubling the quotes and doing nothing to backslashes. Some allow both. Many languages and/or database access libraries have functions that do this in a way appropriate for the database.
The automated, foolproof and very much preferred way is to use parametrised queries and prepared statements that do this for you in a transparent and easy-to-use way. You do not have a specific language tagged, so I can't give you the solution, but the Bobby Tables site has answers for many commonly used programming languages.

How to escape single & double quotes in MySQL select?

select name from movies where id = 1; gives me
name
----------
How the 'A' Stole Christmas
How would I select in order to get
name
----------
How the \'A\' Stole Christmas
I can use replace(title,'\'','\\\'') which turns ugly since I need to do it twice one for single & double quote, Curious to know if there is cleaner approach
Struggling with escaping characters is a sign that you may be unnecessarily converting strings manually as data flows through different systems. The question I would ask is whether it is necessary to have escaped strings for your requirements.
When constructing and executing your queries you should use bind variables which removes the need to quote strings to build up your Sql queries and minimizes the risk of Sql injection security issues.
See http://php.net/manual/en/mysqli-stmt.bind-param.php
Once you have Sql results in a variable or PHP structure it is often better to find functions/libraries such as JSON functions described at https://coderwall.com/p/p2kumg/json_encode-vs-serialize-with-php-arrays
And of course there's http://www.w3schools.com/php/func_string_addslashes.asp as mentioned by D4V1D as a comment.
Edit ...
There also appears to be a Mysql QUOTE() function that does what you are asking.
See http://www.w3resource.com/mysql/string-functions/mysql-quote-function.php

insert and update escape charcter, simple and double quotes in the same time in a MySQL table

I am concerned about inserting text in a MySQl table w.
I have to insert/update text that contains characters such as / " and '
The escape character / could be inserted only if the NO_BACKSLASH_ESCAPES SQL mode is enabled. wich interfere with the characters " and ' see this link http://dev.mysql.com/doc/refman/5.1/en/string-literals.html#character-escape-sequences
If anyone can explain to is in earth the mysql_real_escape_string() I don't came to understated
I would like to find a pure mysql solution
I am not using php. What I am trying to do here is to "simulate " Content Management System: I am about to write a C# coded solution that manage the content in its different forms(article, category ,tag, etc..) and generate .html files, the MySQl database is local in my computer next i will upload the .html files to the server.
I did this to ensure that all my html pages are html valid and because I don't trust any existent solutions (not only when it concerns coding but in life in general)
Please help
each php db connection extension (mysql, mysqli, pdo) has a special way to safe query against sql injections, when you are using mysql extension, it's strongly recommended to use mysql_real_escape_string() function to make safe all variables used in query, it's most widely used function. i think there isn't any pure solution (when you are using mysql extension in php).
from php.net:
mysql_real_escape_string()-Escapes special characters in the
unescaped_string, taking into account the current character set of the
connection so that it is safe to place it in a mysql_query().
Whatever string data can be inserted into SQL query, if formatted according to 2 rules
it is enclosed in quotes (preferably single ones)
it is passed through mysql_real_escape_string()
if both rules followed, there would be not a single problem with whatever characters, either slashes, quotes or anything.
According to your question, / has no special meaning in MySQL. It's \ that is escape character. It can be escaped by another backslash as well.
$str = 'slashes \ quotes \' or whatever " else symbols';
var_dump($str);
$str = mysql_real_escape_string($str);
$sql = "INSERT INTO table SET str='$str'";

Regex Search in phpMyAdmin

Attempting to change the "files" folder location in a Drupal site from /files to /sites/default/files.
In order to avoid changing anything else such as
http://www.google.com/profiles/
I'm trying to use a basic regular expression with a word boundary.
\bfiles/
A quick check in regexpal is working as expected, but when I enter the above in the phpMyAdmin search , checking the "as regular expression" checkbox, I don't get the expected result.
Two questions:
How should I write my expression with a word boundary so that it works in phpMyAdmin?
I'm really a newbie at SQL statements! Would it be possible to write a SQL query that would simply look for every occurrence of "files/" & replace it with "sites/default/files/"?
According to the MySql docs, the regex flavour used is POSIX 1003.2. For this flavour of regex, word boundaries are as follows:
[[:<:]] (beginning) [[:>:]] (end)
so your regex would be:
[[:<:]]files/
If you want to use sql to search and replace all instances of [[:<:]]files/ from a specific field in a table, you could use a UDF such as the one found here
Also, you should be aware of the following while using regex with MySql:
Because MySQL uses the C escape syntax in strings (for example, “\n”
to represent the newline character), you must double any “\” that you
use in your REGEXP strings.

Is there a mySQL equivalent to Postgresql's "Dollar-Quoted String Constants"?

In postgresql, it's possible to use "Dollar-Quoted String Constants" to avoid escaping single quotes in constant strings:
Without Dollar-Quoted String Constants:
'Jeff''s table'
With Dollar-Quoted String Constants:
$$Jeff's table$$
Is there a MySQL equivalent?
On edit: I'm not looking for a way to sanitize inputs, I'm looking for a way to make queries that generate sql easier to read.
No, because it doesn't really work. An attacker just addes a pair of dollar signs to their injection attempt instead.
The correct way to handle this is a system that uses real query parameters, such that the parameter values are never substituted directly into a query string. This is also generally better for performance because the db can do a better job caching the execution plan you don't end up building string dynamically, which tends to be slow in modern languages.
Not having excess concatenation statements greatly improves the readability of the code, as well. Instead of this:
sql = "SELECT * FROM MyTable WHERE Column1=$$" + somevarialbe + "$$ AND Column2=$$" + OtherVariable";
it's just this:
sql = "SELECT * FROM MyTable wHERE Column1=#Value1 AND Column2=#Value2";
Hmm... Okay, I can see some limited utility for this feature now.
Imagine a ticket tracking system with a stored procedure to get open tickets. You might actually hard-code the literal 'open' into the where clause of the query. Not that this would be a good design — ticket status should be in a table with it's own key, so that you'd hardcode the key rather than the text. But it plants the seed for something valid and more-complicated.
You can enclose your string in double quotes instead, e.g.
"Jeff's table"
Note: If this doesn't work, it means that you've got ANSI_QUOTES SQL mode turned on. The MySQL docs say:
If the ANSI_QUOTES SQL mode is enabled, string literals can be quoted only within single quotation marks because a string quoted within double quotation marks is interpreted as an identifier.