Using bcrypt to store passwords

The linkedin password breach highlighted once again the risks associated with storing user passwords. I hope you are not still storing passwords in the clear and are using a one-way salted hash before storing them. But, the algorithm you choose to use is also important. If you don’t know why, go read You’re Probably Storing Passwords Incorrectly.

The choice, at the moment, seems to come down to SHA512 versus Bcrypt encryption. There’s a StackOverflow Q&A discussing the merits of each. Bcrypt gets the nod since its goal is to be slow enough that brute force attacks would take too much time to be feasible, but not so slow that honest users would really notice and be inconvenienced [1].

I wanted to switch one of my personal apps to use bcrypt, which on php means using Blowfish encryption via the crypt() function. There’s no shortage of classes and examples for using bcrypts to hash a string. But I didn’t find anything that outlined how to setup a database table to store usernames and passwords, salt and store passwords, and then verify a login request.

Storing passwords in Mysql

To store passwords in a MySQL database, all we need is a CHAR field of length 60. And you don’t need a separate column for the salt, as it will be stored as part of the password. The SQL for a minimal Users table is shown below.

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` char(60) NOT NULL,
  PRIMARY KEY (`id`),
);

When a user registers providing a username and password, you have to generate a salt and hash the password, before saving it. This gist helped me figure out how to salt and hash them.

function save_user($username, $password, PDO $db)
{
    // create a random salt
    $salt = substr(str_replace('+', '.', base64_encode(sha1(microtime(true), true))), 0, 22);

    // hash incoming password - this works on PHP 5.3 and up
    $hash = crypt($password, '$2a$12$' . $salt);

    // store username and hashed password
    $insert = $db->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $insert->execute($username, $hash)
}

Authenticating Users

When a user comes back to your site and tries to login, you retrieve their credentials and then compare the expected password to the supplied password. Remember we were clever and stored the salt as part of our hash in the password field? Now, we can reuse our stored password as the salt for hashing the incoming password. If its the right password, we’ll have two identical hashes. Magic!

function validate_user($username, $password, PDO $db)
{
    // attempt to lookup user's information
    $query= $db->prepare('SELECT * FROM users WHERE username=?';
    $query->execute(array($username));

    if (0 == $query->rowCount()) {
        // user not found
        return false;
    }

    $user = $query->fetch();
    // compare the password to the expected hash
    if (crypt($password, $user['password']) == $user['password']) {
        // let them in
        return $user;
    }

    // wrong password
    return false;
}

Those are the basics for using bcrypt to store passwords with PHP and MySQL. The main difference I found, was that the hashing and comparison of hashes now happens in PHP. With MD5 and SHA algorithms, you could invoke them using the database functions provided by MySQL. As far as I could find, it doesn’t have a native Blowfish/bcrypt function. If your system provides a crypt() call, you maybe be able to use Blowfish encryption, but it won’t be an option on Windows systems.

Thank you, dd for saving and restoring my MBR

I finally got around to upgrading my dual-boot desktop PC to running Windows XP.  It was just about time, the version of windows I was running was no longer supported and more and more software requires Windows XP nowadays.  I also wanted to start using my Windows partition for more than World of Warcraft and occasional IE6 Testing.  Mini-rant: One might think that, by now, Windows would play nicely if you are installing it on an existing dual-boot setup and not do rude things like naively overwrite your Master Boot Record.  If one thought that, however, one would be very naive indeed.

The common wisdom, when setting up a dual booth system, is to install Windows first, then your other operating systems, since the latter are smart enough to setup a menu at boot time to choose which OS to load.  That’s find advice for a fresh setup, but if you have an existing system you have to take one precaution that will save you time and headaches.  First, make sure you have some sort of Linux "Live" or Install CD that you can boot from after Windows is setup.  Second, before installing Windows, you’ll want to backup your MBR to some removable media, like a USB disk, so that you can restore it after Windows does its thing.

To backup your MBR, use the dd tool, keep in mind you’ll need to change the input and output files to reflect your own system:

dd if=/dev/sda of=/media/usb1/sda-mbr.bin bs=512 count=1

Likewise to restore it, boot your rescue disk, insert your flash drive and run the following to copy it back to the boot drive

dd if=/media/usb1/sda-mbr.bin of=/dev/sda bs=512 count=1

This worked for me, but it could be a bit more intricate. I followed the advice found here and here.

Comedy Central leads the way

Good to see someone is finally asking their users to upgrade to IE6. I hope more websites start ignoring support for IE6 soon, since its such a headache to cater to. Of course, each will have to make its own cost-benefit decision, but we’re pretty close to the point that for most sites, supporting IE6 isn’t worth the time and effort. Just let your page degrade, and provide an avenue for users to upgrade.

Comedy Central New Site Dev Blog: Hey Hey! Ho Ho! IE6 Has Got To Go!

Why? Microsoft wants you to. IE6 has many issues with security and display. Comedy Central wants you to. Once you upgrade to FireFox (Windows or Mac), or IE7 (Windows), you’ll get faster download times, smoother animations and better looking pages.

Microsoft, The best protection it to fix security holes.

In any field, people have heard that its better to spend the time to fix the root cause of a problem than to just address the symptoms. It’s not just common sense, but it costs lest in the long run too. You’d think the largest software maker in the world, would have this drummed into their collective brain by now, but you’d be wrong. Microsoft admitted that it had not patched a bug in its Jet Database Engine (I believe this is the black heart of MS Access) that it knew about since 2005 because it had already blocked the attack vectors it knew about.

But the company hadn’t thought of the attack strategy now being used by hackers. "Everything changed with the discovery of this new attack vector that allowed an attacker to load an .mdb file via opening a Microsoft Word document," he said. "The previous guidance does not work against this new attack. So that’s why we alerted customers to these attacks and are re-investigating Jet parsing flaws — this is a new attack vector discovered that we didn’t know about."

MS Rep claims that they can’t fix the .mdb file format, because its designed to run code. But there should be some way to sand box the code that gets executed, ala javascript and flash. Plus, we’re supposed to believe MS can’t force their users to upgrade to a new file format in MS Office?

HT: cgisecurity.com

Next Internet Explorer 7 upgrade will be opt-out

According to InfoWorld, the next update of IE7 will be automatically downloaded and installed:Microsoft warns businesses of impending autoupdate to IE7.  Just thought you might want to know, in case you want to keep IE6 around.

Companies that stuck with IE6 must take action, Microsoft said, or IE7 may be automatically downloaded and installed to their workers’ PCs. Specifically, administrators who have set WSUS to automatically approve Update Rollups will need to disable the auto-approval rule before Feb. 12 to prevent IE7 from infiltrating their infrastructure. After that date, they must synchronize the update package with their WSUS server and then switch the autoapproval rule back on.

Linux Package management overview

I have to confess that delegating software installation to Debian and Ubuntu’s apt command is what finally converted me to Linux.  I stillhave a bias against .rpms and building from source based on disastrous experiences hunting down obscure .rpms or figuring out why make would not work.  If you’re trying out Ubuntu or another Linux distribution, you should stop and read download squad’s Package management 101

Package management refers to the way your distribution installs and configures (as well as manages and removes) software applications and libraries on your system. When Windows installs an .exe (which is the closest thing in Windows to a package) it usually places it in a single specific place within a directory. Linux installs across a few directories, leaving many new Linux users scratching their heads as to where their .rpm actually went. Most distributions install the executables in /usr/bin, and the libraries in /usr/lib. You may notice related files in /usr/share or /etc.

In short, you’ll want to let your package manager install and upgrade new software for you.  You don’t have to take my word for it, Thank You, Aptitude!

I’ve long believed that the easiest way to install software on a modern operating system is through a well-designed package manager connected to one or more carefully-maintained package repositories.

It really is an upgrade

Much like my dad has done, another Windows Vista customer has "upgraded" a Vista machine to Windows XP.  So, I guess the PR Lady was somewhat correct? BTW – annoying that apple doesn’t let you link directly to one of its ads — its free advertising, mactards!

To be honest there is only one conclusion to be made; Microsoft has really outdone themselves in delivering a brand new operating system that really excels in all the areas where Vista was sub-optimal. From my testing, discussions with friends and colleagues, and a review of the material out there on the web there seems to be no doubt whatsoever that that upgrade to XP is well worth the money.

Get a better PDF viewer

Adobe’s PDF Reader and Acrobat software are up there pretty high on my list of bloated windows software that I’ll never put on a Windows maching I get.  Its slow, bloated, and takes forever to launch, which is particularly annoying when you want to read something right now!  Viw Download Squad, comes news of Sumatra PDF viewer which is free, fast, tiny, and Open Source.

Sumatra is a single 802KB executable file for Windows. No installation required. That means you can run Sumatra off of a flash drive. You can also set it as your default PDF viewer.

I linked to a negative review of Adobe Acrobat 6 four years ago!

Browser upgrades – Firefox 2 or IE7

Of course, you know I’m going to tell you to install Firefox 2.0 once its released, and I don’t have a windows XP machine so no trying out the newly released IE7.  By the way, did you see that security vulnerabilities were already found for IE7, less than 24 hours after its release?  I’m using a release candidate of Firefox2, thanks to an ubuntu upgrade. While the Safari-like close button tabs are taking a little more time to get used to, there are some noticeable, if not drastic, usability enhancements.  The search field, in the top right of the UI, is larger giving you more room too see search terms.  I also like the automatic spell-checking in text areas, it already caught one typo as I wrote this post.

Over at the Wall Street Journal, Walt Mossberg has a more thorough comparison of the two browsers.  If you’ve been sitting on the sidelines, you’ll get the IE7 upgrade automatically via windows update in the coming weeks.  If you can’t wait, download Firefox now.

I have been testing IE 7, and I agree with Microsoft that it’s much
improved. If you are a confirmed IE user, upgrading to this new version
makes perfect sense, because it is likely to be more secure and its new
features make Web browsing better. But if you are already using
Firefox, IE’s main competitor, I see nothing in IE 7 that should make
you switch. It’s mostly a catch-up release, adding to IE some features
long present in Firefox and other browsers. The one big feature in IE 7
that wasn’t already in Firefox, a built-in detector that warns against
fraudulent Web sites, is being added to Firefox in version 2.0.

Windows Vista is Microsoft’s Iraq?

Scott Rosenberg draws an interesting parallel between Microsoft’s attempt to rewrite Windows, and the Bush administration’s foray into Iraq.  Of course, the two aren’t morally equivalent, but its a good intellectual excercise with more than a shred of validity.

Then he says, “It wasn’t executed.” Note the passive voice, correct for it: “We didn’t execute it.” Which means, “We didn’t do it.” That’s, you know, obvious, I’d think.

So its been five years since they started!  In that time Apple has delivered, what, 4 versions of OS X?  On the linux front, there’s been one major kernel revision and a ton of improvements in both the KDE and Gnome camps.  And Firefox came out of the ashes of the Netscape browser to provide a compelling browser alternative.  And Microsoft has given us, the X-Box.