Sunteți pe pagina 1din 7

10 Steps to Protect your Websites from SQL Injection Attacks

February 2010 Anurag Agarwal Director of Education Services, WhiteHat Security

A WhiteHat Security Whitepaper


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

Data theft has become so common that the price of a stolen credit card number in the black market has fallen from $10 in 2006 to a few pennies in 2009. Consumers are losing condence in ecommerce, online banking and other electronic means of doing business. Meanwhile, attackers are devising even more clever ways to steal data and increasing numbers of companies are falling prey to those techniques. Legal and compliance requirements are getting stricter to protect the consumer, but still new incidents are on the rise in 2009. In a recent Verizon Business Data Breach Investigations Report1, 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 attacks to occur without a companys knowledge. Often, it is only when the credit card companies such as VISA and American Express 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 targeted at the database, which stores sensitive information including employee and customer data. This type of attack exploits vulnerabilities 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 into generating a different SQL statement than was originally intended. As a result, the SQL, when executed, fetches a different 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 the attacks in the rst place. Following are 10 steps that both developers and database administrators can take to prevent applications 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 latest patches are applied: Installing the database on a different machine than the Web server or application server is a good practice in case either one is hacked. In the event that your Web server is hacked, there is a big chance that the integrity of that machine will be compromised. As a result, if the database is residing on the same machine, it will be considered compromised as well. If the 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 up quickly.

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 easily found 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 of vulnerability. Even now, we come across cases in which administrators forgot to remove all the default accounts from their database. 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.

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 that application to access the data. Remove all the sample tables. Disable access to any stored procedure that is not required by that application user: It is best to create a different account for every application to connect to the database. That account should have very limited access to the database only for what that application is required to do. If the application is not going to use any stored procedures, then it should not be allowed access through that application account. The idea is to lock down the database with limited access privileges for the application as to avoid any unnecessary access that may lead to compromise 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 statements from 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 allow executing stored procedures from your application, if you are using them. But for the most part, most of these commands are limited and can be restricted from the database itself for every application. This can prevent an attacker from doing too much damage or compromising the integrity of the database even if the application is somehow exploited using a SQL injection vulnerability.

5. Use read-only views for SQL statements that do not require any inserts or updates, e.g. Search functionality or Login functionality: There are many functions in a Web site where the application just needs to get information from the database. For example, 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 information from the database but will prevent you from making any changes to the database. This way even if your application is vulnerable 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, most attacks 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 numeric value, 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 if either 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 format of xxx-xxx-xxxx, then input in any other format should be rejected and an error message returned to the user.

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 routine towards 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) and what characters are allowed for that type of input. Lets take a look at an example with sample code in Java. By using Javas 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, before appending 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 parameterized queries. 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 error message, he knows the application is vulnerable to SQL injection and he can manipulate the query to fetch different results from the database.

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 + and password = + 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 where username = ? 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 of technical 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 the time 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 database including the type of the database, the table names, the column names, and more. Every application should hide raw error messages and display only generic error message like there was an error, please try again later or similar. The application should not disclose any internal details to the user, which can be abused by the attacker. All these error messages should also be logged as they can be extremely helpful in identifying not only the problem but attackers techniques 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 user for tables storing login credentials of a user. So, it is strongly advised to select table names or column names that cannot be easily guessed. The eldname of an e-mail address could be x_eml or olb_mail_addr and the name of the table could be app_usr_det.

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 your application. It adds another layer of complexity and makes it extremely difcult for a script kiddie or automated attacks to exploit 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 greatly reduce the chances of any SQL injection attack against your Web application. If developers are made aware of these points, all it requires is a slight change in their coding style to prevent not only SQL injection attacks, but the majority of Web application attacks. In our experience, developer training has been very helpful in increasing their understanding of website vulnerabilities and the extent of damage they can do. The result is often an improved relationship between the security 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

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

The WhiteHat Sentinel Service Website Risk Management


WhiteHat Sentinel 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. WhiteHat Sentinel is built on a Software-as-a-Service (SaaS) platform designed from the 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 with shrinking resources, WhiteHat Sentinel has become the solution of choice for total website security at any budget level. The entire Sentinel product family is subscription-based. So, no matter how often you run your application assessments, whether its once 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 by both threat and severity ratings via its unique assessment methodology. Built on the most comprehensive knowledgebase in Web application security, WhiteHat Sentinel veries all vulnerabilities, virtually eliminating false positives. So, even with limited resources, 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 narrow the 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 complex websites simultaneously. This scalability of both the methodology and the technology enables WhiteHat to streamline the process of website security. WhiteHat Sentinel was built specically to run in both QA/development and production environments to ensure maximum coverage with no performance impact. And, WhiteHat Sentinel exceeds PCI 6.6 and 11.3.2 requirements for Web application scanning. Simplied Management WhiteHat Sentinel is turnkey no hardware or scanning software to install requiring time-intensive conguration and management. WhiteHat Sentinel provides a comprehensive assessment, plus prioritization recommendations based on threat and severity levels, to better arm security professionals with the knowledge needed to secure an organizations data. WhiteHat Sentinel also provides a Web services API to directly integrate Sentinel vulnerability data with industry-standard bug tracking systems, or SIMs or other systems allowing you to work within your existing framework. With WhiteHat, you focus on the most important aspect of website security xing vulnerabilities and limiting risk.

About the Author Anurag 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 design and 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 with the Web Application Security Consortium and OWASP communities where he initiated a project on Web Application Security Scanner 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 that protect critical data, ensure compliance and narrow the window of risk. WhiteHat Sentinel, the companys flagship product family, is the most accurate, complete and cost-effective website vulnerability management solution available. It delivers the flexibility, 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 firewalls and Snort-based intrusion prevention systems. To learn more about WhiteHat Security, please visit our website at www.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 identification purposes only and may be trademarks or brands of their respective companies. 02.09.10

S-ar putea să vă placă și