Solved

Got hacked, now my php/mysql page doesn't work.

Posted on 2010-11-26
6
385 Views
Last Modified: 2012-05-10
So my website got infected by a .js script attack which screwed up a couple of my pages. I got rid of the script insertions but somehow my registration page doesn't work anymore. Can you look through my code to see if there's any glaring errors that may be causing the problem. I learned PHP in a very intense self taught session and spent 3 days making this page and that was a few months ago so I forget it all now. I can't figure it out for the life of me. I'm pretty sure it's my code is supposed to create a table if it doesn't exist or insert into a pre-existing one, but it just gives an error " invalid table name '(blank)'" no matter what. The page was working perfectly for months until the attack. I've moved severs and created a new database but am still getting the same error.

The url to get to my page: https://s111713.gridserver.com/register.php?date=2011-01-19&location=North+Vancouver

Below is the actual code of that page:
<?php

$db_host = "internal-db.s111713.gridserver.com";
$db_user = "db111713";
$db_pass = 'NOT_TELLING';
$db_name = "db111713_career_nights";

$link = mysql_connect('internal-db.s111713.gridserver.com', 'db111713', 'NOT TELLING', 'db111713_career_nights');
if (!$link) {
die('Could not connect: ' . mysql_error());
}



if (array_key_exists('_submit_check',$_POST)) {

$email=$_POST['email'];
$location=$_POST['location'];
$date=$_POST['date'];
$name_first=$_POST['name_first'];
$name_last=$_POST['name_last'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$street_address=$_POST['street_address'];
$city=$_POST['city'];
$province=$_POST['province'];
$postal_code=$_POST['postal_code'];
$additional_attendees=$_POST['additional_attendees'];
$career_change=$_POST['career_change'];
$registered_course=$_POST['registered_course'];
$how_far_along=$_POST['how_far_along'];
$heard_about=$_POST['heard_about'];
$contact_with=$_POST['contact_with'];
$language=$_POST['language'];
$area_of_expertise=$_POST['area_of_expertise'];

// ************************START OF EMAIL VALIDATION 

function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

// ************************************************END OF EMAIL VALIDATION*************************

if(validEmail($email)=="false"){

}
else{


}

$stripped_date = str_replace("-","",$date);
$year = substr($stripped_date, 0, 4);

$day_number = substr($stripped_date, -2);
$month_number = substr($stripped_date, 4, 2);

if( $month_number == "01" ){
	$month = "January";
}
elseif( $month_number == "02"){
	$month = "February";
}
elseif( $month_number == "03"){
	$month = "March";
}
elseif( $month_number == "04"){
	$month = "April";
}
elseif( $month_number == "05"){
	$month = "May";
}
elseif( $month_number == "06"){
	$month = "June";
}
elseif( $month_number == "07"){
	$month = "July";
}
elseif( $month_number == "08"){
	$month = "August";
}
elseif( $month_number == "09"){
	$month = "September";
}
elseif( $month_number == "10"){
	$month = "October";
}
elseif( $month_number == "11"){
	$month = "November";
}
elseif( $month_number == "12"){
	$month = "December";
}

$pretty_date = $month.", ".$day_number.", ".$year;

$table_create = 'CREATE TABLE IF NOT EXISTS `'.$date.'`(
`name_first` varchar( 255 ) NOT NULL ,
`name_last` varchar( 255 ) NOT NULL ,
`email` varchar( 255 ) NOT NULL ,
`phone` varchar( 255 ) NOT NULL ,
`street_address` varchar( 255 ) NOT NULL ,
`city` varchar( 255 ) NOT NULL ,
`additional_attendees` int(1) NOT NULL ,
`career_change` varchar( 100 ) NOT NULL ,
`registered_course` varchar( 5 ) NOT NULL ,
`how_far_along` varchar( 255 ) NOT NULL ,
`heard_about` varchar( 255 ) NOT NULL ,
`contact_with` varchar( 255 ) NOT NULL ,
`language` varchar( 255 ) NOT NULL ,
`area_of_expertise` varchar( 1024 ) NOT NULL ,
`date` date NOT NULL ,
`location` varchar( 255 ) NOT NULL)';

mysql_query($table_create) or die(mysql_error());

mysql_query("INSERT INTO `$date`(
location,
date,
name_first,
name_last,
email,
phone,
street_address,
city,
additional_attendees,
career_change,
registered_course,
how_far_along,
heard_about,
contact_with,
language,
area_of_expertise)
VALUES(
'$location',
'$date',
'$name_first',
'$name_last',
'$email',
'$phone',
'$street_address',
'$city',
'$additional_attendees',
'$career_change',
'$registered_course',
'$how_far_along',
'$heard_about',
'$contact_with',
'$language',
'$area_of_expertise') ") or die(mysql_error());

?>

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>Register for RE/MAX Career Nights!</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
<!--
body{
	background-image: url(http://www.metrovancouverproperties.com/images/bg_gradient.png);
	background-repeat: repeat;
	font-family: "century gothic", "myriad pro", "trebuchet MS", helvetica, arial, "sans serif";
	font-size: 11pt;
	padding: 10px 20px 5px 20px;
}

.underline{
	text-decoration: underline;
}

.bold{
	font-weight: bold;
}

-->
</style>

</head>

<body>

<div style="padding: 50px; text-align: center;">Excellent, you have successfully registered for our <? echo $pretty_date ?> Career Night in <? echo $location ?> with the following info:<br /><br />

First Name: <span class="bold underline"><? echo $name_first ?></span>&nbsp;&nbsp;
Last Name: <span class="bold underline"><? echo $name_last ?></span><br />
Email: <span class="bold underline"><? echo $email ?></span><br />
Phone: <span class="bold underline"><? echo $phone ?></span><br />
Street Address: <span class="bold underline"><? echo $street_address ?></span>&nbsp;&nbsp;
City: <span class="bold underline"><? echo $city ?></span><br />
Additional Attendees: <span class="bold underline"><? echo $additional_attendees ?></span><br />
Career Change Time Frame: <span class="bold underline"><? echo $career_change ?></span><br />
Registered in Course?: <span class="bold underline"><? echo $registered_course ?></span><br />
How Far Along in Course?: <span class="bold underline"><? echo $how_far_along ?></span><br />
How did you hear about Career Nights? <span class="bold underline"><? echo $heard_about ?></span><br />
Have you had contact with anyone at RE/MAX yet? <span class="bold underline"><? echo $contact_with ?></span><br />
What languages do you speak other than English? <span class="bold underline"><? echo $language ?></span><br />
What is your area of expertise?: <span class="bold underline"><? echo $area_of_expertise ?></span><br /><br />
See You there!</div>

</body>

</html>

<?

$burnaby_south_address = "RE/MAX Central (South)<br>
#1-5050 Kingsway, Burnaby, BC<br><br>
<a href=\"http://maps.google.com/maps?q=re%2Fmax+central+south+burnaby&hl=en&cd=1&ei=wnPBS7mQN6KstAOJqIWkDA&sll=49.232511,-122.985821&sspn=0.116525,0.438446&ie=UTF8&view=map&cid=15517546142468131762&ved=0CEYQpQY&hq=re%2Fmax+central+south+burnaby&hnear=&ll=49.226637,-122.991536&spn=0.009459,0.027874&z=16&iwloc=A\">Click here to see the address in Google Maps</a>";

$burnaby_north_address = "RE/MAX Central (North)<br>
3906 Hastings Street, Burnaby, BC<br><br>
<a href=\"http://maps.google.com/maps?q=re%2Fmax+central+north+burnaby&hl=en&cd=1&ei=E3TBS_bTBIOQsAPmur2mDA&sll=49.253445,-122.982855&sspn=0.066283,0.085457&ie=UTF8&view=map&cid=15143999607291781316&ved=0CDYQpQY&hq=re%2Fmax+central+north+burnaby&hnear=&ll=49.281818,-123.018465&spn=0.009448,0.027874&z=16&iwloc=A\">Click here to see the address in Google Maps</a>";

$north_vancouver = "The Holiday Inn - North Vancouver<br>
Address: 700 Old Lillooet Road, North Vancouver, B.C. V7J 2H5<br><br>
<a href=\"http://maps.google.com/maps?hl=en&ie=UTF8&view=map&cid=16635623857286516046&q=Holiday+Inn+Hotel+and+Suites+North+Vancouver&ved=0CFEQpQY&ei=OmfBS86NK5XWtQOKkoiGBA&hq=Holiday+Inn+Hotel+and+Suites+North+Vancouver&hnear=&z=16&iwloc=A\">Click here to see the address in Google Maps</a>";

if($location=="North Vancouver"){
	$event_address=$north_vancouver;
}
elseif($location=="Burnaby South"){
	$event_address=$burnaby_south_address;
}
elseif($location=="Burnaby North"){
	$event_address=$burnaby_north_address;
}

$to = $email;
$subject = "RE/MAX Career Night Registration";

$message = "
<html>
<body>
<p>You have registered for the RE/MAX Career night on ".$pretty_date.".</p>
<p>It will run from 7:30pm - 9:00pm</p>
<p>The event is located at:<br /><br />
".$event_address."<br><br>
Please call Cassidy at 778-233-0093 (8am - 10pm) if you have any questions about this event.&nbsp; Thanks and see you there!
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";

// More headers
$headers .= 'From: <careers@metrovancouverproperties.com>' . "\r\n";
$alert_message = $name_first." ".$name_last." " .$email." ".$phone."<br /> ".$pretty_date." ".$location;
mail($to,$subject,$message,$headers);
mail("jameshuckabonetech@gmail.com, cassidy.bast@metrovp.ca","New Signup for Career Night",$alert_message,$headers);
}

else{
?>


<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>Register for RE/MAX Career Nights!</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
<!--
body{
	background-image: url(http://www.metrovancouverproperties.com/images/bg_gradient.png);
	background-repeat: repeat;
	font-family: "century gothic", "myriad pro", "trebuchet MS", helvetica, arial, "sans serif";
	font-size: 11pt;
	padding: 10px 20px 5px 20px;
}

input{
	background-color: #cccccc;
}

select{
	background-color: #cccccc;
}
-->
</style>

</head>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<div style="text-align: center;">

First Name: <input name="name_first" type="text" size="30" /> &nbsp; &nbsp;Last Name: <input name="name_last" type="text" size="30" /><br /><br />

Phone Number: <input name="phone" type="text" size="30" /><br /><br />

Email Address: <input name="email" type="text" size="30" /> <span style="font-size: 90%; font-weight: bold;">(location details will be emailed here)</span> <br /><br />

Street Address: <input name="street_address" type="text" size="30" /> &nbsp; &nbsp;

City: <input name="city" type="text" size="30" /><br /><br />

Are you bringing anyone?: 
<select name="additional_attendees">
	<option value="0" selected="selected">No</option>
	<option value="1">Yes, 1 other.</option>
	<option value="2">Yes, 2 others.</option>
	<option value="3">Yes, 3 others.</option>
	<option value="4">Yes, 4 others.</option>
	<option value="5">Yes, 5 others.</option>
</select><br /><br />

What is your time frame for your career change?&nbsp; 
<select name="career_change"><option value="">Select One </option><option value="0-6_months">0 - 6 months</option>
	<option value="after_6_months">after 6 months</option>
</select><br /><br />

Have you registered for the Real Estate Division Course?&nbsp; 
<select name="registered_course">
	<option value="">Select One</option>
	<option value="yes">yes</option>
	<option value="no">no</option>
</select><br /><br />

If so, how far along are you in the course?&nbsp; 
<select name="how_far_along">
	<option value="">Select One</option>
	<option value="na">not applicable/not in course</option>
	<option value="incomplete_assignments">haven't completed assignments</option>
	<option value="completed_assignments">completed assignments</option>
	<option value="booked_an_exam">booked an exam</option>
	<option value="passed_the_exam">passed the exam</option>
	<option value="other">other</option>
</select><br /><br />

How did you hear about this event?&nbsp; 
<select name="heard_about">
	<option value="">Select One</option>
	<option value="craigslist">Craigslist</option>
	<option value="other_website">other website</option>
	<option value="a_friend">a friend</option>
	<option value="brochure">brochure</option>
	<option value="job_ad">job ad</option>
	<option value="recruiter">I spoke with a recruiter</option>
	<option value="called">I called RE/MAX</option>
	<option value="other">other</option>
</select><br /><br />

With whom (if applicable) have you had contact at our RE/MAX group of offices? <input name="contact_with" type="text" size="30" /><br /><br />

Do you use any other languages in business other than English? <input name="language" type="text" size="30" /><br /><br />

What are your areas of expertise or background? <input name="area_of_expertise" type="text" size="30" /><br /><br />

<div style="text-align: center;"><input type="submit" value="Register!" style="font-size: 12pt; background-color: #0054a0; color: #ffffff; padding: 3px;" /></div>

<input type="hidden" name="location" value="<? echo $location; ?>" />
<input type="hidden" name="date" value="<? echo $date; ?>" />
<input type="hidden" name="_submit_check" value="1"/>
</div>

</form>

</body>
</html>
<? } ?>

Open in new window

0
Comment
Question by:jameshuckabonetech
  • 4
6 Comments
 
LVL 10

Expert Comment

by:aboo_s
ID: 34220680
I wouldn't go through the code, but I'll tell you this:

You should check all the references to tables in your code and check that all table names are correct!
If the Database was fully restored then it must the php code, was altered!(somehow!!!)
The fastest way is to conduct search in your code for wrods like INSERT INTO , ALTER ..and so on..
0
 

Author Comment

by:jameshuckabonetech
ID: 34220797
The table name is taken from the url, which is the date and I double checked to make sure the table exists and is definitely correct. Could someone have a look at my INSERT statement to make sure it looks good. Thank you.
0
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 500 total points
ID: 34220835
A couple thoughts:

1. The best way to debug this type of thing, IMO, is to use a lot of echo()s. Echo out the queries before you run them. And also echo out some comments at key places in the code to make sure that it's running the code as you expect.

Knowing the exact values of the queries being run and seeing what code is running will definitely help in this problem.

2. Any mediocre hacker can send whatever POST fields he/she wants. This means that even though your form may have a hidden "date" field, a hacker could change date from "2010-11-27" to something like "';DELETE FROM users;". When you go to create your table using the POST-ed date, the hacker's query gets thrown into the middle. This is called SQL injection and it's one of the most common attacks besides .js script attacks. I wrote an article on this. It explains how to run the attack, and how to protect yourself:

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_686-PHP-Prevent-SQL-Injection.html

So aside from this problem you're having now, you need to fix the SQL injection in your script or else you'll get hacked again.

3. Next, it's usually a bad idea to create a lot of tables dynamically. Especially when you have a table for each day. It can create some serious maintenance problems down the road. Unless you're a very experienced database admin who knows exactly what you're doing, I would recommend having one table and using a date column to be able to segment the records properly.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:jameshuckabonetech
ID: 34220951
Wow, thanks for that information. I know I'll have to change the structure soon but it's been working ok for now. There's nothing sensitive in the database, it's just a quick and dirty way to keep basic info on people that come to our career nights. I have been trying the echos and one thing I don't understand is that echo $date; doesn't produce anything. Shouldn't it take the date variable from the url and echo it? Maybe I'm missing something?
0
 

Author Comment

by:jameshuckabonetech
ID: 34220957
Actually, the hidden fields at the end of my form are supposed to hold the date and location from the url because in the VALUE= attribute, I put <? echo $date; ?> and <? echo $location ?> respectively. But they aren't showing up anymore as you can see from looking at the source of the page. any idea why the variables from the url are no longer being passed to the page?
0
 

Author Closing Comment

by:jameshuckabonetech
ID: 34221073
I went nuts trying to figure this out but I finally have. The same day that I got hacked (unknowingly), I coincidentally turned on php5 which in turn disabled "register_globals" which in turn disabled my crude URL variables. It was a bad coincidence that led me through hours of frustration. But it's finally over. I put register_globals = on in my php.ini file.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now