0

Deter Hackers from your website

hack

The Idea

A while ago now I started learning hacking/pentesting. It still surprises me now how many websites are still exploitable whether it be using Server hacks, XSS (cross site scripting), SQL Injection (SQLi) etc etc. A lot of the hacks used are very simple to protect against, proper sanatisation of data will help stop most forms of these attacks.

Personally I found SQL Injection very easy to master especially if you have written database driven websites/applications before. These attacks exploit un-sanatised data that will allow a user to modify a variable and insert SQL code in to the variables place. I have explained and shown how to do this here. I have pentested quite a few websites recently and the most common exploits I have found have been SQL Injections and XSS so therefore I thought about my websites and the way in which I have used variables in my PHP code and the use of the $_GET method, this led me to creating a function which would help deter a hacker that may attempt to test for SQLi exploits.

The Function

The function will detect if someone is trying common methods to test for SQLi and record the users details in a database as well as displaying this information back to the user to warm/scare them off.

The type of things it will record are, The current page URL, Time/date, OS of user, users web browser, users device, users IP address, users hostname and number of attempts. The function is split into four functions as for example get device type may be handy for CSS styling too.

First we start with the functions that will be used by our function.

Get Current URL (as seen by the user)

function curPageURL() {
 $pageURL = 'http';
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

Check for HTML

function CheckForHTML($string) {
$string = preg_replace("# <(?![/a-z]) | (?<=\s)>(?![a-z]) #exi", "htmlentities('$0')", $string);
return $string;
}

Get the users OS

function getOS() {
    if (isset($_SERVER["HTTP_USER_AGENT"]) OR ($_SERVER["HTTP_USER_AGENT"] != "")) {
        $visitor_user_agent = $_SERVER["HTTP_USER_AGENT"];
    } else {
        $visitor_user_agent = "Unknown";
    }
    // Create list of operating systems with operating system name as array key
    $oses = array(
        'Mac OS X(Apple)' => '(iPhone)|(iPad)|(iPod)|(MAC OS X)|(OS X)',
        'Apple\'s mobile/tablet' => 'iOS',
        'BlackBerry' => 'BlackBerry',
        'Android' => 'Android',
        'Java Mobile Phones (J2ME)' => '(J2ME/MIDP)|(J2ME)',
        'Java Mobile Phones (JME)' => 'JavaME',
        'JavaFX Mobile Phones' => 'JavaFX',
        'Windows Mobile Phones' => '(WinCE)|(Windows CE)',
        'Windows 3.11' => 'Win16',
        'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
        'Windows 98' => '(Windows 98)|(Win98)',
        'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
        'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
        'Windows 2003' => '(Windows NT 5.2)',
        'Windows Vista' => '(Windows NT 6.0)|(Windows Vista)',
        'Windows 7' => '(Windows NT 6.1)|(Windows 7)',
        'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
        'Windows ME' => 'Windows ME',
        'Open BSD' => 'OpenBSD',
        'Sun OS' => 'SunOS',
        'Linux' => '(Linux)|(X11)',
        'Macintosh' => '(Mac_PowerPC)|(Macintosh)',
        'QNX' => 'QNX',
        'BeOS' => 'BeOS',
        'OS/2' => 'OS/2',
        'ROBOT' => '(Spider)|(Bot)|(Ezooms)|(YandexBot)|(AhrefsBot)|(nuhk)|
                    (Googlebot)|(bingbot)|(Yahoo)|(Lycos)|(Scooter)|
                    (AltaVista)|(Gigabot)|(Googlebot-Mobile)|(Yammybot)|
                    (Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)|
                    (Ask Jeeves/Teoma)|(Java/1.6.0_04)'
    );
    foreach ($oses as $os => $pattern) {
        if (eregi($pattern, $visitor_user_agent)) {
            return $os;
        }
    }
    return 'Unknown';
}

Are they using a mobile device

function ismobile() {

$is_mobile = '0';

	if(preg_match('/(android|up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
        	$is_mobile=1;
    	}

	if(isset($_SERVER['HTTP_ACCEPT'])) {
   	if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
        	$is_mobile=1;
    	}
	}

    	$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
    	$mobile_agents = array('w3c ','acs-','alav','alca','amoi','andr','audi','avan','benq','bird','blac','blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno','ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-','newt','noki','oper','palm','pana','pant','phil','play','port','prox','qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar','sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp','wapr','webc','winw','winw','xda','xda-');

    	if(in_array($mobile_ua,$mobile_agents)) {
        	$is_mobile=1;
    	}

    	if (isset($_SERVER['ALL_HTTP'])) {
        	if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
            		$is_mobile=1;
        	}
    	}

    	if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
        	$is_mobile=0;
    	}

    	return $is_mobile;
}

Now for the main function

function Hack() {
	// Create connection to the Database
	$con= mysqli_connect("example.com","username","password","my_db");

	// Check connection to the database
	if (mysqli_connect_errno($con))
  	{
  		echo "Failed to connect to MySQL: " . mysqli_connect_error();
  	}

	// get the users IP address
	$ipaddress = $_SERVER["REMOTE_ADDR"];

	// Get the users hostname using the IP address
	$hostname = gethostbyaddr($ipaddress);

	// get the users agent (browser)
	$browserAgent = $_SERVER['HTTP_USER_AGENT'];

	// set the defualt timezone if differnet from the server
	date_default_timezone_set('UTC');
	// get the time and date
	$timeDate = date('l jS \of F Y h:i:s A');

	// Call the function curPageURL to get the current URL (as seen in URL bar)
	$url = curPageURL();

	// Call the function getos to get the users OS
	$os = getOS();

	// check if the user is using a mobile by calling our function ismobile
	if(ismobile() == 1) { 
		$mobile = "Yes"; 
	} else { 
		$mobile = "No"; 
	}

	// Sanatise the URL ready for the database
	// against XSS
	$newURL = CheckForHTML($url);
	// against SQLi
	$newURL = mysql_real_escape_string($url);

	// Insert data to the database
	$record = mysql_query("INSERT INTO `hack` (`id`, `ipaddress`, `hostname`, `os`, `mobile`, `agent`, `time`, `url`) VALUES (NULL, '".$ipaddress."', '".$hostname."', '".$os."', '".$mobile."', '".$browserAgent."', '".$timeDate."', '".$newURL."')") or die (mysql_error());

	// Get amount of database entries by IP address
	$count_attempts = mysql_query("SELECT * FROM `hack` WHERE ipaddress='".$ipaddress."'") or die (mysql_error());
	// Count entries tofind out the amount of attempts
	$count = mysql_num_rows($count_attempts);

	// Display the data to the user with a warning
	?>
Please do not tamper with the URL’s!

This site has been security tested. We log attempted hacks, These logs include:

Your IP address:
Your Hostname:

Operating System:

Using Mobile Browser:
Browser Agent:

Time and date of attempted hack:

URL as it was submited (for possible SQL Injection attempts):

The amount of recorded attempts:

Take this as a warning! If this has happened by mistake then please email the webmaster.

To use this function we would compare our variable with the expected variable in an IF/Else statement, for example a simple $_get IF/Else would be like;

if ($_GET['page'] == "Home") {
  // code to be executed
} else {
  // call the function
  Hack();

  // end
  exit();
}

I imagine if a hacker were to attempt to hack a website for fun with this function and they saw this message they would leave it alone and move on as it’s not worth the risk. If however the hacker is determined to gain access this sort of information could help you track the hacker.

Hope this helps all, I am open to improvements too.

CygnusH33L

Leave a Reply

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