Posts tagged with: php

Review: Ignite Woo Wishlist & Gift Registry Pro

Not being entirely familiar with all the trappings of the WooCommerce ecosystem I set about finding a good Registry plugin for a friend’s (soon to launch) eCommerce website. Some initial searching lead me to the Wishlist & Gift Registry Pro plugin developed by Ignitewoo, a purveyor of many WordPress/WooCommerce plugins.

Limited Functionality

I really wish that I would have found done my due diligence before paying them any money- the plugin provides almost no functionality that isn’t offered by the completely free YITH Wishlist plugin. On top of that, there is no Registry functionality offered with this plugin either. It is all about Wishlists- with no real customizable functionality.

No Support

After paying Ignite Woo money I have been completely unable to reach anyone in support to answer a myriad of technical questions. I also had an issue with the license key they provided me and have still had no one reach out to me. I’ve contacted them via email, online chat and Twitter and have had absolutely nothing resolved.

Verdict: AVOID

I typically hate to trash other companies as there is no guaranteeing that the experience I have had with them is indicative of how they treat others. However, I have found that the WordPress forums are full of people who have gotten nothing but radio silence from this company. I would highly suggest you avoid their Wishlist & Gift Registry Pro plugin as it, literally, provides no additional functionality over any of the free alternatives. I would also recommend staying away from IgniteWoo in general- their product code is not very clean, their documentation is terrible and their support is non-existant.

I openly invite one of their representatives to get ahold of me. I’d love to work more closely with them and recant my position. Unfortunately we are two months in, they still have our money and have provided no service worthwhile to us.


Securing Passwords, One Way Hashes, PBKDF2, PHP and You

Plain text passwords and simple one way hashes are not enough to protect your users. You need salt, pepper, and peanut butter. Am I crazy you ask? Maybe, but read on.

It happens to big huge companies (LinkedIn, Last.fm, eHarmony), the little guys, and everything in between. Databases get breached and passwords get hacked. It always surprises me when I hear about how many thousands of users had the password “password”, or that the target’s password hashes were cracked in a matter of hours or days- or worse, their passwords were plain text. At this point, it is so easy to make passwords pretty secure with just basic knowledge of cryptography and hashing. As a matter of fact, as a competent developer, you don’t need to know much at all about the how’s and why’s of crypto to secure your users’ data.

First, do not think you are safe because you run your passwords through MD5 or SHA-256. MD5 has been cracked and SHA-256 is barely better than storing their passwords in plain text. Cryptograhic hash functions are NOT password hash functions!

One Way Hashing

A one way hash performs a bunch of mathematical operations that transform input into a (mostly) unique output, called a digest. Because these operations are one way, you cannot ‘decrypt’ the output- you can’t turn a digest into the original input. Good cryptographic hash functions should not generate digests that are the same for different input. Additionally, when the input is changed, just slightly, the resulting digest should be very different.

A typical use case would be when a user signs up for a website and creates a password. The conscientious developer takes the plain text password, runs it through a hashing function (let’s say, MD5) and stores the result in the database. When the user goes to log in the next time they enter their password and the authentication mechanism runs it through MD5 and compares the result against what is stored in the database.

That sounds pretty safe, right? Wrong. It’s akin to locking the door and leaving the window open. If the database was stolen it might make it harder to infer anything about the passwords just by looking at the data, but it doesn’t really make it any harder to guess or “crack” the password.

Password Hash Functions

… are not the same as cryptographic hash functions

Just using a cryptographic function on a plain text password doesn’t defend it very well. There a number of major problems and threats that are not being avoided. The two biggest are speed and recognizability of hashes.

Hashing Speed

Cryptographic hash functions are used for lots of things, most of them have to do with fingerprinting and verifying data. They are designed to be very fast so that the encryption processes isn’t slowed down. This presents a big problem for password hashing. Speed. The faster a function creates a digest, the more frequently an attacker can guess the password and compare the output. MD5, for instance, is so fast that on basic hardware you could guess over 5 billion times per second. Think about it for a second, do you need that speed to allow your users to log in? When it takes 15 seconds to enter your username and password, a few second to log in, and a few seconds of perceived page load time, will they notice the difference between .000001 seconds or 1 second for the authentication mechanism? The answer is no, not to enough of a degree to degrade their experience. For password hashing, slower is good.

