Having trouble with SQL injection - sql

I am a noob when it comes to understanding some of the attacks in SQL injection. I am currently seeing this attack in my log and was wondering if anyone can help me understand what it means
SQL Injection:
410'union/**/select/**/1/**/from/**/(select/**/count(*),concat(floor(rand(0)*2),0x3a,(select/**/concat(user,0x3a,password)/**/from/**/pwn_base_admin/**/limit/**/0,1),0x3a)a/**/from/**/information_schema.tables/**/group/**/by/**/a)b/**/where'1'='1.

Dont understand this completely, but the select concat(user,0x3a,password) from pwn_base_admin clearly tries to get a concatenated string of user names and passwords, divided by a ":"
The concat(floor(rand(0)*2),0x3a,( roughly does the same... the result would be something like 1:aUserName:UsersPassword.
If you need further help please give some more details (RDBMS, the part before the "union"...)
Hope this helps

Someone is actively trying to gain unauthorized access to your system - they're hacking in.
I don't know how critical this system is, but if it is of any importance, you should probably take the system offline until you sort out the database access part of the code. The first place to look for solutions is using bind parameters instead of string concatenation for your sql queries.
There are many resources available that describe how to use bind variables for whatever RDBMS you're using, but here is one article I found to get you started:
http://use-the-index-luke.com/sql/where-clause/bind-parameters

Related

SQL Injection attempt, how does it work

I was looking at the logs and found a sql injection. Looks like it is used alot but I don't really understand how it works. I attempted to submit it through the form they submitted it through but nothing happens.
The injection string is:
(select(0)from(select(sleep(0)))v)/*''+(select(0)from(select(sleep(0)))v)+''"+(select(0)from(select(sleep(0)))v)+"*/
Can't figure out how they injected it. Didn't affect the server from what I can tell. They didn't get any data. But I still want to know how they made it work.
This is a vulnerability check. It's one of the easiest and safest way to figure out if your server is vulnerable to SQL injection - and more importantly, it doesn't need any attention from the would-be attacker! You can use a method like this to test sites automatically for SQL injection vulnerabilities - and in this case, it means that the potential attacker can run any kind of query or command, you seem to have no checks whatsoever. Needless to say, this is bad.
You should consider your server compromised - it's probably on someone's list now, pending further exploitation. Fix the issue ASAP, and ideally prevent the functionality altogether right away if the real fix is going to take some time.
The idea behind this is that a vulnerable server will respond differently to a query with different values for the sleep argument - this means that it's very easy to automatically go through all possible inputs (don't forget that even things like hidden fields and dropdowns can be changed at will) and find out if any of those are vulnerable. When this works, you can either inject a malicious query/command outright, or keep using the sleep to figure out information directly - particularly useful when there's no data you could make appear to the outside by modifying the vulnerable query. By series of yes-no questions (based on simple if(whatever, sleep(5), 0)) you can determine enough to press your attack further.

Optimal set of charecters to disallow/allow that prevent SQL injection perfectly?

I know that sql injection must rely on certain set of special characters used in SQL. So here's the question:
What would be the minimal set of characters to disallow, or as large as possible, a wet to allow, that would prevent SQL injection perfectly?
I understand This is not the best nor the easiest approach to prevent SQL injection, but i just wonder questions like "can you do it even without xxx".
Answering a comment:
Just for the purpose of curiosity, some languages other than English can indeed be written normally without some special characters. for example:
Chinese:“”‘’,。!?:;——
Japanese:””’’、。!?:;ーー
English:""'',.!?:;--
You may want to look up some examples of the kinds of ways a SQL injection attack can be leveraged against a web application with weak security architecture. As far as the "WHY" you'll need to analyze the kinds of site user hacks that can get through what's supposed to be a locked down (but public facing) system.
I turned up this reference for further analysis:
You can see more at the source of this injection:
http://www.unixwiz.net/techtips/sql-injection.html
I know that sql injection must rely on certain set of special characters used in SQL. So here's the question:
There isn't any one character that is absolutely banned, nor are there others that are trusted 100% safe.
EDIT: Response to a revised OP...
A brief history of a type of SQL Injection vulnerability: Without developing data access APIs for your database inputs, the most common approach is "dynamically" constructing SQL statements, then executing the raw SQL (a dangerous mix of developer prepared code and outside user input).
Consider in pseudocode:
#SQL_QUERY = "SELECT NAME, SOCIAL_SECURITY_NUMBER, PASSWD, BANK_ACCOUNT_NUMBER" +
"FROM SECURE_TABLE " + "WHERE NAME = " + #USER_INPUT_NAME;
$CONNECT_TO SQL_DB;
EXECUTE #SQL_QUERY;
...
The expected input when obeyed is a lookup of specific user information based on a single name value input from some user form.
While it isn't my point to accidentally teach a how-to for a new generation of would-be SQL Injection hackers, you can guess that a long concatenated string of code isn't really secure if user input on a web form can also tag on anything they like to the code; including more code of their own.
The utility or danger with using dynamic sql coding is a discussion by itself. You can put a few barriers in front of a dynamic query such as this:
An "input handler" procedure that all inputs from app forms go through before the query code module is executed:
run_query( parse_and_clean( #input_value ) )
This is where you look for things like string inputs too long for expected sizes (a 500 character name???? non-alpha numerical name values?)
Web forms can also have their own scripted input handlers. Usually intended for validating for specific inputs (not empty, longer than three characters, no punctuation, format masks like "1-XXX-XXX-XXXX", etc.) They can also scrub for input hacks such as html coding tags, javascript, urls with remote calls, etc. Sometimes this need is best served here because the offending input is caught before it gets anywhere near the database.
False positives: more often it really is just user error sending malformatted input.
These examples date to the really early days of the Internet. There are lots of source code modules/libraries, add-ons, open-source and paid variants of attempts to make SQL injection much harder to break through into your host systems. Dig around; there is even a huge thread on Stack Overflow that discusses this exact topic.
For the time I have been stumbling around and developing for the Internet, I share a common observation: "perfectly" is a description of a system that has already been hacked. You won't get there, and that isn't the point. You should look towards being the "easy, quick target" (i.e., the Benz in the gas station with windows down, keys in ignition and owner in the restroom)
When you say "can you do it even without...?" The answer is "sure" if it's a "Hello World" type project for some classroom assignment... hosted on your local machine... behind your router/firewall. After all, you gotta learn somewhere. Just be smart where you deploy stuff that isn't so secured.
It's just when you put things out open to the "world" on the Internet, you should always be thinking how the "same task" has to be done differently with a security mindset. Same outputs as your test/dev workspace but with more precautions such as locking down obvious and commonly exploited weaknesses.
Enjoy your additional research, and hopefully this post (devoid of code examples) can encourage your mindset in helpful directions.
Onward.
I know that sql injection must rely on certain set of special characters used in SQL. So here's the question:
What would be the minimal set of characters to disallow, or as large as possible, a wet to allow, that would prevent SQL injection perfectly?
This is the wrong approach to this topic. Instead you need to understand why and how SQL injections happen. Then you can work out measures which prevent them.
Because the cause of SQL injections is the incorporation of user supplied data into SQL command. If the user supplied fragments are not processed properly, they could modify the intention of the SQL command.
Here the aspect of proper processing is crucial, which again depends on the developer’s intention of how the user provided data is supposed to be interpreted. In most cases it’s a literal value (e. g., string, number, date, etc.) and sometimes a SQL keyword (e. g., sort order ASC or DESC, operators, etc.) or even an identifier (e. g., column name, etc.).
These all follow certain syntax rules which can the user provided data can either be validated against and/or enforced:
Prepared statements are the first choice for literal values. They separate the SQL statement and parameter values so that latter can’t be mistakenly interpreted as something other than literal values.
White listing can always be used when the set of valid values it limited, which is the case for SQL keywords and identifiers.
So looking at the use cases for user provided data and the corresponding options that prevent SQL injections, there is no need to restrict the set of allowed characters globally. Better stick to the methods which are best practice and have proved effective.
And if you happen to have a use case that doesn’t fit the mentioned, e. g., allowing users to provide something more complex than an atomic language elements like an arbitrary filter expression, you should break them down into their atoms to be able to ensure their integrity.

Implement a querylanguage

I would like to create my own query language for a web api I wrote. But I have no idea where to start for it.
The language should be like SQL. For that I looked up the NHibernate code, cause I know, that they have the HQL (Hibernate Query Language) but it didn't help.
Are there any instructions or sth.? If this question is wrong here please move and/or tell me where I should ask else.
The first step is a lot of design work, starting be answering the following question:
Is this new Query Language going to be converted to SQL which will be
executed by a standard database engine, or are you going to write your
own database server as well?
If it's going to be converted to SQL (just like HQL) then map out the translations from your language to SQL on paper (and make sure you know the possible SQL constructs you may have to use). Once you've got that, you can start implementing it. Yes, this sounds like BDUF, but the language should be defined in one pass, I think, as it will be more consistent and easier to use if you do it that way. You can always implement it in a more Agile way once you've got that.
If you're going to write own database server, you're on your own....

Executing Dynamic SQL in Oracle (PL/SQL) and Ensuring Security

If I have a valid SQL string; is there anyway I can execute it in my PL/SQL - but guarantee that it is a SELECT statement only...without doing complex parsing to ensure it doesn't have any escape characters/nested commands or any of that jazz?
EDIT:
What I'm really trying to accomplish is a generic, built-in to my application, querying tool. It has a friendly, domain specific GUI and lets a very non-tech user create reasonably complex queries. The tool handles versioning of the searches, adds innerjoins where needed and some other application specific stuff you wouldn't find a typical SQL DEV type tool.
The application successfully creates a SQL Query. The problem is that I also allow users to directly enter their own SQL. I'm worried about potential SQL injection type issues.
I'm not sure if this is the appropriate place; but, in addition to the question - if anyone could recommend a good Oracle book that would get me up to speed on things of this nature - I'd very much appreciate it.
One solution is to GRANT your user only SELECT privilege if that's the only thing the user is authorized to do.
See "Oracle Database Security Guide: Introduction to Privileges"
However, I don't think that your application is necessarily secure just because you restrict the queries to SELECT. There are examples of mischief that can be perpetrated when you allow unsafe use of SELECT queries.
Re your clarified question: I've studied SQL injection and written about it quite a bit. What I can advise as a general rule is: Never execute user input as code. That's how SQL injection occurs.
You can design a domain-specific language and map user input to SQL operations, but make sure there's a layer that translates user choices to the database schema. If you separate user input from your SQL code by introducing a mapping layer, then you should be all right.
See also my answer to "How do I protect this function from sql injection."
Oracle comes with a lot of execute privileges granted to public. As such even a user with no explicit insert/update/delete/execute privileges can do mischief.
Speaking of mischief, even with a SELECT a user could cause trouble. A "SELECT * FROM table FOR UPDATE of column" would lock the entire table. SELECT...FOR UPDATE only requires SELECT privileges.
Dumb queries (eg cartesian joins) could bring a database to its needs (though Resource Manager should be able to block most of them by only allowing queries that would do less than a specified amount of IOs or CPU).
How about giving them a list of approved SQLs to execute and a process for them to nominate SQLs for inclusion ?
If you're giving the user a text area so they can type whatever they want, hey, SQL injection is what you want.
I wouldn't leave the door so open like that, but if I was forced to do it, then I'd run an explain plan on whatever the user wants to do. The optimizer will parse the query and put all the information about the SQL statement in the plan_table table, which you can then query to check if it's really a select operation, which tables/indexes from which schemas are being accessed, if the where clause is something you approve of, if there's any "bad" operations, such as Cartesian joins or full table scans, etc.
Take a look at Oracle's paper on writing injection proof pl/sql. The DBMS_ASSERT built-in package should help you test your SQL for appropriateness.
Even with those tests, I'd be extremely reluctant to give people an open text window for building their queries especially on the public net or in a large organization where you don't know everybody. There are very creative people just looking for opportunities like that.
In oracle, you can just check to see that the first word is "select" or "with". This is due to PL/SQL's Ada heritage, which requires compound statements to be in begin/end blocks, so that the usual SQL injection techniques just cause syntax errors.
Of course, the best answer is to do this by granting permissions and avoiding if possible directly evaluating unknown input. But it is interesting that the begin/end syntax eliminates a lot of SQL injection attack vectors.

Catching SQL Injection and other Malicious Web Requests

I am looking for a tool that can detect malicious requests (such as obvious SQL injection gets or posts) and will immediately ban the IP address of the requester/add to a blacklist. I am aware that in an ideal world our code should be able to handle such requests and treat them accordingly, but there is a lot of value in such a tool even when the site is safe from these kinds of attacks, as it can lead to saving bandwidth, preventing bloat of analytics, etc.
Ideally, I'm looking for a cross-platform (LAMP/.NET) solution that sits at a higher level than the technology stack; perhaps at the web-server or hardware level. I'm not sure if this exists, though.
Either way, I'd like to hear the community's feedback so that I can see what my options might be with regard to implementation and approach.
Your almost looking at it the wrong way, no 3party tool that is not aware of your application methods/naming/data/domain is going to going to be able to perfectly protect you.
Something like SQL injection prevention is something that has to be in the code, and best written by the people that wrote the SQL, because they are the ones that will know what should/shouldnt be in those fields (unless your project has very good docs)
Your right, this all has been done before. You dont quite have to reinvent the wheel, but you do have to carve a new one because of a differences in everyone's axle diameters.
This is not a drop-in and run problem, you really do have to be familiar with what exactly SQL injection is before you can prevent it. It is a sneaky problem, so it takes equally sneaky protections.
These 2 links taught me far more then the basics on the subject to get started, and helped me better phrase my future lookups on specific questions that weren't answered.
SQL injection
SQL Injection Attacks by Example
And while this one isnt quite a 100% finder, it will "show you the light" on existing problem in your existing code, but like with webstandards, dont stop coding once you pass this test.
Exploit-Me
The problem with a generic tool is that it is very difficult to come up with a set of rules that will only match against a genuine attack.
SQL keywords are all English words, and don't forget that the string
DROP TABLE users;
is perfectly valid in a form field that, for example, contains an answer to a programming question.
The only sensible option is to sanitise the input before ever passing it to your database but pass it on nonetheless. Otherwise lots of perfectly normal, non-malicious users are going to get banned from your site.
One method that might work for some cases would be to take the sql string that would run if you naively used the form data and pass it to some code that counts the number of statements that would actually be executed. If it is greater than the number expected, then there is a decent chance that an injection was attempted, especially for fields that are unlikely to include control characters such as username.
Something like a normal text box would be a bit harder since this method would be a lot more likely to return false positives, but this would be a start, at least.
One little thing to keep in mind: In some countries (i.e. most of Europe), people do not have static IP Addresses, so blacklisting should not be forever.
Oracle has got an online tutorial about SQL Injection. Even though you want a ready-made solution, this might give you some hints on how to use it better to defend yourself.
Now that I think about it, a Bayesian filter similar to the ones used to block spam might work decently too. If you got together a set of normal text for each field and a set of sql injections, you might be able to train it to flag injection attacks.
One of my sites was recently hacked through SQL Injection. It added a link to a virus for every text field in the db! The fix was to add some code looking for SQL keywords. Fortunately, I've developed in ColdFiusion, so the code sits in my Application.cfm file which is run at the beginning of every webpage & it looks at all the URL variables. Wikipedia has some good links to help too.
Interesting how this is being implemented years later by google and them removing the URL all together in order to prevent XSS attacks and other malicious acitivites