Sql injection character fields
Is it true that with MSSQL in the background, character fields can't be used for sql injection?
A) One source says that in MSSQL single quotes are escaped into double quotes.
B) Another source says that " SQL injection (within ColdFusion apps) is really only an issue with non textual fields. If a text value is tampered with you'll end up with tampered text, but that text will all be part of the core string (within quotes) passed as a value, and will therefore not be executed as separate statements. Numbers, on the other hand, are not enclosed within quotes, and so extraneous text can be tampered "
Questions about A): How does escaping 's with "s help, by making string literals in MSSQL not valid?
How could A) above be true when names like O'Mally are being stored with a single quote ?
Questions about B) Does it mean code like DELETE * FROM atable would just be stored as a string and not execute ?
If so, is that accurate ?
To actually answer your question's.
A) A single quote in SQL is a comment. To store a single quote as DATA one has to escape it by doubling it. So to store O'Mally it would be passed as o''Mally.
The simple SQL injection attack is to end a number value with a random value, that is followed with a ; to end the SQL statment and then another statement can be run, this is then followed by a single quote to comment out any other SQL in the original statement. ColdFusion automatically escapes single quotes in text fields in most situations, so this is harder to do with text fields, but not impossible.
Similar Messages
-
How to construct a sql query when field having single quote
Hi all,
I have been working on web application , here is my requirement:
I'm constructing sql statement dynamically from dynamic user input (form data). In one of the field having single quote.
while executing the query it is getting problem because of single quote .. so how do i resolve my problem.
single quote should be there. (I'm using Ms-Access as my database).
Thanks in advance
abelUse PreparedStatement. Always. It not only eases setting Java objects in a SQL query, but also protects you against SQL injections.
Prepare yourself: [http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html]. -
SQL Injection, replace single quote with two single quotes?
Is replacing a single quote with two single quotes adequate
for eliminating
SQL injection attacks? This article (
http://www.devguru.com/features/kb/kb100206.asp
) offers that advice, and it
enabled me to allow users to search name fields in the
database that contain
single quotes.
I was advised to use "Paramaterized SQL" in an earlier post,
but I can't
understand the concept behind that method, and whether it
applies to
queries, writes, or both.Then you can use both stored procedures and prepared
statements.
Both provide better protection than simply replacing
apostrophes.
Prepared statements are simple:
Set myCommand = Server.CreateObject("ADODB.Command")
...snip...
myCommand.CommandText = "INSERT INTO Users([Name], [Email])
VALUES (?, ?)"
...snip...
myCommand.Parameters.Append
myCommand.CreateParameter("@Name",200,1,50,Name)
myCommand.Parameters.Append
myCommand.CreateParameter("@Email",200,1,50,Email)
myCommand.Execute ,,128 'the ,,128 sets execution flags that
tell ADO not to
look for rows to be returned. This saves the expense of
creating a
recordset object you don't need.
Stored procedures are executed in a similar manner. DW can
help you with a
stored procedure through the "Command (Stored Procedure)"
server behavior.
You can see a full example of a prepared statement by looking
at DW's
recordset code after you've created a recordset using version
8.02.
"Mike Z" <[email protected]> wrote in message
news:eo5idq$3qr$[email protected]..
>I should have repeated this, I am using VBScript in ASP,
with an Access DB.
> -
How to get a currency format for a character field
for some specifix reason, we have a requirement to show character field (which results in value 633948) in the format $633,948
how do i do this?
if i do SELECT to_char(:c_1,'$999,999')) from dual;
it gives me ora: 01722: invalid number error
c_1 is a user parameter of data type characterTry using TO_NUMBER first, as in something like:
SQL> VARIABLE c_1 VARCHAR2(6)
SQL> EXECUTE :c_1 := '633948';
PL/SQL procedure successfully completed.
SQL> SELECT TO_CHAR(TO_NUMBER(:c_1), '$999,999') FROM DUAL;
TO_CHAR(T
$633,948Hope this helps. -
SQL Injection and variable substitutions
Hello helpful forum, I'm trying to understand what really goes on "behind" the scenes
with the variable substitutions in order to protect from sql injections.
I'm using apex 3.0.0.00.20
The trickiest component seems to be a Report of type "pl/sql returning sql", since
multiple dynamic sql interpretations are done there.
consider the following innocent looking disaster:
DECLARE
l_out VARCHAR2(2000);
BEGIN
l_out := 'select * from test_injection t where t.name like ''%' || :NAME || '%''';
RETURN l_out;
END;
if NAME is a single quote the report will return:
failed to parse SQL query: ORA-00911: invalid character
which hints to the fact that NAME is not escaped, and you are in fact able to access db functions
as in: '||lower('S')||'
I also tried to put there a function that runs in a autonomous transaction to log its calls, and
I see that it's called five times for each request.
consider now the similar solution (notice the two single quotes):
DECLARE
l_out VARCHAR2(2000);
BEGIN
l_out := 'select * from test_injection t where t.name like ''%'' || :NAME || ''%''';
RETURN l_out;
END;
with this second example nothing of the above is possible.
So my theory (please confirm it or refute it) is that there is a first variable substitution done
at the pl/sql level (and in the second case :NAME is just a string so nothing is substituted).
Then the dynamic sql is executed and it returns the following string:
select * from test_injection t where t.name like '%' || :NAME || '%'
now another substitution is done (at an "APEX" level) and then query is finally executed to return
the rows to the report.
The tricky point seems to be that the first substitution doesn't escape the variable (hence the error
with the single quote), while the second substitution does.
Please let me know if this makes sense and what are the proper guidelines to avoid sql injection with
the different kinds of reports and components (SQL, pl/sql returning sql, processes, ...)
ThanksGiovanni,
You should build report regions like this using the second method so that all bind variables (colon followed by name) appear in the resultant varchar2 variable, l_out in your example, which will then be parsed as the report query. This addresses not only the SQL injection problem but the shared-pool friendliness problem.
Scott -
In trying to help another user, I was reminded of a problem I
face
often. Trying to create a DW recordset using an IN clause (I
think this
got broken in the 8.0.2 update and seems to still be broken
in CS3).
I create a string held in a variable like this:
$ids = (1,5,9,23,6)
My advanced recordset is this:
SELECT * FROM tbl WHERE id IN varIds
Then I set the variable parameters to type=text,
default=(-1), and
runtime to $ids.
The generated SQL doesn;t work because DW puts single quotes
around my
variable and the SQL query becomes invalid. DW creates this:
SELECT * FROM tbl WHERE id IN '(1,5,9,23,6)'
It should be:
SELECT * FROM tbl WHERE id IN (1,5,9,23,6)
So, I edited the SWITCH block at the top of the document to
include a
"custom" type, which is the same as the TEXT type but without
the single
quotes.
case "custom":
$theValue = ($theValue != "") ? $theValue : "NULL";
break;
Then in my SQL statement, I manually changed "text" to
"custom".
This work fine, but does that open me up to SQL injection or
other bad
stuff?
Alec Fehl, MCSE, A+, ACE, ACI
Adobe Community Expert
AUTHOR:
Microsoft Office 2007 PowerPoint: Comprehensive Course
(Labyrinth
Publications)
Welcome to Web Design and HTML (Labyrinth Publications)
CO-AUTHOR:
Microsoft Office 2007: Essentials (Labyrinth Publications)
Computer Concepts and Vista (Labyrinth Publications)
Mike Meyers' A+ Guide to Managing and Troubleshooting PCs
(McGraw-Hill)
Internet Systems and Applications (EMC Paradigm)It looks like you're using PHP ... to protect from SQL
injections I always
do this:
$query = "SELECT * FROM tbl WHERE col='%s' AND col2 IN
(%d,%d)"
$query = sprintf($query,"val",34,23);
$result = mysql_query($query);
This method ensures that if a user puts "DELETE FROM tbl" in
an input
field, it will not cause any deletions, instead the words
'DELETE FROM tbl'
will be inserted. Check out sprintf in the PHP manual - good
stuff!
One thing to remember about SQL injection, the injected SQL
has to be
entered somehow by the end-user (usually with a form); I may
be wrong, but
this sql statement looks like it is contained entirely within
your scripts
(i.e. it isn't getting getting a user-generated value to
build any part of
the SQL statement). Again, I'm guessing here - but it looks
that way.
Alex
"Alec Fehl" <[email protected]> wrote in message
news:[email protected]...
> In trying to help another user, I was reminded of a
problem I face often.
> Trying to create a DW recordset using an IN clause (I
think this got
> broken in the 8.0.2 update and seems to still be broken
in CS3).
>
> I create a string held in a variable like this:
> $ids = (1,5,9,23,6)
>
> My advanced recordset is this:
>
> SELECT * FROM tbl WHERE id IN varIds
>
> Then I set the variable parameters to type=text,
default=(-1), and runtime
> to $ids.
>
> The generated SQL doesn;t work because DW puts single
quotes around my
> variable and the SQL query becomes invalid. DW creates
this:
>
> SELECT * FROM tbl WHERE id IN '(1,5,9,23,6)'
>
> It should be:
>
> SELECT * FROM tbl WHERE id IN (1,5,9,23,6)
>
> So, I edited the SWITCH block at the top of the document
to include a
> "custom" type, which is the same as the TEXT type but
without the single
> quotes.
> case "custom":
> $theValue = ($theValue != "") ? $theValue : "NULL";
> break;
> Then in my SQL statement, I manually changed "text" to
"custom".
>
> This work fine, but does that open me up to SQL
injection or other bad
> stuff?
>
>
> --
> Alec Fehl, MCSE, A+, ACE, ACI
> Adobe Community Expert
>
> AUTHOR:
> Microsoft Office 2007 PowerPoint: Comprehensive Course
(Labyrinth
> Publications)
> Welcome to Web Design and HTML (Labyrinth Publications)
>
> CO-AUTHOR:
> Microsoft Office 2007: Essentials (Labyrinth
Publications)
> Computer Concepts and Vista (Labyrinth Publications)
> Mike Meyers' A+ Guide to Managing and Troubleshooting
PCs (McGraw-Hill)
> Internet Systems and Applications (EMC Paradigm) -
SQL Injection when using Search by Example on a View Object
It seems that the SQL queries generated by "Search by Example" pattern (When you drop a view object as a Search Form) are not using bind parameters, and will be vulnerable to SQL injection attacks. This pattern is very handy and could be very useful to create search pages. Is there a way to avoid SQL Injection and still use this feature in ADF?
ChandreshHi,
from a training slide developed by Duncan Mills:
When the user is in Find mode and enters some information, he or she is constructing a ViewCriteria row. Each attribute in the View object exists in this row and any values that the user enters into the fields are mapped into these attributes.
In most circumstances, you will only ever have one criteria row, although the developer can allow multiple rows if the Create operation is called during Find mode.
To parse the entered query values, you need to look at each row, and then at each attribute. Calling getAttribute() returns the value the user entered (if any) for that field. You can then pass that string to a filter routine (shown in the next slide), which inspects this value for errors.
The filter routine can then change the example value if required and reset the criteria.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
protected String detectInjection(String criteria) {
boolean reject = false;
String testPattern = "^(>=|<=|=<|=>|<|>|<>|!=|=|BETWEEN|IN|LIKE|IS)";
String testCriteria = criteria.trim().toUpperCase();
if (testCriteria != null && testCriteria.length() > 0) {
Pattern pattern = Pattern.compile(testPattern);
Matcher matcher = pattern.matcher(testCriteria);
if (matcher.find())
reject = true;
return reject?null:criteria;
}Frank -
SQL Injection & CF code Attacks
One thing I've noticed with sites using CF is that many, many
programmers do not take into account SQL Injection and CF Form/URL
variable attacks. I've seen SO many CF pages that blow up when the
input varies in the slightest, displaying CF error messages,
datasources, variable names, etc.
Seems not enough programmers use CFTRY/CFCATCH or even know
about it. I've seen where SQL table names and datasources were
being passed in a URL!! It's frightening
Interested in everyone's BEST PRACTICES to avoid these type
of attacks.
I'll start it off with a few I use:
Use CFTRY / CFCATCH.
ALWAYS set the maxlength value on form input text boxes and
make sure the value matches the corresponding column length in your
DB. If you do not, someone can enter a huge amount of data in the
field, causing your CF routine or DB to choke.
Scope all variables, URL, Form, etc.
Use numbers/integers whenever possible for URL variable
values.
Avoid using varchar as the data type in your stored
procedures for passed URL or Form variables. Use INT instead.
Validate user input using CF before passing to your SQL, etc.
queries. Test for allowed/disallowed characters, blanks, length of
input value, etc.
Use stored procedures whenever possible.
Don't make URL or Form variable names too descriptive. ex.
?m=100 is better than ?memberID=100In addition to the things listed above, you should never
expect the values sent from any form submission to be 100% as they
are coded. There are tons of programs out there that can be used to
intercept and alter the submitted data before it hits your server.
It is a slow process, but we are locking down any and all form
variables not just type="text" and textarea's.
If a user has the ability to alter submitted data, they can
change the values for all types of form fields (hidden, radio,
checkbox, select, button, etc...). A lot of our old code did not
take that into consideration and simply allowed the value entered
from a "predefind" (hard coded value) form type (radio, checkbox,
etc...) directly into the database without a check.
Another step is to turn off "Enable Robust Exception
Information" in the CF Administrator. This step will help in not
giving an attacker the complete SQL statement being used in your
code. Note: This is a recomended practice for all production CF
servers as it is, but it never hurts to say it. CFTRY/CFCATCH
blocks work as well to hid that info, but neither way will
prevent an attack.
You also can not rely on client side JavaScript for
validation.
CR -
SQL Injection with CF7 and MS SQL 2005
I looked through a bunch of SQL injection posts and couldn't
find a definitive answer to this...
Let me introduce this by saying that I know I should be using
CFQUERYPARAM with EVERY CF variable in a CFQUERY tag. No excuses.
But for a necessary quick fix, if I only use it for numeric
DB fields, is SQL injection still possible (using MS SQL 2005)?
I've yet to successfully perform SQL injection while manipulating a
variable surrounded by single quotes in the query.
Scenario 1) select * from users where user_id=#form.user_id#
...is a gimme to hack, but
Scenario 2) select * from users where
password='#form.password#' ...is another story
Has anyone ever heard of a successful SQL injection attack in
a Scenario 2 situation.
I'll fix everything up eventually, but I've got a Pen Test
coming up soon, and a lot of raw code to review.
Thanksquote:
Originally posted by:
Dan Bracuk
What others can do is more relevent than what we think. When
in doubt, test.
very true, although my final solution went more like, "When
in doubt, manually add about 600 cfqueryparams in 406 cfquery
tags". -
SQL Injection and Java Regular Expression: How to match words?
Dear friends,
I am handling sql injection attack to our application with java regular expression. I used it to match that if there are malicious characters or key words injected into the parameter value.
The denied characters and key words can be " ' ", " ; ", "insert", "delete" and so on. The expression I write is String pattern_str="('|;|insert|delete)+".
I know it is not correct. It could not be used to only match the whole word insert or delete. Each character in the two words can be matched and it is not what I want. Do you have any idea to only match the whole word?
Thanks,
Ricky
Edited by: Ricky Ru on 28/04/2011 02:29Avoid dynamic sql, avoid string concatenation and use bind variables and the risk is negligible.
-
We have recently had an SQL injection attack on our site. The web form in question was calling a second cfm with a post command. The second cfm did the actually db insert. After extensive research and revamping of the web form I believed that I had shut it down rather convincingly. I did the following to secure the form:
- implemented the cfqueryparam tag on all applicable fields being entered in the form
- introduced a hidden, random numeric variable for verification before completing the insert; it tests for its existence and if it is numeric
- consolidated the two cfms into one page so the entry and insert are done in one cfm (to eliminate injection going directly thru insert cfm)
However, I am still getting intermittent injection errors into my MS SQL table. I don't believe it is getting in through the revised web form and am at a loss as to how it's getting through.
I am now at the point that I am looking for a utility that will scan through my site or specific pages to identify SQL injection vulnerabilties. I found something called SQLFury and downloaded it; however, there is literally no documentation with it and I have no idea how to run it. I've researched the web and found no assistance on how to use this utility. Is anyone familiar with this utility or does anyone know of any other utility that will assist with validating ColdFusion methods?
Any assistance would be very much appreciated.Ian:
Thanks for the information. The utility is helpful and confirmed for me that my page was secure from SQL injection. The additional insight you provided has lead me to discover that my issue was not an SQL injection, but a Cross Scripting attack. A web vulnerability utility from Acunetix helped me determine that.
Thanks again,
...Wes -
SQL Injection and cfqueryparam
I was told to look into <cfqueryparam> to assist in
fighting sql-injection
and it makes perfect sense, up until I thought of a different
scenario...
This tag seems great when you are dealing with numbers or
text that you can
restrict the number of characters, but what if you have a
textarea that
allows for a large amount of text to be entered? I.E. a
search field for
records that uses keywords.
How you stop someone from entering damaging sql into an area
that accepts
this?
Thanks for any education.
Wally Kolcz
MyNextPet.org
Founder / Developer
586.871.4126WebDev wrote:
It works because <cfqueryparam ....> tells the DBMS
that this data is a
value NOT SQL. The DBMS will then never process it as SQL.
When you
write the SQL and Values straight into the code, then the
DBMS does not
know what is what and assumes it all must be SQL.
An Example...
<cfquery ....>
SELECT aField FROM aTable WHERE aField = '#aValue#'
</cfquery>
With this code, ColdFusion process the entire body of the
<cfquery...>
tag into a string and sends that entire string to the DBMS as
SQL. The
DBMS then processes what it was given. If somebody can modify
the
aValue variable to change the SQL string - that is what is
processed.
<cfquery ...>
SELECT aField FROM aTable WHERE aField = <cfqueryParam
value="#aValue#"...>
</cfquery>
With this code ColdFusion process the SQL and the queryParam
as separate
things. It sends the DBMS the SQL with parameters and a list
of values
to be used in those parameters. The DBMS knows the parameters
are not
SQL and will not process it as SQL and if the parameter
contains SQL it
will just be used as a value and not parsed.
FYI... That is how <cfqueryparam...> can improve
performance. By
knowing what parts of the SQL are variables, it can cache the
SQL and
just use different variables when they are passed to the
DBMS.
HTH
Ian -
hi
How can we solve SQL injection problem in JDBC ?
this means if we have a form with text field and the user must enter a number say 4 , instead he entered "4 or true" this will concatenated with the SQL query and return all records because of "or true"....
is there any solutions ?
i tried PreparedStatment and it words but not alwayes
good lucki clearfied this in my first post
if u didnt got what i mean u can google it
http://www.google.com
thanksYou didn't gently provide keywords, like I always do, so I cannot learn from you.
Well, with a "reproduceable example" I mean that you have to post a short but complete working code snippet which reproduces the problem. So that we can copy'n'paste it in our environment here and test/debug it ourself and then eventually confirm the SQL injection. -
SQL Injections and XSS - Escaping Special Characters
Hi, hope someone can help in regards to security and SQL Injections and XSS.
We are using APEX 4.0.2 on Oracle 11.2.0.2.
1. It seems the special characters we have entered into normal 'Text Items' 'Text Areas' etc are not being escaped (ie <,>,&, '). If I enter them into the field (ie Surname) they are saved as is into session state and the database - no escaping. Am I missing something such as an environment setting as I thought the "smart" oracle escaping rules would cater for this.
Surely I don't have to manually do each of then.
Just to confirm, am I looking in the correct places to assess if the characters are escaped or not - ie should they show as '&<>' in session state and/or the database ?
2. Also, for the Oracle procedures such as '‘wwv_flow.accept’ , ‘wwv_flow.show’ , 'wwv_flow_utilities.show_as_popup_calendar' - do these escape special characters. If not, then they must be vulnerable to SQL Injections attacks.
Thx
NigelRecx Ltd wrote:
Just to pitch in, escaping values internally (either in the database or session state) is extremely problematic. Data searches, string comparison, reporting and double escaping are all areas which suffer badly when you do this.
Stripping characters on input can also cause problems if not considered within the context of the application. Names such as "O'Niel", statistical output such as "n < 300", fields containing deliberate HTML markup can be annoying to debug. In certain situations stripping is totally ineffective and may still lead to cross-site scripting.
Apex applications that share the database with other applications will also be affected.
The database should contain 'raw' unfettered data and output should be escaped properly, as Joel said, at render time. Either with Apex attributes or using PLSQL functions such as htf.escape_sc() as and when required.Do not needlessly resurrect old threads. After a couple of months watches expire and the original posters are not alerted to the presence of your follow-up.
Shameless plug: If you are in the game of needing to produce secure Apex code, you should get in touch.This crosses the line into spam: it violates the OTN Terms of Use—see 6(j).
Promotional posts like this are liable to be removed by the moderators. -
Using CFMX7:
In trying to block out SQL Injection we are implementing
‘<cfquery params’ on all related query statements
for our application, however this is an undertaking for several
queries that need to be validated with params.
In the meantime, we have been exploring methods which include
the ODBC statement lockouts in CF Admin for the database
connection.
What we have found is the following; setting the Allowed SQL
of ‘DROP’ to FALSE, will catch an injection of DROP
TABLE only if that statement is in the actual body of the query,
alone.
This is trapped as exception:
<cfquery
name="tryDrop" datasource="mydatasource">
DROP TABLE mytest
</cfquery>
However, the following is NOT caught:
<cfquery
name="tryDrop" datasource="mydatasource">
UPDATE mytest SET sortorder = 5; DROP TABLE mytest
</cfquery>
In this case, the ODBC still allows the DROP statement to be
executed.
We have also tested this case as shown above as well as a SQL
INJECT item using a variable for an INT field (below), which also
is allowed.
<cfset
myString = “1; DROP TABLE mytest;”> <!---
simulate a form variable, INT field --->
<cfquery name="tryDrop" datasource="mydatasource">
UPDATE mytest SET sortorder = #myString#
</cfquery>
Is there a patch or fix that will correct the ODBC level to
prevent this case?
Note: after the setting the SQL Command DROP to false, we
tried restarting CF Service and also tried suspending all ODBC
connections for that datasource and neither solved the problem.
Any information would be appreciated.quote:
Originally posted by:
jb_aggie
Also, in MS SQL Server 2000 is there a way to restrict these
permissions for a database user on the database level? I can only
find this permission on the table level.
USE master
GO
-- run only if user account exists in master database
-- if it does you should probably remove it from master, it
should have access only to user created databases, not system
databases
IF EXISTS ( SELECT * FROM sysusers WHERE [name] = 'test' )
BEGIN
DENY
CREATE DATABASE,
CREATE DEFAULT,
CREATE FUNCTION,
CREATE PROCEDURE,
CREATE RULE,
CREATE TABLE,
CREATE VIEW,
BACKUP DATABASE,
BACKUP LOG
TO test
END
USE MyDatabase
GO
DENY
CREATE DEFAULT,
CREATE FUNCTION,
CREATE PROCEDURE,
CREATE RULE,
CREATE TABLE,
CREATE VIEW,
BACKUP DATABASE,
BACKUP LOG
TO test
Also remove the user from all roles except public and grant
only the permissions needed for your application and only the
database(s) used by your application.
As long as your account is not an administrative account or
owner of database objects it should not be able to DROP tables.
http://msdn.microsoft.com/en-us/library/aa258841(SQL.80).aspx
Maybe you are looking for
-
Iphone 5 no longer able to sync to itunes...HELP!!!!
Hey guys, I have tried numerous atempts to getting my iPhone 5 to be able to sync with my MacBook Pro but to no avail. It seems as though this all started after updating to the new OSX Yosemite as well as updating to the new iTunes 12.0.1. Whenever I
-
Display issues in both os x and windows 7
I Use bootcamp for most of my games and recently there has been a lot ofis elation but lately it has gotten really bad as I'm writing this there is a thunderbolt and a y with the upper left and bottom lines not solid like the top right I will upload
-
Deactivate authorization checks in BSP or function modules?
Hi all I have a BSP application that seems to use a standard function module that performs an unwanted authorization check on object M_MATE_VKO (Material check on sales organization) I know it is possible to globally deactivate authorization checks i
-
Why do we need to upload meta data through IDX2
Hi Experts, Why do we need to uplaod the meta data through idx2 ,if we won't do that what will be the impact on oue scenario. Regards
-
Getting Error while doing Control Panel - Windows Update Error code is 80070103
Getting Error while doing Control Panel -> Windows Update Error code is 80070103. The optional Windows 7 update is Microsoft - Other hardware - WinUsb Device Please provide your email ID to send the Error screen shot.