Recognizability of Hashes

What happens when 10,000 people all use “password” as their password? Their hashes are all the same! If you just get one account cracked, you automatically crack everyone else with the same hash. If an attacker has a huge, precomputed list of hashes (called a rainbow table), they can scan your database looking for any hashes that match. They’ve already cracked accounts without even guessing a password yet! They could have a huge percentage of your system’s passwords before ever once making a guess.

Fortunately though, there are a few relatively easy things you can do to make their life harder. You don’t need to do anything heroic and the code isn’t even that tricky. Heck, most of it already exists and is free to use.

Salting

Talk about low hanging fruit. All you have to do is add some random characters to their password (and keep track of them). A salt is a random sequence of data which is added to the hash function or the password string itself. Say you generated a salt “12345” and had a password “password”, you could put them together “password12345″ and run that through your hash function to produce a digest that wouldn’t be so easily given up. Every password should have its own salt and should be at minimum, 32 characters or more to make it harder to guess the digest.

This is a basic salt generation algorithm. Do NOT use this function for generating salts where you are trying to protect details like credit card numbers, or even email addresses for that matter. It’s a pretty poor implementation, really.

When we create a user password we’ll generate a salt, add it to the password string, hash the password to get a digest, then store the salt and digest in the database. To log the user in subsequently we could use functions like the following:

Password Stretching

Stretching is creating a digest of a digest (of a digest of a digest … of a digest … you get it.) If you create a digest of a password, then create a digest of that X number of times you can no longer simply create a digest (from a rainbow table or otherwise) and compare it directly to the digest that is stored in the database. To compare passwords you’ll have to run the exact same number of iterations if hashing digests to compare passwords. This is useful on multiple fronts: it slows things down and (in conjunction with salted passwords) your hashes no longer look the same as everyone else’s. It stands to reason that if hashing a password once takes X amount of time, hashing it twice will take approximately 2X. You’ve just cut in half the number of times an attacker can guess your passwords. Congratulations! A good system takes so long to process a single digest that guessing a password using brute force will take more than a lifetime.

Let’s modify our password hashing function:

Notice that I have re-salted every hash to add extra randomization to the digest… just another wrinkle to throw at an attacker.

Pepper

Additionally, you can have an application wide salt, called a pepper. Think of it as a salt for the salt, except this salt is unique only to the application, server, environment, or database.
You could use it like that hash('sha256', $pepper . $password . $salt);

Adaptive Key Derivation

Adaptive key derivation functions generate digests from passwords while applying salts and stretching. They implement many more wrinkles and are tested against attack vectors you may never think of- which is the important part. They are tested against attack vectors. Rolling your own cryptographic functions introduce a lot of unnecessary exposure and take more time than using generally accepted libraries, implementations and functions. I’m going to focus on the one I know best, PBKDF2. There are others such as bcrypt and mcrypt

Peanut Butter Keeps Dogs Friendly Too

PBKDF2 (Password-Based Key Derivation Function) is probably the most widely used derivation function. It is a container for a hash function, e.g. SHA-1 or RIPEMD,. For each input it applies a salt and iterates the hash many times in such a way that not much entropy (length and randomness) is lost. Primarily, it is done in such a way that it is SLOW to generate a single digest. The US government and NSA use this for generating strong encryption keys.

Adaptive keys are great first step, but remember, this is one tiny piece of securing user data.

Below is a very basic class I created that can be used for generating salts and digests through a variety of ways. You can download it here. This file will be updated regularly, so stay in touch!


Authentication Using WordPress and Zend Framework

I recently had the need to implement a Zend Framework web app that could authorize against WordPress without necessarily using WordPress as the front end. I was very relieved to find out it was quite easy to do!

In your application’s index.php (typically found at public/index.php) you need to include the WordPress header file to make sure you have access to the WordPress functions later in your application:

