JWT – JSON Web Token – An Introduction

While RESTful APIs are conquering the web development space, session based authentication or cookie based authentication is getting obsolete. Since RESTful APIs are stateless, the client is responsible to maintain the state. Some technologies are available and JWT is one of them. indeed my favourite, in this post will get to know what JWT is.

What is JWT?

JSON Web Token (JWT) is an open standard which provides authentication and integrity for secure transmission of information between two parties or more in a form of JSON objects.

JWT based Authentication

JWT can be used to maintain sessions or states, so it can be used to authenticate users as well. For an example in a web application, assume that information is retrieved after the user logs in to the application. Once the user enters the username and the password, the server can authenticate the user and issue a JWT. Then after, the user produce the JWT when requesting information from the server. The server verifies the authenticity of the JWT and send requested information.

Information integrity

JWT can also be used to transfer information securely. Initially it does not provide any confidentiality, though it provides integrity. That means, since the JWT contains a signature, a 3rd party cannot tamper information the token holds, hence it assures the JWT holds information that the original issuer entered.

JWT is an open standard

JWT is an open standard, it is available as RFC 7519.

Structure of JWT

JWT consists of 3 parts. The header, the payload and the signature. Indeed, it is two JSON objects plus a string (signature). The JWT is a string where the above mentioned three parts are base64 encoded and appended, separated by . (dots).

The Header

In general, there are two fields in the header, the algorithm and the type.

for an example:


{
"alg": "HS256",
"typ": "JWT"
}

alg stands for the signing algorithm and the typ denotes the type which is obviously JWT.

The Payload

This is the second part of the token and it holds all required information. In the standard these information are termed as claims. Altogether claims are divided into 3 sections, registered, public and private.
registered – These are set of predefined claims, for an example claim iss denotes the issuer, exp denotes the expiry date. Other registered claims include iss, sub, aud, exp, nbf, iat and jti. If you are interested refer to the RFC.
public – these claims can be defined by the specific standards. However to avoid collisions it is better to check JWT Claims Registry before hand.
private – these claims are custom defined based on the requirement of the application. In order to avoid collisions make sure the claims are namespace bound.

Following is an example:

{
"iss": "mybloginc.",
"jti": "a676e7683c10263f",
"myblog-username": "john",
"myblog-admin": true
}

Note that registered claims such as iss and jti are used along with private claims such as username and admin which are application specific. To avoid collisions, there are used with the namespace prefix ‘myblog-‘.

The Signature

This is the last part of the JWT. It contains the signature of the JSON objects of the header and the payload.

signature = hash {json of header + “.” + json of payload}

Implementing JWT in PHP

Following is a simple implementation of a JWT. The code is self-explainable. The final value which is the JWT can be checked using www.jwt.io

<?PHP
//used to sign the JWT, this must be a secret, only the server knows
$secret = 'NobodyKnows123***';

//creating application specific information
$session_id = md5(rand(100000,1000000).time());
$username = 'AuthenticatedUser';

//define JWT header
$header_array = array("alg"=>'HS256', "typ"=>'JWT');

//define JWT payload
$payload_array = array(
"iss" => 'ebckurera JWT blog post',
"sub" => 'creating JWT using PHP',
"exp" => time()+60,
"nbf" => time(),
"iat" => time(),
"jti" => md5(rand(1000,10000).time()),
"myapp-username" => $username,
"myapp-session_id" => $session_id
);

//arrays converting to JSON objects
$header_json = json_encode($header_array);
$payload_json = json_encode($payload_array);

//constructing the string to be signed
$unsigned_token = base64_encode($header_json) . '.' . base64_encode($payload_json);

//signing the content
$signature = hash_hmac('sha256', $unsigned_token, $secret);

//constructing the JWT
$signed_token = $unsigned_token . '.' . $signature;

echo $signed_token;

?>

JWT

