Saturday 14 July 2012

Tagged under: , , ,

Secure Login Code using PHP and MySQL / Preventing SQL Injection using PHP

Many Web pages accept parameters from web users and generate SQL queries to the database. SQL Injection is a trick to inject SQL script/command as an input through the web front end.

Your application may be susceptible to SQL Injection attacks when you incorporate invalidated user input into the database queries. Particularly susceptible is a code that constructs dynamic SQL statements with unfiltered user input.



Consider the following example code:
Sql DataAdapter myCommand = new SqlDataAdapter(
"Select * from Users
Where UserName = ' "+txtuid.Text+" ", conn);

Attackers can inject SQL by terminating the intended SQL statement with the single quote character  followed by a semicolon character to begin a new command and then executing the command to their choice. Consider the following character string entered into the .txtuid field.
' OR 1=1
This results in the following statement to be submitted to the database for execution:
SELECT * FROM Users WHERE UserName = ' ' OR 1 = 1;

Because 1=1 is always true, the attacker retrieves very row of data from the user table.

Now, to prevent such an attack, a secure login technique is required. Here, in this article, we discuss the coding of a secure login script using PHP and MySQL.


Step I: Create a database and a table 'members' in it:

CREATE TABLE `members` (
  `username` varchar(20),
  `password` varchar(128)
)



Step II: Create a Login Form:

<form action="process_login.php" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Login" />
</form>


Connect to MySQL Server:

$host = 'localhost'; // Host name Normally 'LocalHost'
$user = 'root'; // MySQL login username
$pass = ''; // MySQL login password
$database = 'test'; // Database name
$table = 'members'; // Members name
 
mysql_connect($host, $user, $pass);
mysql_select_db($database);


Step III: Now, you need to provide mechanism to avoid SQL Injection. For this, escape special characters like ", ', \

We can escape special characters (prepend backslash) using mysql_real_escape_string or addslashes functions. In most cases PHP will this do automatically for you. But PHP will do so only if the magic_quotes_gpc setting is set to On in the php.ini file.
If the setting is off, we use mysql_real_escape_string function to escape special characters. If you are using PHP version less that 4.3.0, you can use the addslashes function instead.

name = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
 
$result = mysql_query("SELECT * FROM $table WHERE username = '$username' AND password = '$password'
");


Here, we use the MD5(Message Digest 5) Algorithm, that generates the message digest for the password. So, while writing the script for registration page, care must be taken that the md5 of the password entered by the user must be stored in the database, instead of the actual text password. In a real world situation, do not use MD5, as it is no longer considered secure. Use some other secure hashing algorithm.

Validating the login:

if(mysql_num_rows($result))
{
  // Login
  session_start();
  $_SESSION['username'] = htmlspecialchars($username); 
}
else
{
  // Invalid username/password
  echo '<p><strong>Error:</strong> Invalid username or password.</p>';
}
 
// Redirect
header('Location: http://www.example.com/loggedin.php');
exit;


You are done!! This code will help prevent the SQL injection problem. However, it must be noted that no script is 100% secure. So, it is advisable to provide multilevel security process, which make the login more secure.

Wednesday 11 July 2012

Tagged under: , , ,

Auto Refresh a Web Page using AJAX

AJAX is nothing but Asynchronous JavaScript and XML. It is not a new programming language, but a new way to use the existing standards. It is the art of exchanging data with a server, and updating parts of a web page without reloading the whole page!!

Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. JavaScript and XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

 Using JavaScript for periodically refreshing a page can be quite annoying, as the entire page reloads time to time. Hence, a better option would be to use AJAX.
Include the following code in the <head> section of the page....

<script src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
 $.ajaxSetup({ cache: false });
$('#loaddiv').fadeOut('slow').load(window.location.href).fadeIn("slow");
}, 20000);
</script>


The section now refreshes after every 20 seconds. You can change the 20000 value to suite your requirements.
You can remove the ".fadeOut('slow')" and ".fadeIn(Slow)" parts if you want the page to be refreshed unnoticed.

Now, whichever section you want to be refreshed, must be included within the <div id="loaddiv"> tags as follows:

<div id="loaddiv">
<!--Your Content goes here-->
</div>


You are now done!! Enjoy as your page refreshes without you noticing!!

Sunday 8 July 2012

Tagged under: ,

Checking if your Computer has been violated and infected with DNS Changer

Domain name system (DNS) is the part of the internet that links a website name (say example.com) to its numerical internet protocol equivalent (say 123.456.789.098). As the cyber world awaits Monday, when the FBI will shut down servers affected by the DNS changer malware, there is still a day to check if your system has been affected.
Various cyber security firms are offering free solutions. You can visit www.mcafee.com/dnsdetect to check if your computer is infected.
You can also manually check if your DNS server has been changed.

