Incredible HTML5 Examples

No Comments »

Google Images Box – CSS 3D example:

Andrew Hoyer | Cloth Simulation:

CanvasMol:


Privacy is dead, people.

4 Comments »

Many people go online on internet via a wifi routers and typically only the computer directly connected to the device can interrogate it for ID information.  But bad news guys because Google location data can be used to pinpoint exactly where you live 🙁

Google database created when its cars were carrying out surveys for its Street View service.

Google Street View car, Getty The data gathered by Google’s Street View cars

This database links Mac addresses of routers with GPS co-ordinates to help locate them. It can be use to identify someone’s location to within a few meters.

Now the actual issue:

This pin point location can be gathered by some crafted web page without asking your permissions which is possible with bug in most of the wifi routers and it is using Firefox location sharing.

1) Click here to Enter your Wifi Router MAC address and see where you are.

2) Click here to open java applet, collect that information for you and display your location. (not working. I am working on it)

3) Click here Firefox will ask your location.

Sources:

http://www.bbc.co.uk
http://www.computerworld.com
http://www.itworld.com

Recovering a lost Mysql root password

No Comments »

Lost MySQL root password Recovery

/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &

This stops MySQL and reloads it without the authentication (grant) tables, so we can connect to MySQL without a password. Beware this locks out all of your applications until the password reset process is completed. Now we need to go in an reset the password

su -
mysql -u root -p

It will prompt you for a password, just hit enter. You should now be inside the MySQL terminal and ready to change the root password:

update user set password=PASSWORD(”NEW-PASSWORD”) where User=’root’;

Of course, replace NEW-PASSWORD with your chosen root password. Now all that remains is to restart MySQL in the normal manner in order for it to pick up the authentication tables correctly and let your customers and applications back in

# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Simple Construction of a RAW TCP/IP Packet

1 Comment »
#!/usr/local/bin/perl

use Socket;

$src_host = $ARGV[0]; # The source IP/Hostname
$src_port = $ARGV[1]; # The Source Port
$dst_host = $ARGV[2]; # The Destination IP/Hostname
$dst_port = $ARGV[3]; # The Destination Port.

 if(!defined $src_host or !defined $src_port or !defined $dst_host or !defined $dst_port) {
   print "Usage: $0 <source host> <source port> <dest host> <dest port>\n";
   exit;
 } 
 else {
  main();
 }
 
sub main {
 my $src_host = (gethostbyname($src_host))[4];
 my $dst_host = (gethostbyname($dst_host))[4];

 socket(RAW, AF_INET, SOCK_RAW, 255) || die $!;
 setsockopt(RAW, 0, 1, 1);
 
 my ($packet) = makeheaders($src_host, $src_port, $dst_host, $dst_port);
 my ($destination) = pack('Sna4x8', AF_INET, $dst_port, $dst_host);
 send(RAW,$packet,0,$destination);
}

sub makeheaders {
 local($src_host,$src_port,$dst_host,$dst_port) = @_;
 my $zero_cksum = 0;
 # Lets construct the TCP half
 my $tcp_proto          = 6;
 my ($tcp_len)          = 20;
 my $syn                = 13456;
 my $ack                = 0;
 my $tcp_headerlen      = "5";
 my $tcp_reserved       = 0;
 my $tcp_head_reserved  = $tcp_headerlen .
                          $tcp_reserved;
 my $tcp_urg            = 0; # Flag bits
 my $tcp_ack            = 0; # eh no
 my $tcp_psh            = 0; # eh no
 my $tcp_rst            = 0; # eh no
 my $tcp_syn            = 1; # yeah lets make a connexion! :)
 my $tcp_fin            = 0;
 my $null               = 0;
 my $tcp_win            = 124;
 my $tcp_urg_ptr        = 0;
 my $tcp_all            = $null . $null .
                          $tcp_urg . $tcp_ack .
                          $tcp_psh . $tcp_rst .
                          $tcp_syn . $tcp_fin ;

 # In order to calculate the TCP checksum we have
 # to create a fake tcp header, hence why we did
 # all this stuff :) Stevens called it psuedo headers :)

 my ($tcp_pseudo) = pack('a4a4CCnnnNNH2B8nvn',
  $tcp_len,$src_port,$dst_port,$syn,$ack,
  $tcp_head_reserved,$tcp_all,$tcp_win,$null,$tcp_urg_ptr);

 my ($tcp_checksum) = &checksum($tcp_pseudo);

 # Now lets construct the IP packet
 my $ip_ver             = 4;
 my $ip_len             = 5;
 my $ip_ver_len         = $ip_ver . $ip_len;
 my $ip_tos             = 00;
 my ($ip_tot_len)       = $tcp_len + 20;
 my $ip_frag_id         = 19245;
 my $ip_frag_flag       = "010";
 my $ip_frag_oset       = "0000000000000";
 my $ip_fl_fr           = $ip_frag_flag . $ip_frag_oset;
 my $ip_ttl             = 30;

 # Lets pack this baby and ship it on out!
 my ($pkt) = pack('H2H2nnB16C2na4a4nnNNH2B8nvn',
  $ip_ver_len,$ip_tos,$ip_tot_len,$ip_frag_id,
  $ip_fl_fr,$ip_ttl,$tcp_proto,$zero_cksum,$src_host,
  $dst_host,$src_port,$dst_port,$syn,$ack,$tcp_head_reserved,
  $tcp_all,$tcp_win,$tcp_checksum,$tcp_urg_ptr);

 return $pkt;
}