Note that the header, the payload and the signature are separated by dots ( . ). Both the header and the payload are base64 encoded.


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJlYmNrdXJlcmEgSldUIGJsb2cgcG9zdCIsInN1YiI6ImNyZWF0aW5nIEpXVCB1c2luZyBQSFAiLCJleHAiOjE1MjY5NjI3NTAsIm5iZiI6MTUyNjk2MjY5MCwiaWF0IjoxNTI2OTYyNjkwLCJqdGkiOiIxMzRhYTlkODlmOWU3NDUxMDdiNzkyNzFmZWIyNzQzNCIsInVzZXJuYW1lIjoiQXV0aGVudGljYXRlZFVzZXIiLCJzZXNzaW9uX2lkIjoiMjMzNGZjYzEyZmI3ZDJlOTdiOWJmNTg5NWEzY2Q0MzQifQ==.b51b39d6a780cd5dff26fa89bd912b59af623cfffa467652b499f08da3520fb2

Security

Is JWT a secure medium? In general it is not, nevertheless it depends on the implementation. Always make sure JWT is used over HTTPS only. Otherwise it is very easy to employ a Man-In-the-Middle (MIM) attack. Then if there is no proper mechanism used, it is vulnerable to replay attacks as well. It can be easily avoided using a JWT per transaction. Further the payload can be encrypted so that it provides confidentiality as well (in this case the, JWS’s capability of information transmission gets limited). As JWT use signatures, in default it is non-repudiation as well.

With proper mechanisms in place JWT is a well secured to be used for web applications for both user authentication and information transmission.

Conclusion

JWT is a fairly secure mechanism that can be used in user authentication and information transmission between clients and RESTfull APIs, in general with all web applications as well. By default it provides, authentication and integrity, it uses signatures therefore it is non-repudiation as well. It is subjected to replay attacks and Man-In-the-Middle attacks though. However with proper implementation, JWT becomes more secure and powerful.

Advertisements

Combining CodeIgniter and WordPress (back-end)

CodeIgniter is a light-weight web framework which enables speedy development, hence it would be a great tool for evolutionary prototyping. In fact for small scale prototypes, my favorite web framework is WordPress. Yes, WordPress is a CMS but with the creativity you can convert it to a framework too. Then comes CodeIgniter, it comes with a comprehensive framework and the best thing in CodeIgniter is, it is easy to control, easy to override. Often I combine WordPress and CodeIgniter to harness the power of the admin panel of the WordPress for small scale web sites.

Plan

The plan is to extract a post from WordPress database by it’s id and show the title and the content of the news.

Prerequisites