I have the following code in my LoginController.php (application/modules/public/controllers/LoginController.php) file.

doWordpressAuth function

IndexAction


How to Specify Non-String PHP Data Types in Zend Config XML and INI Files

Zend Config INI and Zend Config XML are adapters in the Zend Framework that allow you to store your application or website configuration data (such as database connector information and salt values) in an easy to interpret text file (I happen to prefer INI files over XML because INI is more terse).

The biggest downside to these files is that they don’t store PHP data types or values like NULL, FALSE, or TRUE, and you can’t specify an int, double, or float, the adapters only return strings.

Here is the recursive code for converting all your values:

Here is how I use it in my Bootstrap.php file in my Zend Framework application:

The following config file will end up looking like the following array (before turning it into a Zend_Config object)


Install / Upgrade PHP 5.3 on CentOS 5 / RHEL 5

As I was setting up a staging VM (CentOS 5), I quickly realized I could only get PHP 5.1 from the standard repositories. Thanks to this blog post, I was able to quickly get up and running with PHP 5.3.

From the command line on your server, run the following:

This, of course, assumes that your LAMP stack is already installed. If not, you would want to replace ‘update’ with ‘install’.

Make sure that you run the last update command (if you’re running an update) as noted above. Not including one of the three packages will result in a bunch of file conflict errors.


Using mysqli Extension to Query MySQL from PHP Instead of the mysql Extension

I was answering a very basic question on stackoverflow today that boiled down to “How do I query mysql from PHP using a user input” and was horrified to see the first two answers.

The first answer went along the lines of:
[code=”php”]
$result = mysql_query(“SELECT * FROM table WHERE field = ‘”. $_POST[‘input’] .”‘”);
while($row = mysql_fetch_array($result)){
//do stuff
}
[/code]

This is bad. Very bad. Very, very bad.
This is the kind of thing that allowed (maybe a bit of hyperbole, but stick with me) Sony to be brought to its knees. This is how all your user data gets stolen. This is how Anonymous makes you look like a fascist who wants to eat babies. It’s bad. It did come from someone with a pretty low score on SO, but I’m living proof that a low score on SO doesn’t mean you don’t know what you’re doing.

Why?

The first MAJOR problem is: You are taking direct, unsanitized user input. You have not validated that the input is correct, even relates to what you are having them input, or is safe.
By taking direct input straight from the user (by directly using the $_POST variable nonetheless) they could attack via sql injection at worst, and the $_POST field may not exist, giving you an error, at best.

The second problem is the use of the mysql extension in PHP. According to the manual, the mysql extension should only be used in 4.1.3 and lower, anything newer should be using mysqli for improved performance and security.

I have heard there are some issues with mysqli in certain cases that essentially require the use of the mysql_ extension to get around them. As far as I know, these are few in number and getting better by the day. I personally, haven’t ever had a problem with mysqli.

On to a more correct example:
[code=”php”]
$db = new mysqli(“localhost”,”user”,”password”,”database”);

if(mysqli_connect_error())
{
printf(“Connection failed:%s \n”,mysqli_connect_error());
exit();
}

$input = mysqli_real_escape_string($db, $_POST[‘search’]);

/*
* Validate that $input is correct after escaping
* Implement your validation below!
*/

if($result = $db->query(“SELECT * FROM table WHERE field = $input”, MYSQLI_ASSOC))
{
while($row = $result->fetch_object())
{
// $row is an associative array
// Do something here
}
}
$db->close();
[/code]

What’s better about this code?

First, it’s not perfect. You could pick it apart, but it’s a good example of where to start and I wrote it in about 45 seconds.
It shows:

  • Connecting to the mysql database
  • Ensuring a connection occured and handling the mysql connection error
  • Querying the database
  • Escaping user input AND THEN validating
  • Iterating through the mysql results
  • Closing the database connection (people never remind beginners to do this)!

The basics shouldn’t be so complicated that it takes two months to make heads or tails of what your code really does (I’m looking at you Zend Framework), but it should start with a good explanation of the big picture.


Adding HTML Tags to a Zend Form Element

