PHP - Sql Injection Victim, How To Prevent?
Our admin panel for a gaming community was recently hit by a successful MySQL injection attack.
Here are the parameters they entered into forms to gain access. Code: [Select] ${99319+100354} Code: [Select] <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE acunetix [ <!ENTITY acunetixent SYSTEM "http://testphp.vulnweb.com/dot.gif"> ]> <xxx>&acunetixent;</xxx> Not sure which one worked, or how they even managed to POST to that page. But how do these two strings work? What do they do? Similar TutorialsWill this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  $_POST['user_name'] = "CLUEL3SS"; $_POST['user_pass'] = "test123"; $_POST['confirm_pass'] = "test123"; $_POST['user_email'] = "user@email.com"; $_POST['confirm_pass'] = 'user@email.com'; function testFunc($inputVars){ foreach($inputVars as $key=>$value){ $escapeData[$key] = mysql_real_escape_string($value); } return $escapeData; } var_dump(testFunc($_POST)); I'm trying to make a user system for my site and I want to make sure its secure enough to void off injection attackers. Any useful advice and and suggestions would be greatly appreciated! Thanks! I have the following code ($c2 is my connection variable): Code: [Select] $host = $_GET['host']; $loginQuery = mysql_query("SELECT * FROM sessions WHERE hostname LIKE '". $host ."' ORDER BY id DESC", $c2) or print(mysql_error()); In the URL, someone were to put host=127.0.0.1', they would have an error message spit out to them (something along the lines of: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''127.0.0.1'' ORDER BY id DESC' at line 1), indicating a SQL Injection exploit. How would I go about fixing this, and also preventing SQL Injection? Thanks a bunch, Mark Hello, I have a syntax error on line 203 that is causing my code NOT work. Could someone please look at it and tell me what is wrong & more important how to fix it? Below is what I am getting. This " ~ " is server path info " Parse error: syntax error, unexpected $end in /~ /~ /~ /phptestform/real_form_processing.php on line 203" Also, how do I prevent "header injection", to keep my mail form from being open to abuse by spammers? thanks mrjap1 Code: [Select] <?php # Script if (isset($_POST['submit'])) { // Handle the form. // Register the user in the database. require_once ('mysql_connect_page.php'); // Connect to the db. // Create a function for escaping the data. function escape_data ($data) { global $dbc; // Need the connection. if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } return mysql_real_escape_string($data, $dbc); } // End of function. $message = NULL; // Create an empty new variable. // Check for a first name. if (empty($_POST['first_name'])) { $fn = FALSE; $message .= '<p>You forgot to enter your first name... its Required!</p>'; } else { $fn = escape_data($_POST['first_name']); } // Check for a last name. if (empty($_POST['last_name'])) { $ln = FALSE; $message .= '<p>You forgot to enter your last name... its Required!</p>'; } else { $ln = escape_data($_POST['last_name']); } // Check for an email address. if (empty($_POST['email'])) { $e = FALSE; $message .= '<p>You forgot to enter your email address... its Required!</p>'; } else { $e = escape_data($_POST['email']); } // Check for a address. if (empty($_POST['address'])) { $u = FALSE; $message .= '<p>You forgot to enter your address... its Required!</p>'; } else { $u = escape_data($_POST['address']); } // Check for a country. if (empty($_POST['country'])) { $u = FALSE; $message .= '<p>You forgot to enter your country... its Required!</p>'; } else { $u = escape_data($_POST['country']); } if ($salutation && $first_name && $last_name && $address && $city && $state_province && $zip_code && $email && $zip_code && $newsletter && $registration_date ) { // If everything's OK. $query = "SELECT id FROM visitors WHERE address='$address'"; $result = @mysql_query ($query); // Run the query. if (mysql_num_rows($result) == 0) { // Make the query. This code is what you will use to prevent duplicate of usernames $query = "INSERT INTO `mrjap1_database`.`visitors` (`id` , `salutation` , `first_name` , `last_name` , `address` , `city` , `state_province` , `zip_code` , `country` , `email` , `newsletter` , `registration_date`) VALUES ( NULL , '$_POST[salutation]', '$_POST[first_name]', '$_POST[last_name]', '$_POST[address]', '$_POST[city]', '$_POST[state_province]', '$_POST[zip_code]', '$_POST[country]', '$_POST[email]', '$_POST[newsletter]', '$_POST[registration_date]' , NOW() )"; $result = @mysql_query ($query); // Run the query. if ($result) { // If it ran OK. exit(); // Quit the script. } else { // If it did not run OK. $message = '<p>You could not be registered due to a system error. We apologize for any inconvenience.</p><p>' . mysql_error() . '</p>'; } mysql_close(); // Close the database connection. } else { $message .= '<p>Please try again.</p>'; } } // End of the main Submit conditional. // Print the error message if there is one. if (isset($message)) { echo '<font color="red">', $message, '</font>'; } ?> <?php // ALL THE SUBJECT and EMAIL VARIABLES $emailSubject = 'MY TEST EMAIL SCRIPTING!!! '; $webMaster = 'myemailaddress@gmail.com'; // GATHERING the FORM DATA VARIABLES $salutation = $_POST['salutation']; $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $address = $_POST['address']; $city = $_POST['city']; $state_province = $_POST['state_province']; $zip_code = $_POST['zip_code']; $country = $_POST['country']; $email = $_POST['email']; $newsletter = $_POST['newsletter']; $registration_date = $_POST['registration_date']; $date = date ("l, F jS, Y"); $time = date ("h:i A"); $body = <<<EOD <br /><hr><br /> <strong>Salutation: </strong>$salutation <br /> <strong>First Name:</strong>$first_name <br /> <strong>Last Name: </strong>$last_name <br /> <strong>Address: </strong>$address <br /> <strong>City: </strong>$city <br /> <strong>State_Province: </strong>$state_province <br /> <strong>Zip Code: </strong>$zip_code <br /> <strong>Country: </strong>$country <br /> <strong>Email:</strong> $email <br /> <strong>Zip Code:</strong> $zip_code <br /> <strong>Newsletter:</strong> $newsletter <br /> <strong>Registration Date:</strong> $date at $time <br /> EOD; // THIS SHOW ALL E-MAILED DATA, ONCE IN THE E-MAILBOX AS READABLE HTML $headers = "From: $email\r\n"; $headers .= "Content-type: text/html\r\n"; $success = mail($webMaster, $emailSubject, $body, $headers); // THE RESULTS OF THE FORM RENDERED AS PURE HTML $theResults = <<<EOD <!DOCTYPE HTML> <html lang="en"> <head> <style type="text/css"> body { font-family:Arial, Helvetica, sans-serif; font-size:11px; font-weight:bold; } #thankyou_block { width: 400px; height: 250px; text-align:center; border: 1px solid #666; padding: 5px; background-color: #0CF; border-radius:8px; -webkit-border-radius:8px; -moz-border-radius:8px; -opera-border-radius:8px; -khtml-border-radius:8px; box-shadow:0px 0px 10px #000; -webkit-box-shadow: 0px 0px 10px #000; -moz-box-shadow: 0px 0px 10px #000; -o-box-shadow: 0px 0px 10px #000; margin: 25px auto; } p { font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 18px; letter-spacing:1px; color: #333; } </style> <meta charset="UTF-8"> <title>THANK YOU!!!</title> </head> <body> <div id="thankyou_block"> <br><br><br> <h1>CONGRATULATIONS!!</h1> <h2>YOUR FORM HAS BEEN PROCESSED!!!</h2> <p>You are now registered in our Database...<br> we will get back to you very shortly.<br> Please have a very wondeful day.</p> </div> </body> </html> EOD; echo "$theResults"; ?> I'm confused, can this result in css/sql injection? Code: [Select] if(isset($_GET['action'])){ if($_GET['action'] == 'details'){ $cupID = $_GET['cupID']; $ergebnis = safe_query("SELECT gameaccID, name, start, ende, typ, game, `desc`, status, checkin, maxclan, gewinn1, gewinn2, gewinn3 FROM ".PREFIX."cups WHERE ID = '".$cupID."'"); $ds=mysql_fetch_array($ergebnis); ... Some german fellow was explaining, translate to English briefly: "$ CupID is not escaped. NEN here I could just "; DROP TABLE` cups `Paste and your table is no longer available eez. Or I could inject javascript, your current session read out, accept it and act as an admin ... " I am trying to understand what he means by this... is this query vulnerable to an injection and why/how? I am having a wamp issue so I can't try these out right now. According to the book I'm learning php with, I can easily avoid injection attacks this way:
$a= stripslashes($a);
$a= mysql_real_escape_string($a);
What concerns me is the repetition of the variable, $a. Does it matter? Intuitively, it should.
$a changes. By the time $a hits mysql_real_escape_string it is slash-free. So it is a totally different "value" but still contained in the original variable which may have had slashes...just has me concerned a bit.
I know PDOs are the best way. I'm not there yet, unfortunately.
Edited by baltar, 23 May 2014 - 10:36 AM. Hi, I'm sure many of you heard of "pastebin", if not the short of it, is that you can submit your code (+100 languages), and you can display it to your friends via a link with syntax highlighting available. So, One way to store the code is surely in txt files, but I would really prefer to have it stored in a mysql database. My only concern is people trying to run a sql injection, so how do i get around all this? I don't want the user's content to be changed, but I don't want SQL injections either.. is this even possible at all? Any tips appreciated, also if you could think of another alternative than txt files and mysql. I want to know which part of my script has the hole..as i can find lots of php script and even folder can be injected into my public_html how they do that, and which part need to be checked? is that the upload part <enctype> or what?? thanks in advance I'm trying to use dependency injection to pass a database connection to an object but I'm not sure why it's not working. I have my "dbClass" below that connects to a MySQL database. Code: [Select] class dbClass { public $db; function __construct() { $this->db = mysql_connect("localhost","username","password") or die ('Could not connect: ' . mysql_error()); return $this->db; } } Then I have my "baseClass". This is the class that I want to feed to connection too. Code: [Select] class baseClass { public $mysql_conn; function __construct($db) { $this->mysql_conn = $db; $rs = mysql_select_db("webdev_db", $this->mysql_conn) or die ('Could not connect: ' . mysql_error()); } } And this is my index.php file. The error I'm getting is "supplied argument is not a valid MySQL-Link resource". However I tripled checked and my db connection details are definately correct. Code: [Select] $db = new dbClass(); $baseclass = new baseClass($db); Thanks for any help. i just want to ask this simple question let say i have this basic query $place=$_GET['place']; mysql_query("SELECT * FROM table WHERE place='$place'"); this is a nice target for sql injection.. but what if i replace the whole special characters that could be added $replacethis=array("-","`"); $withthis=array("",""); $place=str_replace($replacethis,$withthis,$_GET['place']); mysql_query("SELECT * FROM table WHERE place='$place'"); Are they still able to do the basic sql injection by trying to get the error by adding special character although i didn't use mysql_real_escape_string() ?? then what if i protect the file by changing the setting of the permission to either 644 or 755? thanks in advance Hello, I have a video game site - mostly vBulletin which is fine but there are a few extra bits to the site that I have done myself. I'm pretty new to PHP so my code isn't great. Anyway, I wanted to test my code for SQL Injection but I looked on Google and most of the tools seemed to come from hacker sites etc which I'm not downloading. I eventually found an addon for Firefox called SQL Inject Me and ran that. It said everything was alright but when I checked my MySQL tables they were full of junk code it had inserted. One of my pages doesn't even have any visible fields. It's just a page with a voting submit button and some hidden fields so how does it inject the code into the tables? The insert page code is: Code: [Select] $db = mysql_connect("localhost", "username", "password"); mysql_select_db("thedatabase",$db); $ipaddress = mysql_real_escape_string($_POST['ipaddress']); $theid = mysql_real_escape_string($_POST['theid']); $gamert = mysql_real_escape_string($_POST['gamert']); $serveron = mysql_real_escape_string($_POST['serveron']); $check= mysql_query("select * from voting2 where ipaddress='$ipaddress'"); $ipname = mysql_fetch_assoc($check); if($ipname['ipaddress'] == $ipaddress) { echo 'It appears you have already voted. Click <a href="vote.php">here</a> to return to the votes.'; } else { mysql_query ("INSERT INTO voting2 (theid,ipaddress,gamert,serveron2) VALUES ('$theid','$ipaddress','$gamert','$serveron')"); echo 'Your vote has been added. Click <a href="vote.php">here</a> to view the updated totals.'; } How can I make it safer against SQL injection? Thanks i am using a Anti MySQL Injection my friend made for me config.php //Anti MySQL Injection function anti_injection($sql) { // removes words that contain sql syntax $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql); $sql = trim($sql); // strip whitespace $sql = strip_tags($sql); // strip HTML and PHP tags $sql = addslashes($sql); // quote string with slashes return $sql; } <?php include "./config.php"; $title = $_POST[title]; $type = $_POST[type]; $episode = $_POST[episode]; $year = $_POST[year]; $genre = $_POST[genre]; $status = $_POST[status]; $summary = $_POST[summary]; $pictures = $_POST[pictures]; $title = anti_injection($title); $type = anti_injection($type); $episode = anti_injection($episode); $year = anti_injection($year); $genre = anti_injection($genre); $status = anti_injection($status); $summary = anti_injection($summary); $pictures = anti_injection($pictures); ?> When i enter the data from the text box and click submit it still puts the data in to the date base but it shows ]Notice: Use of undefined constant title - assumed 'title' in C:\wamp\www\studying\take 2\addin11.php on line 41 Notice: Use of undefined constant type - assumed 'type' in C:\wamp\www\studying\take 2\addin11.php on line 42 Notice: Use of undefined constant episode - assumed 'episode' in C:\wamp\www\studying\take 2\addin11.php on line 43 Notice: Use of undefined constant year - assumed 'year' in C:\wamp\www\studying\take 2\addin11.php on line 44 Notice: Use of undefined constant genre - assumed 'genre' in C:\wamp\www\studying\take 2\addin11.php on line 45 Notice: Use of undefined constant status - assumed 'status' in C:\wamp\www\studying\take 2\addin11.php on line 46 Notice: Use of undefined constant summary - assumed 'summary' in C:\wamp\www\studying\take 2\addin11.php on line 47 Notice: Use of undefined constant pictures - assumed 'pictures' in C:\wamp\www\studying\take 2\addin11.php on line 48 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 Deprecated: Function sql_regcase() is deprecated in C:\wamp\www\studying\take 2\config.php on line 30 And thanks to the Anti MySQL Injection my Primary key in my database dont work :s can you help? thank you Hi all, I thought instead of just simple do all the security stuff automatically, why not see for myself what the it can do. So I made a simple table besides the other tables named delete_me, made a form and started testing. But for some reason I can get that table to drop. this is what i did on the front end with help from he http://en.wikipedia.org/wiki/SQL_injection in all 3 fields (firstname, lastname email) put a value and in the last one i put: but nothing happend. if someone knows what i am doing wrong please tell me because I think it's vital in order to protect yourself one needs to know what he or she is up against. Hello People, Been reading up on these and trying to understand them more. Say I have a file called page.php?id=12345 and when users hit the page I run this code in the background: $id = $_GET['id']; $query = "UPDATE tbl SET live = '1' WHERE id = '".$id."'"; That page is not open to any attack right? Even though i'm using $_GET. Am I right in thinking that attacks only happen on online forms. So for example there is no way an attacker could somehow output all the data in my table tbl Thank yo im having some robots injecting gibberish i wnat to deny amy links in the requesttext of the form for some reason i tested it and it accepted a http link Code: [Select] if (preg_match("/http/i","$RequestText")){ exit();} thanks Hey Guys! I have the following Working php script (receives the variables from Flash) //LOGIN! if ($action == "login") { //retreive data from flash $username=mysql_real_escape_string($_POST['Username']); $password=mysql_real_escape_string($_POST['txtPassword']); $result = mysql_query("SELECT name, activated from buyers WHERE email = '$username' AND password = md5('$password')"); $cant = 0; while($row=mysql_fetch_array($result)) { echo "name$cant=$row[name]&activated$cant=$row[activated]&"; $cant++; } echo "cant=$cant&"; if (mysql_num_rows($result) > 0) { echo "status1=exists"; } else { echo "status1=Incorrect Login"; } } As you can see I have used mysql_real_escape_string for the variables $username and $password that are coming from Flash. I would really appreciate some guidence if this is the only safe code I need in this script? For example: Does $action == "login" need also mysql_real_escape_string ?? That variable $action is also coming from flash (but is not inputted by a user) Any ideas? Thanks in advance, Cheers! (I'm putting this in PHP since it's not a question specific to MySQL or other DB stuff.)
I have a page that uses the GET id to find a product. GET variables are sanitized, and the SQL string is escaped even though it's expecting a number only. So the code seems safe to me. I'm getting some error_log results that appear to be hack attempts:
SELECT Well, I just want to know, if I add mysql_real_escape_string and strip_tags to a checkbox, does this mean it is 100% protected from SQL injection and XSS attack? For example: Code: [Select] <input type=checkbox' name="checkbox"/> $checkbox = mysql_real_escape_string(stip_tags($_POST['checkbox'])); |