Make sure WordPress database and CodeIgniter (get it from https://www.codeigniter.com/download) is ready on the server. Specially make sure mod_rewrite (.htaccess) is enabled in apache too.

Connecting the database to CodeIgniter

Database configuration file resides in application/config/ and it is a matter of editing database.php file. Open the file and provide required information such as username, password and database name.

Getting Ready

CodeIgniter is Model-View-Controller (MVC) based. Therefore it is required to create three classes, Controller, Model and View. Lets name, the controller as News, model as Model_News and view as View_Model. In CodeIgniter class names should start with a capital letter. Prefixing it not mandatory, nevertheless a good practice for easy identification.

The View

Will start from the View, the view class should resides in View_News.php. View needs to be created inside the folder application/view.

<?PHP

echo "<h3>$head_line</h3>";
echo "$news_text";

echo "<hr/>Generated on ". date('Y M d', time()) . " - powered by CodeIgniter + WordPress";
?>

The Model

The model should be in the folder application/models and should be named as Model_News.php. The class Model_News should be extended form the CI_Model class. As the database is added to configuration, it is possible to get it connected with less code lines. The output of the db->query( ) is an object.

<?PHP
class Model_News extends CI_Model{
function query_news_by_id($id){

$this->load->database();

$sql = "SELECT * FROM wp_posts WHERE post_status='publish' AND ID=$id";
$query = $this->db->query($sql);

$output = new News_Objects();

if($query){
foreach ($query->result() as $row)
{
$output->Title = $row->post_title;
$output->Body = $row->post_content;
}
}
return $output;
}
}

class News_Objects{
}

?>

The Controller

Controller needs to be created inside the application/controllers folder. Create News.php file inside the folder and create the News class by extending the CI_Controller class. In side the class there is a function to manage the flow. It takes an argument which is the news id and pass it to the model, the output from the model then passes to the view. To pass data to the view, an array is used. $objData helps passing data from model to view. All elements of this array become variables in the view, the element name, index becomes the variable name. Notice that load->model( ) and load->view( ) are used to load model and view respectively.

<?PHP
class News extends CI_Controller{
function show($id=1){
$this->load->model('Model_News');
$news = $this->Model_News->query_news_by_id($id);
$objData['head_line'] = $news->Title;
$objData['news_text'] = $news->Body;
$this->load->view('View_News', $objData);
}
}
?>

Accessing the content

To access the content following URL can be used.

http://localhost/index.php/news/show/1

Make sure to replace localcost with your server root.

After index.php it is the controller name follow by the method and it’s parameters.

That is it, it is really easy to understand, isnt it ? Give a try and let me know if you encounter any issues.

Symmetric-Key Encryption using openSSL

I wrote few blog posts on Asymmetric Key encryption using PHPSecLib library recently and this blog post is on Symmetric-Key Encryption and I ll be using PHP openSSL extension for the implementation. OpenSSL is a open source library which implements SSL and other major cryptographic functions. It is extensively used in Linux, Windows and other operating systems. Luckily PHP got an extension, so we can straightaway use it.

Instead of PHPSecLib, openSSL can be used to implement RSA cryptography functions in PHP as well.

The major drawback in Symmetric-Key Encryption is the usage of the same key to encrypt and decrypt data. However unlike in Asymmetric-Key encryption (I would say RSA hereafter) there is no limit on the data size that can be encrypted and it is relatively faster than RSA. As a result RSA is used to exchange Symmetric Keys securely and then the client and the server continues to communicate based on symmetric-key encryption. Not only for communication but also we can use symmetric key encryption in data storage too. For an example before storing data on a database, it is a good practice to encrypt those data, in such a scenario symmetric key encryption is much more suitable than RSA.

There are plenty of other libraries which provide symmetric key encryption, however it is recommended to use libraries like openSSL or PHPSecLib as they are extensively tested and well maintained. My advice is to use openSSL as much as possible, however due to limitations on your server, it may not be possible to use openSSL for RSA but it can always be used for symmetric key encryption.

Will check the PHP code for the task. It is simple !

My PHP version is PHP Version 7.0.10 and using OpenSSL/1.0.2h, if you want to check yours you can use phpinfo(); function which gives all information regarding your PHP installation.

<?PHP 
$text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data'; 

$encryption_key = 'password'; $iv = 'randomdigit16bit'; 

$encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); 

$encrypted_data = base64_encode($encrypted_data); 
var_dump($encrypted_data); 
?>

The code is self explaining, openssl_encrypt is the function that should be used and $text is the data that should be encrypted, then the next parameter is the cipher method, $encryption_key is the key to decrypt the encrypted text. This needs to be stored as it is required later to decrypt the data. I ll discuss about storing keys securely in a future blog post, as it is quite out of the scope for this topic.

Decryption is to be carried out as follow:

<?PHP

$text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data';

$encryption_key = 'password';
$iv = 'randomdigit16bit';

$encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);

//$encrypted_data = base64_encode($encrypted_data);

$decrypted_data = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);

var_dump($decrypted_data);

?>

Same as the openssl_encrypt function openssl_decrypt function could be used. Note that same $encryption_key and the $iv have been used.

Same as the $encryption_key, $iv should be same in encryption and decryption. $iv is known as the Initialization Vector which adds an extra layer of protection. It can be a random 16 bits string and the value should be stored as it requires in the decryption process as same as the encryption key.

The role of the $iv (Initialization Vector) is to differentiate the encrypted text. For an example the encryption key could be common per user or your web site etc. But you can use a random $iv per each encryption. As a result if you encrypt the same value using the same key, the result is going to be different when you use two different $iv.

Following method can be used to generate 16 bits IV. Make sure you store the IV otherwise decrypted data will not be able to decrypt back.

