Blog Home »

SQL Injection Prevention Techniques (Series-II)

July 9th, 2009 admin Posted in Security Testing 4 Comments »

By Atish Singh

(Continued from SQL Injection Prevention Techniques (Series-I))

Stored Procedures

Stored procedures have the same effect as the use of prepared statements when implemented safely*. They require the developer to define the SQL code first, and then pass in the parameters. The difference between prepared statements and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, and then called from the application. Both of these techniques have the same effects in preventing SQL injection so it’s your choice, which approach makes the most sense for you.

Safe Java Stored Procedure Example

The following code example uses a CallableStatement, Java’s implementation of the stored procedure interface, to execute the same database query. The “sp_getAccountBalance” stored procedure would have to be predefined in the database and implement the same functionality as the query defined above.

String custname = request.getParameter(”customerName “); // This should REALLY be validated
 try {
  CallableStatement cs = connection.prepareCall(”{call sp_getAccountBalance(?)}”);
  cs.setString(1, custname);
  ResultSet results = cs.executeQuery();  
  // … result set handling
 } catch (SQLException se) {   
  // … logging and error handling
 }

Safe VB .NET Stored Procedure Example

The following code example uses a SqlCommand, .NET’s implementation of the stored procedure interface, to execute the same database query. The “sp_getAccountBalance” stored procedure would have to be predefined in the database and implement the same functionality as the query defined above.

 Try
  Dim command As SqlCommand = new SqlCommand(”sp_getAccountBalance”, connection)
  command.CommandType = CommandType.StoredProcedure
  command.Parameters.Add(new SqlParameter(”@CustomerName”, CustomerName.Text))
  Dim reader As SqlDataReader = command.ExecuteReader()
  ‘ …
 Catch se As SqlException
  ‘ error handling
 End Try

There are some additional security and non-security benefits of stored procedures also that are worth considering. One security benefit is that if you make exclusive use of stored procedures for your database, you can restrict all database user accounts to only have access to the stored procedures. This means that database accounts do not have permission to submit dynamic queries to the database, giving you far greater confidence that you do not have any SQL injection vulnerabilities in the applications that access the database. Some non-security benefits include performance benefits (in most situations), and having all the SQL code in one location potentially simplifies maintenance of the code and keeps the SQL code out of the application developers’ hands, leaving it for the database developers to develop and maintain.

Escaping all User Supplied Input

Each DBMS supports a character escaping scheme using which you can escape special characters to indicate to the DBMS that the characters you are providing in the query are intended to be data, and not code. If you escape all user supplied input using the proper escaping scheme for the database you are using, the DBMS will not confuse that input with SQL code written by the developer, thus avoiding any possible SQL injection vulnerabilities.

Additional Defenses

Least Privilege

To minimize the potential damage of a successful SQL injection attack, you should minimize the privileges assigned to every database account in your environment. Do not assign DBA or admin type access rights to your application accounts. We understand that this is easy, and everything just ‘works’ when you do it this way, but it is very dangerous. Start from the ground up to determine what access rights your application accounts require, rather than trying to figure out what access rights you need to take away. Make sure that accounts that only need read access are only granted read access to the tables they need access to. If an account only needs access to portions of a table, consider creating a view that limits access to that portion of the data and assigning the account access to the view instead of the underlying table. Rarely, if ever, grant the create or delete access to database accounts.
If you adopt a policy where you use stored procedures everywhere, and don’t allow application accounts to directly execute their own queries, then restrict those accounts to only be able to execute the stored procedures they need. Don’t grant them any rights directly to the tables in the database.
SQL injection is not the only threat to your database data. Attackers can simply change the parameter values from one of the legal values they are presented with, to a value that is unauthorized for them, but the application itself might be authorized to access. As such, minimizing the privileges granted to your application will reduce the likelihood of such unauthorized access attempts, even when an attacker is not trying to use SQL injection as part of their exploit.

While you are at it, you should minimize the privileges of the operating system account on which the DBMS runs. Don’t run your DBMS as root or system! Most DBMSs run out of the box with a very powerful system account. For example, MySQL runs as system on Windows by default! Change the DBMS’s OS account to something more appropriate, with restricted privileges.

White List Input Validation