For the purposes of styling I had the need to put an opening <div> at the beginning of one element, and a closing </div> tag at the end of another. The Zend Framework guides don’t do a great job of detailing this.

On the element you want to add the opening div tag you would do the following:
[code=”php”]
$open_element->addDecorator(array(
array(‘openDiv’ =>’HtmlTag’),
array(‘tag’ => ‘div’, ‘openOnly’ => true)
));
[/code]

On the element you want to add the closing div tag:
[code=”php”]
$close_element->addDecorator(array(
array(‘closeDiv’ =>’HtmlTag’),
array(‘tag’ => ‘div’, ‘closeOnly’ => true)
));
[/code]


Removing ShareThis from your WordPress Front Page

After installing the ShareThis social plugin for WordPress I was surprised to find that there isn’t an easy option to exclude the social links from showing up on the front page. Luckily, it’s as easy as inserting a small bit of code into the sharethis.php plugin file.
On my system the file is located at [code]{wordpress root directory}/wp-content/plugins/share-this/sharethis.php[/code]

Open up the file in your favorite editor and go to nearly the bottom of the file and find the function (around line 601 in the version that I have) st_makeEntries

Add in the following code
[sourcecode=”php”]
if(is_front_page()){ return ”; }
[/sourcecode]

So that the beginning of your function looks like this:
[sourcecode=”php”]
function st_makeEntries(){
if(is_front_page()){ return ”; }
global $post;
… the rest of the function follows …
[/sourcecode]

We are basically bypassing the code that builds the social badges and returning nothing instead of the HTML that the code would otherwise build.


Custom Username Validator Using Zend_Validate_Abstract for Zend Framework

Do you find yourself having to use multiple steps to validate a new username? If you’ve got a create user screen, or some other form that requires the creation of a username (or some other input that must be unique and is in a datastore), you can create a custom validator that uses a database mapper to validate that the input is unique.

First step, create a lookup method in your mapper (or whatever class you use for datastore access) that will query your datastore to verify the input is unique. In this case, I’m using a MySQL database backend and am using a mapper/model hierarchy and am only showing the relavant function from my mapper class.

[sourcecode=”php”]

public static function isRegisteredUser($username)
{
try
{
$table = new Ashurex_Model_DbTable_UserView();
$stmt = $table->select()
->where(‘username = ?’)
->bind(array($username));

$row = $table->fetchRow($stmt);

if(!($row == null))
{
return true;
}
else
{
return false;
}
}
catch(Exception $e)
{
self::logException(__METHOD__,$ex);
return null;
}
}

[/sourcecode]

Next, we’ll create a custom validator that extends Zend_Validate_Abstract and utilizes our mapper function during validation.

[sourcecode=”php”]
class Ashurex_Validate_Text_Username extends Zend_Validate_Abstract
{
const INVALID = ‘textInvalid';
const NOT_NAME = ‘notName';
const STRING_EMPTY = ‘textStringEmpty';
const STRING_LENGTH = ‘textStringLength';
const NAME_TAKEN = ‘textNameTaken';

protected static $_filter = null;
protected $_allowEmpty;

protected $_messageTemplates = array(
self::INVALID => ‘Invalid characters entered’,
self::NOT_NAME => ‘Input contains characters not valid for a username’,
self::STRING_EMPTY => ‘No input entered’,
self::STRING_LENGTH => ‘Username must be between 6 and 64 characters’,
self::NAME_TAKEN => ‘Username is already taken’
);

public function isValid($value)
{
// Make sure a value was entered
if(($value == null)||($value == ”))
{
$this->_error(self::STRING_EMPTY);
return false;
}

// The value must be a string
if (!is_string($value)) {
$this->_error(self::INVALID);
return false;
}

// Set the internal value to the input
$this->_setValue($value);

// Validate that the input is alphanumeric
$al = new Zend_Validate_Alnum();
if(!$al->isValid($value))
{
$this->_error(self::INVALID);
return false;
}

// Validate that the string length meets requirements
$sl = new Zend_Validate_StringLength(array(‘min’ => 6,’max’ => 64));
if(!$sl->isValid($value))
{
$this->_error(self::STRING_LENGTH);
return false;
}

// Make sure the username doesn’t already exist
if(Ashurex_Model_Mapper_User::isRegisteredUser($value))
{
$this->_error(self::NAME_TAKEN);
return false;
}

return true;
}
}
[/sourcecode]

Finally, we can use our new validator just as we would any other validator. The following code is an excerpt from my custom create user form:
[sourcecode=”php”]
class Ashurex_Form_Admin_AddUser extends Zend_form
{
public function init()
{
$this->setName(‘add_user_form’);
$this->setMethod(‘post’);

$username = new Zend_Form_Element_Text(‘username’);
$username->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));
$username->setValidators(
array(
new Ashurex_Validate_Text_Username(),
));
$username->setRequired(true);
$username->setLabel(‘Username’);

… lots of other code follows …

}
}

