Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL injection Attack

How do i secure my site to SQL injection attacks? Im using PHP and mysql. Do i have to alter my mysql Query?

For example, i have one query like this:

<?php
$q=$_GET["q"];// im getting the Q value from the other form,from drop down box[displaying data using Ajax
$a1=$_POST['hosteladmissionno'];
$a2=$_POST['student_name'];
$a3=$_POST['semester'];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("hostel", $con);

$a1="SELECT  hosteladmissionno,student_name,semester FROM registration 
WHERE mess_type ".$q."' AND  status_flag=1";

$result = mysql_query($a1);

if ($result === false) {

    die(mysql_error());
}
echo "<table border='1' width=80%>
<tr>
 <th width=5%> S.No</th>
<th width=10%>H.Admin No</th>
<th width=10%>Student Name</th>
<th width=5%>No of Days</th>
</tr>";
 $i=0;
while($row = mysql_fetch_array($result))
  {
  $i=$i+1;
  echo "<tr>";
  echo "<td  align=center>" .$i."</td>";
  echo "<td size=10 align=center>" . $row['hosteladmissionno'] . "</td>";
  echo "<td size=35  align=center>" . $row['student_name'] . "</td>";
  echo "<td  align=center>  <input type='text' name='days' size=2> </td> ";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Do i have to include any alteration in my query to avoid Injection attacks? Any suggestion would be helpful.Thanks in advance. Cheers!

like image 867
Coolbreeze Avatar asked Mar 29 '11 06:03

Coolbreeze


1 Answers

Your query appears (EDIT: appeared, in the first version of the query) to be entirely static - i.e. it doesn't use any user-supplied data. In that case, there's no risk of SQL injection.

SQL injection attacks involve taking user input and including that directly in a SQL query, instead of the preferred method of using a parameterized SQL statement and including user-supplied values that way. (I don't know the details of how that's done in PHP... I certainly hope it's possible.)

EDIT: Okay, now you've changed your code, including this:

$a1="SELECT  hosteladmissionno,student_name,semester FROM registration 
WHERE mess_type ".$q."' AND  status_flag=1";

Where $q is retrieved from a text box. Now I assume you really meant the second line to be:

WHERE mess_type='".$q."' AND  status_flag=1";

But that's still vulnerable to SQL injection attack. Suppose the value of q is:

' OR 'x'='x

Your SQL statement would then end up as

SELECT hosteladmissionno,student_name,semester FROM registration 
WHERE mess_type='' OR 'x'='x' AND  status_flag=1

which clearly isn't the logic you're after.

You should use parameters for the values, as shown on this PHP prepared statement page.

like image 193
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet