আগামী ১৫ ডিসেম্বর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ২৬ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

Introduction to PHP Security part 1

Introduction to PHP Security part 1

In this post we will discuss a very common method of hacking a website (or rather, a database) called SQL Injection. The object of this post is not to help anyone destroy/deface other websites, but to help you protect your website from such an attack. In this post I will explain the basics of how SQL Injection works and in my next post I shall focus on what can be done so that your website does not become a victim of SQL Injection.

SQL Injection: What is it?

SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

In essence, SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.

SQL Injection: An In-depth Explanation
Web applications allow legitimate website visitors to submit and retrieve data to/from a database over the Internet using their preferred web browser. Databases are central to modern websites – they store data needed for websites to deliver specific content to visitors and render information to customers, suppliers, employees and a host of stakeholders. User credentials, financial and payment information, company statistics may all be resident within a database and accessed by legitimate users through off-the-shelf and custom web applications. Web applications and databases allow you to regularly run your business.

SQL Injection is the hacking technique which attempts to pass SQL commands (statements) through a web application for execution by the backend database. If not sanitized properly, web applications may result in SQL Injection attacks that allow hackers to view information from the database and/or even wipe it out.

Such features as login pages, support and product request forms, feedback forms, search pages, shopping carts and the general delivery of dynamic content, shape modern websites and provide businesses with the means necessary to communicate with prospects and customers. These website features are all examples of web applications which may be either purchased off-the-shelf or developed as bespoke programs.

These website features are all susceptible to SQL Injection attacks which arise because the fields available for user input allow SQL statements to pass through and query the database directly.

But before that, you just make database named phpsecurity. Then make table with the following query:

CREATE TABLE `user` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`uname` VARCHAR( 50 ) NOT NULL ,
`password` TEXT NOT NULL ,
PRIMARY KEY ( `id` ) ,
UNIQUE ( `uname` ));
INSERT INTO `user` (`id`, `uname`, `password`) VALUES
(2, 'sohel', md5('sohel'))

We are going to make a form for login as follow:

<!--Listing Program: Login.php-->

<html>

<head><title>Login</title></head>

<body>

<form method="post">

Username <input type="text" name="uname">

<br>

Password <input type="password" name="pass">

<br>

<input type="submit" name="submit" value="Login">

</form>

</body>

</html>

<?php

error_reporting(0);

extract($_POST);

if ($submit or $uname){

$conn = mysqli_connect('localhost','root','','zend18') or die(mysqli_connect_error());

$sql = "SELECT * FROM user

WHERE uname='".$uname."'

AND password=md5('$pass')";

echo $sql;
$query = mysqli_query($conn,$sql) or die(mysql_error($conn));




if (mysqli_num_rows($query) > 0){

echo "success enter";

}else{

echo "sory, wrong pair (username and password)";

}

}

?>

Try to execute it and enter the right user.

PHP SQL Injection TestPicture 1: Login is succeeded in enter

We intentional publish the SQL so that you can know on how the sql is actually happens. Next, we are trying to input any username that is not in database.

PHP SQL Injection Fail

Picture 2: Username is not found>

Next, we are trying to enter it even we don’t know about the true user.

Enter username: ‘ or uname != ‘

password: ‘ or password !=’

Then click the Login button.

Login using sql injection

Picture 3: Succeeded in enter

You are succeeded in entering it because of the sql modification through the text control become:

SELECT count(1) as ada FROM user
WHERE uname='' or uname != '' AND password=md5('')
or password !=('')

There is another possibility that you will get another result such like this:

PHP SQL INJECTION Prevention

Picture 4: The quotation mark is given the backlash sign

In the picture above, we can see the quotation mark that you already input and it is started with backlash. Automatically, the input quotation mark is already protected with backlash. Why there can be two different results? It is because the setting of this php.ini. Try to open your php.ini (in some of the windows installation, php.ini is located in C:/windows or its php folder). Find the line as you can see as follows:

...

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = On

; Magic quotes for runtime-generated data, e.g. data
; from SQL, from exec(), etc.

magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with ''
; instead of \').
magic_quotes_sybase = Off

...

If in magic_quotes_gpc is given with On value, then backlash will be given into every quotation marks. Apart from the php.ini setting, I’m going to explain about two general ways as follow:

  • Username and password using alphanumeric.
  • Tight validation.

