• ARTICLES
SEARCH

How-To Geek

HTG Explains: How Hackers Take Over Web Sites with SQL Injection / DDoS

image

Even if you’ve only loosely followed the events of the hacker groups Anonymous and LulzSec, you’ve probably heard about web sites and services being hacked, like the infamous Sony hacks. Have you ever wondered how they do it?

There are a number of tools and techniques that these groups use, and while we’re not trying to give you a manual to do this yourself, it’s useful to understand what’s going on. Two of the attacks you consistently hear about them using are “(Distributed) Denial of Service” (DDoS) and “SQL Injections” (SQLI). Here’s how they work.

Image by xkcd

Denial of Service Attack

image

What is it?

A “denial of service” (sometimes called a “distributed denial of service” or DDoS) attack occurs when a system, in this case a web server, receives so many requests at one time that the server resources are overloaded the system simply locks up and shuts down. The goal and result of a successful DDoS attack is the websites on the target server are unavailable to legitimate traffic requests.

How does it work?

The logistics of a DDoS attack may be best explained by an example.

Imagine a million people (the attackers) get together with the goal of hampering Company X’s business by taking down their call center. The attackers coordinate so that on Tuesday at 9 AM they will all call Company X’s phone number. Most likely, Company X’s phone system will not be able to handle a million calls at once so all the incoming lines will tied up by the attackers. The result is that legitimate customer calls (i.e. those that are not the attackers) do not get through because the phone system is tied up handling the calls from the attackers. So in essence Company X is potentially losing business due to the legitimate requests being unable to get through.

A DDoS attack on a web server works exactly the same way. Because there is virtually no way to know what traffic is sourced from legitimate requests vs. attackers until the web server is processing the request, this type of attack is typically very effective.

Executing the attack

Due to the “brute force” nature of a DDoS attack, you need to have lots of computers all coordinated to attack at the same time. Revisiting our call center example, this would require all the attackers to both know to call at 9 AM and actually call at that time. While this principle certainly will work when it comes to attacking a web server, it becomes significantly easier when zombie computers, instead of actual manned computers, are utilized.

As you probably know, there are lots of variants of malware and trojans which, once on your system, lie dormant and occasionally “phone home” for instructions. One of these instructions could, for example, be to send repeated requests to Company X’s web server at 9 AM. So with a single update to the home location of the respective malware, a single attacker can instantly coordinate hundreds of thousands of compromised computers to perform a massive DDoS attack.

The beauty of utilizing zombie computers is not only in its effectiveness, but also in its anonymity as the attacker doesn’t actually have to use their computer at all to execute the attack.

SQL Injection Attack

image

What is it?

A “SQL injection” (SQLI) attack is an exploit that takes advantage of poor web development techniques and, typically combined with, faulty database security. The result of a successful attack can range from impersonating a user account to a complete compromise of the respective database or server. Unlike a DDoS attack, an SQLI attack is completely and easily preventable if a web application is appropriately programmed.

Executing the attack

Whenever you login to a web site and enter your user name and password, in order to test your credentials the web application may run a query like the following:

SELECT UserID FROM Users WHERE UserName='myuser' AND Password='mypass';

Note: string values in a SQL query must be enclosed in single quotes which is why they appear around the user entered values.

So the combination of the entered user name (myuser) and password (mypass) must match an entry in the Users table in order for a UserID to be returned. If there is no match, no UserID is returned so the login credentials are invalid. While a particular implementation may differ, the mechanics are pretty standard.

So now let’s look at a template authentication query which we can substitute the values the user enters on the web form:

SELECT UserID FROM Users WHERE UserName=’[user]‘ AND Password=’[pass]‘

At first glance this may seem like a straightforward and logical step for easily validating users, however if a simple substitution of the user entered values is performed on this template, it is susceptible to an SQLI attack.

For example, suppose “myuser’–” is entered in the user name field and “wrongpass” is entered in the password. Using simple substitution in our template query, we would get this:

SELECT UserID FROM Users WHERE UserName='myuser'--' AND Password='wrongpass'

A key to this statement is the inclusion of the two dashes (--). This is the begin comment token for SQL statements, so anything appearing after the two dashes (inclusive) will be ignored. Essentially, the above query is executed by the database as:

