Best way of avoiding SQL injection?

Hey,
I was wondering what you guys would recommend to prevent SQL injections. Now, I know that you can use the PreparedStatement and setString for cases like this:
String userName  = request.getParameter("username");
String sqlString = "SELECT * FROM UserTable WHERE USERNAME='" + userName ;but what can you do when you have cases like these:
String userdef_table  = request.getParameter("userdef_table");
String userName  = request.getParameter("username");
String sqlString = "SELECT * FROM "+ userdef_table +" WHERE USERNAME='" + userName ;Note: userdef_table can be created by the admin so I wont know what tables are around.
thanks,
domet

For Your First Question
1) using PreparedStatement is the best way, but yes you will have to catch the Table Not Found Exception very well in case the passed table deso not exist... Thats The Only Logical Answer For your Query
For Your Second Query
1) Create a String variable which will have the required reflex string ie the text you would liketo have after LIKE keyword and then pass the variable to the prepare statement
this
?% will not work for its wrong SQL query
String likeThis = "%Bill%"; <or what ever>
the Query part will be like this ".......like ?"
setString(....,likeThis);
Hope This Works
Bhaskar

Similar Messages

  • What is a best way to write SQL ?

    Sample Case
    drop table t;
    drop table b;
    create table t ( a varchar2(4), b number, c varchar2(1));
    insert into t values ('A00', 10, 'R');
    insert into t values ('A01', 11, 'R');
    insert into t values ('A02', 12, 'R');
    insert into t values ('A03', 13, 'R');
    insert into t values ('A00', 10, 'P');
    insert into t values ('A01', 11, 'P');
    insert into t values ('A02', 12, 'P');
    insert into t values ('A03', 13, 'P');
    commit;
    create table b ( j varchar(4), k varchar2(1), l varchar2(5), m number(3), n varchar2(5), o number(3));
    insert into b values ('A00', 'P', 'FIXED', 100, 'FLOAT', 60);
    insert into b values ('A01', 'P', 'FIXED', 101, 'FIXED', 30);
    insert into b values ('A02', 'R', 'FLOAT', 45, 'FLOAT', 72);
    insert into b values ('A03', 'R', 'FIXED', 55, 'FLOAT', 53);
    commit;
    10:19:13 SQL> select * from t;
    A B C
    A00 10 R
    A01 11 R
    A02 12 R
    A03 13 R
    A00 10 P
    A01 11 P
    A02 12 P
    A03 13 P
    8 rows selected.
    10:19:19 SQL> select * from b;
    J K L M N O
    A00 P FIXED 100 FLOAT 60
    A01 P FIXED 101 FIXED 30
    A02 R FLOAT 45 FLOAT 72
    A03 R FIXED 55 FLOAT 53
    1/     In table t each reference having 2 records one with P another is with R
    2/     In table b each refrence merged into single record and there are many records which are not existing in table t
    3/      both t and j tables can be joined using a = j
    4/     If from table t for a reference indicator is 'P' then if have to pick up l and m columns, if it is 'R' then I have to pick up n and o columns
    5/     I want output in following format
    A00     P     FIXED          100
    A00     R     FLOAT          60
    A01     P     FIXED          101
    A01     R     FIXED          30
    A02     P     FLOAT          72
    A02     R     FLOAT          45
    A03     P     FLOAT          53
    A03     R     FIXED          55
    6/     Above example is a sample ouput, In above example I have picked up only l,m,n,o columns, but in real example there are many columns ( around 40 ) to be selected. ( using "case when" may not be practical )
    Kindly suggest me what is a best way to write SQL ?
    thanks & regards
    pjp

    Is this?
    select b.j,t.c as k,decode(t.c,'P',l,n) as l,decode(t.c,'P',m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 45
    A02 R FLOAT 72
    A03 P FIXED 55
    A03 R FLOAT 53
    8 rows selected.
    or is this?
    select b.j,t.c as k,decode(t.c,b.k,l,n) as l,decode(t.c,b.k,m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 72
    A02 R FLOAT 45
    A03 P FLOAT 53
    A03 R FIXED 55
    8 rows selected.

  • Best way to avoid an interface?

    so far i have been able to record my keyboard via midi, my synth through a guitar cable with an attachment at the end that plugs it into the line in (not sure what its called) and same goes for guitar
    so what i am wondering if there is a simple cheap way to get a mic plugged in without buying an interface
    and if so is there any big quality differences without an interface
    i have noticed that some of the garage band effects on my guitar produce some static and i am not sure if its the settings or what
    thanks : )
    also if i would be able to plug in a mixer without an interface
    so basically what i am asking is
    a. how to plug a mic and mixer into my mac and into garage band without an interface and
    b. is there a quality difference (especially with guitar)

    don1212 wrote:
    ok sweet so the mixer will fix clipping
    my band is investing in some drum mics and a new vocal mic too so the mixer will be really helpful
    as for the guitar effects in garage band do they sounds pretty professional when they arent clipping?
    i would really like to use them but i wanna mek sure they sounds quality when recorded
    As long as you are contemplating a mixer, you might as well contemplate an interface. So the best answer to your question: The best way to avoid an interface? Is: Don't! You are using your computer to record audio from a variety of sources - guitar, mic, whatever... why get a second rate solution when a first rate solution exists? If budget is an issue, there are cheap interfaces just like there are cheap mixers. They're cheap enough so you could probably afford both if you needed a mixer and an interface, or some interfaces include the functions of both an interface and a mixer so you'd only need one.
    I have a feeling that some of your "clipping" issues would go away with a proper interface that is designed to shuttle sound from the outside world into your computer just the way you want.
    You might want to check out a major music retailer like www.sweetwater.com which has a very thorough selection of gear on their website. They are also very helpful if you call them, although don't let them sell you anything you don't want!
    Oh, and the guitar effects in GB sound surprisingly good!
    Interface!!!

  • What is the best way to avoid latency when using the io plug in?

    What is the best way to avoid latency when using the io plug in?

    Hi colin a.
    Welcome to the Support Communities!
    The article below may be able to help you with this.  Click on the link to see more details and screenshots. 
    Logic: About I/O buffer size and monitoring latency
    http://support.apple.com/kb/ht1314
    Cheers,
    - Judy

  • What is the best way to practice SQL language?

    I’m new in database world and want to practice SQL language. I’ve been playing around with Oracle XE, but I realized it’s not very practical to play around with SQL using XE since its sql editor is not user friendly to debug the script. I’m trying to build schemas from scratch and play around with it using SQL. What is the best way to do this?
    Thanks in advance

    Valerie Debonair wrote:
    I’m new in database world and want to practice SQL language. I’ve been playing around with Oracle XE, but I realized it’s not very practical to play around with SQL using XE since its sql editor is not user friendly to debug the script. I do not think that is a valid criticism at all. The basic tools needed to learn SQL is SQL*Plus and a willingness to learn.
    There is no "+debugging+" for SQL either... except to break it into simpler steps, testing that... and perhaps using "+explain plan+" to get the execution plan.
    Granted that SQL*Plus is not the best tool for displaying data... but then learning SQL should be done using small data sets (not too many columns and few rows) - as even a small data set can represent all the data model complexities needed for learning SQL.
    The examples you use, the test tables and the practical exercises used in the learning process are by far more important how "pretty" the tool being used is.
    FWIW, I do 99% of all my SQL work and PL/SQL development using SQL*Plus - it is a very capable tool.

  • Access-SQL Server (Client Server Configuration) Best Way To Refresh SQL Server Records ?

    We are using Access 2013 as the front end and SQL Server 2014 as the back end to a client server configuration.
    Access controls are bound to the SQL fields with the same names. When using Access to create a new record in a Form, the data are not transferred to SQL if the form is exited to display a different Form or Access is closed. If the right or left arrow navigation
    buttons at the bottom of the form are first used to display either the previous or next record, then the data in the new record are correctly transferred to SQL.
    What is the best way to refresh the new SQL record prior to the closing of the new record in the bound Access form ? We have tried Requery of the entire form and with all of the individual controls without success. We are looking for a method of refreshing
    SQL that functions in a manner similar to that of what happens with the navigation buttons.
    Thank you very much for your assistance.
    Robert Robinson
    RERThird

    Hi Stefan,
    I had added the code to set me.dirty = False in response to the On Dirty event and didn't realize that it was working properly. I had tried other several approaches and must have become confused somewhere along the line.
    I retested the program. On Dirty is working and the problem is solved.
    Thank you very much for your assistance.
    Robert Robinson
    RERThird

  • How to detect SQL type to avoid SQL injection

    Hi,
    I work in a gsm company and we develop a program to make trend analysis. Users of this program know how to write SQL statements. I want them to write specific sql statements as input statement of my program (SELECT ... from ...). Mostly SELECT statements. I have PL/SQL blocks and dynamic SQL's in my program. I get user defined SQL statements and execute them as Dynamic Sql's.
    Here is the problem: I need to understant what type of SQL they give as input parameter of my program to avoid wrong operations (DELETE, TRUNCATE, DROP...)
    First i thought about the REGEXP to understant if its a SELECT SQL or DELETE SQL..
    Is there any recommend about this problem? Does Oracle have any procedure to detect it?
    Thanks

    acadet wrote:
    BluShadow wrote:
    a_yavuz wrote:
    I work in a gsm company and we develop a program to make trend analysis. Users of this program know how to write SQL statements. I want them to write specific sql statements as input statement of my program (SELECT ... from ...). What is the specification behind these "specific sql statements"?
    This should allow you to define a lexicon of permitted terms within the language and, if it's not too complex, you could then write a lexicon/language parser to validate each of the statements submitted, thus ensuring they cannot permit anything that is not expected. It may not be a simple tasks, depending on how complex your sub-language of SQL is, but if you are wanting to truly allow users to use SQL rather than some user interface that restricts input and prevents injection, then it's one of the safer ways of doing it.Hi,
    This is exactly what the database does through the technique of grants. Why reinvent the wheel.
    AndreAssuming you're only talking about access to database objects etc. and that the database user shouldn't be able to perform those tasks through a controlled interface. What if they should be able to e.g. delete records, but only through a controlled screen, whereas the selection of data is to be flexible and permit SQL.
    The original question sounds more like he wants to permit a certain subset of the SQL language as he says he wants them to write "specific sql statements". If there is a definition of what form those statements should take then a restricted lexicon parser could be written to cater for those.

  • Importing my iPhoto library into Aperture.  Best way to avoid duplicates?

    Hi,
    I'm a new Mac user.  I have been in the very slow and tedious process of transferring my photos from my HP hard drive to my Mac.  I used iPhoto for a very brief time before purchasing Aperture 3.  (I've used photoshop for years.)  I haven't yet Imported or consolidated or whatever the correct term would be the iPhoto library into the Aperture library.  I've been avoiding it because I know there are some duplicates.  Mainly just a few "Events" from the last few weeks before starting using Aperture.  Now with the new update, it seems like it's a great time to get it all consolidated into an Aperture library that I can use in both iPhoto and Aperture.  What's the easiest way for me to proceed?  I'm sorry for my lack of proper Mac terms....I'm learning!
    Thanks so much for your help!
    Christy

    Clear as mud??
    If you want to see all your images - those now in your Aperture Library and those in your iPhoto Library- then you need to merge both Libraries into one Library - I'd import your iPhoto Library into the Aperture Library.
    This combined Library will be compatible with both Applications.
    To merge your iPhoto Library into the Aperture Library do the following:
    Make a backup of your current iPhoto library (libraries)
    Upgrade to iPhoto 9.3, if you have not already done so.
    Open your iPhoto Library at least once in Photo 9.3 to upgrade the Library.
    Unhide all hidden images. You cannot unhide them when viewing the Library in Aperture.
    Quit iPhoto.
    If you have not already upgraded to Aperture 3.3, do it like this:
    Backup your current Aperture library.
    Rebuild the Aperture Database using the Aperture Library First Aid Tools: Launch Aperture with the cmd-options-key combination (⌘⌥) firmly held down, then select  "Rebuild Database".
    After rebuilding upgrade to Aperture 3.3 and launch Aperture to upgrade the Aperture Library.
    With Aperture still open, double click your iPhoto Library. Aperture will prompt you, if you want to add or merge your iPhoto Library - choose "Merge". This will avoid importing duplicate images, as far as Aperture can tell that those are the same images - same filename.
    You will have to weed out some duplicates yourself - this is best be done by sorting the images by capture date, then duplicate shots will appear side by side.
    Post back, if you have more questions.
    Regards
    Léonie

  • What's the best way to avoid seams in patterns?

    I read an article that suggested avoiding tiles with fractions of pixels, but that does not solve it for me. Here's an enlarged section of a pattern.
    I've found ways around it by turning it into a tile, pasting into Photoshop, trimming by a pixel and then filling with the pattern in Photoshop. But, that's a lot of time spent trying to get around a program glitch. Any suggestions?

    It helps sometimes. For this pattern I'd rethink the art.
    With the new Pattern Builder there's rarely a need to duplicate items. Simply configure the tile with only the art needed:
    Note there are no duplicate elements. All you need are primaries.
    Setting up art this way eleiminates seams in the middle of objects entirely.

  • Best way to write sql

    hi,
    i have a table named as tbl_a
    tbl_a
    filelds     values
    a_name     a     b
    a_desc     s     s
    a_amt     1     -5
    a_amt_in
    now i want to merge this values in a table called as tbl_b which has same structure
    logic required is:
    if value is negative for a_amt then insert this value in a_amt_in
    is this possible to write in single insert..
    or what logic would be best
    regards

    its giving F/WG error
    ORA-00909: invalid number of arguments
    select decode(sign(GOA_EX_IN,-1,GOA_EX_OUT,GOA_EX_IN) ) from EA_DSR_T WHERE TATA_IN IS NULL
    update t_ea set goa_ex_in=(select decode(sign(GOA_EX_IN,-1,GOA_EX_OUT,GOA_EX_IN) ) from EA_DSR_T WHERE TATA_IN IS NULL )

  • Best way to avoid requirement for network ACL after upgrade to 11g

    Hi All,
    After upgrade from 10g to 11g, I found Network ACLs required to make code using SYS.UTL_SMTP to work. Otherwise there is an error: ORA-24247: network access denied by access control list (ACL).
    Do you know an elegant way to get rid of ACLs? I mean to open the network for all user's code, like it was on 10g, instead of checking what is actually needing it and doing specific ACLs for users. Database parameter disabling ACL restrictions seems natural option here, but it looks like Oracle not introduced such.
    Kind Regards,
    Artzaw

    I don't know of a way to disable ACLs, no.  I'd imagine that there probably is a hidden parameter that Oracle Support could direct you to.  I'm hard-pressed to imagine why you'd really want to disable that functionality, though.
    You can create an ACL that allows access to an arbitrary host on an arbitrary port (host => '*.*.*.*' and with NULL lower_port and upper_port values). 
    Justin

  • Best way to avoid having duplicate copies of songs on multi-account mac?

    In our household, we have several ipods, and 4 user accounts on our main household workhorse mac. As our music tastes are different but with some overlap, I wondered if there was alternative to wasting a bunch of harddrive space storing some identical albums in each user's own account? Can I just just set up each users ITunes configuration to use a common / shared folder for the music somewhere outside our own user account zone? Ideally I can see us then just setting up our personal playlists out of that common pool of music? Sounds too simple.
    I don't want to sacrifice the separate user accounts, as I have work data in my area which needs to be secured from kids etc..
    If so, are there any drawbacks? will it kick up a fuss if several users logon at once? will the ipods cooperate or will mass confusion ensue?
    Any ideas or guidance from the i-intellegentsia appreciated...
    Mac G5 dual 2.5 Mac OS X (10.4.3) loaded

    I went ahead and moved the files and it works fine from everyone's account. No duplication of music files necessary.

  • What is the best way to avoid The orange "Media Pending" screen?

    I have my students save their captured footage and project in the same folder so they won't have issues. But I found today after loading larger files from Panasonic AG-AC8 cameras it was happening a lot. Anything I need to do differently? Thanks.

    Thanks. I think I was just doing it wrong, because it doesn't crash anymore, lol.
    Importing from Photo Booth requires saving to desktop, rather than sharing via media browser. A bit manual, but seems to work!
    Thanks again!

  • 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?
    Chandresh

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

