10 steps to protect your websites from sql injection attacks

Upload: madmiko

Post on 04-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    1/7

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    2/7

    10 Steps to Protect your Websites from SQL Injection Attacks | February 2010

    Data theft has become so common that the price of a stolen credit card number in the black market has fallen from $10in 2006 to a few pennies in 2009. Consumers are losing condence in ecommerce, online banking and other electronicmeans of doing business. Meanwhile, attackers are devising even more clever ways to steal data and increasing numbersof companies are falling prey to those techniques. Legal and compliance requirements are getting stricter to protectthe consumer, but still new incidents are on the rise in 2009. In a recent Verizon Business Data Breach InvestigationsReport1 , studying over 600 incidents in the past ve years, SQL Injection was identied as the single largest attack

    vector responsible for data theft

    This nding is not surprising. Given the way Web applications are designed, it is very common for SQL injection attacksto occur without a companys knowledge. Often, it is only when the credit card companies such as VISA and AmericanExpress notify the victimized company, that they learn about the hack and by then, its too late.

    SQL injection attacks have the potential to cause signicant and costly damage to an organization. They are targetedat the database, which stores sensitive information including employee and customer data. This type of attack exploitsvulnerabilities in your application and manipulates the SQL queries in the application via input from the Web browser.

    In a SQL injection attack, a malicious user can send arbitrary input to the server and trick the Web application intogenerating a different SQL statement than was originally intended. As a result, the SQL, when executed, fetches adifferent set of results from the database than the application would have originally requested. SQL injection attacks are

    most frequently used to gain unauthorized access to, or manipulate the data residing in, the database on the server.Much has already been written about how SQL injection attacks are performed. The focus here is to prevent theattacks in the rst place. Following are 10 steps that both developers and database administrators can take to preventapplications from being vulnerable to SQL injection attacks.

    For Database Administrators

    1. Install the database on a different machine than the Web server or application server. Make sure all the latestpatches are applied:

    Installing the database on a different machine than the Web server or application server is a good practice in case eitherone is hacked. In the event that your Web server is hacked, there is a big chance that the integrity of that machine will becompromised. As a result, if the database is residing on the same machine, it will be considered compromised as well. Ifthe database is compromised, than the attacker can easily exploit the Web server as well.

    Also, if the machine has to be shut down, having the database on a different machine helps to bring the system back upquickly.

    2. The database should have all the default accounts and passwords disabled, including the super-user account:

    The default accounts for any database, including the super-user accounts, are listed in the manuals, or can be easilyfound on the Internet. It was not until 2002-2003 when the SQL Slammer worm was exploited because the database

    administrators did not change the default password of their database, that people started paying attention to this type ofvulnerability. Even now, we come across cases in which administrators forgot to remove all the default accounts from theirdatabase. Attackers will always start with the path of least resistance by trying to connect using the default username/password to see if any one of them is open. If you need an account for use by the application or a super user account,create a new one under a different name with similar privileges, but do not use the default settings.

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    3/7

    10 Steps to Protect your Websites from SQL Injection Attacks | February 2010

    3. Create an application user account in your database that has the minimum privileges necessary for thatapplication to access the data. Remove all the sample tables. Disable access to any stored procedure that is notrequired by that application user:

    It is best to create a different account for every application to connect to the database. That account should have verylimited access to the database only for what that application is required to do. If the application is not going to useany stored procedures, then it should not be allowed access through that application account. The idea is to lock downthe database with limited access privileges for the application as to avoid any unnecessary access that may lead tocompromise should your application be vulnerable to SQL injection.

    4. Identify the list of SQL statements that will be used by the application and only allow such SQL statementsfrom the application, e.g. Select, Insert, Update, etc:

    Most of the applications I have seen use a very limited set of SQL statements (e.g. Select, Insert, Update, Exec).Even delete is not used much since the records in the database are rarely deleted by the application. In addition,the application will not be dropping any tables, so why allow these commands from your application? You can allowexecuting stored procedures from your application, if you are using them. But for the most part, most of these commandsare limited and can be restricted from the database itself for every application. This can prevent an attacker from doingtoo much damage or compromising the integrity of the database even if the application is somehow exploited using aSQL injection vulnerability.

    5. Use read-only views for SQL statements that do not require any inserts or updates, e.g. Search functionality orLogin functionality:

    There are many functions in a Web site where the application just needs to get information from the database. Forexample, login functionality or search functionality. We do not need to insert or update anything back to the database;we just need to get some information to process within the application. A read-only view will let you get the informationfrom the database but will prevent you from making any changes to the database. This way even if your application isvulnerable to SQL injection, the attacker wont be able to make any changes to your tables or columns in the database

    and as a result the integrity of your database will not be compromised.

    For Developers

    6. Sanitize the input by validating it in your code:

    Input Validation is the most important aspect of Web Application Security. By conducting proper input validation, mostattacks can be avoided, SQL injection included. Input needs to be validated for the following:

    a. Data Type The data entered should be of correct type. For example, if the data entered should be of numericvalue, then it should be converted into numeric rst. If the converted value is not numeric, an error message should

    be returned to the user.b. Data Length Check the length of the input data for both minimum and maximum length. For example, if the

    username should be minimum eight characters and maximum 50 characters, it should be checked for both and ifeither of the conditions is not met, an error message should be returned to the user.

    c. Data Format Another thing to look for is the format of the input. If the phone number to be entered is in the formatof xxx-xxx-xxxx, then input in any other format should be rejected and an error message returned to the user.

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    4/7

    10 Steps to Protect your Websites from SQL Injection Attacks | February 2010

    There are many rules for Input Validation and I have mentioned only few above. There is a sample Input Validation routinetowards the end of the article for reference.

    Input Validation Techniques

    Ideally, architects can dene in the design phase what type of input is expected (alphabet, numeric, alphanumeric) andwhat characters are allowed for that type of input. Lets take a look at an example with sample code in Java. By usingJavas Regex API (java.util.regex), the input validation routine can be greatly simplied:

    Username validation The following rules will apply:

    1. It can contain the following alphabets a-z, A-Z, 0-9,@

    2. It is a single word and hence no spaces allowed

    3. Maximum characters allowed 50

    4. Minimum characters allowed 8

    Pattern pattern = Pattern.compile([A-Za-z0-9@]{8,50}+);

    Matcher matcher = pattern.matcher(formname);

    if(!matcher.matches())

    errorMessage(Name contains illegal characters);

    If the application is accepting numeric input, it should be converted to numeric and checked for the type rst, beforeappending into your SQL query. If it throws a NumberFormatException, it is not a valid input.

    try {

    int onum = Integer.parseInt(order_num);

    }catch(NumberFormatException nfe)

    {

    errorMessage(Only numeric characters allowed);

    }

    7. Use parameterized queries instead of dynamic queries. For example, in Java, use Prepared Statement instead

    of Statement Object:

    One of the reasons SQL injection is so successful is developers use of dynamic queries, as opposed to parameterizedqueries. An attacker inserts a database escape character (like single quote or double dash, etc.) in a dynamic query,breaking the syntax and as a result getting an error message from the database. Once an attacker sees that errormessage, he knows the application is vulnerable to SQL injection and he can manipulate the query to fetch differentresults from the database.

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    5/7

    10 Steps to Protect your Websites from SQL Injection Attacks | February 2010

    For example, this is a sample of vulnerable code and will lead to SQL Injection:

    String username = request.getParameter(username);

    String password = request.getParameter(password);

    String sql = select * from user_table where username = + username + andpassword = + password + ;

    Statement stmt = con.createStatement();

    ResultSet rs = stmt.executeQuery(sql);

    This is the secure way of doing the same thing.

    String username = request.getParameter(username);

    String password = request.getParameter(password);

    PreparedStatement pstmt = con.prepareStatement(Select * from user_table whereusername = ? and password = ?);

    pstmt.setString(1, username); //Validated input

    pstmt.setString(2, password); //Hashed Encryption

    ResultSet rs = pstmt.execute();

    8. Employ proper error handling and logging within the application so that a database error or any other type oftechnical information is not revealed to the user:

    Attackers thrive on raw error messages. Whenever an application throws a raw error message on the screen, most of thetime it provides a great deal of information to the attacker about the application. The attacker will try to provide different

    input to see different error messages. By doing so, the attacker can gather a lot of useful information about the databaseincluding the type of the database, the table names, the column names, and more. Every application should hide rawerror messages and display only generic error message like there was an error, please try again later or similar. Theapplication should not disclose any internal details to the user, which can be abused by the attacker. All these errormessages should also be logged as they can be extremely helpful in identifying not only the problem but attackerstechniques as well.

    9. Choose names for tables and elds that are not easy to guess:

    If the application is vulnerable to SQL injection but is tightly locked down by other measures as mentioned in this article,an attacker can still try to guess table names and column names by trying different names. For example, login or userfor tables storing login credentials of a user. So, it is strongly advised to select table names or column names that cannotbe easily guessed. The eldname of an e-mail address could be x_eml or olb_mail_addr and the name of the tablecould be app_usr_det.

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    6/7

    10 Steps to Protect your Websites from SQL Injection Attacks | February 2010

    10. Use stored procedures instead of raw SQL wherever possible:

    Yes, stored procedures can be exploited by SQL injection, but its not as easy as manipulating raw SQL within yourapplication. It adds another layer of complexity and makes it extremely difcult for a script kiddie or automated attacks toexploit your application. After all, its all about defense in depth.

    Conclusion

    As you can see, it is not difcult to prevent SQL injection attacks. By simply following the steps above, you can greatlyreduce the chances of any SQL injection attack against your Web application. If developers are made aware of thesepoints, all it requires is a slight change in their coding style to prevent not only SQL injection attacks, but the majority ofWeb application attacks. In our experience, developer training has been very helpful in increasing their understanding ofwebsite vulnerabilities and the extent of damage they can do. The result is often an improved relationship between thesecurity and development teams that leads to more secure websites.

    References

    1 Verizon Business Data Breach Investigations Report

    Verizon http://www.verizonbusiness.com/resources/security/reports/2009_databreach_rp.pdf

  • 8/13/2019 10 Steps to Protect Your Websites From SQL Injection Attacks

    7/7

    The WhiteHat Sentinel Service Website Risk Management

    WhiteHat Sentinel is the most accurate, complete and cost-effective website vulnerability management solutionavailable. It delivers the exibility, simplicity and manageability that organizations need to take control of websitesecurity and prevent Web attacks. WhiteHat Sentinel is built on a Software-as-a-Service (SaaS) platform designed fromthe ground up to scale massively, support the largest enterprises and offer the most compelling business efciencies,lowering your overall cost of ownership.

    Cost-effective Website Vulnerability Management As organizations struggle to maintain a strong security posture withshrinking resources, WhiteHat Sentinel has become the solution of choice for total website security at any budget level. Theentire Sentinel product family is subscription-based. So, no matter how often you run your application assessments, whether itsonce a week or once a month, your costs remain the same.

    Accurate WhiteHat Sentinel delivers the most accurate and customized website vulnerability information available rated byboth threat and severity ratings via its unique assessment methodology. Built on the most comprehensive knowledgebase inWeb application security, WhiteHat Sentinel veries all vulnerabilities, virtually eliminating false positives. So, even with limitedresources, the remediation process will be sped up by seeing only real, actionable vulnerabilities, saving both time and money,dramatically limiting exposure to attacks.

    Timely WhiteHat Sentinel was specically designed to excel in rapidly-changing threat environments and dramatically narrowthe window of risk by providing assessments on your schedule. Whether its a quarterly compliance audit, new product roll-out,

    or weekly business-as-usual site updates, WhiteHat Sentinel can begin assessing your websites at the touch of a button.

    Complete WhiteHat Sentinel was built to scale to assess hundreds, even thousands of the largest and most complexwebsites simultaneously. This scalability of both the methodology and the technology enables WhiteHat to streamlinethe process of website security. WhiteHat Sentinel was built specically to run in both QA/development and productionenvironments to ensure maximum coverage with no performance impact. And, WhiteHat Sentinel exceeds PCI 6.6 and 11.3.2requirements for Web application scanning.

    Simplied Management WhiteHat Sentinel is turnkey no hardware or scanning software to install requiring time-intensiveconguration and management. WhiteHat Sentinel provides a comprehensive assessment, plus prioritization recommendationsbased on threat and severity levels, to better arm security professionals with the knowledge needed to secure an organizationsdata. WhiteHat Sentinel also provides a Web services API to directly integrate Sentinel vulnerability data with industry-standardbug tracking systems, or SIMs or other systems allowing you to work within your existing framework. With WhiteHat, you focuson the most important aspect of website security xing vulnerabilities and limiting risk.

    About the AuthorAnurag Agarwal is Director of Education Services at WhiteHat Security. He has 15 years of experience designing, developing,managing and securing Web applications at companies including Citigroup, Cisco, HSBC Bank, and GE Medical Systems.He is an active contributor to Web application security industry research and has written several articles on secure designand coding for various publications. Mr. Agarwal is a frequent speaker on Web application security and maintains a website,www.attacklabs.com, where he publishes proof of concepts for various Web application attacks. He is actively involved withthe Web Application Security Consortium and OWASP communities where he initiated a project on Web Application SecurityScanner Evaluation Criteria. He publishes a blog on Web application security at http://myappsecurity.blogspot.com

    About WhiteHat Security, Inc.

    Headquartered in Santa Clara, California, WhiteHat Security is the leading provider of website risk management solutions thatprotect critical data, ensure compliance and narrow the window of risk. WhiteHat Sentinel, the companys agship productfamily, is the most accurate, complete and cost-effective website vulnerability management solution available. It delivers the

    exibility, simplicity and manageability that organizations need to take control of website security and prevent Web attacks.Furthermore, WhiteHat Sentinel enables automated mitigation of website vulnerabilities via integration with Web application

    rewalls and Snort-based intrusion prevention systems. To learn more about WhiteHat Security, please visit our website atwww.whitehatsec.com.

    WhiteHat Security, Inc. | 3003 Bunker Hill Lane, Suite 220 | Santa Clara, CA 95054-1144 | www.whitehatsec.com

    Copyright 2010 WhiteHat Security, Inc. | Product names or brands used in this publication are for identi cation purposes onlyand may be trademarks or brands of their respective companies. 02.09.10