SELECT UserID FROM Users WHERE UserName='myuser'

The glaring omission here is the lack of the password check. By including the two dashes as part of the user field, we completely bypassed the password check condition and were able to login as “myuser” without knowing the respective password. This act of manipulating the query to produce unintended results is a SQL injection attack.

What damage can be done?

A SQL injection attack is caused by negligent and irresponsible application coding and is completely preventable (which we will cover in a moment), however the extent of the damage which can be done depends on the database setup. In order for a web application to communicate with the backend database, the application must supply a login to the database (note, this is different than a user login to the web site itself). Depending on what permissions the web application requires, this respective database account can require anything from read/write permission in existing tables only to full database access. If this isn’t clear now, a few examples should help provide some clarity.

Based on the above example, you can see that by entering, for example, "youruser'--", "admin'--" or any other user name, we can instantly login to the site as that user without knowing the password. Once we are in the system doesn’t know we are not actually that user so we have full access to the respective account. Database permissions will not provide a safety net for this because, typically, a web site must have at least read/write access to its respective database.

Now let’s assume the web site has full control of its respective database which gives the ability to delete records, add/remove tables, add new security accounts, etc. It is important to note that some web applications could need this type of permission so it is not automatically a bad thing that full control is granted.

So to illustrate the damage which can be done in this situation, we will use the example provided in the comic above by entering the following into the user name field: "Robert'; DROP TABLE Users;--". After simple substitution the authentication query becomes:

SELECT UserID FROM Users WHERE UserName='Robert'; DROP TABLE Users;--' AND Password='wrongpass'

Note: the semicolon is in a SQL query is used to signify the end of a particular statement and the beginning of a new statement.

Which gets executed by the database as:

SELECT UserID FROM Users WHERE UserName='Robert'

DROP TABLE Users

So just like that, we have used an SQLI attack to delete the entire Users table.

Of course, much worse can be done as, depending the SQL permissions allowed, the attacker can change values, dump tables (or the entire database itself) to a text file, create new login accounts or even hijack the entire database installation.

Preventing a SQL injection attack

As we mentioned several times previously, a SQL injection attack is easily preventable. One of the cardinal rules of web development is you never blindly trust user input as we did when we performed simple substitution in our template query above.

An SQLI attack is easily thwarted by what is called sanitizing (or escaping) your inputs. The sanitize process is actually quite trivial as all it essentially does is handle any inline single quote (‘) characters appropriately such that they cannot be used to prematurely terminate a string inside of a SQL statement.

For example, if you wanted to lookup “O’neil” in a database, you couldn’t use simple substitution because the single quote after the O would cause the string to prematurely end. Instead you sanitize it by using the respective database’s escape character. Let’s assume the escape character for an inline single quote is prefacing each quote with a \ symbol. So “O’neal” would be sanitized as “O\’neil”.

This simple act of sanitation pretty much prevents an SQLI attack. To illustrate, let’s revisit our previous examples and see the resulting queries when the user input is sanitized.

myuser'-- / wrongpass:

SELECT UserID FROM Users WHERE UserName='myuser\'--' AND Password='wrongpass'

Because the single quote after myuser is escaped (meaning it is considered part of the target value), the database will literally search for the UserName of "myuser'--". Additionally, because the dashes are included within the string value and not the SQL statement itself, they will be considered part of the target value instead of being interpreted as a SQL comment.

Robert'; DROP TABLE Users;-- / wrongpass:

SELECT UserID FROM Users WHERE UserName='Robert\'; DROP TABLE Users;--' AND Password='wrongpass'

By simply escaping the single quote after Robert, both the semicolon and dashes are contained within the UserName search string so the database will literally search for "Robert'; DROP TABLE Users;--" instead of executing the table delete.

In Summary

While web attacks evolve and become more sophisticated or focus on a different point of entry, it is important to remember to protect against tried and true attacks which have been the inspiration of several freely available “hacker tools” designed to exploit them.

Certain types of attacks, such as DDoS, cannot be easily avoided while others, such as SQLI, can. However, the damage which can be done by these types of attacks can range anywhere from an inconvenience to catastrophic depending on the precautions taken.

Jason Faulkner is a developer and IT professional who never has a hot cup of coffee far away. Interact with him on Google+

  • Published 11/16/11

