WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder



Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Anti SQL injection-PHP
Categories : PHP, MySQL, Security
s f
Date : Sep 02nd 2008
Grade : 3 of 5 (graded 9 times)
Viewed : 10112
File : No file for this code example.
Images : No Images for this code example.
Search : More code by s f
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

Introduction:

This tiny article was born after my web site hacked by a turkey group, so I can't access / read my web site. The website was urbanized by MYSQL and PHP. The hackers demolish my site by using SQL injection, so I clear up / recovering the site from their evil data and I did some Anti-SQL injection coding to prevent for future attacks.Ok let’s start with general hacking information.

Dealing with hack attempts, evil web bots, and worms has been an ongoing headache. Most of these problems come from dynamic IP addresses, so simply blocking the offender is only a temporary solution, and we may use to Examining logs and putting blocks in place is time consuming. Remembering to remove blocks on dynamic IP addresses is also a problem. Best way to avoid the SQL injection by using some anti-SQL injection coding.


About deadly injection:
Most of the web applications are used to get users information. The input information is used for many purpose one of which is to query the databases. And hacker use this key to input some malfunction by their tricks ,generally SQL injection defined as trying to input his data through the web application’s user interface that would give malicious user the sensitive information edit / modify the protected data or crash the entire system etc. The SQL injections have several methods to inject; my site was affected by SQL Manipulation, which was succeeding by using the URL.
Categories of SQL injection:

There are four main categories of SQL Injection attacks against databases
SQL Manipulation: manipulation is process of modifying the SQL statements by using various operations such as UNION .Another way for implementing SQL Injection using SQL Manipulation method is by changing the where clause of the SQL statement to get different results.
Code Injection: Code injection is process of inserting new SQL statements or database commands into the vulnerable SQL statement.
Function Call Injection: Function call injection is process of inserting various database function calls into a vulnerable SQL statement. These function calls could be making operating system calls or manipulate data in the database.
Buffer Overflows: Buffer overflow is caused by using function call injection. For most of the commercial and open source databases, patches are available. This type of attack is possible when the server is un-patched




How to Find Affected Site:

Most of the hacker used to inject their data’s through the feed back, poll, search pages because all the above pages are frequent and possible to get the input from end users. In my website all polling and comment / feed back pages are filled with hacker information also my main content page was loaded with their images. Some time the web site redirect to hackers own page!

So try to look for pages that allow you to submit data, i.e.: login page, search page, feedback, etc. Sometimes, HTML pages use POST command to send parameters to another PHP page. Therefore, you may not see the parameters in the URL. However, you can check the source code of the HTML, and look for "FORM" or META tag in the HTML code. You may find something like this in some HTML codes:

<FORM NAME="index" METHOD="post" ACTION="index.php?search=insert into">
<META NAME="AUTHOR" CONTENT="Hacked AnadoluHackers.ORg">


Even they change the keyword content, All the hacker in formations are come from our database

<div align="center"><strong>|Anatolian Hackers |</strong> <br><br><strong><a href="http://www.anadoluhackers.org/">WwW.AnadoluHackers.ORg</a><strong><br><br>Hacked </strong><div>


You should always check every parameter of every script on the server. Developers and development teams can be awfully inconsistent. One parameter in one script might be vulnerable, another might not. Even if an entire web application is conceived, designed, coded and tested by one programmer, one vulnerable parameter might be overlooked. You never can be sure. So Test everything.

How to avoid SQL Injection?

Most of the web browsers will not properly interpret requests containing punctuation characters and many other symbols unless they are URL-encoded. In practice, though, you will need to substitute %25 for percent sign, %2B for plus sign, etc., in the HTTP request statement.
Anyway following prevention is better for ever first attacks

Filter out character like single quote, double quote, slash, back slash, semi colon, extended character like NULL, carry return, new line, etc, in all strings from:
 Input from users
 Parameters from URL
 Values from cookie

for numeric value, convert it to an integer before parsing it into SQL statement. Or using ISNUMERIC to make sure it is an integer.

Anti SQL injection

The following lines will be useful for recover your site from evil bots ,if you find any of your module / entire content affected by SQL injection means ,first you must search the hackers words / URL /image data from your Data base ,even some time they replace our user / admin password. So you must check all of your precious data. And then you must inject [add] the Anti-SQL injection code in to your website’s header side!

I used following two type of anti SQL injection, that is one is IP Blocking, and another one is URL validating .

IP Blocking:

I used the IP blocking method but it’s not worthy in certain circumference, anyway I describe about this vaccine! If you found the IP range of hacker group means, you can block the particular IP / ranges, even the proxy IP through the following simple code.

<?
$ip_proxy
=$_SERVER ["HTTP_X_FORWARDED_FOR"];
?>