[/sourcecode]


Zend Framework HTML5 Form Elements

By default, Zend Framework 1.11 doesn’t have any native HTML5 form elements, but with some help from Enrise you can use their HTML5 Form Elements. I won’t go over the intricacies of creating custom forms and elements, but I will quickly show how to use the Glitch_Form_Element objects in a useful manner.

One of the neat things about the Glitch HTML5 elements is that they auto-detect the doctype being used in your Zend Framework application and will switch how they render to HTML. For example, if your doctype is set to ‘HTML5′ the Glitch_Form_Element_Text_Email object will render as an HTML5 email input and look like:
[sourcecode language=”html”]

[/sourcecode]
However, if your doctype is set to something else, it will render it as a standard text input like so
[sourcecode language=”html”]

[/sourcecode]
Pretty slick, eh? The best part is, the functionality is already built in. All you have to do is make sure you are setting your doctype.
I set mine in my Bootstrap.php file like so:
[sourcecode language=”php”]
protected function _initView()
{
// create view here if you need to change default options, but front
// controller will create view automatically.
$documentType = new Zend_View_Helper_Doctype();
$documentType->doctype($this->_config->resources->view->doctype);
}
[/sourcecode]
My application.ini config file has the default configuration block:

Finally, my form class looks just about like any other Zend_Form:
[sourcecode language=”php”]
class Ashurex_Form_Admin_AddUser extends Zend_Form
{
public function init()
{
$this->setName(‘add_user_form’);
$this->setMethod(‘post’);

$username = new Zend_Form_Element_Text(‘username’);
$username->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));
$username->setValidators(
array(
new Zend_Validate_Alnum(),
new Zend_Validate_StringLength(array(‘min’ => 6,’max’ => 64)),
));
$username->setRequired(true);
$username->setLabel(‘Username’);

$firstname = new Zend_Form_Element_Text(‘first_name’);
$firstname->setLabel(‘First Name’);
$firstname->setRequired(true);
$firstname->setFilters(
array(
new Zend_Filter_StringTrim(),
));
$firstname->setValidators(
array(
new Ashurex_Validate_Text_PersonName(),
new Zend_Validate_StringLength(array(‘min’ => 1,’max’ => 64)),
));

$lastname = new Zend_Form_Element_Text(‘last_name’);
$lastname->setLabel(‘Last Name’);
$lastname->setRequired(true);
$lastname->setFilters(
array(
new Zend_Filter_StringTrim(),
));
$lastname->setValidators(
array(
new Ashurex_Validate_Text_PersonName(),
new Zend_Validate_StringLength(array(‘min’ => 1,’max’ => 64)),
));

$email = new Glitch_Form_Element_Text_Email(‘email’);
$email->setLabel(‘Email’);
$email->setRequired(true);
$email->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));

$submit = new Zend_Form_Element_Submit(‘submit’);
$submit->setRequired(false);
$submit->setIgnore(true);
$submit->setLabel(‘Save’);

$cancel = new Zend_Form_Element_Submit(‘cancel’);
$cancel->setRequired(false);
$cancel->setIgnore(true);
$cancel->setLabel(‘Cancel’);

$this->addElements(array($username,$email,$firstname,$lastname,$submit, $cancel));
}
}
[/sourcecode]