It is always recommended to prevent attacks as early as possible in the processing of the user’s (attacker’s) request. Input validation can be used to detect unauthorized input before it is passed to the SQL query. Developers frequently perform black list validation in order to try to detect attack characters and patterns like the ‘ character or the string 1=1, but this is a massively flawed approach as it is typically trivial for an attacker to avoid getting caught by such filters. Moreover, these filters frequently prevent authorized input, like O’Brian, when the ‘ character is being filtered out.
White list validation is appropriate for all input fields provided by the user. White list validation involves defining exactly what IS authorized, and by definition, everything else is not authorized. If it’s well structured data, like dates, social security numbers, zip codes, e-mail addresses, etc. then the developer should be able to define a very strong validation pattern, usually based on regular expressions, for validating such input. If the input field comes from a fixed set of options, like a drop down list or radio buttons, then the input needs to match exactly one of the values offered to the user in the first place. The most difficult fields to validate are so called ‘free text’ fields, like blog entries. However, even those types of fields can be validated to some degree, you can at least exclude all non-printable characters, and define a maximum size for the input field.

AddThis Social Bookmark Button

SQL Injection Prevention Techniques (Series-I)

July 9th, 2009 admin Posted in Security Testing 4 Comments »

By Atish Singh

Here a set of techniques is mentioned, which provide prevention from SQL Injection, one of the dangerous security vulnerability. This technique is beneficial for the technologies, such as Java, .net, php and so on.

Prevention from SQL Injection requires lot of defensive measures to be taken for your application. The basic defensive measures to be taken are considered as the primary defense that consists of some programming techniques, defined as follows:

Primary defenses:
1. Parameterization(Prepare statement)
2. Stored Procedure
3. Escaping all user supplied input

Although, applying the primary defense techniques, you can secure your application from the basic security vulnerabilities, if you want to secure the application a step ahead, then you need to use extra defensive measures defined as follows:

Extra Defenses:
1. Least Privilege
2. White List Input Validation

Let’s take an example that is unsafe and is vulnerable for SQL Injection.
The following (Java) example is UNSAFE, and would allow an attacker to inject code into the query that would be executed by the database.
 String query = “SELECT account_balance FROM user_data WHERE user_name = “+ request.getParameter(”customerName”);
 
 try {
  Statement statement = connection.createStatement();
  ResultSet results = statement.executeQuery(query);
     }

In the preceding example, the invalidated “customerName” parameter that is simply appended to the query allows an attacker to inject any SQL code they want. Unfortunately, this method for accessing databases is common to be used among programmers.
Considering the preceding example, let’s now discuss the defensive measures that can be used to prevent SQL Injections.

Primary Defenses

Prepared Statement
     Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker enters the userID of xyz’ or ‘1′=’1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string xyz’ or ‘1′=’1.

Language specific recommendations:
• Java EE – use PreparedStatement() with bind variables
• .NET – use parameterized queries like SqlCommand() or OleDbCommand() with bind variables
• PHP – use PDO with strongly typed parameterized queries (using bindParam())
• Hibernate - use createQuery() with bind variables (called named parameters in Hibernate)

Safe Java Prepared Statement Example
The following code example uses a PreparedStatement, Java’s implementation of a parameterized query, to execute the same database query.
 String custname = request.getParameter(“customerName”); // this should REALLY be validated too

 // perform input validation to detect attacks
 String query = “SELECT account_balance FROM user_data WHERE user_name =?”
 
 PreparedStatement pstmt = connection.prepareStatement(query);
 pstmt.setString(1, custname);
 ResultSet results = pstmt.executeQuery( );

Safe C# .NET Prepared Statement Example
With .NET, it’s even more straightforward. The creation and execution of the query doesn’t change. All you have to do is simply pass the parameters to the query using the Parameters.Add() call as shown here.
 String query =
   “SELECT account_balance FROM user_data WHERE user_name = ?”;
 try {
  OleDbCommand command = new OleDbCommand (query, connection);
  command.Parameters.Add(new OleDbParameter(”customerName”, CustomerName Name.Text));
  OleDbDataReader reader = command.ExecuteReader();
  //
 } catch (OleDbException se) {
  // error handling
 }

Hibernate Query Language (HQL) Prepared Statement (Named Parameters) Examples

 First is an unsafe HQL Statement
 
 Query unsafeHQLQuery = session.createQuery(”from Inventory where productID=’”+userSuppliedParameter+”‘”);
 
 Here is a safe version of the same query using named parameters
 
 Query safeHQLQuery = session.createQuery(”from Inventory where productID=:productid”);
 safeHQLQuery.setParameter(”productid”, userSuppliedParameter);

(to be continued…)

AddThis Social Bookmark Button

Application Security | PCI DSS Overview

April 26th, 2009 admin Posted in Security Testing No Comments »

By Avinash K. Tiwari

