Discover. Dream.

I found this picture/quote on the internet and I just had to share it with you.

Namespaces in php 5.3

PHP 5.3, introduced in June 2009 and has some really interesting enhancements. Some of you may know about the promise of namespace support in php 6. Because this was a popular requested feature, namespaces have been introduced in php 5.3.

What are namespaces and why are they convenient?

‘Namespaces’ are default in almost every other (OOP) language, such as C++ and C#. They separate classes and other objects (such as methods) in logical units, mostly to avoid name collisions. A program (or web site, as is probably the case in php) may use several frameworks and libraries. These may hold methods and/or classes that are named the same, for example a class named Date. Prior to php 5.3, this would lead to the well known error “Could not redeclare class Date in file/name.php on line no“. This, of course, could be a problem when you want to use multiple frameworks and/or third-party libraries.

The problem of name colissions was dealt with before by using something called ‘poor man’s namespacing’, which has been used in, for example, the Zend Framework. This looks something like this:

< ?php
class Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive extends Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum
{
	public function __construct()
	{
		$this->addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCase());
	}
}

This of course is not very handy all the time. So, how do namespaces solve this problem?

Namespaces in php 5.3

A namespace in php can be thought of as an extra layer around (part of) your code. Every class en method name within it is unique and does not conflict with classes or methods with the same name in other namespaces.

To declare a namespace in php, use the keyword ‘namespace’ on the first line of your file. Your classes and methods you define below it. All code within that file will be in that namespace. Let’s look at an example on how to use namespaces:

< ?php
namespace MichielvdVelde\Core;
 
class Database
{
	public function __construct()
	{
	}
}

The class Database will now reside in the namespace MichielvdVelde\Core. If you were to make another namespace, which also holds a class named Database, this would be fine.

So, how do you use classes within a namespace? This is really kind of simple. There are two method.

Method one

Add the namespace to the declaration of the class. Like this:

< ?php
require_once 'MichielvdVelde/Core.php';
 
$db = new MichielvdVelde\Core\Database();

But this method is not really an improvement over poor man's namespacing. Therefore, there is a second method.

Method two

By using the 'use' keyward, you cam import namespaces in your code. This more closely resembles namespacing as implemented in other languages such as C++ and C#.

< ?php
require_once 'MichielvdVelde/Core.php';
 
use MichielvdVelde\Core as CORE;
 
$db= new CORE\Database();

As you can see, this is more aliasing than really importing. But still, this method is very useful.

Gotcha's

Functions are also part of namespaces

When defining functions in files with the 'namespace' keyword at the top, thsey are also part of that namespace.

< ?php
namespace MichielvdVelde\Core;
 
function getDatabase()
{
}
< ?php
require_once 'MichielvdVelde/Core.php';
 
getDatabase(); // Geeft E_FATAL error: Undefined function getDatabase()
 
use MichielvdVelde\Core as CORE;
 
CORE\getDatabase(); // This does work

Autoload changes

Autoload on Windows does not use the \ very well. You may need to change your autoload function for this:

< ?php
function __autoload($className)
{
	$className = str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
	require $className;
}
 
$db = new MichielveVelde\Core\Database();

Also note that you need to define __autoload within the global scope. If you define it within a namespace, php won't find it. If you do want to use the autolaod function from within a namespace, use the spl_autoload_register function:

spl_autoload_register('MichielvdVelde\\Core\\Autoloader');

Conclusion

PHP 5.3 introduces support for namespaces which will be very handy in organizing and cleaning up your code. Although it may take some time for web hosters to support php 5.3, you can experiment with it by installing the latest version of XAMPP on your omputer, which has php 5.3 included.

Comment problems fixed

The site had some problems regarding comments. Non-members were unable to place comments as they didn’t pass the spam protection, for some reason. This has now been fixed, I am now using Aksimet to provide spam protection.

You can comment again, so let me know what you think about my posts! And be nice about it ;)

[Opinion] Apple’s Quest for World Dominance – the iPad

Disclaimer: obsessed Apple fans should stop reading right now, unless you can take criticism.