Step I: Open Command Prompt.
           Navigate to Start-> Run.  Type cmd and hit enter.


StepII: (For Windows XP)Type ipconfig/all and hit enter.
           (For Windows 7) Type ipconfig/allcompartments/all and hit enter.


Step III: (For Windows XP) The command you entered displays information about your computer’s network settings. Read the line starting with "DNS Servers". There might be two or more IP addresses listed there. These are the DNS servers your computer uses. Write down these numbers.

(For Windows 7) The output will be very long, since Windows7 by default has support for IPv6. Most likely, you want to look for the IPv4 information under the section entitled “Ethernet adapter…”. Look for the “DNS Servers” line, and write down these numbers. There may be two IP addresses listed there.

Step IV: Check if your DNS settings are OK

Compare your DNS settings with the known malicious Rove DNS settings listed below:
Starting IP Ending IP CIDR
85.255.112.0 85.255.127.255 85.255.112.0/20
67.210.0.0 67.210.15.255 67.210.0.0/20
93.188.160.0 93.188.167.255 93.188.160.0/21
77.67.83.0 77.67.83.255 77.67.83.0/24
213.109.64.0 213.109.79.255 213.109.64.0/20
64.28.176.0 64.28.191.255 64.28.176.0/20

 What if you are infected?
If you computer is infected, please refer the page that list tools to clean DNS Changer and other self help guides to clean your computer – http://www.dcwg.org/fix/

Monday 2 July 2012

Tagged under: , , ,

How to create CAPTCHA using PHP

CAPTCHA:  Completely Automated Public Turing Test To Tell Computers and Humans Apart.

A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown alongside, but current computer programs can't:

The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.

Generating a simple CAPTCHA and its verification is quiet a simple task using PHP. In this post, I would do the same, but the CAPTCHA generated would be a simple one, while the reader can add his own creativity to it later!!

  • Step I: Create a file captchaimg.php, and add the following code to it:

<?php 
session_start(); 
header("Content-Type: image/png");
$text=substr(md5(uniqid(rand(), true)),0,5);
$_SESSION["vercode"] = $text; 
$height = 25; 
$width = 65; 
  
$image_p = imagecreate($width, $height); 
$black = imagecolorallocate($image_p, 0, 0, 0); 
$white = imagecolorallocate($image_p, 255, 255, 255); 
$font_size = 14; 
  
imagestring($image_p, $font_size, 5, 5, $text, $white); 
imagejpeg($image_p, null, 80); 
?>


You can check the above file by opening it in your browser. Everytime you refresh, a new, random alphanumeric string is generated in the CAPTCHA.
  • Step II: Create a form form.php, and add the following code to it:
<?php 
session_start(); 
if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='')
  { 
     echo  '<strong>Incorrect verification code.</strong>'; 
  } else { 
     // add form data processing code here 
     echo  '<strong>Verification successful.</strong>'; 
}; 
?>
<form action="form.php" method="post"> 
Comment: <input type="text" name="coment"> 
Enter Code <img src="captchaimg.php" /><input name="vercode" type="text" /> 
<input name="Submit" type="submit" value="Submit" /> 
</form>


Now, this is it!! Your basic CAPTCHA is ready!! It will look like below:

Another Example:
For this, you need to include a font file in your project folder. I have used AngelicWar.ttf. Download the font from the download box alongside.
Now, Overwrite the file captchaimg with the following code:

<?php
session_start();
header("Content-type: image/png");
$_SESSION["vercode"]="";
$im = imagecreate(105, 50); //Size of the image Width, Height

imagecolorallocate($im, 167, 218, 239);  //Set background color 
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);        

$font = 'AngelicWar.ttf'; // You can replace font by your own        
for($i=0;$i<=5;$i++) {
    $numb=substr(md5(uniqid(rand(), true)),0,1);
    $_SESSION["vercode"].=$numb;
    $angle=rand(-25, 25);
    imagettftext($im, 20, $angle, 8+15*$i, 30, $black, $font, $numb);    
    // Add shadow to the text    
    imagettftext($im, 20, $angle, 9+15*$i, 34, $grey, $font, $numb);    
}
imagepng($im);
imagedestroy($im);
?>

Now, this will result in following CAPTCHA:


For the following CAPTCHA use cheapink.ttf from the download box alongside.



You can enhance it by using two different strings in a single CAPTCHA image, or using some string characteristics.

Want help in creating more creative CAPTCHA?? Feel free to Contact Me.