As the number security breaches has increased, regulatory and industry requirements have become more stringent. One of the most popular compliance standard is PCI DSS. It was developed by the major credit card companies as a guideline to help organizations that process card payments prevent credit card fraud, cracking and various other security vulnerabilities and threats. A company processing, storing, or transmitting payment card data must be PCI DSS compliant or risk losing their ability to process credit card payments and being audited and/or fined. Here is brief overview of what PCI DSS is all about.

What is PCI- DSS?

· PCI stands for Payment Card Industry.

· PCI-DSS actually stands for PCI Data Security Standards (DSS), currently at version 1.2. PCI DSS is a set of comprehensive requirements for enhancing payment account data security. It was developed by a council (PCI SSC) which includes American Express, Visa International, MasterCard Worldwide, Japan Credit Bureau (JCB). The council is responsible for developing and managing the PCI DSS standards, establishing and maintaining Qualified Security Assessors (QSA) and Approved Scanning Vendors (ASV).

Who must comply with PCI?

Any company that stores, processes or transmits cardholder data must comply with PCI. Compliance to PCI is assurance to the organization that IT infrastructure and business processes are secure. It can serve as great marketing tool for company and instill greater confidence in customer’s and stakeholders’ minds.

Scope of PCI –DSS

All systems that store, process or transmit Cardholder’s data.

a) Applications processing Cardholder’s data ( e.g. e-commerce application, sales processing application)

b) Network Infrastructure

c) Storage Area Networks

d) Data Extracts including Cardholder’s data.

e) Backups

f) Log Files

g) Paper records

h) People

i) Org wise processes and structure

j) Third parties that stores or transmit Cardholder’s data on Organization’s behalf such as suppliers and dealers.

Who can help you get PCI DSS?

a) Consulting Agencies: Consulting agencies can help you find gaps, implement processes to fill the gaps and do a pre audit to make you prepare for final audit by QSA.

b) QSA: A security company qualified by PCI SSC to assess compliance to the PCI DSS standard. QSA’s are certified by PCI SSC to perform on site security assessments for verification of compliance with PCI DSS.

A list of QSA’s can be found at

http://www.pcisecuritystandards.org/pdfs/pci_qsa_list.pdf

AddThis Social Bookmark Button

Application Security: OWASP top 10

August 9th, 2008 admin Posted in Security Testing 1 Comment »

By: Avinash  K Tiwari

The Open Web Application Security Project (OWASP) is a worldwide free and open community focused on improving the security of application software. The OWASP community includes corporations, educational organizations, and individuals from around the world. This community works to create freely-available articles, methodologies, documentation, tools, and technologies. Purpose of OWASP is working for finding and fighting the causes of insecure software.

Official web site: www.owasp.org

OWASP’s most successful projects include the book-length OWASP Guide and the widely adopted OWASP Top 10 awareness document.

In this post, I am going to focus on “What OWASP Top Ten” is all about.

The Open Web Application Security Project (OWASP) Top Ten Project provides a minimum standard for web application security. It lists the top ten most critical web application security vulnerabilities, representing a broad concensus. Project members include a variety of security experts from around the world who have shared their expertise to produce this list. You should consider adopting security standards and begin assessing that your web applications do not contain these security flaws. Addressing the OWASP Top Ten is an effective first step towards changing your software development culture into one that produces secure code for your web applications.

Following are the OWASP top 10 vulnerabilities with a brief description

Cross-site scripting (XSS) flaws:
Hackers can impersonate legitimate users, and control their accounts.
Impact : Identity Theft, Sensitive Information Leakage, …

Injection flaws:
Hackers can access backend database information, alter it or steal it.
Impact: Attacker can manipulate queries to the DB / LDAP / Other system

Malicious File Execution
Execute shell commands on server, up to full control
Impact: Site modified to transfer all interactions to the hacker.

Broken authentication and session management:
Session tokens not guarded or invalidated properly
Impact : Hacker can “force” session token on victim; session tokens can be stolen after logout

Cross-Site Request Forgery
Attacker can invoke “blind” actions on web applications, impersonating as a trusted user
Impact : Blind requests to bank account transfer money to hacker

Information Leakage and Improper Error Handling
Attackers can gain detailed system information
Malicious system inFORMATION may assist in developing further attacks

Insecure storage
Weak encryption techniques may lead to broken encryption
Impact: Confidential information (SSN, Credit Cards) can be decrypted by malicious users

Insecure Communication:
Sensitive info sent unencrypted over insecure channel
Impact: Unencrypted credentials “sniffed” and used by hacker to impersonate user

Failure to Restrict URL Access
Hacker can forcefully browse and access a page past the login page
Impact : Hacker can access unauthorized resources