The above line refers the predefined variable in PHP $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.

The $_SERVER ['HTTP_X_FORWARDED_FOR'] header giving the IP address of the connection that it proxies, so we use to separate the IP and it's proxy address by using explode function., also we can get the IP address by using $_SERVER['REMOTE_ADDR'] but which is not worth full in web site hosted by sub domain. I hope you know about explode function that is Split a string by string

<?
$tnt
=explode (',',$ip_proxy);
$ip=explode ('.',$tnt[0]);
$proxy=explode ('.',$tnt[1]);
?>


next thing is we should block all IP address which are in the text file, here I have specified some turkey IP address in text file which doesn’t have full structure of IP address format ,you can change code for checking full format of IP address !.
<text file
80
81
82
End text file>

<?
$filename
="input.txt";//text file
$lines = array (); //set as array
$file = fopen ($filename, "r"); //Open the file for reading only

while (! feof ($file)) {     //read file line by line into a new array element
   
$lines [] = fgets ($file, 4096); //Gets line from file pointer
   
}
$x = count ($lines);

for (
$y = 0; $y < $x; $y++) {
if((
trim($lines[$y])==$ip[0])||(trim($lines[$y])==$proxy[1]))//check the IP/proxy address   
           
{   echo 'Banned';//if  IP match the listed IP means ,you can redirect/do some function here  .
           
}
else {  echo
'welcome'; }         
     }     
?>



I hope above simple code is useful and learn something about IP blocking, anyway I believe second vaccine is very useful for avoiding SQL injection ,because most of the SQL injection used to inject the malicious data through URL by some SQL queries ,so we can validate the every URL of our site by following PHP Vaccine code !!


<?
$req_url
= $_SERVER['REQUEST_URI'];
$piece = explode("?", $req);
$my_url = $ piece [0];
$subject = $ piece [1];

$pattern='/script|http|<|>|%3c|%3e|SELECT|UNION|UPDATE|AND|exe|exec|INSERT|tmp/i'

// detecting
if (preg_match($pattern, $subject) {//block }
else {//allow }
?>



The above code used to split the URL and then perform a regular expression by using preg_match function .if any of SQL statement exists in browser means it will returns the number of times pattern matches. So we can easily avoid / detect the URLs.
And finally we must check the SQL input, luckily PHP have one function named mysql_real_escape_string() for avoiding SQL injection , but you need to be careful when using this function though because if you already have magic_quotes_gpc turned “on” and then you use mysql_real_escape_string() you will end up escaping things that have already been escaped. The following function found on the PHP webpage will use mysql_real_escape_string() to correctly escape data inserted into your queries regardless of the magic_quotes_gpc setting.




<?
function quote_insert($value)
{

    if (
get_magic_quotes_gpc()) {
       
$value = stripslashes($value);
    }
    if (!
is_numeric($value)) { //if not int
       
$value = "'" . mysql_real_escape_string($value) . "'";
    }
    return
$value;
}
?>


It's important to note that the quote_insert () function will automatically add single quotes to strings passed into it so you do not need to add yourself
Conclusion:
In this article we've seen what SQL injection, injection types is and how to defend the attacks. It’s not always possible to guard against every type of SQL injection attack, however hopefully after reading this article you now know about the Anti SQL injection coding. And it makes some pits in your programming brain!!!



A damaged image generator (class) for validating text. CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart
Categories : PHP, PHP Classes, Security, GD image library, Security
A login page that require username, password and userlevel.
Categories : PHP, Security, Sessions, MySQL, Databases
Function to generate readable/remeberable random password
Categories : PHP, Security, Security
Secure Login
Categories : PHP, MySQL, Cookies, Security
A Simple Script that stores encrypted messages in databases
Categories : PHP, Databases, MySQL, Security
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
Password protection for Phorum 3.1.x with userlevels and log.
Categories : PHP, MySQL, Authentication, Security
email new items in db
Categories : PHP, Email, Databases, MySQL, Beginner Guides
The simple counter with use MySql and gd.
Categories : MySQL, HTTP, Graphics, PHP, Databases
GroupIT Engine v1.00rc1
Categories : PHP, Content Management, MySQL, Databases
mySQL/PHP/search with multientry form and table output with colored rows
Categories : PHP, Beginner Guides, MySQL, HTML and PHP, Databases
Amazon book cover handling
Categories : HTML and PHP, PHP, MySQL, Ecommerce
IPTables Bandwidth statics
Categories : PHP, Security, Network
This simple function will take a few arguments and easily set a associative array for each column in a result from a MySQL query
Categories : Databases, PHP, MySQL, Arrays
Newbie Notes #4 - Trapping dumb MySQL query errors
Categories : PHP, Databases, MySQL, Debugging, Beginner Guides