Pubcon Las Vegas 2012 SQL Injection


Published on

How to crack into a website using sql injection so you know how to stop it from happening to you. To see more on the topic you can review the 2011 presentation by Ralf Schwoebel and Todd Keup which includes this information on recognition, understanding and prevention but also monitoring and server setup best practices.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Good Morning! I want to thank Brett Tabke and his organization for all their hard work in putting a conference like this together. Each time I attend I find myself a beneficiary of the knowledge shared at this gathering. Thanks Brett, for the opportunity to not only be here, but to be here once again as a speaker. I would also like to thank my good friend Ralf Schwoebel for volunteering to facilitate this session as well as my esteemed panel of peers. But most of all thank you for being here today. I am honored by your presence and the privilege to share what I am able regarding CSS and HTML coding today. For those of you that are familiar with the WebmasterWorld web site and the forums at WebmasterWorld, I am an active member and one of the moderators of the PHP Server Side Scripting Forum. I go by the nickname “coopster” and I want you to know that I would absolutely love the opportunity to make your personal acquaintance today. I am approachable and friendly. Please don't hesitate to introduce yourself.
  • What is cracking? What is a cracker? What is hacking? What is a hacker? A cracker is a saltine or soda cracker which is a thin, usually square tidbit made from white flour, shortening, yeast, and baking soda, with most varieties lightly sprinkled with coarse salt. And a hacker is an evil computer programmer with nasty intentions. Correct? RFC 1392 Internet Users' Glossary defines: cracker: an individual who attempts to access computer systems without authorization. These individuals are often malicious, as opposed to hackers, and have many means at their disposal for breaking into a system. hacker : A person who delights in having an intimate understanding of the internal workings of a system, computers and computer networks in particular. The term is often misused in a pejorative context, where "cracker" would be the correct term. Over the years the terms have become synonymous and it is a thorn in the side for some programmers. You see, hackers were once recognized as legitimate computer programmers with exceptional skill and good intentions. These white hat code monkeys often refer to programming as hacking, or hacking code, and were proud to be identified as a hacker. Much like a lumberjack might hack wood. As a matter of fact, the original definition for hacker is “one who makes furniture with an ax.” It is the work you perform to make a living. Alas, times have changed. And the terms cracking and hacking have merged into one notorious concept … malicious computer programming. Computer programmers and lumberjacks around the world feel they have been wronged :) Paul Bunyan is not happy. Most programmers nowadays understand that culture has merged these two definitions and accept the fact. But if you ever get one that goes off the deep end when you call him or her a hacker you now know why. By the way, the primary difference between the two is motivation.
  • What can I do to defend myself ? I will show you ways to protect yourself.
  • What motivates a cracker? Money Destruction; defacement of websites Extract intellectual property Access customer account information and other data Site administrator passwords which allows full control of the web application Host malicious scripts leading site visitors to download malware SEO gains; inserting links, tracking cookies, etc. Fun. Showing off to peers that share the same lack of ethics and morals.
  • Tools of the trade include scanner tools which are readily available (meaning free download) to run and install. All a cracker has to do is point the software at your web site. Many crackers will use botnets (compromised computers) and proxy servers to hide their tracks; more on this later.
  • A very common exploit is SQL Injection and most often they target Open Source Software installations such as Wordpress, phpMyAdmin, Joomla, bulletin boards, etc. Other common attack points include additional software pre-installed on your server.
  • We are going to take you step-by-step through an SQL Injection. For some of you this may be the first time you have even heard the term so we want to take a moment to show you what it looks like because a picture speaks a thousand words …
  • Standard login … look familiar? Probably. Most of us use a login similar to this each day. How about this next one, paging? Did you ever think that paging could cause you problems?
  • The HTML for the standard login form. And on the server side we see how the form value is not filtered and then used in a query.
  • First you must know that the double dashes here represent standard SQL comment syntax. MySQL has extended the standard syntax for this comment style and requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on). The query will ask for all records because a boolean true value is found in the WHERE clause. Everything after the comment is ignored.
  • Let's go back to that paging for a moment. In this case the database connection on the server side has a user that has ability to create other users. See how easy it might be to create a superuser in PostgreSQL? Unescaped input is so dangerous. The zero and semicolon terminate the first statement. Known vulnerabilities are compromised on the database server and the cracker has now added a superuser profile.
  • Updates can also be compromised. In this example a malicious user goes from resetting their password to gaining privileges. Removing entire tables is possible too. Here the query is expecting an integer for the id value but since the programmer did not properly validate and allows a string to be passed to the query we end up losing our table.
  • Points of interest: According to SQL Injection contributed to 83% of all successful hacking related data breaches since 2005. A recent study by Imperva discovered an average of almost 71 SQL injection attempts per hour with maximum spikes of 1,300 per hour. Attackers are using much more complex variants now to evade the old 'or 1=1'; attempts.
  • Now what do I do? Cleanup and plug the hole. The faster you can do the latter, the better off you are. However, you may need to do the first before you can do the last. If you find this is not necessary then by all means get your preventive measures in place first! If you find a file has been modified and you didn't modify it, examine it. Compare it to your last known good copy. If it was a database table entry, check the last update on that entry. Fix the content being delivered to your public visitors, especially if there has been a JavaScript trojan injected into your html documents. Your damage assessment may require you to revert to a last known copy. This is where versioning systems come in extremely handy! Do not forget to change your passwords! Disclaimer: this list is not extensive.
  • Patching your code might require casting values to types you expect. Here is an example of casting a user-supplied ticket number. Of course, you would probably want to validate more than what you see here. For example, a zip code or date value. You know what it should look like, how many digits in what position, etc. So help your user format as you expect and then validate what has been supplied. The next option shows an example of escaping the data (and casting at the same time) for a MySQL query.
  • How do I know a compromise has occurred? Oh you'll know. Remember the motivation discussion earlier? Defaced web site, odd links showing up, new pages, trojan viruses being delivered to end users, etc. Discovery is best when done by monitoring. Monitoring allows you to plug holes you discover first. And hopefully you won't have to discover compromises later! You can log your form submissions and especially those that are modifying sensitive files or tables, like your users table if you are using a database. If an admin profile is added or updated you might trigger an email or text message yourself. Use your system tools like logwatch. And the same tools used for cracking can be used for prevention. As a matter of fact, many of them were first developed for use in this manner! An example of this is SQLmap, which is one of many free sophisticated SQL detection engines readily available. SQLmap, slqninja, Havij, Pangolin, etc. Identify access patterns of automated tools. You can create and deploy a blacklist of hosts that initiate SQL injection attacks if you would like.
  • More avoidance techniques: Always use customized users with very limited privileges for database connections. Never trust user-supplied input. Validate everything. If you are expecting an integer value, check for it! Cast it to the proper data type if necessary. And escape the data using string escape functions that are specific to the database to which you are connecting. For example, MySQL is different than DB2. Never dump raw database information to the display such as column (field) names, table names or database names. And structure your application to handle any raw errors and provide user-friendly error messages instead. No, "The Microsoft Sequel Server is temporary unavailable" is not an appropriate message.
  • Pause for a moment to share some information regarding botnets … Guess which country has the most compromised computers in the world? United States accounts for 58%, followed by Sweden, China, Great Britain and Vietnam. Germany did make the list but tied with the European Union at 1%. A recent study showed that The SQLi attacks observed since July originated from 3,845 hosts. However, the distribution of activity between them is uneven: The top three hosts accounted for 23% of the attacks, and the next seven sources accounted for 18% of the attacks. However, five of these seven hosts are Akamai proxies, so the traffic was just routed through them from the attacker-controlled hosts. (source: Imperva, Anatomy of an SQL Injection Attack)
  • Pubcon Las Vegas 2012 SQL Injection

    1. 1. Todd Keup ::magnifisites.comWhat Every WebmasterShould Know About CodeInstallationCracking and HackingTodd Keup@toddkeup
    2. 2. Todd Keup ::magnifisites.comCracker versus hacker
    3. 3. Todd Keup ::magnifisites.comOverview• Motivation• Tools of the trade• Common attacks• Defending yourself
    4. 4. Todd Keup ::magnifisites.comMotivation• Drop links or cookies• Steal logins, blackmail people• Building botnets• Redirect advertising• Crush competition• Steal credit cards• Abuse your server (email, attacks, etc.)
    5. 5. Todd Keup ::magnifisites.comTools of the trade• Basic hacking became easier• Portscanners, evil software suites areavailable to the public• SARA, brutus, etc.: endless list
    6. 6. Todd Keup ::magnifisites.comCommon attacks• SQL injection• Additional software problems• How to protect yourself• Your checklist
    7. 7. Todd Keup ::magnifisites.comSQL Injection• How it looks• What happens when it succeeds• Recovery– Cleanup– Plugging the hole (prevention)• Monitoring and discovery
    8. 8. Todd Keup ::magnifisites.comSQL Injection
    9. 9. Todd Keup ::magnifisites.comSQL Injection<form method="post" action="process">Username: <input name="username" type="text" value="">Password: <input name="password" type="password" value=""><input name="submitform" type="submit" value="Submit"></form>Incorrectly filtered escape charactersquery = "SELECT * FROM users WHEREname = " + username + " AND pass = " + password + ";"
    10. 10. Todd Keup ::magnifisites.comSQL InjectionIncorrectly filtered escape charactersquery = "SELECT * FROM users WHEREname = " + username + " AND pass = " + password + ";"Renders:query = "SELECT * FROM users WHEREname = OR 1=1 -- AND pass = doesNotMatter;"
    11. 11. Todd Keup ::magnifisites.comSQL InjectionIncorrectly filtered escape characters<?php$offset = $_GET[start];$query = "SELECT id, name FROM products ORDER BY nameLIMIT 20 OFFSET $offset;";$result = pg_query($connection, $query);?>// cracker encodes the following into the "start" value of the url0;insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)select cracker, usesysid, yes,yes,jackfrom pg_shadow where usename=postgres; --
    12. 12. Todd Keup ::magnifisites.comSQL InjectionIncorrectly filtered escape charactersquery = "UPDATE users SET pwd=$pwd WHERE uid=$uid;";// user enters: OR name LIKE %admin%; -- and it renders:UPDATE users SET pwd=abc WHERE uid=me OR name LIKE %admin%; -- ;Incorrect type handlingquery = "SELECT * FROM students WHERE id = " + expectedInteger + ";"// user enters: 1;DROP TABLE studentsSELECT * FROM students WHERE id = 1;DROP TABLE students;
    13. 13. Todd Keup ::magnifisites.comSQL InjectionImage courtesy of
    14. 14. Todd Keup ::magnifisites.comSQL InjectionCleanup, aisle nineCheck your access logsCheck file modification timeRevert to backup?Change passwordsPatch the hole
    15. 15. Todd Keup ::magnifisites.comSQL InjectionCasting a type value$ticket = (integer) $_POST[ticketnumber];Properly filtering data$query =sprintf("SELECT * FROM Users WHERE user=%s AND pass=%s",mysql_real_escape_string($user),mysql_real_escape_string($pass));mysql_query($query);
    16. 16. Todd Keup ::magnifisites.comSQL InjectionMonitor and DiscoverAudit your site regularly• Log form submissions• Monitor changes to user files• Use your system tools• Use the same tools crackers employ• Identify access patterns of automated tools• Blacklist hosts that initiate attacks
    17. 17. Todd Keup ::magnifisites.comSQL InjectionMonitor and Discover• Never connect to the database as asuperuser or as the database owner.• Check expected data type• Escape user supplied values• Do not print out any database specificinformation, especially about the schema• Do not dump raw errors to the display
    18. 18. Todd Keup ::magnifisites.comBotnets
    19. 19. Todd Keup ::magnifisites.comThank YouTodd
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.