Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Website Security tips - Sql Injection and its prevention with Java

In this article we will learn how we can protect our website from sql injection attacks.

This article will teach you how you may protect your website from Sql injection attacks. This is really important and must be taken care if while making your new website.

Here we are going to learn following :

  1. SQL INJECTION
  2. Prevention using prepared statement

First we will discuss what is sql injection.

SQL Injection is actually a way where hacker put malicious database query on your website form and any other loophole and gets unauthorized access.

We will need a table from mysql to show the threat.

I have made one table named master with 2 columns which are username and password.It contains the username and password which authenticates a user to visit my website.

The structure of table is shown.

Now we make a simple java program which accepts the username and password from user and then tell if they are correct or not.

Listing 1: Verify username and password

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Security 
{
	public static void main(String[] args) 
	{
		try
		{
	   	  String myusername="",mypassword="";
		  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		  System.out.println("Enter your username");
		  myusername = br.readLine();
		  System.out.println("Enter your password");
		  mypassword = br.readLine();
		  String url = "jdbc:mysql://localhost:3306/";
		  String dbName = "article";
		  String driver = "com.mysql.jdbc.Driver";
		  String userName = "root"; 
		  String password = "anurag";
		  Class.forName(driver).newInstance();
		  Connection conn = DriverManager.getConnection(url+dbName,userName,password);
		  Statement st = conn.createStatement();
		  ResultSet res = st.executeQuery("SELECT * FROM  master where username=\""+myusername+"\"and password=\""+mypassword+"\"");
		  if (res.next()) {
		  String user = res.getString("username");
		  System.out.println("Welcome " + user);
		  }
		  else
		  {
			  System.out.println("Wrong credentials");
		  }
		  conn.close();
		  } catch (Exception e) {
		  e.printStackTrace();
		  }
		  }
}

Output 1 :

Enter your username
csanuragjain
Enter your password
mrbool
Welcome csanuragjain

Output 2:

Enter your username
csanuragjain
Enter your password
anurag
Wrong credentials

Here,first I will explain the program and then the 2 possible output.After this we will discuss the way to bypass this login and to prevent the bypass.We will discuss this program in short since I have already discussed connection with mysql in my previous posts.

  1. We make a new class named Security.And then define a main method
  2. We define a bufferedReader which will be responsible for obtaining the user input
  3. After obtaining the input we start making connection to mysql.This is done by defining the connection drivers and providing appropriate username ,password and driver.
  4. After this we will make a query ie "SELECT * FROM master where username=\""+myusername+"\"and password=\""+mypassword+"\""
  5. Here in query we are obtaining all those records where the username and password matches the one given by the user
  6. We execute this using the statement object and store the result in Resultset object.
  7. Now if user provided us with correct info then resultset must be having some value so that if (res.next()) will result into true otherwise it will result in false
  8. We display appropriate message according to user input.
  9. Here we show two possible output.In first one we gave correct username and password.The program accepts that and welcome the user.But in 2nd output we gave correct username but wrong password so it gave a fail message

Now we will discuss the problem in this program and how this problem can result into big security problem.We give one more possible input in the output as below:

Enter your username
csanuragjain
Enter your password
" OR "x"="x
Welcome csanuragjain

Here we have passed the wrong password but then also program accept that password.Want to know why this happened.Actually what we entered made the full query as:

SELECT * FROM  master where username="csanuragjain"and password="" OR "x"="x"

Here we are selecting all records from master where (username is csanuragjain , password is blank ) or x=x which is always true.And we know that false or true=trueSo this statement results to true and we are allowed to login even with wrong credentials

Now we will learn how to protect from this attack.For prevention make use of Prepared Statements like shown below:

Listing 2: Prepared Statements

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Security 
{
	public static void main(String[] args) 
	{
		try
		{
	   	  String myusername="",mypassword="";
		  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		  System.out.println("Enter your username");
		  myusername = br.readLine();
		  System.out.println("Enter your password");
		  mypassword = br.readLine();
		  String url = "jdbc:mysql://localhost:3306/";
		  String dbName = "article";
		  String driver = "com.mysql.jdbc.Driver";
		  String userName = "root"; 
		  String password = "jain";
		  Class.forName(driver).newInstance();
		  Connection conn = DriverManager.getConnection(url+dbName,userName,password);
		  String sql="SELECT * FROM  master where username=? and password=?";
		  PreparedStatement ps=conn.prepareStatement(sql);
		  ps.setString(1,myusername);
		  ps.setString(2,mypassword);
		  ResultSet res = ps.executeQuery();
		  if (res.next()) {
		  String user = res.getString("username");
		  System.out.println("Welcome " + user);
		  }
		  else
		  {
			  System.out.println("Wrong credentials");
		  }
		  conn.close();
		  } catch (Exception e) {
		  e.printStackTrace();
		  }
		  }
}

Output:

Enter your username
csanuragjain
Enter your password
" OR "x"="x
Wrong credentials

Here:

  1. We did everything same upto making a connection
  2. After that we make a prepared statement using the connection object. We pass the sql query to be executed in parameter.
  3. The main thing is the in sql query we fill all the input parameter with?. There values are later filled.
  4. We fill the values using the setString method in which 1st argument tell that for which parameter number or in simple term which question mark number,value we are providing.Like here we had first ? For username so we fill username and position as 1.
  5. After that the execute this statement and rest procedure is similar to previous.
  6. In output I again try to give malicious input but this time program rejects it so that the program is no more vulnerable.

This is all for today's article. See you in the next article.

Check out our java online courses. There are a lot of videos to watch and learn.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login