Add quotes in stored procedure - mysql

I have a stored procedure whereby text is the input. Is it possible to accept text without quotes and then through the replace function insert single quotes inside the procedure?

Use MySQL's QUOTE() function:
Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (“\”), single quote (“'”), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.
mysql> SELECT QUOTE('Don\'t!');
-> 'Don\'t!'
mysql> SELECT QUOTE(NULL);
-> NULL

If you know where and how to put back the quotes, it is possible.

If I understand correctly that you want to be able to write, for example:
foo(All human beings are born free and equal in dignity and rights.)
and have it be interpreted as:
foo('All human beings are born free and equal in dignity and rights.')
then — no. This is not possible.

Related

"a"+'b'+"c",What does two double quotes and one single quote combination mean in mysql

For example
SELECT "hello"'jacky'"hi" as value from dual;
the result is hellojackyhi
But it confuse me that the use of this pattern "a"+'b'+"c".
What does this pattern exactly mean?It's a use of double quotes and single quote, is it mean I can always combine 3 string using this pattern "a"+'b'+"c"?
MySQL has a "feature" where it concatenates strings that are adjacent (and separated by a space):
select 'a' 'b' 'c'
---> abc
This works for both single quotes and double quotes. Of course, double quotes might also be a column name.
So, this is a short-cut for string concatenation. I strongly recommend that you use CONCAT() instead, so the intention is clear.

SQL injection when single quotes are escaped with two single quotes

Is there any way to perform a SQL injection when single quotes are escaped by two single quotes? I know the MySQL server is using this specific technique to prevent against an attack. I'm trying to log in as a specific user but all of the common injections I've tried for the password have not worked successfully (i.e. ' or '1'='1, ' or ' 1=1, etc.).
No, and yes.
There's no way to have an unsafe values "breakout" of literal values that are enclosed in single quotes, if the value being supplied is "escaped" by preceding single quotes by with an additional single quote.
That is, assuming that your statement is guaranteeing that string literals are enclosed in quotes, as part of the "static" SQL text.
example perl-ish/php-ish
$sql = "... WHERE t.foo = '" . $safe_value . "' ... ";
^ ^
I've underscored here that the single quotes enclosing the literal are part of the SQL text. If $safe_value has been "escaped" by preceding each single quote in the "unsafe" value with another single value to make it "safe"...
$unsafe_value $safe_value
------------- ------------
I'm going I''m going
'she''s' ''she''''s''
1'='1 -- 1''=''1 --
As long as the escaping is handled properly, that we guarantee that potentially unsafe values are are run through the escaping, then including single quotes in data values is not a viable way to "breakout" of a literal with the SQL text.
That's the "no" part of the answer.
The "yes" part of the answer.
One of the biggest problems is making sure this is done EVERYWHERE, and that a mistake has not been made somewhere, assuming that a potentially unsafe string is "safe", and is not escaped. (For example, assuming that values pulled from a database table are "safe", and not escaping them before including them in SQL text.)
Also, the single quote trick is not the only avenue for SQL injection. The code could still be vulnerable.
Firstly, if we're not careful about other parts of the statement, like the single quotes enclosing string literals. Or, if for example, the code were to run the $sql through some other function, before it gets submitted to the database:
$sql = some_other_function($sql);
The return from some_other_function could potentially return SQL text that was in fact vulnerable. (As a ridiculous example, some_other_function might replace all occurrences of two consecutive single quotes with a single single quote. DOH!)
Also, with the vast number of possible unicode characters, if we're ever running through a characterset translation, there's also a possibility that some unicode character could get mapped to a single quote character. I don't have any specific example of that, but dollars to donuts that somewhere, in that plethora of multibyte encodings, there's some unicode character somewhere that will get translated to a single quote in some target.
There's a default character in the target for unmapped characters in the source, and that's usually a question mark (or a white question mark in a black diamond.) It would be a huge problem if the default character in the target (for unmapped characters in the source) was a single quote.
Bottom line: escaping unsafe strings by replacing single quotes with two single quotes goes a long ways towards mediating (mitigating?) SQL injection vulnerabilities. But in and of itself, it doesn't guarantee that code is not vulnerable in some other way.
if the input accepts unicode and is implicitly converted to ascii in the database (not as uncommon as it sounds) then an attacker can simply substitute ʻ or ʼ (0x02BB or 0x02BC) in place of single tick to get around the escaping mechanism and the implicit conversion will map those characters to single ticks (at least that's the case in SQL Server)

Escaping a forward slash in an SQL name? It can be "escaped", but SQL believes it to be multiple columns

The last person in my job has flooded column names with special characters such as (?,!, and /), as well as used many reserved keywords for column names (more often than not, timestamp or user is used).
Normally, I step around this by using double quotes or brackets to escape the SQL object. A subset of the full list of columns are below:
DriverID,
Department,
Odometer,
MerchantState,
MerchantCity,
gallons/Units,
timestamp,
tax
Inside my query, I wrap the two columns in question (gallons/units and timestamp) inside double quotes. Timestamp because it's a reserved keyword, and Gallons/units, because without the quotes, SQL reads the query, stops at the slash, and tells me "Gallons" is not a column inside the table.
If I do wrap double quotes around the column name, SQL returns a different error: "Operand should contain 1 column(s)".
I've tried every variant (only capturing the slash in quotes, quoting both, using brackets, mixing brackets and quotes, etc. but with to no avail).
Is there anything I can do to fix this query short of renaming the column name and changing the associated code in the program that pulls from it? (the really tedious task I'm trying to avoid).
In SQL Server, identifiers can be delimited using square brackets, e.g.
SELECT [gallons/units] ...
In MySQL, identifiers can be delimited using backticks, e.g.
SELECT `gallons/units` ...
(NOTE: If MySQL SQL_MODE includes ANSI_QUOTES, then double quotes are treated as delimiters for identifiers, similar to the way Oracle handles double quotes; absent that setting, double quotes are handled as delimiters for string literals. With ANSI_QUOTES included SQL_MODE, "gallons/units" will be interpreted as an identifier (column name). Without ANSI_QUOTES, MySQL will see it as a string literal, as if it were enclosed in single quotes.)
FOLLOWUP:
As far as an error "operand should contain only 1 column(s)", that's usually a problem with query semantics, not an issue with escaping identifiers.
A subquery in the SELECT list can return only a single expression, for example, this would throw an error:
Query: SELECT 'foo' , ( SELECT 'fee' AS fee, 'fi' AS fi )
Error Code: 1241
Operand should contain 1 column(s)
You can try backticks instead of double quotes
`gallons/units`
There are a couple of options. First, have you tried using %/ to escape the slash?
Example: "select * from 'gallons%/units';"
Second one I've found, which may or may not be helpful, is to provide an escape character definition, such as
http://blogs.msdn.com/b/zainala/archive/2008/08/17/using-and-escape-clause-in-sql-server-like-query.aspx
select * from MyTable where Description like '|[summary|]%' escape '|'
In your case
select * from 'gallons|/units' escape '|'
You indicate both mysql and sql-server in your tags, so I'm not sure which server support I should be looking for exactly.

DECODE Function in SQL

I am trying to insert the following query and I get syntax errors. Can you please help me with the below query:
INSERT INTO ABCTABLE (COLUMN1) values ('DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))');
Since you haven't really said anything other than "this query doesn't work, fix it", I have to take a stab in the dark what you want. From the query you have, I'm therefore guessing you want the value of the column to be DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))
In which case, you have to escape the single quotes within your string literal. Do this by doubling up the quotes:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''0000000000000000'',LPAD(TO_NUMBER(MDSE_CD,''16'','' ''))')
Try properly escaping the inner single quotes
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('**DECODE**(MDSE_CD,NULL,''0000000000000000'',**LPAD**(TO_NUMBER(MDSE_CD,''16'','' ''))');
The problem is the use of quote marks. If we tried to break up your query it would look like this:
INSERT INTO ABCTABLE
(COLUMN1)
values
(
'DECODE(MDSE_CD,NULL,'
0000000000000000
',LPAD(TO_NUMBER(MDSE_CD,'
16
','
'))'
);
...which clearly makes no sense.
You might want to think about how to escape a quote mark inside a string.
Sql Server:
DECOD function in Sql Server can be replaced with CASE construct
LPAD function in Sql Server has not a direct correspondence but you can pad your string using string manage function REPLACE (replicate a character a number of specified times)
My Sql:
DECOD function in MySql can be replaced with CASE construct
LPAD function in MySql is existent
What do you want to store... a string literal 'DECODE(MDSE...))', or did you want to call a function to derive a value?
To store a string literal containing single quotes, you need to "escape" each single quote within the string with an extra single quote, e.g.
O'Hare Int'l ==> 'O''Hare Int''l'
The DECODE function is Oracle specific. That expression will need to be rewritten using different functions in both MySQL and SQL Server.

explain these lines of mysql string Literals

I Have selected these lines from Mysql official site dev.mysql.com.
I am unable to understand what these lines means.
There are several ways to include quote characters within a string:
A “'” inside a string quoted with “'” may be written as “''”.
A “"” inside a string quoted with “"” may be written as “""”.
I did not understand how this sql.
mysql> SELECT 'hel''lo';
Outout: hel'lo
Please Help
You have a string inside single quotes, then it finds another quote, escaped by yet another code. So, it will translate into
'(start of string)hel'(escaping the next quote)'(the escaped quote)lo'(ending the string)
And thus outputting:
hel'lo
It's simple. If you need to put a quote within a string literal delimited by those quotes, you can't use just a standalone quote character (like 'O'Brien') since there's no easy way to tell which of the second or third quote is the closing quote.
So they introduce a rule. If the SQL interpreter is within a quoted string and it finds another quote, it uses these rules:
if the quote is immediately followed by another quote, assume the user wants one quote within the literal.
otherwise it's the closing quote for the literal.
So, for example, consider:
select * from people where surname = 'O'Brien' order by id
Now you and I can tell which of those quotes actually terminates the string literal because we understand how names work. The computer does not take that for granted, instead requiring:
select * from people where surname = 'O''Brien' order by id
and turning the '' inside the literal into a single '.