Comments (31)

  1. Alex H.

    That was a very nice and clear explanation for the layman. There is a third standard attack that one often hears about in the news etc.; the buffer overflow. Maybe you can apply your clear insight on that topic in a future post.

  2. Karan S.

    Very good post, explanation of 2 widely used attacks.
    But your explanation of DOS also contained Distributed DOS so might want to clear that up.
    Also it would be nice to mention Http track where a “user” can copy all the url related files from the server if its not protected.
    all in all good post :)

  3. mayurnagekar

    Karan- u wud want to talk abt http attack. Are you referring to open directory listing ?

  4. dragonbite

    Great info! I hear about “sanitizing” and “scrubbing” the input but this nicely outlines now only how but why! Thanks!

  5. JohnJoseph

    Thank you for such a simplified and clear explanation that even a non-tech person like me can understand.

  6. CitrusRain

    I once seen a job site for a news company have a textbox with instructions to use different sql keywords…

    Litterally having the user make the query.

  7. Bob S

    Explanations of the effectiveness of their tricks are fine for illuminating the process, I wish someone would please explain why these puerile troublemakers get so much apparent pleasure from doing these childish things to louse up the internet experience for average users!

    Why can’t all the brains in the Industry – who are able to detect the source of the problems caused by the script kiddies in the medium, do something other than simply react to these attacks after the damage has been done?

    Maybe the internet needs a massive security overhaul that doesn’t include so many backdoors built into it that practically invites so many people with questionable ulterior motives to track everybodies’ personal IP and the ability to log their daily internet activity!

  8. jokerbelmont

    Easily one of the best articles I’ve read on this site. Thanks!!! :)

  9. Jason Faulkner

    @Bob S – Typically hackers are in it for either money (or some other tangible gain) or notoriety. However, I think in LulzSec’s case it is motivated by a sense of injustice. They are the equivalent of vigilantes doling out what they feel is appropriate justice.

    As for “the brains in the industry” solving the problems – I showed how SQLI attacks can be prevented. If you are victim of this, it is your own fault. However, you cannot really stop DDoS attacks (unless you have a massive distributed system capable of handling the attacking traffic), but as long as your web server is set up correctly, this is nothing more than a temporary inconvenience.

  10. _Ron

    Very nice write up on these two types of attacks. Now if we could also get web sites to work property with tracking tokens and PCI data.

  11. Ammar

    amazing article

  12. Bengie

    Sanitizing is “a” way to help prevent SQL Injection, but it isn’t 100%.

    Other languages may have different names, but MS SQL allows “paramerterized” inputs. It allows your application to separate the SQL command from the parameters while making your code easier to understand. This means it is impossible to send anything via a parameters that will change the SQL command, while not having any of the headache of sanitizing your input.

    A pseudocode example:

    sqlcmd = “select 1 from tbl_User where vchUserName = @UserName and vchPassword = @Password”

    sqlcmd.parameters.add(“UserName”, txtUserName.Text)
    sqlcmd.parameters.add(“Password”, txtPassword.Text.hash)

    sqlcmd.execute

    That’s it. 100% secure from an SQL Injection point of view.

  13. Lisa

    Thank you for this valuable information. I hope you continue with the your good work. Just a quick comment on denial of service. Denial of service may or may not be an attack. The government has issued rebates in the past, for example on appliances and the site could not handle it, and crashed. A crashed site may not be for deviant behavior, but unintended traffic without proper precautions.

  14. Sridhar

    Brilliant article! Keep ‘em coming!

  15. Amir

    thanks. i needed to know that. your explanation rocked!

  16. Jim

    “Jason Faulkner is a developer and IT professional who never has a hot cup of coffee far away” makes little sense and is easily misinterpreted. A better rephrasing is: “who always has a cup of hot coffee nearby”.

  17. Todd

    Im new at learning how to protect my laptop the right ways and well Though I understand what this article says. I dont understand how to prevent SQL attacks (which I know I keep getting from Facebook) I am a Facebookaholic (I have 6 accounts) and I am constantly having problems like lag, wont connect, lots of probs wit adobe flash player. I love my facebook games that I play but tired of all the issues.

    Can Anyone Help??

  18. Pipo

    Nice article. I tried to learn a bit of PHP and MySQL back in college, and I think I remember reading before that PHP (or Apache?) automaticaly sanitizes/escapes user input before executing SQL code?

  19. Dom

    Pipo, I believe you a referring to php’s get magic quotes function which can be, but is not always enabled on different hosts. If you’re going to write portable code then you may get in trouble with relying on this feature, I also believe that its not as complete a solutions to sql injection as using mysql_real_escape_string (http://php.net/manual/en/function.mysql-real-escape-string.php for more info) mysql_real_escape_string isn’t fool proof either for instance it doesn’t comment out % chars which can cause trouble when used in conjunction with a MYSQL LIKE query.

  20. Karan S.

    @mayurnagekar
    Sometimes the directory doesn’t need to be open, i dont want to go deep on a basic website attack article.
    But if you want to take a look at it then once your logged into any site you can download, their source code to .swf file

    @Lisa
    Your absolutely right when it comes to small company hosting where viewing user limit is around 300 but when a major corporation website goes down, that is the DOS …..well DDOS (corp. cant be taken down by DOS attack lol)
    simple example would be college website on the day of registration, if all the students jump on the website @ 12:00am to register, the site will go down (considering the whole student body). Of course that wouldn’t be a DOS/DDOS but on a non registration day if it happens, you know what caused it.

  21. Jason Faulkner

    Thanks everyone for the compliments. I am glad you found this article informative!

    @Bengie – Utilizing parameters instead of escaped string replacements in a query, from an SQLI protection standpoint is essentially the same. As you pointed out, a nice thing about using parameters is you don’t have to sanitize the data yourself as SQL will do it for you.

    @Lisa – You are correct, a denial of service doesn’t always come from an attack. For example it is common for a small blog to get linked to on a major site which sends lots of legit traffic which the small blog’s server can’t handle. The result is the same as a coordinated DDoS attack.

    @Todd – The concepts in this article would only apply, in implementation, to web developers or server admins. As an end user, there isn’t anything you can to protect yourself against these types of attacks.

    @Pipo – @Dom’s answer is correct. Personally, I like to manually handle the sanitation of data in the event a function like that gets turned off (accidentally) or deprecated.

  22. Bengie

    “@Bengie – Utilizing parameters instead of escaped string replacements in a query, from an SQLI protection standpoint is essentially the same. As you pointed out, a nice thing about using parameters is you don’t have to sanitize the data yourself as SQL will do it for you.”

    Not really.

    Sanitizing works by escaping and filtering special chars, Parameterization works by splitting up the command stream from the input stream. You can’t use certain special chars with Sanitation because it CAN’T properly input them without exploit. Parameterization does not have this limitation.

    A bug in your Sanitation can result in an SQLI, a bug in Parameterization cannot.

    Also, Parameterization allows for streaming of inputs and binary data, which Sanitation cannot do.

  23. Bengie

    I wish I could edit…. “Not really” in my last reply should have been “kind of”

    I did not mean to be that harsh as your post was mostly correct from a usability standpoint.

    Sorry

  24. Marc

    I believe that best practice for SQL fed by web servers is to compile the SQL into a “prepared statement” with parameters. That way the code part of the statement, which is what gets executed, cannot be changed no matter what gets stuffed into the parameter fields. Then load the parameters from the web server. Same end result as sanitizing, but even more secure.

  25. Deepak Murthy

    Nicely explained!!!

  26. Danish Satkut

    @Jason, Hi! This was a very informative article and easy to understand. But I would like to criticize your choice of words in the first paragraphs “hacker group” and “hacked” instead of “cracker group” and “cracked or attacked”. I know this may stem a controversy over here, but still as a member of the community it is our responsibility to spread the awareness among the masses.
    http://datatracker.ietf.org/doc/rfc1392/?include_text=1

  27. Gulshan

    You should mention XSS!

    And if SQLI attacks are fixed by escaping characters, how do hackers still get them to work?

  28. James Liu

    XKCD is awesome! :D

  29. lew

    i totally get it! awesome!

  30. Jireh Ladera

    Great article! Now I know how DDoS and SQL Injection works. A very layman’s term approach! Loved it! :)

  31. French Kenny Ramos

    Amazingly explained the basics of hacking a website! I’d definitely should make sure my codes are secure!

Enter Your Email Here to Get Access for Free:

Go check your email!