$iv = openssl_random_pseudo_bytes (16);

That is it, simple and handy isnt it?

RSA cryptography in PHP (How To?)

Being security is one of the utmost considerations in current web site/ application development process, I am sure you have spent a lot of time writing codes to handle encryption in your applications.

In this article I am trying to present one of my favorite ways to solve this issue, the RSA encryption/ decryption handling in your PHP development.

This is quite straight forward as I am using PHPSecLib package. I was using openSSL library for PHP for few years and recently started dealing with this package. It is pretty cool implementation so I started loving it.

First of all you need to get the package, it is available to download[1] and it comes with MIT license[2], GPL compatible[3].

If your intention is to use PHPSecLib only for RSA encryption and decryption I suggest including only two directories which are Crypt and Math in your production environment.

First step towards the RSA encryption is to create the public and private keys. Note that I have secured the keys with a passphrase.

$rsa = new Crypt_RSA();
$rsa->setPassword('pa$$wrd5');
$keys=$rsa->createKey(1024);

echo $keys['privatekey'];
echo $keys['publickey'];

The code is self explaining. createKey() method is taking the bit value of the key and output an array which contains the Private and Public keys. setPassword() is optional, you can omit it if you dont want to create the keys with a passphrase. If you want to use 2048 bit key then provide 2048 as an argument in createKey() instead 1024.

Once keys are ready you can start the encryption. I am using using the public key. Passphrase is not required when encrypting.

$rsa->loadKey($keys['publickey']);
$plaintext = 'Text to be transmitted securely !!!';
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;

Decryption goes as follow (using the private key), note that the passphrase is mandatory:

$rsa->loadKey($keys['privatekey']);
$rsa->setPassword('pa$$wrd5');
$re_plaintText =  $rsa->decrypt($ciphertext);
echo $re_plaintText;

I have written a static class to demonstrate how encryption can be carried out. Please check the following:

***DO NOT use this code in your production env as the code lacks lot of fine tuning and security measures***

This is just to illustrate how the PHPSecLib can be used in a code


<?PHP

include('Crypt/RSA.php');

class myRSA
{
	public static $privateKey = '';
	public static $publicKey = '';
	public static $keyPhrase = '';
	
	public static function createKeyPair()
	{
		$rsa = new Crypt_RSA();
		$password = base64_encode(sha1(time().rand(100000,999999)));
		$rsa->setPassword($password );
		$keys=$rsa->createKey(2048);		
		myRSA::$privateKey=$keys['privatekey'];
		myRSA::$publicKey=$keys['publickey'];
		myRSA::$keyPhrase=$password;
	}

	public static function encryptText($text)
	{
		$rsa = new Crypt_RSA();
		$rsa->loadKey(myRSA::$publicKey);
		$encryptedText = $rsa->encrypt($text);
		return $encryptedText;
	}

	public static function decryptText($encryText)
	{
		$rsa = new Crypt_RSA();
		$rsa->setPassword(myRSA::$keyPhrase);
		$rsa->loadKey(myRSA::$privateKey);
		$plaintext = $rsa->decrypt($encryText);
		return $plaintext;
	}
}
?>

<?php

//create keys
myRSA::createKeyPair(1024);

//Text to encrypt
$text = "A secret lies here, send the text via a secure mode";
echo 'Text : '.$text;

$secureText = myRSA::encryptText($text);
echo 'Encrypted : '.$secureText;

$decrypted_text =  myRSA::decryptText($secureText);
echo 'Decrypted Text : '.$decrypted_text;
?>

PHPSecLib API Documentation is available here.[4] A handy reference to check when you get stuck or need more info on methods.

[1] http://phpseclib.sourceforge.net/index.html

[2] https://en.wikipedia.org/wiki/MIT_License

[3] https://www.gnu.org/licenses/license-list.html#X11License

[4] https://api.phpseclib.org/master/

CAPTCHA with no $_SESSION

Due to the nature of the stateless behavior of HTTP, managing the current state of a connected user is a tricky scenario to handle in web site development or rather in web application development.