The first way, the visitor is obliged to do the registration by using username and password with alphanumeric. Alphanumeric is abbreviation from alphabet and numeric. User must use the alphabet letter and number. Alphabet means the letter of a-z and A-Z while numeric means 0-9. By using alphanumeric, you already anticipate the input possibility in using another character.

How about the code to filter the input beside alphanumeric? You can insert the code as follow:

if ((ctype_alnum($uname) == false) or
(ctype_alnum($pass) == false)){
die("Sorry, you must enter alphanumerik.");
}

In above, the line code is examining whether the content of the $uname and $pass is alphanumeric or not. If one of the content isn’t alphanumeric, the process will be stopped immediately.

You can insert the above code in the data checking process block in database:

<!--Listing Program: Login2.php-->

<html>

<head><title>Login2</title></head>

<body>

<form method="post">

Username <input type="text" name="uname">

<br>

Password <input type="password" name="pass">

<br>

<input type="submit" name="submit" value="Login">

</form>

</body>

</html>

<?php

error_reporting(0);

extract($_POST);

if ($submit or $uname){

if ((ctype_alnum($uname) == false) or

(ctype_alnum($pass) == false)){

die("Please, Enter Alpha Numeric Value.");

}

$conn = mysqli_connect('localhost','root','','phpsecurity') or die(mysqli_connect_error());

$sql = "SELECT count(1) as number FROM user

WHERE uname='".$uname."'

AND password=md5('".$pass."')";

echo $sql."<BR>";

$q = mysqli_query($conn,$sql) or die(mysqli_error($conn));

$r = mysqli_fetch_array($q);

$number = $r[number];

mysqli_close($conn);

if ($number > 0){

echo "Success enter";

}else{

echo "Sorry, wrong pair";

}

}

?>

PHP Alpha Numeric Validation to prevent sql injection

Picture 5: The quotation mark and not alphanumeric

The second way, you just validate your user input using regular expression.

<!--Listing Program: Login3.php-->

<html>

<head><title>Login3</title></head>

<body>

<form method="post">

Username <input type="text" name="uname">

<br>

Password <input type="password" name="pass">

<br>

<input type="submit" name="submit" value="Login">

</form>

</body>

</html>

<?php

error_reporting(0);

extract($_POST);

if ($submit or $uname){

if ((!preg_match('/^[a-z0-9]+$/i', $uname)) and (!preg_match('/^[a-z0-9]+$/i', $pass))){

die("Please, Enter Alpha Numeric Value.");

}

$conn = mysqli_connect('localhost','root','','phpsecurity') or die(mysqli_connect_error());

$sql = "SELECT count(1) as number FROM user

WHERE uname='".$uname."'

AND password=md5('".$pass."')";

echo $sql."<BR>";

$q = mysqli_query($conn,$sql) or die(mysqli_error($conn));

$r = mysqli_fetch_array($q);

$number = $r[number];

mysqli_close($conn);

if ($number > 0){

echo "Success enter";

}else{

echo "Sorry, wrong pair";

}

}

?>

You have been known a little bit about SQL Injection above. Now, we are going to discuss more about the attack possibilities through SQL Injection deeply. If in the XSS, it has the impact to the visitor who visit/open your site, and then in the SQL Injection, it attacks directly to site itself. The main target of this attack is your database.

Usually, the target of this SQL injection is to break your data. It uses strings which contains of query that is going to be executed by database. It could be mean that it breaks the data that is published, modifying the data, or even deleting the data.

You can see the general description of this matter as follows:

<!--Listing Program: select.php-->

<form method="post" action="select.php">

Enter your name:

<input type="text" name="name">

<input type="submit" name="submit" value="Submit">

</form>

<?php

error_reporting(0);

extract($_REQUEST);