sub checksum {
 # This of course is a blatent rip from _the_ GOD,
 # W. Richard Stevens.
  
 my ($msg) = @_;
 my ($len_msg,$num_short,$short,$chk);
 $len_msg = length($msg);
 $num_short = $len_msg / 2;
 $chk = 0;
 foreach $short (unpack("S$num_short", $msg)) {
  $chk += $short;
 }
 $chk += unpack("C", substr($msg, $len_msg - 1, 1)) if $len_msg % 2;
 $chk = ($chk >> 16) + ($chk & 0xffff);
 return(~(($chk >> 16) + $chk) & 0xffff);
}



Syntax Highlighter

1 Comment »

SyntaxHighlighter:

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript.


PHP Validations

1 Comment »

Validate Email

We can perform an email validation through this function.

	function isValidEmail($email){
		return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
	}

After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead.

	function isValidEmail($email){
		return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
	}

PHP 5.2 and above.

function fnValidateEmail($email)
{
  return filter_var($email, FILTER_VALIDATE_EMAIL);
}

Sanitize Email

We can further sanitize our email to ensure that everything is alright.

function fnSanitizeEmaill($string) {
     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}

PHP 5.2 and above.

function fnSanitizeEmaill($url)
{
  return filter_var($url, FILTER_SANITIZE_EMAIL);
}

Validate Email Exist

This is not possible but certain validation can be use to validate email existence.

