SQL Injection Tutorial

Posted on:
tags: , , , , , , , , , , , ,

The SQL Injection is a very danger code injection technique to exploit security vulnerability of a database layer of an application...
Here I am going teach you about this technique for your preventions from this attacks...

This post is for education purpose, kindly use this tutorial for your knowledge only...
This demonstration is just to make the people aware of SQL injection on websites. Not to encourage the people to hack into websites. I will not be held responsible if you do anything illegal.
Before going for SQL Injection I would like to explain you about SQL ...
So, here we go ...!
 

Introduction to SQL
Simple Definition
 SQL is a standard language for accessing and manipulating databases.
  • SQL stands for Structured Query Language
  • SQL lets you access and manipulate databases
  • SQL is an ANSI (American National Standards Institute) standard

Features of SQL
  • SQL can execute queries against a database
  • SQL can retrieve data from a database
  • SQL can insert records in a database
  • SQL can update records in a database
  • SQL can delete records from a database
  • SQL can create new databases
  • SQL can create new tables in a database
  • SQL can create stored procedures in a database
  • SQL can create views in a database
  • SQL can set permissions on tables, procedures, and views

RDBMS
·         RDBMS stands for Relational Database Management System.
·         RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
·         The data in RDBMS is stored in database objects called tables.
·         A table is a collection of related data entries and it consists of columns and rows.

 

Database Tables

A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City)

SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement will select all the records in the "Persons" table:
SELECT * FROM Persons

Kindly note that

  • SQL is not case sensitive

Semicolon after SQL Statements?

Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.


SQL DML and DDL

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
  • SELECT - extracts data from a database
  • UPDATE - updates data in a database
  • DELETE - deletes data from a database
  • INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes (keys), specifies links between tables, and imposes constraints between tables. The most important DDL statements in SQL are:
  • CREATE DATABASE - creates a new database
  • ALTER DATABASE - modifies a database
  • CREATE TABLE - creates a new table
  • ALTER TABLE - modifies a table
  • DROP TABLE - deletes a table
  • CREATE INDEX - creates an index (search key)
  • DROP INDEX - deletes an index

Use of Quotes, AND & OR
Quotes Around Text Fields
• SQL uses single quotes around text values (most database systems will also accept double quotes).
• Although, numeric values should not be enclosed in quotes. The AND & OR Operators
• The AND operator displays a record if both the first condition and the second condition is true.
• The OR operator displays a record if either the first condition or the second condition is true.



Introduction to SQL Injection
SQL injection is techniques used to exploit weaknesses in applications. When programs are written, some parameters used in the creation of the application code can leave weaknesses in the program. Generally, the purpose of SQL injection is to convince the application to run SQL code that was not intended. SQL injection is a hacking method used to attack SQL databases. SQL injection  is a exploits in that it is usually delivered via a user input field. The input field is where a user may enter a username and password on a website, add data to a URL, or perform a search for a keyword in another application. The SQL injection vulnerability is caused primarily by unverified or unsanitized user input via these fields.

SQL Server injection vulnerabilities are caused by the same issue: invalid parameters that are not verified by the application. If programmers don’t take the time to validate the variables a user can enter into a variable field, the results can be serious and unpredictable. Sophisticated hackers can exploit this vulnerability, causing an execution fault and shutdown of the system or application, or a command shell to be executed for the hacker.

SQL injection countermeasures are designed to utilize secure programming methods. By changing the variables used by the application code, weaknesses in applications can be greatly minimized. This report will detail how to perform a SQL injection and explore the best countermeasures to prevent the attack.

SQL injection occurs when an application processes user-provided data to create a SQL statement without first validating the input. The user input is then submitted to a web application database server for execution. When successfully exploited, SQL injection can give an attacker access to database content or allow the hacker to remotely execute system commands. In the worst-case scenario, the hacker can take control of the server that is hosting the database. This exploit can give a hacker access to a remote shell into the server file system. The impact of a SQL injection attacks depends on where the vulnerability is in the code, how easy it is to exploit the vulnerability, and what level of access the application has to the database. Theoretically, SQL injection can occur in any type of application, but it is most commonly associated with web applications because they are most often attacked.