Insecure Direct Object Reference
Web application returns contents of sensitive file (instead of harmless one)
Impact: Attacker can access sensitive files and resources

We will be discussing each one the vulnaribilities in detail in the coming posts.

Moreover, more information about the following critical web application security vulnerabilities is on the OWASP website: http://www.owasp.org/index.php/OWASP_Top_Ten_Project

(Copyrighted by CresTech Software Systems Pvt. Ltd.)

Your Testing Partner

AddThis Social Bookmark Button

Application Security : Unlocking the myth

July 27th, 2008 admin Posted in Security Testing 2 Comments »

By Avinash K Tiwari

More and more companies are relying on Web-based applications to provide online services to their employees, to support e-commerce sales and to lever¬age portals, discussion boards and blogs that help staff better communicate with customers, partners and suppliers. However, as the number and complex¬ity of Web applications have grown, so have the associated security risks. With increasing frequency, incidents of Web application breaches resulting in data theft are popping up as front-page news.

Some of news you can’t ignore

World story

• 40 Million Credit Cards Compromised
• 55 Million Customer Records Exposed, 130+ Security Breaches in 2005
• $105 Billion In Cyber crime Proceeds in ’04, More than Illegal Drug Sales

There have been quite a few Govt and FSS security breaches in India recently.
• Hacker breaks into 17 bank a/cs
• Bank of India site hacked, served up 22 exploits
• Maharashtra govt website hacked
• Goa govt’s info website hacked

A fact which can’t be ignored:

Close to 80% of web sites are vulnerable to Cross-site scripting, which can be executed even by a novice hacker. Your website could be one as well.

A myth that our website is safe:

“We have Firewalls in Place”
“We Use Network Vulnerability Scanners”
“we use SSL”

What’s the real picture??

Lets take a look at the different security layers used in the protection of a web application:

In order to protect the desktop, users and organizations install antivirus protection
The communication layer is protected by encrypting the traffic, using SSL
Firewalls and IDS are used to only allow specific communication (port) access (i.e. WEB traffic)

Let’s take each layer one by one

When we talk about web traffic desktop security is not in picture

Using SSL will encrypt the web traffic and make life difficult for a hacker intercepting the traffic. But, use of SSL can’t stop a hacker from manupulating the data by directly accessing the application

Firewalls are set up to allow outsiders access to specific resources, and to prevent them from accessing other resources. For example, an outside individual wouldn’t be allowed to directly connect to a database, but they can make a request to a web server.  This means the firewall would be configured to deny traffic on a standard database port 1443, but allow traffic through ports 80 and 443 - web application ports.  This system is clearly no protection at all against malicious attacks aimed at the web application.

The next protection an HTTP request encounters is an intrusion detection system.  The IDS has been set up to look for signatures in the traffic that might indicate an attack.  For example, they may look for a SQL statement embedded within a request, or they might look for a script tag that indicates a potential XSS attack.  The challenge with these systems is that if the request is encoded in some alternative format (such as Unicode Transformation Format, UTF-7) or perhaps the traffic is encrypted using SSL, the intrusion detection system is often not able to interpret or understand the requests.  The IDS offers little to no protection against the web application attack.

The last system that the HTTP request might encounter before the web server is probably an application firewall.  These are the smartest of all the network protections and can be configured explicitly to only allow certain traffic that it knows to be good.  The problem with these systems is that it’s very expensive to maintain the correct configurations or valid algorithms and testing  of these systems to recognize good traffic.  If the web application firewall has been designed to fail securely (a web application security principle), that is, if you’re not sure what to do, they block the user, the web application firewall may block legitimate traffic. For this reason, most application firewalls are usually designed to break one of the founding principles of security (fail securely) by allowing through traffic that they don’t understand.

So, as you can see, even with antivirus, firewalls and IDS, you still have to allow web traffic through your firewalls, IDS and IPS. This web traffic can be friendly, or it could be malicious – but there is no way to know which one it is. Since web users can access your application over the web, they can perform all sorts of malicious activities and either steal, manipulate or destroy information.

So the bottomline is  THE WEB APPLICATION MUST DEFEND ITSELF.

(Copyrighted by CresTech Software Systems Pvt. Ltd.)

AddThis Social Bookmark Button


Home   |   About Us  |   QA Library   |   Learning Center   |   FAQs   |   Career Center  |   Link Exchange   |   Contact Us
Copyright © QACampus.com. All Rights Reserved.
Powered By : codeplatter
Vision / Mission CresTech Connection Management Team
QACampus Courses ClassRoom Training Live Projects E-courses
Blog Forum QA Library
Career Center Hot Job Upload Resume