function check_email($email)
{
	$email_error = false;
	$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
	if ($Email == '') { email_error = true; }
	elseif (!eregi('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }
	else {
	list($Email, $domain) = split('@', $Email, 2);
		if (! checkdnsrr($domain, 'MX')) { email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode('@', $array);
		}
	}

	if (email_error) { return false; } else{return true;}
}

Validate Number Only

We can use PHP built-in function to validate whether a given value is a number.

function fnValidateNumber($value)
{
	#is_ double($value);
	#is_ float($value);
	#is_ int($value);
	#is_ integer($value);
	return is_numeric($value);
}

PHP 5.2 and above.

function fnValidateNumber($value)
{
	#return filter_var($value, FILTER_VALIDATE_FLOAT); // float
	return filter_var($value, FILTER_VALIDATE_INT); # int
}

Sanitize Number

We can force all value to be only numeric by sanitize them.

function fnSanitizeNumber($str)
{
	#letters and space only
	return preg_match('/[^0-9]/', '', $str);
}

PHP 5.2 and above.

function fnSanitizeNumber($value)
{
	#return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // float
	return filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int
}

Validate String Only

Sometimes to validate name we can use this function to restrict only letters and spaces.

function fnValidateStringr($str)
{
	#letters and space only
	return preg_match('/^[A-Za-z\s ]+$/', $str);
}

Sanitize String

We can sanitize it instead of validate user input.

function fnSanitizeStringr($str)
{
	#letters and space only
	return preg_replace('/[^A-Za-z\s ]/', '', $str);
}

PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.

function fnSanitizeStringr($str)
{
	return filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '<br>HELLO</br>' => 'HELLO'
}

Validate Alphanumeric Characters

This validates alphanumeric characters.

function fnValidateAlphanumeric($string)
{
	return ctype_alnum ($string);
}

Sanitize Alphanumeric Characters

This sanitize alphanumeric characters. eg. “HELLO! Do we have 90 idiots running around here?” => “HELLO Do we have 90 idiots running around here”

function fnSanitizeAlphanumeric($string)
{
	return preg_replace('/[^a-zA-Z0-9]/', '', $string);
}

Validate URL Exist

This function will check whether a given URL exist and not only validate it.

	function url_exist($url)
	{
		$url = @parse_url($url);

		if (!$url)
		{
			return false;
		}

		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';

		if ($path == '')
		{
			$path = '/';
		}

		$path .= (isset($url['query'])) ? '?$url[query]' : '';

		if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
		{
			if (PHP_VERSION >= 5)
			{
				$headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

				if (!$fp)
				{
					return false;
				}
				fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
				$headers = fread($fp, 4096);
				fclose($fp);
			}
			$headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
			return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
		}
		return false;
	}

Validate URL Format

This function will validate a given url to ensure the format is correct.

function fnValidateUrl($url){
return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url);
}

PHP 5.2 and above.

function fnValidateUrl($url)
{
  return filter_var($url, FILTER_VALIDATE_URL);
}

Sanitize URL

PHP 5.2 and above.

function fnSanitizeUrl($url)
{
  return filter_var($url, FILTER_SANITIZE_URL);
}

Validate Image Exist

This function will check whether a given image link exist and not only validate it.

	function image_exist($url) {
	if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
	}

Validate IP Address

This function will validate an IP address.

function fnValidateIP($IP){
	return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
}

PHP 5 and above. This can also specific validation for IPV4 or IPV6.

function fnValidateIP($ip)
{
  return filter_var($ip, FILTER_VALIDATE_IP);
}

Validate Proxy

This function will let us detect proxy visitors even those that are behind anonymous proxy.

function fnValidateProxy(){
	if ($_SERVER['HTTP_X_FORWARDED_FOR']
	   || $_SERVER['HTTP_X_FORWARDED']
	   || $_SERVER['HTTP_FORWARDED_FOR']
	   || $_SERVER['HTTP_VIA']
	   || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
	   || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
	{
		exit('Proxy detected');
	}
}

Validate Username

Before we validate whether a given username is matches the one in our database, we can perform a validation check first to prevent any unnecessary SQL call.

function fnValidateUsername($username){
	#alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)
	return preg_match('/^[a-zA-Z\d_@.]{6,50}$/i', $username);
}

Validate Strong Password

Another good thing is to validate whether a particular password given by the user is strong enough. You can do that using this function which required the password to have a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.

function fnValidatePassword($password){
	#must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
	return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
}

Validate US Phone Number

This function will validate US phone number for US users.

function fnValidateUSPhone($phoneNo){
	return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phoneNo);
}

Validate US Postal Code

This function validate US postal code.

function fnValidateUSPostal($postalcode){
	#eg. 92345-3214
	return preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$postalcode);
}

Validate US Social Security Numbers

This function validate US Social Security Numbers.

function fnValidateUSSocialSecurityCode($ssb){
	#eg. 531-63-5334
	return preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn);
}

Validate Credit Card

This function validate credit card format.

function fnValidateCreditCard($cc){
	#eg. 718486746312031
	return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
}

Validate Date

This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.

function fnValidateDate($date){
	#05/12/2109
	#05-12-0009
	#05.12.9909
	#05.12.99
	return preg_match('/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.][0-9]?[0-9]?[0-9]{2})*$/', $date);
}

This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.

function fnValidateDate($date){
	#2009/12/11
	#2009-12-11
	#2009.12.11
	#09.12.11
	return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#'', $date);
}

Validate Hexadecimal Colors

This is a good validation for people who allows their user to change color in their system.

function fnValidateColor($color){
	#CCC
	#CCCCC
	#FFFFF
	return preg_match('/^#(?:(?:[a-f0-9]{3}){1,2})$/i', $color);
}

Make Query Safe

This function help sanitize our data to be SQL injection safe.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..

Make Data Safe

This function help to keep us protected against XSS, JS and SQL injection by removing tags.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..