During a web application SQL injection attack, malicious code is inserted into a web form field or the website’s code to make a system execute a command shell or other arbitrary commands. Just as a legitimate user enters queries and additions to the SQL database via a web form, the hacker can insert commands to the SQL Server through the same web form field. For example, an arbitrary command from a hacker might open a command prompt or display a table from the database. A database table may contain personal information such as credit card numbers, social security numbers, or passwords. SQL Servers are very common database servers and used by many organizations to store confidential data. This makes a SQL Server a high-value target and therefore a system that is very attractive to hackers.


What an attacker can do?

* ByPassing Logins

* Accessing secret data

* Modifying contents of website

* Shutting down the My SQL server

According to OWASP (Open Web Application Security Project) Top 10 Web Application Security Risks for 2010 are:
         A1: Injection
         A2: Cross-Site Scripting (XSS)
         A3: Broken Authentication and Session Management
         A4: Insecure Direct Object References
         A5: Cross-Site Request Forgery (CSRF)
         A6: Security Misconfiguration
         A7: Insecure Cryptographic Storage
         A8: Failure to Restrict URL Access
         A9: Insufficient Transport Layer Protection
         A10: Unvalidated Redirects and Forwards




Finding a SQL Injection Vulnerable websites:
Our best partner for SQL injection is Google. We can find the Vulnerable websites(hackable websites) using Google Dork list. google dork is searching for vulnerable websites using the google searching tricks. There is lot of tricks to search in google. But we are going to use "inurl:" command for finding the vulnerable websites.
SomeExamples:
inurl:index.php?id=
inurl:gallery.php?id=
inurl:article.php?id=
inurl:pageid=
Copy one of the above command and paste in the google search engine box. Hit enter. You can get list of web sites. We have to visit the websites one by one for checking the vulnerability.
So Start from the first website:
Note: if you like to hack particular website, then try this:
site: www.victimsite.com dork_list_commands. for eg: site:www.victimsite.com inurl:index.php?id=