The Mac, the Macbook, the iPod, the iPhone, and now the iPad – God save us; Apple is taking over the world!
First of all, Apple claims it’s intention is not to compete with the personal computer and Microsoft’s operating system Windows. But we all know this is bullshit. Apple is on a Quest for World Wide Dominance and you know it! Just like the New World Order conspiracy theories, Apple is silently building a strong user base by snooping off market shares from a lot of markets!

Take over the world, while you still can

It began with the computer; the Apple Mac. But that wasn’t enough. It wasn’t enough that software developers are practically forced to write software for both Windows and Mac, no sir. Everyone calls Microsoft restrictive in their policies regarding Windows, but that is nothing compared to Apple’s stance. You couldn’t even run Mac on an ordinary pc – apparently the standardized Von Neumann architecture as implemented since the advent of the microcomputer in 1981 from IBM isn’t good enough for them (why a PowerPC CPU instead of an Intel/AMD CPU that is compatible with the rest of the world?).

Since then, Apple has showed laptops (such as the Macbook Air, an ‘ultra-thin’ laptop without even a dvd drive), MP3 and Media players (the whole iPod range, from the original iPod to ther iPod video and what not), mobile phones (the iPhone, which is more restrictive than a 18th century corset), and now the iPad – a real Apple table computer!
First of all; who would ever want to have a tablet computer? Okay, web designers maybe. But Regular Rick isn’t interested in them – at least when they’re not working in Atlantis, the city of the Ancients (Stargate Atlantis reference, if you saw it, you know what I mean).
Second, it is the TWENTY-FIRST CENTURY for crying out loud! What in God’s name was Apple thinking when they DIDN’T IMPLEMENT MULTITASKING?! As with the iPhone, where multitasking is also noticeably absent, the iPad also does not have multitasking. I can not wrap my mind around this; in a world of two, four, six or even eight core processors, the Apple hardware doesn’t even support basic multitasking – something that was possible from very early in Windows. This, in my eyes, is an idiotic decision, both from a hardware and a marketing standpoint.

Marketing: follow the hype

The iPad has Apple’s own 1GHz CPU implemented. This ARM-based processor operates at 1 Gigahertz, which is ‘quite high’ (the only other 1GHz ARM-processor is implemented in Google’s Nexus One smart phone). This tells me the iPad is not meant as a full blown computer, because even simple laptops have dual core processors these days. I guess Apple wanted to keep the costs down on the hardware (so they could charge more for the design).

