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, ...)
Thanks

Giovanni,
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

Similar Messages

  • 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.4126

    WebDev 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

  • XML Validation using java for SQL Injection and script validation

    I have an input coming from xml file.
    I have to read that input and validate the input against sql injections and scripts.
    I require help now how to read this xml data and validate against the above two options.
    I am a java developer.
    in this context what is marshelling?

    http://www.ibm.com/developerworks/library/x-javaxmlvalidapi.html?ca=dgr-lnxw07Java-XML-Val
    http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/package-summary.html
    The following code validates the xml against a xml schema
    // define the type of schema - we use W3C:
    String schemaLang = "http://www.w3.org/2001/XMLSchema";
    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
    Schema schema = factory.newSchema(new StreamSource("sample.xsd"));
    Validator validator = schema.newValidator();
    // at last perform validation:
    validator.validate(new StreamSource("sample.xml"));Message was edited by:
    haishai

  • 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 '&amp;&lt;&gt;' 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
    Nigel

    Recx 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&mdash;see 6(j).
    Promotional posts like this are liable to be removed by the moderators.

  • 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:29

    Avoid dynamic sql, avoid string concatenation and use bind variables and the risk is negligible.

  • SQL injection and SQLFury

    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

  • Abap mapping and variable substitution in File adapter

    Hi experts!!.
    I am new in abap mapping, but I can do one abap mapping succesfully, but my problem is:
    I need to do a variable substitution in my file receiver adapter:
    Target directory = %cliente&/out
    File Name Scheme = TC%Fecha%.EFI
    ¿Using abap mapping is this possible? How I can do it?.
    Please is very urgent.
    Thanks in advance, and best regarts.

    Yes you can,.
    DynamicConfigurationKey key = DynamicConfigurationKey.create(
        “http://sap.com/xi/XI/System/File”,
        “FileName”);
    will become
    DynamicConfigurationKey key = DynamicConfigurationKey.create(
        “http://sap.com/xi/XI/System/File”,
        “Directory”);
    In the receive file adapter all you would need to do is select Adapter Specifc Attributes --> File Name and Directory and givce some dummy values for the filename and directroy. In the runtime values will be taken from the SOAP header which you set in the mapping.
    Regards
    Bhavesh

  • [ask] about oracle sql injection and escalation

    Hello,i'm student , i'm studying oracle,now i want to research about oracle sql injection,i had read some tuttorial such as *'Hacking Oracle From Web,Advanced SQL Injection In Oracle Databases,Oracle Hacker HandBook ...'* but when i try to demo on localserver (11.0.1.6) but not run,and this is my demo
    -- first,i created table users
    create table users (name nvarchar2(50),pass nvarchar2(50))
    -- then i created procedure with system user
    create or replace procedure system.adduser(u nvarchar2,p nvarchar2)
    as
    begin
      insert into users values(u,p);
    end;
    -- grant execute privilege to oc user
    grant execute on adduser to oc
    -- login with user oc and create a procedure
    create or replace procedure sqli
    as
    begin
      execute immediate 'grant dba to oc';
    end;
    -- and then,i run system's procedure
    declare
    begin
      system.adduser('admin','admin'' ; execute immediate  ''declare begin sqli() end;');
    end;
    i hope oracle master help me to i can understand and improving my knowledge
    Thanks

    The best forum for this is probably Forum Home » Java » SQLJ/JDBC
    Presumably you are refering to oracle.sql.TIMESTAMP. While this is intended to (and does) correspond to java.sql.Timestamp it can't be a subclass because it needs to be a subclass of oracle.sql.Datum.

  • Dynamic file and variable substitution

    Hi Experts,
    I am working on a scenario where filename is reading from payload.based on header value ,i am creating file along with item records.I did variable substitution also.whenever header value changes ,a new file shud be created.
    I placed two records in my input message...
    <ns1:MT_DC_Send xmlns:ns1="http://urn:psr/ff/DC">
             <Source>
               <b> <FName>XYZ</FName>
                <FType>F</FType>
                <Input>Item1</Input></b>         </Source>
             <Source>
               <b> <FName>ABC</FName>
                <FType>F</FType>
                <Input>Item2</Input></b>
             </Source>
          </ns1:MT_DC_Send>
    but only one file is getting created with name XYZ.txt(I used cont conversion)
    output fiile data is
    <b>
    Item1
    Item2</b>
    Regards,
    Srinivas

    Srini,
    Thanks for the patience. The link which u sent is not working.
    Please find the total scenario in the below URL's, if u find any discrepancies , please let me know.
    <b>Structures defined</b>:http://www.flickr.com/photo_zoom.gne?id=956871756&size=o
    Create corresponding message types & Interfaces(Outbound:OB/Inbound:IB)
    <b>Mapping Logic:</b>
    First change the message occurrence:
    http://www.flickr.com/photo_zoom.gne?id=956027877&size=o
    Part1 :http://www.flickr.com/photo_zoom.gne?id=956871778&size=o
    Part2 :http://www.flickr.com/photo_zoom.gne?id=956871880&size=o
    Part3 :http://www.flickr.com/photo_zoom.gne?id=956871906&size=o
    UDF used in Part3 mapping:
    Test_Function[Cache:Queue, Input:FName, data]
    String local ="";
    for(int j=0;j<FName.length;j++)
    if(j==0)
    result.addValue(""data[j]"");
    local =FName[j];
    else
    if(FName[j].equals(local))
    result.addValue(""data[j]"");
    local =FName[j];
    else
    result.addContextChange();
    result.addValue(""data[j]"");
    local =FName[j];
    Message Mapping results:http://www.flickr.com/photo_zoom.gne?id=956027763&size=o
    <b>Interface Mapping:</b>
    http://www.flickr.com/photo_zoom.gne?id=956027893&size=o
    <b>Interface Determination:</b>
    http://www.flickr.com/photo_zoom.gne?id=956027913&size=o
    <b>Check your ID Objects:</b>
    http://www.flickr.com/photo_zoom.gne?id=956888454&size=o
    <b>Receiver Comm.Channel:</b>
    http://www.flickr.com/photo_zoom.gne?id=956027857&size=o
    Thats it!!!
    Now run the scenario. I used the same data which I used in the above URL's
    <b>SXMB_MONI</b>:http://www.flickr.com/photo_zoom.gne?id=956871938&size=o
    <b>Outputs</b>:http://www.flickr.com/photo_zoom.gne?id=956027957&size=o
    In the output file the first line which u see in the csv files are Item tag as per ur input. The second line is the filename , I don't know how to suppress the filename element in the output file. <b><i>Our friends has to help it out</i></b>.
    <b>Note:</b> While copying the test data from Mapping editor don't forget to remove the Messages element from the source.
    I hope it helps you!!!!!
    Best regards,
    raj.

  • File adaptor and variable substitution

    i have used variable substitution in the reciever comm channel to dynamically alter the folder ...Question is ..is there a way to do this from the sender comm channel..
    I know, i know we can write a custom module..etc..etc..
    I mean besides that ..is there a way sap provides out of the box...
    Michal..what do you think..?
    PS: your blog on var subst is very good !
    Regards
    Venkat

    Hi Venkat,
    For implementing variable substitution on the sender side. you can develop your own module as per your requirement.
    Only question is you can easily implement this on receiver side receives payload information coming after the mapping. While processing communication channel, it has payload to refer for variable substitution..
    While on the sender side communication channel do not have payload to implement variable substitution.
    Can you explain in detail about condition you want to apply in variable substitution.
    - Gaurav Jain

  • SQL*Loader and "Variable length field was truncated"

    Hi,
    I'm experiencing this problem using SQL*Loader: Release 8.1.7.0.0
    Here is my control file (it's actually split into separate control and data files, but the result is the same)
    LOAD DATA
    INFILE *
    APPEND INTO TABLE test
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    first_id,
    second_id,
    third_id,
    language_code,
    display_text VARCHAR(2000)
    begindata
    2,1,1,"eng","Type of Investment Account"
    The TEST table is defined as:
    Name Null? Type
    FIRST_ID NOT NULL NUMBER(4)
    SECOND_ID NOT NULL NUMBER(4)
    THIRD_ID NOT NULL NUMBER(4)
    LANGUAGE_CODE NOT NULL CHAR(3)
    DISPLAY_TEXT VARCHAR2(2000)
    QUESTION_BLOB BLOB
    The log file displays:
    Record 1: Warning on table "USER"."TEST", column DISPLAY_TEXT
    Variable length field was truncated.
    And the results of the insert are:
    FIRST_ID SECOND_ID THIRD_ID LANGUAGE_CODE DISPLAY_TEXT
    2 1 1 eng ype of Investment Account"
    The language_code field is imported correctly, but display_text keeps the closing delimiter, and loses the first character of the string. In other words, it is interpreting the enclosing double quote and/or the delimiter, and truncating the first two characters.
    I've also tried the following:
    LOAD DATA
    INFILE *
    APPEND INTO TABLE test
    FIELDS TERMINATED BY '|'
    first_id,
    second_id,
    third_id,
    language_code,
    display_text VARCHAR(2000)
    begindata
    2|1|1|eng|Type of Investment Account
    In this case, display_text is imported as:
    pe of Investment Account
    In the log file, I get this table which seems odd as well - why is the display_text column shown as having length 2002 when I explicitly set it to 2000?
    Column Name Position Len Term Encl Datatype
    FIRST_ID FIRST * | O(") CHARACTER
    SECOND_ID NEXT * | O(") CHARACTER
    THIRD_ID NEXT * | O(") CHARACTER
    LANGUAGE_CODE NEXT 3 | O(") CHARACTER
    DISPLAY_TEXT NEXT 2002 VARCHAR
    Am I missing something totally obvious in my control and data files? I've played with various combinations of delimiters (commas vs '|'), trailing nullcols, optional enclosed etc.
    Any help would be greatly appreciated!

    Use CHAR instead aof VARCHAR
    LOAD DATA
    INFILE *
    APPEND INTO TABLE test
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
      first_id,
      second_id,
      third_id,
      language_code,
      display_text    CHAR(2000)
    )From the docu:
    A VARCHAR field is a length-value datatype.
    It consists of a binary length subfield followed by a character string of the specified length.
    http://download-west.oracle.com/docs/cd/A87860_01/doc/server.817/a76955/ch05.htm#20324

  • Powershell dynamic T-SQL (string and variable contatenation)

    Hi, How do I build a dynamic t-sql through Powershell?
    $Query2 = @"
           INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])
         VALUES (" + $MaintLogRecords.Server + " ,"  + [Datetime]$MaintLogRecords.Startime + " , "  + $MaintLogRecords.Status + " )
    Write-Host $Query2
    results:
    servername
      INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])
         VALUES (" + System.Data.DataRow.Server + " ,"  + [Datetime]System.Data.DataRow.Startime + " , "  + System.Data.DataRow.Status + " )
    When I was expecting:
    servername
      INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])
         VALUES ('servername' ,'somedate' , 'success')
    When I do writehost for the values they show correctly I just really don't know how to build the dynamic t-sql correctly.
    Thanks!
    Paula

    Wrap the values with $() 
    PS C:\Test> $Query2 = @"
    INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])
    VALUES ("$($MaintLogRecords.Server)" , "$($MaintLogRecords.Startime)" , "$($MaintLogRecords.Status)" )
    Write-Host $Query2
    INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])
    VALUES ("" , "" , "" )

  • SQL Injection - cfqueryparam and other techniques to stop abuse?

    We have been having a lot of issues with SQL injection lately and so we are trying various methods to secure the data better.
    First off we have been utlizing cfqueryparam on the queries that are being hit. I am also optimizing the data tables so that more maxlengths are in place.
    What else can be done to improve security? I have looked up everything and anything on the internet and keep seeing the cfqueryparam.
    Does changing the variables or table names make any difference? We are trying that, but I want to make sure it is not a waste of our time.
    Thanks for any other suggestions.

    CFqueryparam is a good fist step, though you should note that it will not protect some queries.  For example if you have a sort by or order by that is dynamic, cfqueryparam wont help in that case.  You will need to review data and validate for that.
    You should also be checking for XSS vulnarabilities.
    http://www.12robots.com/index.cfm/2008/8/4/Persistent-XSS-Attacks-and-countermeausures-in- ColdFusion
    The blog above has a great number of CF sercurity related posts.
    Pete Freitag has a nice security scanner that will look at your CF server and highlight any missing patches and some other issues
    http://www.petefreitag.com/item/721.cfm
    There are some open source projects that will also filter out common sql injection and xss attacks on a code level.
    http://portcullis.riaforge.org/
    Finally there are several conferences in the CF world coming up, and all surely have some security sessions.  You may want to attend.

  • What is the difference btwn Variable Substitution and Dynami Configuration

    Hi Gurus
    Could you please explain the difference between the Variable Substituion and Dynamic Configuration.
    whn shall we use them and in what scenarios?
    thanx in advance

    Please go through this blog
    /people/shabarish.vijayakumar/blog/2009/03/26/dynamic-configuration-vs-variable-substitution--the-ultimate-battle-for-the-file-name
    Also this
    /people/madanmohan.agrawal/blog/2009/05/20/combining-three-different-aspects-of-pi-asma-af-module-and-variable-substitution-in-one-shot
    Edited by: Baskar Gopal on Mar 31, 2011 9:04 AM

  • SQL injection hacking

    Hello all,
    Someone is telling me that a site of mine is vulnerable to a
    hacking
    technique called "SQL injection". They cited a URL such as
    http://www.mydomain.com/gallery.cfm?VarCatID=29
    as an example.
    I Googled SQL injection, and found a lot of information,
    which I'm in the
    midst of reading.
    What I really want to know is, how serious a risk is this?
    Should I be
    taking action, and if so, what?
    Aren't there millions of sites that use that type of URL
    string?? Are they
    all unsafe too?
    Patty Ayers | www.WebDevBiz.com
    Free Articles on the Business of Web Development
    Web Design Contract, Estimate Request Form, Estimate
    Worksheet

    Thank you, Tom!
    Patty Ayers | www.WebDevBiz.com
    Free Articles on the Business of Web Development
    Web Design Contract, Estimate Request Form, Estimate
    Worksheet
    "Tom Muck" <[email protected]> wrote in
    message
    news:ecuu0f$dbn$[email protected]..
    > If you are passing an integer on a querystring, make
    sure you validate
    > that an integer is being passed, either by using a
    cfparm, cfqueryparam,
    > or by using the val() function on the passed querystring
    variable:
    >
    > <cfquery name="blah" datasource="#mydsn#">
    > SELECT * FROM mytable WHERE catid =
    > <cfqueryparam cfsqltype="cf_sql_integer"
    value="#url.VarCatID#">
    > </cfquery>
    >
    > The DW 8.0.2 update changed the way that DW does this so
    injection is no
    > longer a concern.
    >
    > --
    > --
    > Tom Muck
    > co-author Dreamweaver MX 2004: The Complete Reference
    >
    http://www.tom-muck.com/
    >
    > Cartweaver Development Team
    >
    http://www.cartweaver.com
    >
    > Extending Knowledge Daily
    >
    http://www.communitymx.com/
    >
    >
    > "P@tty Ayers"
    <[email protected]> wrote in message
    > news:ecut8j$cg6$[email protected]..
    >> Hello all,
    >>
    >> Someone is telling me that a site of mine is
    vulnerable to a hacking
    >> technique called "SQL injection". They cited a URL
    such as
    >>
    http://www.mydomain.com/gallery.cfm?VarCatID=29
    as an example.
    >>
    >> I Googled SQL injection, and found a lot of
    information, which I'm in the
    >> midst of reading.
    >>
    >> What I really want to know is, how serious a risk is
    this? Should I be
    >> taking action, and if so, what?
    >>
    >> Aren't there millions of sites that use that type of
    URL string?? Are
    >> they all unsafe too?
    >>
    >>
    >> --
    >> Patty Ayers | www.WebDevBiz.com
    >> Free Articles on the Business of Web Development
    >> Web Design Contract, Estimate Request Form, Estimate
    Worksheet
    >> --
    >>
    >>
    >>
    >>
    >
    >

Maybe you are looking for