if (strlen($name)>0){

$conn=mysqli_connect("localhost","root","","phpsecurity");

$q = mysqli_query($conn,"SELECT * FROM user

WHERE uname = '$name'") or die(mysql_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

If you put a name, then you will get the data that you want.

Prevent SQL Injection using type castingPicture 6: Find name

So, there is a fad people who enters masud’ or ‘1. The result will be as in the picture 6.

PHP SQL Injection CodesPicture 7: Manipulating string query

Why it can be happened? Honestly, he/she insert another order that make its query become change like this:

SELECT * FROM user WHERE uname = '$name' or '1

Magic Quotes

You have been introduced about the problems of the magic quotes in above. You can practice the previous example when the magic_quotes_gpc status in the off position. It enables the single (‘) or the double (“) quotation mark is slip away. It simply brings a problem when you input the word with the quotation mark in it such as masud’s.

PHP Magic QuotesPicture 8: The quotation mark in words can make error

The problem is that, for example, our application is built in the magic_quotes_gpc status in the off position, then its server uses on position. How to solve this differentiation? If in the off position, we add backlash (\) before the quotation mark while in the on position, we just let it go. If we already add backlash and its server is in the off position, then it will become a problem too. How to solve this problem?

We can do the examination first toward the position from server. If it is in the on position, then we will make the backlashes disappears. Next, we use the mysql_escape_string(). You can see the example in the following code:

<!--Listing Program: magicquotes.php-->

<form method="post" action="magicquotes.php">

Enter your name:

<input type="text" name="name">

<input type="submit" name="submit" value="Submit">

</form>

<?php

//error_reporting(0);

extract($_REQUEST);

if (strlen($name)>0){

$conn=mysqli_connect("localhost","root","","phpsecurity");

if(get_magic_quotes_gpc()){

$name= stripslashes($name);

}

$name = mysqli_real_escape_string($name);

$q = mysqli_query($conn,"SELECT * FROM user WHERE uname

like '%$name%'") or die(mysql_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

PHP Magic Quotes SecurityPicture 9: Release the quotation mark

With the above condition, you don’t care whether magic_quotes_gpc is in the off or on position. Though you allow the quotation mark input to get through, user can also change it as in fulfilling masud’ or ‘1.

The Data Type Accuracy

Here is the interesting case:

<!--Listing Program: userinfo.php-->

<form method="post" action="userinfo.php">

Enter user ID:

<input type="text" name="uid">

<input type="submit" name="submit" value="Submit">

</form>

<?php

error_reporting(0);

extract($_REQUEST);

if (strlen($uid)>0){

$conn=mysqli_connect("localhost","root","","phpsecurity");

if(get_magic_quotes_gpc()){

$uid = stripslashes($uid);

}

$uid = mysqli_real_escape_string($uid);

$q = mysqli_query($conn,"SELECT * FROM user

WHERE id = $uid") or die(mysqli_connect_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

We supply the user searching facility by using their id. Hopefully, the searcher enters the user id number that is searched. But, the user isn’t only done this thing. They also do another thing such as entering 1 or 2. The result is that there are a lot of competent users. Not only one.

PHP SQL Injection TechniquePicture 10: Using or to slip away

To solve this problem, you have to make sure about the data type that is used. We have to verify whether the data is the same with our hope or not. If not then we have to change it. Example, you just add (int) to input the integer datas.

<!--Listing Program: cast.php-->

<form method="post" action="cast.php">

Enter user ID:

<input type="text" name="uid">

<input type="submit" name="submit" value="Submit">

</form>

<?php

error_reporting(0);

extract($_REQUEST);

if ($uid > 0){

$conn=mysqli_connect("localhost","root","","phpsecurity") or die(mysqli_connect_error());

$uid = (int)$uid;

$uid = mysqli_real_escape_string($uid);

$q = mysqli_query($conn,"SELECT * FROM user

WHERE id = $uid") or die(mysql_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

SQL INJECTION USING CROSS-SITE SCRIPTING

Cross-Site Scripting (XSS) is one of the general vulnerabilities from web application. They ways of this working are that most of the attackers save the CSS, HTML, or Javascript code in database. Next, if there is user accesses the page/the part of this page then there will be information that is taken or changed into the third party site.

It can be able to that XSS changes your web appearance. When the page is published, the codes that are inserted are going to work so that your web appearance is change. You know that it will happen because the code that is inserted is client side code.

There are two kinds of XSS vulnerabilities:

  • Direct action, where the injection input is only published into the injection user.
  • Stored action, where some of the visitors candidate sees the injection content. It is very dangerous than direct action.

Here are the simple examples where user can change your site appearance. Make the code as follow and execute:

1st: Create a database called Camments

2nd: Create a table using this query:

CREATE TABLE COMMENT (

`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `name` VARCHAR( 40 ) NOT NULL ,
 `email` VARCHAR( 100 ) NOT NULL ,
 `comments` TEXT NOT NULL

) ENGINE = InnoDB;

Now Create a Comment Form

</pre>
<!--Listing Program: FormSimple.php-->

<?php

$conn=mysqli_connect("localhost","root","","comments");

error_reporting(0);

extract($_REQUEST);

if($comment){

$sql=mysqli_query($conn,"INSERT INTO comment set name='$name', email='$email', comments='$comment'") or die(mysqli_error());

if(mysqli_affected_rows($sql)>0){

echo"Your Comment Successfully Submitted";

}

}

else{

echo" Please Write your comment";

}

?>

<html>

<style>

P.biru {font-size:12pt; color:blue}

</style>

<body>

<form method="get" action="SimpleForm.php">

<table border="0" width="400" cellpadding="5">

<tr>

<td class="biru">Your name:</td>

<td> <input type="text" name="name" size="20"></td>

</tr>

<tr>

<td class="biru">Your email:</td>

<td> <input type="text" name="email" size="20"></td>

</tr>

<tr>

<td class="biru">Enter your comment:</td>

<td><textarea name="comment" cols="15" rows="4"></textarea></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

<?php

$query=mysqli_query($conn,"SELECT * FROM comment");

while($rows=mysqli_fetch_array($query)){

?>

<p>Your name :<?=$rows['name'];?>

<p>Email:<?=$rows['email'];?>

<p>Comment:<?=$rows['comments'];?>

<?php

}

?>

</body>

</html>
<pre>

To solve this problem, you have to make sure about the data type that is used. We have to verify whether the data is the same with our hope or not. If not then we have to change it. Example, you just add (int) to input the integer datas.

<!--Listing Program: cast.php-->

<form method="post" action="cast.php">

Enter user ID:

<input type="text" name="uid">

<input type="submit" name="submit" value="Submit">

</form>

<?php

error_reporting(0);

extract($_REQUEST);

if ($uid > 0){

$conn=mysqli_connect("localhost","root","","phpsecurity") or die(mysqli_connect_error());

$uid = (int)$uid;

$uid = mysqli_real_escape_string($uid);

$q = mysqli_query($conn,"SELECT * FROM user

WHERE id = $uid") or die(mysqli_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

SQL INJECTION USING CROSS-SITE SCRIPTING

Cross-Site Scripting (XSS) is one of the general vulnerabilities from web application. They ways of this working are that most of the attackers save the CSS, HTML, or Javascript code in database. Next, if there is user accesses the page/the part of this page then there will be information that is taken or changed into the third party site.

It can be able to that XSS changes your web appearance. When the page is published, the codes that are inserted are going to work so that your web appearance is change. You know that it will happen because the code that is inserted is client side code.

There are two kinds of XSS vulnerabilities:

  • Direct action, where the injection input is only published into the injection user.
  • Stored action, where some of the visitors candidate sees the injection content. It is very dangerous than direct action.

Here are the simple examples where user can change your site appearance. Make the code as follow and execute:

1st: Create a database called Camments

2nd: Create a table using this query:

CREATE TABLE COMMENT (

`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `name` VARCHAR( 40 ) NOT NULL ,
 `email` VARCHAR( 100 ) NOT NULL ,
 `comments` TEXT NOT NULL

) ENGINE = InnoDB;

Now Create a Comment Form

<!--Listing Program: FormSimple.php-->

<?php

$conn=mysqli_connect("localhost","root","","comments")or die(mysqli_connect_error());

error_reporting(0);

extract($_REQUEST);

if($comment){

$sql=mysqli_query($conn,"INSERT INTO comment set name='$name', email='$email', comments='$comment'") or die(mysql_error());

if(mysqli_affected_rows($sql)>0){

echo"Your Comment Successfully Submitted";

}

}

else{

echo" Please Write your comment";

}

?>

<html>

<style>

P.biru {font-size:12pt; color:blue}

</style>

<body>

<form method="get" action="FormSimple.php">

<table border="0" width="400" cellpadding="5">

<tr>

<td class="biru">Your name:</td>

<td> <input type="text" name="name" size="20"></td>

</tr>

<tr>

<td class="biru">Your email:</td>

<td> <input type="text" name="email" size="20"></td>

</tr>

<tr>

<td class="biru">Enter your comment:</td>

<td><textarea name="comment" cols="15" rows="4"></textarea></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

<?php

$query=mysqli_query($conn,"SELECT * FROM comment");

while($rows=mysqli_fetch_array($query)){

?>

<p>Your name :<?=$rows['name'];?>

<p>Email:<?=$rows['email'];?>

<p>Comment:<?=$rows['comments'];?>

<?php

}

?>

</body>

</html>

PHP SQL Injection With Cross Site ScriptingPicture11: The appearance of the simple form

In that form, you hoped that there is a visitor inputs their comments. But there is a visitor who input the content fadly as follows:

<script type="application/javascript">alert("Hello");</script>

PHP SQL Injection ResultPicture 12: When you refresh your page it always show a hello message

After you already known on how this attack happens, now, it is time to protect your site. There is one way that you can use to prevent XSS such as the using of encoding, the handling of HTML attribute, filtering, etc.

Encoding Solution

If you use this way means that you are encoding the special characters which have meaning in HTML language such as < (less than), > (larger than), & (ampersand), ” (two quotation mark), and ‘ (quotation mark). All of these special characters will be convert into HTML entity such as & will be changed into &.

In PHP, the function to run this thing is htmlspecialchars(). The example as following:

<!--Listing Program: FormSimple2.php-->

<?php

$conn=mysqli_connect("localhost","root","","comments") or die(mysqli_connect_error());

error_reporting(0);

extract($_REQUEST);

if($comment){

$sql=mysqli_query($conn,"INSERT INTO comment set name='".htmlspecialchars($name)."', email='".htmlspecialchars($email)."', comments='".htmlspecialchars($comment)."'") or die(mysqli_error($conn));

if(mysqli_affected_rows($sql)>0){

echo"Your Comment Successfully Submitted";

}

}

else{

echo" Please Write your comment";

}

?>

<html>

<style>

P.biru {font-size:12pt; color:blue}

</style>

<body>

<form method="get" action="FormSimple.php">

<table border="0" width="400" cellpadding="5">

<tr>

<td class="biru">Your name:</td>

<td> <input type="text" name="name" size="20"></td>

</tr>

<tr>

<td class="biru">Your email:</td>

<td> <input type="text" name="email" size="20"></td>

</tr>

<tr>

<td class="biru">Enter your comment:</td>

<td><textarea name="comment" cols="15" rows="4"></textarea></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

<?php

$query=mysqli_query("SELECT * FROM comment");

while($rows=mysqli_fetch_array($query)){

?>

<p>Your name:<?=$rows['name'];?>

<p>Email:<?=$rows['email'];?>

<p>Comment:<?=$rows['comments'];?>

<?php

}

?>

</body>

</html>

Executing that program code and entering the input as we have been done in the previous exercise. The result will be as in the picture 2.3. You can see that the input isn’t considered as HTML but it already publishes as the usual text.

PHP SQL Injections Using Forms

Picture 13: The using of htmlspecialchars()

Strip_tags()

You must be already known about the strip_tags() function in PHP. This function will discard HTML inside the string that is inputted.

Here are the simple Form where user can insert their website url for seo or web site publishing:

PHP SQL Injections Using PHP Form

CODE:

<!--Listing Program: StripTags.php-->

<?php

$conn=mysqli_connect("localhost","root","","comments")or die(mysqli_connect_error());

error_reporting(0);

extract($_REQUEST);

if($comment){

$sql=mysqli_query($conn,"INSERT INTO comment set name='".strip_tags($name)."', email='".strip_tags($email)."', comments='".strip_tags($comment)."'") or die(mysql_error());

if(mysqli_affected_rows($sql)>0){

echo"Your Comment Successfully Submitted";

}

}

else{

echo" Please Write your comment";

}

?>

<html>

<style>

P.biru {font-size:12pt; color:blue}

</style>

<body>

<form method="get" action="StripTags.php">

<table border="0" width="400" cellpadding="5">

<tr>

<td class="biru">Your name:</td>

<td> <input type="text" name="name" size="20"></td>

</tr>

<tr>

<td class="biru">Your email:</td>

<td> <input type="text" name="email" size="20"></td>

</tr>

<tr>

<td class="biru">Enter your comment:</td>

<td><textarea name="comment" cols="15" rows="4"></textarea></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

<?php

$query=mysqli_query($conn,"SELECT * FROM comment");

while($rows=mysqli_fetch_array($query)){

?>

<p>Your name:<?=$rows['name'];?>

<p>Email:<?=$rows['email'];?>

<p>Comment:<?=$rows['comments'];?>

<?php

}

?>

</body>

</html>

Here is the Output:

PHP Form SQL Injection Sollution

What about if user wants to add the bold accent in its string input? We can allow the user in using some of the HTML order as following:

<!--Listing Program: limitstrip_tag.php-->

<?php

$input = "PHP <b>Security</b> is an important lesson for beginners.
Minimal provision for developing a <i>secure</i> website.";

echo strip_tags($input,"<b><i>");

?>

You just let the strig_tags() know that there is an exception so that the user will not act over. You still allow the user in using <b> and <i>. This technic gives freedom to the user in using the HTML tag that is already allowed. Usually, you give this exception in the discussion forms, send writing, etc.

PHP SQL Injections Some of the HTML tag is allowed

The FILE attack

Operator FILE in SQL is the thing that you should have to watch. This operator has a freedom in the data searching that can be used by user. Here is the example of showing the name based on its initial letter.

<!--Listing Program: like.php-->

Find name with character initial:

<a href='like.php?name=a'>A</a> |

<a href='like.php?name=b'>B</a> |

<a href='like.php?name=b'>C</a> |

<br>

<?php

error_reporting(0);

extract($_REQUEST);

if (strlen($name)>0){

$conn=mysqli_connect("localhost","root","","phpsecurity");

if(get_magic_quotes_gpc()){

$name = stripslashes($name);

}

$name = mysqli_real_escape_string($name);

$q = mysqli_query($conn,"SELECT * FROM user

WHERE uname like '$name%'") or die(mysql_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

We supply a link so that it can be clicked by the visitor to publish the user with the initial letter that you have been clicked. You can publish the user with the intial letter as you want by using SQL as follow:

SELECT * FROM user WHERE uname like '$name%'

Then, there is a fad user who types the sign of % in the initial letter in URL directly. Example: ?name=%a. You can guess that the query text becomes:

SELECT * FROM user WHERE uname like '%a%'

Means that the order publishes all of the users that contains of the word ‘a’ and not only the word with the initial word ‘a’.

PHP File Attack Security

To solve this problem, you just add a little addcslashes function such like this:

<!--Listing Program: likesave.php-->

<a href='likesave.php?name=a'>A</a> |

<a href='likesave.php?name=b'>B</a> |

<a href='likesave.php?name=b'>C</a> |

<br>

<?php if (strlen($nama)>0){

$conn=mysqli_connect("localhost","","","phpsecurity");

if(get_magic_quotes_gpc()){

$name = stripslashes($name); }

$name = addcslashes(mysql_real_escape_string($name),"%");

$q = mysqli_query($conn,"SELECT * FROM user

WHERE uname like '$nama%'") or die(mysql_error());

while($r = mysqli_fetch_array($q)){

echo $r[1];

echo "<br>";

}

}

?>

What’s the effect of addcslashes? They add backlash in every words such as:

echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]

Include File

We oftens find the include file that is given with extention .inc. These files contains of the data that is often used. It is better for us to put the code lines into one file that is include file better than if we write it. Sometimes, this include file contains of the important data such as the data to access database. If we just only give named with connection.inc, the visitor can be able to access the file and can see your big secret. It’s too dangerous. So, we have to protect it.

You can protect it by using the facility access in web server such as .httaccess in apache and adding the following code. It means that all of the .inc file cannot be accessed.

<Files ~ "\.inc$">
Order allow, deny
Deny from all
</Files>

Another alternative is by making php file with php extension. So, the complete name likes config.inc.php. It’s safest than .inc

CODE INJECTION

Code injection is the vicious attack which can dangerous your site. Code Injection can cause many things. It can do many things as the things that can be done in php, steal information, modify database, change the local file and script, and compromise with your computer system!

In this chapter, we are going to learn anything that can be done in PHP to prevent these problems. It needs to be brought into beginner in PHP programming and also for those who already get an order.

We oftens use include or require. It is one of the ways to enter into our application. To save it, we need some steps. The first step is to correct the code.

Full path

Usually, we use the code as follow:

include "config.inc";

This is the unsecured process of writing. It is better for us if we use the writing model with the complete path as follow:

require "/home/web/include/config.inc";

Or, it can be like this:

<code>require "./include/config.inc";</code>

Using Constant

Usually, we save full path in one variable. Thus, we can call it anytime such as:

$_dir_ = "/home/web/include/";

Unfortunately, it stills have a risk toward the infiltrator. If the variable value is modified by the visitor then it could be possible that we cannot find a file that we want. It also has a risk toward code injection.

The better way is using constantan. The example as the following:

define("__INC__DIR__","/home/web/include/");

The constantan’s value isn’t change and it is the safety way. You can call it with the following model:

require __INC__DIR__ . "config.inc";

The risk of this model is that if the directory cannot be found, it will become the fatal error.

About this variable, we always warned in using register_global. Some of the written also asks us to becareful with the global variables. Once you got injection, it can spread into some places which need the variable.

SECURITY USING CAPTCHA

Now, we are going to discuss about technic that is used by the web page form to prevent the input release which is done by machine automatically. This technic is called Captcha.

CAPTCHA is the abbreviaton from Completely Automated Public Turing to tell Computers from Humans Apart and it is a program that can do the selection in where:

  1. Most of the people can get through
  2. The computer programs cannot to be through

For example, you make a form as in the picture . Here is the listing program form:

PHP Security Using Captcha

Here are the codes from the from above:

<!--Listing Program: form.php-->

<html>

<body>

Sign up now. Get great prizes:

<form method="post" action="list.php">

<table>

<tr>

<td>Name:</td>

<td><input type="text" name="name" size="30"></td>

</tr>

<tr>

<td>Address:</td>

<td><input type="text" name="address" size="50"></td>

</tr>

<tr>

<td><input type="submit" value="Submit"></td>

<td> </td>

</tr>

</table>

</form>

</body>

</html>

After fill the form, the visitor will click the submit button. The visitor data will be taken into the list.php page. Here are the list.php page codes:

<!--Listing Program: list.php-->

<?php

$conn=mysqli_connect("localhost","root","","phpsecurity") or die(mysqli_connect_error());

extract($_REQUEST);

mysqli_query($conn,"INSERT INTO registration SET name='$name', address='$address'") or die(mysql_error());

?>

Congratulations you have successfully signed up .... Prize immediately sent to your home.

In that list page, the visitor data will be taken into database. If succeeded, “the present will be sent immediately…”, that’s the promise.

To practice this exercise, you have to make the registration table first. Here is the sql:

CREATE TABLE registration(

id INT( 11 ) NOT NULL AUTO_INCREMENT ,
 name VARCHAR( 50 ) NOT NULL ,
 address VARCHAR( 255 ) NOT NULL ,
 PRIMARY KEY ( id )

)

Now try to input one data or some datas.

Now, we are trying to change the data input function by computer. Presently, we make a wonderful program code to attack the form. Just type the following program code:

<!--Listing Program: breakthrough.php-->

<?php

$url = "http://localhost/security/login/list.php?name=bejo&address=dimana-mana";

for($i=0;$i<=100;$i++){

$f = fopen($url,'r');

fclose($f);

}

?>

Is that all? Yes, you’re right. Although it just consists of few lines but it is potential to attack form web. Try to execute the page.

Next, open your database. Look to see that the table already contains of 100 datas in the easy way.

PHP Security

Imagine if the code line is looping a thousand times by a lot of fad users. The result is that our server is down and our database fulls with the datas that we don’t want to.

Captcha is the Solution

To prevent this attack, we need verification that cannot be done automatically. It means that the form needs an extra step which can be done by the human touching in order to get send the form.

The solution is using Captcha.

In order to make it easy, we use the captcha class that is already made by someone. You can find this at http://www.google.com/recaptcha

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

8 comments on “Introduction to PHP Security part 1

Leave a Reply

Your email address will not be published. Required fields are marked *