Checking the Vulnerability:
Now we should check the vulnerability of websites. In order to check the vulnerability ,add the single quotes(') at the end of the url and hit enter. (No space between the number and single quotes) For eg:
http://www.victimsite.com/index.php?id=2'
 If the page remains in same page or showing that page not found or showing some other webpages. Then it is not vulnerable.  If it showing any errors which is related to sql query,then it is vulnerable. Cheers..!! For eg: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'' at line 1(same as below image)





The Purpose of SQL Injection

SQL injection attacks are used by hackers to achieve certain results. Some SQL exploits will produce valuable user data stored in the database, and some are just precursors to other attacks.

The following are the most common purposes of a SQL injection attack:

Identifying SQL Injection Vulnerability The purpose is to probe a web application to discover which parameters and user input fields are vulnerable to SQL injection.

Performing Database Finger-Printing The purpose is to discover the type and version of database that a web application is using and “fingerprint” the database. Knowing the type and version of the database used by a web application allows an attacker to craft databasespecific
attacks.

Determining Database Schema To correctly extract data from a database, the attacker often needs to know database schema information, such as table names, column names, and column data types. This information can be used in a follow-on attack.

Extracting Data These types of attacks employ techniques that will extract data values from the database. Depending on the type of web application, this information could be sensitive and highly desirable to the attacker.

Adding or Modifying Data The purpose is to add or change information in a database.

Performing Denial of Service These attacks are performed to shut down access to a web application, thus denying service to other users. Attacks involving locking or dropping database tables also fall under this category.

Evading Detection This category refers to certain attack techniques that are employed to avoid auditing and detection.

Executing Remote Commands These types of attacks attempt to execute arbitrary commands on the database. These commands can be stored procedures or functions available to database users.

Performing Privilege Escalation These attacks take advantage of implementation errors or logical flaws in the database in order to escalate the privileges of the attacker.




Recent News of SQL Injection attacks
 
Forget script kiddies hacking into websites just to deface them with flashing “H@X0rs rulez” messages. Todays attacks are all about the very adult business of stealing and intercepting data to generate profit.
New evidence for this trend shows in a sharp rise of SQL injection attacks measured by web hosting company FireHost, which reports that between the first and second quarter of 2012, thenumber of SQL injection attacks against FireHost’s clients rose 69%.
Attacks Follow the Money
SQL injection attacks use false SQL database commands entered into a site’s Web interface to obtain data not normally available for public consumption - like passwords, personal information, and the holy of holies for hackers: credit card data. They are rapidly becoming the weapon of choice for attackers, FireHost Security Operations Center Manager Greg Tatum said, because that’s where the money is.
“We’re seeing a huge climb in the number of SQL injection attacks from the last quarter and over the past six months,” Tatum explained. “These attacks are monetary-based rather than fame-based.”
SQL injection attacks at FireHost rose from 277,770 in the first quarter to 469,983 in the second quarter of the year. That still ranks SQL injection-type attacks as only the third most popular type of attacks hitting FireHost and its clients, trailing directory traversal and cross-site scripting attacks.
Directory (or path) traversal attacks try to trick a website into providing access to files on the Web server that would otherwise be restricted. Like SQL injection attacks, they work by attacking the Web application itself, but they are also much easier to execute - which explains their top position on FireHost’s list. Once access to a Web server’s restricted files is obtained, intruders can have the run of the website, and can make it do nearly anything they want.
Cross-site scripting is almost as feared as SQL injection attacks, but instead of working on mining data from a website, these attacks flip the vector around and go after individual users. Cross-site scripts embed script tags in URLs and when unsuspecting users to click on those compromised links, malicious Javascript code can be executed on the victim’s machine.
Big Damage When Successful
Even though SQL injections are not as common, they grab bigger headlines because when they’re successful, they can cause a lot of user pain at once.
The 450,000 Yahoo Voices accounts' password breach on July 11 reportedly used a union-based SQL injection, for instance.
Unless evidence of the attack surfaces after the fact (little clues can help, such as nearly a half-million account passwords suddenly showing up on a hacker community forum), SQL injections are usually very hard to detect, which is the way profit-motivated hackers like it.
Tatum believes that SQL injection attacks will soon become even more common. “As more e-commerce and health care sites come online, these attacks will be more prevalent,” he predicted.
Defacing websites will always remain popular among a certain set of hackers. But the days of the loud and obnoxious attacks being the worst we have to worry about are coming to a close. Now it’s the silent but deadly attacks that Web administrators need to fear the most.




The primary defenses that are used to fight include,
     •    Prepared Statements (Parameterized Queries) - Parameterized queries force developers to define all the SQL code, then pass in each parameter to the query, which allows the database to distinguish between code and data, regardless of what input is supplied.
     •    Stored Procedures - a stored procedure is defined and stored in the database itself, and then called from the application rather than something that a user is allowed to enter.
     •    Escaping all User Supplied Input - Each DBMS supports one or more character escaping schemes specific to certain kinds of queries. If you then 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 include
     •    Least Privilege – or minimizing the privileges assigned to every database account, so that users have enough permission to do their job, but no more.
     •    White List Input Validation - Input validation is used to detect unauthorized input before it is processed by the application, thereby preventing the attack
 
 

CONCLUSION

SQL injection which is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. A webmaster should follow its countermeasures techniques to protect their website’s database from the attackers.




---------------------------------------------------------------------------------
Posted By Sundeep aka SunTechie

Sundeep is a Founder of Youth Talent Auzzar, a passionate blogger, a programmer, a developer, CISE and these days he is pursuing his graduation in Engineering with Computer Science dept.
Add Sundeep as a Friend on 

















< >