Maybe you are looking for

  • Android plugin not working in Eclipse on Arch 64bit

    Hi, I'm having some trouble getting the android plugin to work. I know there are a lot of similar threads about this on this forum and google but nothing seems to work. I have installed Eclipse 4.2 through pacman. I removed openJDK and installed Orac

  • Is there any limitation of devices for purchased content?

    Hi there, Is there any limitation of devices i can download content i purchased on itunes store? For example if i bought a movie or and album, to how many devices maximum i can download this movie (of course with the same APPLE ID) Thank you in advan

  • HTTP 500 Internal Server Error( I got this error,when I open my web page.)

    I'm using JDeveloper 10.1.3. I deploied my application at Target platform is Standalone OC4J 10g 10.1.3. I can open my application at my local host. I tried to do same way for company server. I can't open my application, I created my application adf

  • Create BDC for Shipments

    Dear Friends. I have to connect 2 different BDCs in a program. First BDC. Starts from tcode VL06P, as I enter Route and Warehouse Num, A list of deliveries is displayed. I have to pick the Ship to Party from this list and start the second BDC. Second

  • Loupe very slow!

    Hi, Generally ver. 2.1 is speedy on both my computers - intel iMac 2.16Ghz 2GB Ram as well as the latest MacBook. Problem appears after applying highlights & shadows adjustment. Loupe becomes unusable - almost completely unresponsive. Same when panni