Few solutions are in place already and $_SESSION is one of the ways available in PHP. $_SESSION, the global array is not my favorite choice but it is handy. The sever based session management approach is not 100% reliable but it would do the work in most of the cases.

On the other hand, distinguishing user inputs versus inputs from malicious bots seems quite challenging these days. Simple tricks such as “honeypot” are quite old and easy to overcome, of course bots are now capable enough to skip “honeypots” without much effort. Then comes much promising solutions such as Google’s new invention, reCAPTCHA where a sophisticated techniques can identified the origin of the inputs blocking spams on your site, web application etc.

However life is not that easy, there are plenty of scenarios where we need to come up with our own strategy to deal with these inputs. If you cannot use reCAPTCHA or any other 3rd party CAPTCHA solution then the best would be implementing one of your own. This is the riskiest but there can be instances that this is the only way forward. I was in such a situation few months back and I though of sharing how I overcame it.

Avoiding $_SESSION

It is not hard to find plenty of tutorials to follow, implementing simple CAPTCHA verification in PHP. Almost every solution is based on $_SESSION, using server based sessions, a global array in PHP. This is easy and simple. Few lines of code would do the trick. As same as the way mentioned in this article. I am not a fan of server based sessions therefore I wanted to skip it.

In this post I am trying to explain how I solved the stateless issue without using server based sessions.

Breaking the Problem

The main issue that we need to solve is identifying the legitimate requests/ inputs and filter out the rest. In order to achieve this, when the relevant input form has been requested by a client, the server adds an image which is a human readable text. Bots may not be able to identify what is in it. Then the user inputs the code and sends the request to the server. As it is not possible to include the verification code in the client side request, the server doesn’t know what has been sent earlier. That is where server based sessions comes for the rescue. It is possible to store the verification code in a session variable.  Then when the user has submitted the form, the server can simply checks if the entered verification code value matches the value in the session. If so it is a human, test passes. Since we are trying to omit using server based sessions, we need to come up with a way to identify what has been sent earlier.

Solution

Step 1

Following is a typical code snippet (captcha.php) to create the CAPTCHA image. It is pretty straight forward and it can be seen that the verification code has been assigned to the session variable, $_SESSION[‘rand_code’] = $string;

<?php
session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {     // this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122)); }   
$_SESSION['rand_code'] = $string;   
$dir = 'fonts/';   
$image = imagecreatetruecolor(170, 60); 
$black = imagecolorallocate($image, 0, 0, 0); 
$color = imagecolorallocate($image, 200, 100, 90); // red 
$white = imagecolorallocate($image, 255, 255, 255);   imagefilledrectangle($image,0,0,399,99,$white); 
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);   
header("Content-type: image/png"); 
imagepng($image); 
?>

Following shows how it has been included in the HTML, client side.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>
" enctype="multipart/form-data" method="post"><input name="name" type="text" />

<input name="email" type="text" />

<textarea name="message"></textarea>

<img src="captcha.php" />

<input name="code" type="text" />

<input name="submit" type="reset" value="Send" />
</form>

When analyzing the HTML code, you will soon realize that the code can be exploited simply with a Cross Site Scripting (XSS) attack as it barely uses $_SERVER[‘PHP_SELF’] in form action. I will not be focusing on that since I am not going to use sessions here. Following is the modified prototype version.

Step 2

I have changed the client side code as follow. Notice that a hidden filed has been introduced. A randomly generated number with hash coded act as the reference id here. The reference has been passed when creating the CAPTCHA image and also it gets submitted when the user submits the form.

<?PHP
require_once 'dataBaseConnection.php';
<form action="verify.php" enctype="multipart/form-data" method="post">
Name: <input name="name" type="text" />

Email <input name="email" type="text" />

Message
<textarea name="message"></textarea>

<!--?PHP   $captchaId = sha1(rand(1000000,9999999).time());  dataBaseConnection::registerReference($captchaId);  $path='captcha.php?ref='.$captchaId;   ?--> <img src=""<?PHP" /> "/>
Enter the above code
<input name="c_id" type="hidden" value="<?PHP echo $captchaId; ?>" />