The iPad is in my opinion a ridiculous addition to the Apple fleet of hardware. Things that consumers take for granted these days are not implemented, there are extreme limitations to what you can run on it (as with the iPhone, you can only download and install apps from the Apple Store, meaning Apple decides what will and what will not run on somebody’s iPad. Although jail-breaking is probably in the iPad’s future.

Basic flaws of the iPad:

  • No multitasking
  • No camera
  • No Flash
  • Not even a single USB port, no HDMI or other display ports
  • Once again Apple controls the customer by determining which apps the customer can or can not run, through their App Store

So…?

So the iPad will be the next big thing.

Addition
Don’t get me wrong; I think Apple is great. The only thing I really dislike is the amount of control Apple holds over its customers, with only allowing certified applications to run – and even then, only one at a time (this is true for the mobile platforms of the iPhone and iPad). Another big objection of mine is they charge ridiculous prices for what I consider to be sub standard hardware (in terms of speed etc), just because ‘it looks nice’. But i have to applaud Apple too; the customers buy it completely. Hail Apple’s marketing strategy – the design is a one-time expense, hardware costs need to be spent with every unit.

What does the next decade have in store for us?

This is the question that so-called ‘futurists’ are trying to answer. Because the first year of the second decade of the second millennium has just begun, and because we are advancing toward a technological singularity, these are extremely turbulent times of rapid (technological) advances. Is this really happening? Yes! Technological advances happen much more quickly every time, and this will continue to happen. Futurist Ray Kurzweil explains this with an example:

When I was an MIT undergraduate in 1965, we all shared a computer that took up half a building and cost tens of millions of dollars. The computer in my pocket today is a million times cheaper and a thousand times more powerful. That’s a billion-fold increase in the amount of computation per dollar since I was a student.

Also, keep in mind Moore’s Law, which claims that the amount of transistors on CPU’s doubles every 18 to 24 months. Until now, this law has been true, and according to experts, will remain true for some time.
So, let’s look at some predictions made by several futurists, shall we? Let’s take a look at the next decade.

The decade according to Jack Uldrich

Jack UldrichThese are some of the predictions done by Jack Uldridge, who manages the web site Jump the Curve. He is a known futurist, author and speaker, hired by lots and lots of companies to speak at conferences and such. For more info about him, was well as hit – very interesting – blog posts, go to his web site.

Among others, Jack predicts the cost of sequencing an individual’s genome will drop to $1,000 or lower. This allows Average Joe to have his genome sequenced and will lead to personalized medical treatment and medicine based on the patient’s genes.
Furthermore, he predicts doctors will be able to operate people over the internet using robots. This will allow a specialist to operate a patient in another country without having to gly that specialist over, which is expensive. Also, brain-neural interfaces will be introduced leading to a myriad of possibilities.

To 2020; what lies on the horizon, if it were up to Ray Kurzweil

Ray KurzweilRay Kurzweil, a ‘top futurist’, has done some predictions about the next decade as well. Let’s take a look at what the next decade has in store for us according to this man, shall we?

Memory devices will be in our clothing, and the meaning of ’smartphone’ will transform. Instead of looking at a tiny screen, images will be projected directly on our retinas, providing an image as large as our field of view. We can expect information about things around us to be displayed on this, essentially implementing augmented reality. The Internet will make sure we can see the latest information on our screens, as well as new forms of advertising, such as floating ads in mid-air, streamed through the Internet by companies such as Google (the part about floating ads I added, but it isn’t a far stretch). We’ll watch movies and read books in this new virtual playground.
Renewable energy will take a dive and solar power costs will decrease, making it a viable – and affordable – means of producing clean energy. Other than that, our ’software’, our base DNA, will be able to be ‘updated’; to live longer, and to reduce or remove decease and cancer.

Stay sober

Now, such wild predictions have been done for decades. Remember the ‘a fully functional humanoid robot in every household by the year 2000′? That hasn’t happened, an I suspect many of the things mentioned above will not, or to a lesser degree, happen as well. But is is important to keep in mind the technological singularity; technological advances happen quicker and quicker, and maybe in 2020 I look back at this post (assuming it still exists somewhere) and look at the ignorance of these futurists; who knows.
The next decade will without a doubt be an interesting one, with lots and lots of futuristic discoveries and new technologies emerging. To close, here are five of my predictions for the next decade:

  1. Google will grow even larger;
  2. We will still use fossil fuels for at least 50% of energy production, and most cars will still run on them;
  3. Exciting new technologies to increase the welfare of entire counties, and even the world – for example, fields of solar panels to produce clean energy – will still not happen because of the bureaucracy and ‘budgetary constraints’;
  4. Kids will still run around with guns and education will not be available for everyone;
  5. And maybe one positive point; experimental UCAV’s (Unmanned Combat Areal Vehicles) will reduce the casualties of war (mostly for the United States though).

Maybe it’s a bleak view, but I’d love to be proven wrong.

What are your predictions for the decade? Comment and share your vision!

James Cameron’s Avatar Blog Series: Introduction

“They’ve sent us a message, that they can take whatever they want, and no one can stop them. Well we will send them a message… that this, this is OUR land!”

Avatar poster

The poster of Avatar

The buzz word recently; Avatar. Unless you’ve been sleeping under a rock for the last month or two, you of course know “Avatar” is the name of James Cameron’s (known from the films Titanic and the Terminator film series) newest film, which features photo realistic CGI to tell most of the story.  With Sam Worthington, Zoë Saldana, Sigourney Weaver, Michelle Rodriguez and Stephen Lang in the leads, Avatar is an epic science fiction film which stands out with its detailed environments filled with unique plants and animals.

Avatar describes the word of Pandora, a moon orbiting the gas giant, Polyphemus in the Alpha Centauri system, almost 5 light years from here. In the future, The Resources Development Administration (RDA), a corporation with a military force larger than that of most countries. The corporation travels to Pandora to mine a valuable resource, hilariously named ‘unobtainium‘, and encounter the indigenous sentient and sapient Na’vi, tall (approximately 3 meters/10 feet), blue-skinned humanoids who live in tribes (clans).
Unfortunately, the largest deposit of unobtainium that has been found, is right below the home of the Omaticya Clan, a clan of proud forest warriors, who are unwilling to give up their home.

Without going in too much detail and ruining the film for you if you haven’t seen it yet, I will just say the film is about the struggle of the Na’vi people in the fight against the human ‘invaders’. Jake Sully, a wounded marine who has lost the use of his legs, goes to Pandora in the place of his brother, who has been killed, in the Avatar Program – where human operators are linked to Avatar bodies (essentially Na’vi DNA combined with human DNA to allow the operator to take control of the body). His mission is to gain their thrust, and get them to move.

Pandora’s majestic virtual floating mountains dwarf a massive gunship

Now, the film has several very interesting things about it, ranging from the diverse plant and animal life on Pandora to the amazingly realistic computer generated environments and people. Being intrigued by the film, I will dedicate a blog series on the film and everything it contains.

This blog is serving as an introduction. Some topics I intend to discuss:

  • The computer generated imagery, of course, as this still is a mostly computer oriented blog;
  • The environment, the abnormalities and the explanations behind them;
  • The ships and vehicles used in the film;
  • The customs and other interesting facts about the Na’vi.

So, if you’re interested, come back in a few days, and I might have posted one or more blogs in the series.

The next phase of virtual reality

Today, three dimensional games and simulations on two dimensional surfaces (computer monitors) are real popular and the quality of the graphics is increasing every minute, it seems. Still, no matter how great the graphics, it is still on a 2D surface and will never be really real to the person using it.

So, how cán this be done? Obviously you all know those bulky Head-Up-Displays (HUD’s) with built-in monitors so you are in a semi-real world. Some even provide head tracking so you can look around. But this still isn’t really real. So, how do we create a virtual world that approaches our consensus reality? A very interesting book series, called Netforce Explorers, sketches a novel approach to this; someone with an implant can ‘plug in’ to the Net, which is nothing more than a realistically looking world within the computer.
Although the idea of a ‘brain implant’ may scare some people away from it, this actually is really intriguing idea; the central nervous system is connected directly to the computer to provide direct neural input, bypassing the ‘real’ senses of the body.

The reason I started this post is to show you the following video. The man you see on it is Ray Kurzweil, “Inventor, Author, Futurist”. Enjoy his views on virtual reality in the future.

Forensic IT How-To: Using Volatility to examine your RAM dump

In the previous forensic how-to, we have made a dump of your computer’s active RAM, or Random Access Memory. This is the memory that stores everything you’re working on and with when your computer is on. Viruses and other malware can run exclusively in your RAM, but you can also possibly find cryptographic keys – for example, for whole disk encryption – here.
As you can imagine, whether you’re a forensic IT”ist (working for the police or a private company) or a home user, you can get some very interesting information from your RAM dump. So, let’s Start!

Required software
Before we can actually start, we need some software. We need two pieces of software. Well, we actually need one, but to use it, we need another.
You may or may not be familiar with Python. Python is a multi-purpose scripting language where even you can script in. From entire programs to dedicated scripts for data processing, it’s possible.
“So, where can I find this Python?” you ask? Well, we’ll go to python.org. Please make sure you download the 2.x.x version of Python (I am using version 2.6.4)! The newer version, in the 3.x.x range, will not work with the next piece of software we’ll need.
Install Python and go to the directory where you installed it.

The second piece of software we need it actually written in Python. It is called the Volatility Memory Forensics Framework. This software is capable of analyzing the RAM dump we made earlier. You can find the software on volatilesystems.com. Download the newest version (I am using version 1.3 beta in this post). Download, unpack and remember where you’ve unpacked it.

So, to sum up, we need the following two pieces of software, in order:

  1. Python for Windows
  2. Volatility Memory Forensics Framework

Download and install these two components according to the instructions above.

Step One: the command prompt and setting it up
Yes, a young person’s nightmare; the command prompt. For the older – or crazier – people among you, you are most likely quite familiar with the command prompt.

To open one, simply press the Start button, and whether or not you’re on an OS higher than XP, click “Execute…”. If you have a search field, don’t. Then type the command cmd. This will open a command prompt for you.
Now we only need to set it up. We need to add a path to the cmd’s path string. For this, you need the directory you installed Python in. For me, this is D:\Program Files\Python 2.6.4. Type in the following (change the path to Python with your own path):

> PATH=%PATH%;D:\Program Files\Python 2.6.4

This will add your Python’s install path to the paths of the command prompt. For experienced cmd/DOS people, you can of course do this in your sleep.

Now, go to the folder you unpacked Volatility in. For me, this is C:\Users\Michiel\Desktop\Volatility-1.3_Beta. I do this with the following command:

> cd C:\Users\Michiel\Desktop\Volatility-1.3_Beta

Now, you are in the folder you unpacked Volatility to. We are now ready to start for real.

Step Two: Dissect that dump!
Now you are ready to start for real. Yes – this time I mean it. If you’ve been smart enough to read the Readme.txt file that came along with Volatility, you know what is possible.

For now, we’ll just print out a list of processes that were running when the RAM dump was made. My dump is located at D:\ram.dmp. I type in the following:

> pyhton volatility pslist -f D:\ram.dmp

This gives me a list of all running processes, as demonstrated in this image (note that it may take a while – depending on the size of your RAM dump – before any results show up):

These processes were running when I made the dump. You can for example compare the list with the list your task manager process list, to find ‘hidden’ processes that might indicate malicious behavior.

Of course the Volatility Memory Forensics Framework can do lots and lots more. You can find a list of all its options in the readme file that accompanied it. For this example’s sake, we’ll show off one more:

> pyhton volatility connscan-f D:\ram.dmp

This produces a list of all network connections that were active when the dump was made (this, also, may take a while):

Final words
And then some final words. The Volatility Framework is of course (almost) infinity more feature rich than shown in this how-to. I encourage you to walk through the readme file, it will provide you with a list of features.
I wish you much excitement when scavenging through your own memory dumps with Volatility. In the next how-to – I have no idea when it will come, though – I will write a piece about scanning for viruses within your dump.

Hope to see you later and don’t forget to leave a comment if you liked it! See ya!

Security article: Password security in PHP

This article will deal with password security. Especially, passwords of your web site’s (or program’s) users. Although the title of this posts suggests it only applies to PHP scripts, it can in fact be used for and programming or scripting language (except the PHP examples, or course).

On many web sites, visitors can register themselves, for example to be able to post on the forums or place comments. These users have to fill in a password, that allows only them to log in with that specific name on that specific user account.
But, how is this password stored? There are basically three methods, ranging from dumbest to smartest:

  1. Clear text, the password directly into the database or other storage medium;
  2. Encrypted, the password encrypted with an algorithm (e.g. AES), with a key;
  3. Hashed; a one-way hash (e.g. MD5, SHA1).

As you might suspect, storing the password as clear text is the most idiotic thing you can do! Imagine a hacker breaks into your database; he instantly has all passwords for all users on your web site. Is that what you want? I think not.

Option two is storing the password as encrypted text. This requires an encryption algorithm, such as Advanced Encryption Standard, and a key. This requires the key to be stored as well, and no matter how good you put it away. On the other hand, it allows you to decrypt the password and use it for verification. And you can give them their original password when they’ve lost it. But this still isn’t the best solution. See option three.

Option three: hashes
The third option is in my opinion, and that of a lot of people who know, hashing. A hash is, according to Wikipedia:

A cryptographic hash function is a deterministic procedure that takes an arbitrary block of data and returns a fixed-size bit string, the (cryptographic) hash value, such that an accidental or intentional change to the data will change the hash value. The data to be encoded is often called the “message”, and the hash value is sometimes called the message digest or simply digest.

So, a hash is a string that is based 0n the original text. This is handy, as it is almost impossible to reverse the hash, so the password is safe. And when you need to check a password, you simply hash the inputted password too and compare.

What kind of hash functions are there? Basicly, the following two are the most used:

  1. MD5
  2. SHA(1)

MD5
MD5 stands for Message Digest 5, and has been developed by Ron Rivest in 1991 to replace MD4. How can you use it in php?

// Method one
$hash = md5("password");
// Method two
$hash = hash('MD5', "password");

This results in a 32-digits hexadecimal string, for example 5f4dcc3b5aa765d61d8327deb882cf99. This is always the same for the same string. This provides a great method for password saving, because the password can never (or, with extreme difficulty) be reverse-engineered. When you need to check a password, you simply hash that too, and compare the strings.

SHA1
SHA1 is another cryptographic hash function. According to Wikipedia:

The SHA hash functions are a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the NIST as a U.S. Federal Information Processing Standard. SHA stands for Secure Hash Algorithm.

SHA1 generates a hexadecimal string of 40 characters, instead of the 32 of MD5. SHA1 is considered more secure. Using this in php is not more difficult:

// Method one
$hash = sha1("password");
// Method two
$hash = hash('SHA1', "password");

This generates the has, for example 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8.

This is it for now. I’ll write an article about cracking hash ciphers in the furure, which is mainly brute-forcing. Bye-bye.

A cryptographic hash function is a deterministic procedure that takes an arbitrary block of data and returns a fixed-size bit string, the (cryptographic) hash value, such that an accidental or intentional change to the data will change the hash value. The data to be encoded is often called the “message”, and the hash value is sometimes called the message digest or simply digest.

How-To: Use the PHP Data Objects class to access your database

If you’re a PHP developer, you are of course aware of PDO; PHP Data Objects. Or are you?
PDO is the new form to communicate with databases, for example MySQL, PostgreSQL and MSSQL. When you’re using MySQL, you may be using the following methode to connect to your database:

$connection = new mysqli('localhost','username','password');

Or, even worse:

mysql_connect('localhost','username','password');

This of course is hopelessly outdated, and with PHP version 6 on the way, will soon be removed from the standard installed libraries. But there is a better, more Object Oriented way to connect to your database, and that is PHP Data Objects.

What is PDO?
According to php.net:

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn’t rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.

Connecting to your MySQL database
So, how does one use it? Below is an example for MySQL (other databases might require a slightly different approach):

$connectionString = "mysql:host=localhost;dbname=database";
$pdo = new PDO($connectionString, 'username', 'password');

Now you can use the $pdo variable to do things, e.g.:

Retrieve information from tables

$results = $pdo->query("SELECT * FROM table");
foreach($results as $result)
{
	echo $result['field'] . "<br />\r\n";
}

This is how you can read data from your database tables. Note that you don’t use the while loop and the fetch_num or fetch_assoc (or similar) in this case, but a foreach loop. You can access the field values as you would in an ordinary array.

Queries that don’t return anything: the wrong way to do it
For queries that don’t return anything, for example INSERT and UPDATE queries, PDO provides the exec method. This method returns the amount of rows affected (if any) by the query. Using it is simple:

$pdo->exec("INSERT INTO 'table' (id, value) VALUES ('1','this is the value')");

But this method is susceptible to SQL injections. Therefore, the PDO class gives us another method to insert or alter information in/from the database: prepared statements. A prepared statement is SQL injection safe and the right way to do things, especially if you need to insert or alter user submitted information. Here an example of how to use prepared statements:

$stmt = $pdo->prepare("INSERT INTO table (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
 
// insert a row
$name = 'one';
$value = 1;
$stmt->execute();

This is a safe way to insert or update data in your database. Of course you can use prepared statements with SELECT queries as well.

The Basics
This provides you with the basics to select, insert and update data from.to your MySQL database. Later I will expand on this subject, and dive into the more complex possibilities of PDO, as wel as how to access other databases than MySQL.

Related Links