<input name="code" type="text" />

<input name="submit" type="submit" value="Send" />

and then the captcha.php has been modified too.

<?php
$string = '';
$refCode = '';

if(isset($_GET['ref']))
{
$refCode = $_GET['ref'];
}else{
die('<error>NO REF CODE FOUND !</error>');
}

for ($i = 0; $i < 8; $i++)
{
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}

$dir = 'fonts/';

$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 10, 10, 10); // red
$invColor = imagecolorallocate($image, 200, 200, 200); // invisible_ink
$white = imagecolorallocate($image, 255, 255, 255);

imagefilledrectangle($image,0,0,399,99,$white);
for($i=0; $i<100; $i++) 
{ 
imagettftext ($image, 20, rand(0,10), 0, $i*10, $invColor, $dir."ts.ttf", 'xxxxxxxxxxxxxxxxxxxxxxxxx'); 
} 
imagettftext ($image, 30, 2, 10, 40, $color, $dir."ts.ttf", $string);
header("Content-type: image/png"); 
imagepng($image); 
require_once 'dataBaseConnection.php'; dataBaseConnection::addVerificationCode($refCode, $string); //store the reference and the code in the database 
?>

The static methods dataBaseConnection::registerReference stores the reference code which will later be an input to captcha.php. The system automatically logs the timestamp and set the status of the record to ‘CREATED’. Then in the captcha.php file static method dataBaseConnection::addVerificationCode adds the generated verification code to the relevant reference .

Step 3

Then comes the verify.php code which validates the entered code against the code in the database.

<?php require_once 'dataBaseConnection.php'; if(isset($_POST['submit']))   {  	$enteredCode=trim($_POST['code']);  	$referenceCode=trim($_POST['c_id']);     $dataSet = dataBaseConnection::getCode($referenceCode);     $timeTaken = time() - $dataSet['pvt_created_date'];     if($timeTaken>$dataSet['pvt_life_time'] || $dataSet['pvt_captcha_status']!='CREATED')
    {
    	die('expired code');
    }

    //var_dump($referenceCode); die($enteredCode);
	if($enteredCode==$dataSet['str_verification_code'])
	{
		dataBaseConnection::updateCode($referenceCode,'VERIFIED');
		echo 'verified';//this is a human
		//Process the input as this is a legit request
	}else{
		dataBaseConnection::updateCode($referenceCode);
		echo 'not verified';//most probably not a human
	}
}
?>

If both codes match then the static method dataBaseConnection::updateCode changes the status of the verification code to ‘VERIFIED’ in the database while the status has been set to ‘USED’ for the verification code if they dont match. That expires the verification code and it will not be possible to use it again. Further there is a check to make sure that the code has not been expired too.

How secure this is

It is not difficult to train a bot to reading CAPTCHAs. Therefore to make this much stronger it is required to have an image with higher entropy.

Another weak point is, the reference code is getting exposed to the attacker. However there reference number has no relationship with the code. Therefore the attacker cannot predict the code by cracking the reference code. This is possible as we store the reference and the verification code in the database.

An attacker cannot use a brute force attack as the status of the verification code has been updated after an attempt has been made disregarding the results. So once tried the code is set to expired. Setting lifetime of the code can be used to limit the time available for the attacker to crack the image. In this case 300 seconds.

Further it is required to restrict direct access to captcha.php file from the outside, simply using .htaccess entry. Otherwise it is possible to carry out a Denial-of-service attack targeting the generation of the captcha image which in return could have lead to a database failure.

It is important to track client details but will discuss it in another post.

Conclusion

How to implement a captcha verification solution without using server based sessions has been discussed above. Complete source code can be found here. Please check it out and let me know any flaws you observe. This is a mere implementation of the concept and no other aspects were considered when developing the code and no proper testing has been carried out. Therefore if you are going to use it in your code please be careful unless you know what you are doing.

__construct() in PHP, OOP with PHP

In PHP it is possible to use the construct method which is really useful, in java we can have several constructor methods and the rule is the method name should be as same as the class name. In PHP the rule is quite different. It uses a special method __construct which is called once an object is created or simply when new operator is used. Therefore this method is also known as “magic method” and it is one of the few magic methods in PHP.

Without further text, following would be an example of using constructor method with in PHP OOP.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct() {
		$this->length = 10;
		$this->depth = 10;
		$this->height = 10;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1();
echo $box->getVolume();

This looks really simple. How would it be if we need to have more than one constructor methods which can accept arguments.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct($a=10,$b=10,$c=10) {
		$this->length = $a;
		$this->depth = $b;
		$this->height = $c;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1(10,2.5);
echo $box->getVolume();

$box2=new Cube1(2);
echo $box2->getVolume();

Since in PHP the __construct method cannot be override directly as in Java but there are few techniques to use so that it is possible in the indirect way. Will discuss them in the next post.

It is up to you to use your imagination and creativity to make use the of this feature.

Hope this is the time to discuss the PHP Hack Challenge I and at the moment we have discussed this in the class. For others benefit who read my blog I think of noting the discussion.

If you find any other way of smart thinking please let me know, a simple comment will do it.

Code

<?php $_F=__FILE__;$_X='Pz4JCTxkNHYgY2wxc3M9ImNsNTFyIj48L2Q0dj4NCgk8L2Q0dj48IS0tIC9jMm50MTRuNXIgLS0+DQoNCgk8ZDR2IDRkPSJmMjJ0NXIiPg0KDQo8c3AxbiA0ZD0iYmwyZy1uMW01Ij48P3BocCBibDJnNG5mMignbjFtNScpOz8+PC9zcDFuPiA8P3BocCBibDJnNG5mMignZDVzY3I0cHQ0Mm4nKTsgPz4gQzJweXI0Z2h0ICZjMnB5OyA8P3BocCA1Y2gyIGQxdDUoJ1knKTs/PiAtIDwxIGhyNWY9Imh0dHA6Ly90MnB3cHRoNW01cy5jMm0iIHQ0dGw1PSJXMnJkcHI1c3MgVGg1bTVzIiB0MXJnNXQ9Il9ibDFuayI+VzJyZHByNXNzIFRoNW01PC8xPiBkNXY1bDJwNWQgYnkgPDEgaHI1Zj0iaHR0cDovL3d3dy53NWJoMnN0NG5nZjFuLmMybSIgdDR0bDU9Ilc1YiBIMnN0NG5nIEYxbiIgdDFyZzV0PSJfYmwxbmsiPlc1YiBIMnN0NG5nIEYxbjwvMT4NCgk8L2Q0dj48IS0tIC9mMjJ0NXIgLS0+DQo8L2Q0dj48IS0tIC93cjFwcDVyIC0tPg0KPC9kNHY+PCEtLSAvYjJkeS00biAtLT4NCjw/cGhwIHdwX2YyMnQ1cigpOyA/Pg0KPC9iMmR5Pg0KPC9odG1sPg==';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>

As the first step we should identified what are in the code snippet. We can use ; to separate lines. May be then we can see things clearly.

<?php
$_F=__FILE__;
$_X='Pz4JCTxkNHYgY2wxc3M9ImNsNTFyIj48L2Q0dj4NCgk8L2Q0dj48IS0tIC9jMm50MTRuNXIgLS0+DQoNCgk8ZDR2IDRkPSJmMjJ0NXIiPg0KDQo8c3AxbiA0ZD0iYmwyZy1uMW01Ij48P3BocCBibDJnNG5mMignbjFtNScpOz8+PC9zcDFuPiA8P3BocCBibDJnNG5mMignZDVzY3I0cHQ0Mm4nKTsgPz4gQzJweXI0Z2h0ICZjMnB5OyA8P3BocCA1Y2gyIGQxdDUoJ1knKTs/PiAtIDwxIGhyNWY9Imh0dHA6Ly90MnB3cHRoNW01cy5jMm0iIHQ0dGw1PSJXMnJkcHI1c3MgVGg1bTVzIiB0MXJnNXQ9Il9ibDFuayI+VzJyZHByNXNzIFRoNW01PC8xPiBkNXY1bDJwNWQgYnkgPDEgaHI1Zj0iaHR0cDovL3d3dy53NWJoMnN0NG5nZjFuLmMybSIgdDR0bDU9Ilc1YiBIMnN0NG5nIEYxbiIgdDFyZzV0PSJfYmwxbmsiPlc1YiBIMnN0NG5nIEYxbjwvMT4NCgk8L2Q0dj48IS0tIC9mMjJ0NXIgLS0+DQo8L2Q0dj48IS0tIC93cjFwcDVyIC0tPg0KPC9kNHY+PCEtLSAvYjJkeS00biAtLT4NCjw/cGhwIHdwX2YyMnQ1cigpOyA/Pg0KPC9iMmR5Pg0KPC9odG1sPg==';
eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));
?>

now you can see things more clear way2 variables and then eval() is used with base64_decode(). Therefore we can use base64_decode() and see what is in the eval()

if you run following snippt you can get the code encoded by base64.

<?PHP
$txt= base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw==');
echo $txt;
?>

The output would be

$_X=base64_decode($_X);$_X=strtr($_X,'123456aouie','aouie123456');$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);eval($_R);$_R=0;$_X=0;

again if we separate them using ; , following would be the result,

$_X=base64_decode($_X);
$_X=strtr($_X,'123456aouie','aouie123456');
$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);
eval($_R);$_R=0;$_X=0;

Then if you check the original code you will see two variable $_F and $_X are also available.

$_X is base 64 encoded, will decode and see what it contains.

This is the output.

?>		<d4v cl1ss="cl51r"></d4v>
	</d4v><!-- /c2nt14n5r -->

	<d4v 4d="f22t5r">

<sp1n 4d="bl2g-n1m5"><?php bl2g4nf2('n1m5');?></sp1n> <?php bl2g4nf2('d5scr4pt42n'); ?> C2pyr4ght &c2py; <?php 5ch2 d1t5('Y');?> - <1 hr5f="http://t2pwpth5m5s.c2m" t4tl5="W2rdpr5ss Th5m5s" t1rg5t="_bl1nk">W2rdpr5ss Th5m5</1> d5v5l2p5d by <1 hr5f="http://www.w5bh2st4ngf1n.c2m" t4tl5="W5b H2st4ng F1n" t1rg5t="_bl1nk">W5b H2st4ng F1n</1>
	</d4v><!-- /f22t5r -->
</d4v><!-- /wr1pp5r -->
</d4v><!-- /b2dy-4n -->
<?php wp_f22t5r(); ?>
</b2dy>
</html>

Therefore the $_X contains a HTML code. The next thing is to deal with the strtr() function. The beauty of this function is it replace 1 with a, 2 with o, 3 with u like that.

$_X=strtr($_X,'123456aouie','aouie123456');

Therefore after running this function the $_X will be converted as below.

?>		<div></div>
	</div><!-- /container -->

	<div id="footer">

<span id="blog-name"><?php bloginfo('name');?></span> <?php bloginfo('description'); ?> Copyright &copy; <?php echo date('Y');?> - <a href="http://topwpthemes.com" title="Wordpress Themes" target="_blank">Wordpress Theme</a> developed by <a href="http://www.webhostingfan.com" title="Web Hosting Fan" target="_blank">Web Hosting Fan</a>
	</div><!-- /footer -->
</div><!-- /wrapper -->
</div><!-- /body-in -->
<?php wp_footer(); ?>
</body>
</html>

Above is the code that tried to hide using base64 encode and use eval to execute the code.

__FILE__ is called as Magic Constants and I have discussed them earlier in this blog.

However in this code snippt it is easy to breat it as you can see the base64_decode function if that function cant be seen then you are in a bit trouble. In such cases you have to examine the encoded text. Most of the time if you can see = or == at the end of the text, that can be encoded using base64. So it is better to try it first.

Apparently think what are the further actions that can be taken to increase the quality of the code.