Thursday, July 10, 2008

Back From the Dead

So my... third... foray into blogging about my life has so far been a pretty spectacular failure, no updates for 3 months? Lose.

So, just for kicks I've been writing a small PHP authentication library for myself lately, nothing too fancy or spectacular, and it's been kicking my ass.

The basic structure is simple - once authenticated, the system stores some data in a cookie - the username and a hash of a various bunch of things, including the user's password. As the user moves about my site the system just checks the hash for validity. Elementary, but works well enough for a low-traffic site that doesn't demand iron-clad security.

$cookie = sanitize($cookie);
parse_str($cookie, $output);

Simple? Not quite:


Expected output:
[username] => potato
[phash] => 9ee26cb97a7e32d9c0f1c02199295bc3
Actual output:
['username] => potato
[phash] => 9ee26cb97a7e32d9c0f1c02199295bc3\'

What the, how did those quotes sneak in there? Worse yet... if I run this on my dev box locally (OS X):
[\'username] => potato
[phash] => 9ee26cb97a7e32d9c0f1c02199295bc3\'

Notice the difference? PHP was friendly enough to provide this explanation:

Note: The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

Which means that, as a means for security, quotes and slashes get escaped properly. Great. I don't see any quotes or slashes in my input. What gives? Google hasn't turned up anything relevant, so I'm unfortunately stuck on this.


Unknown said...

turn off magic quotes?

Anonymous said...

Are you sure the sanitize function isn't doing something weird?

I just tried to duplicate it on my MacBook and worked fine.

Running PHP 5.2.5 with magic_quotes_gpc turned on.

eric m said...

Thanks for not using the Internet verb 'Fail'. I would've stopped reading right then and there.

Unknown said...

this post fails at fail

Ars said...

Why are you using sanitize or parse_str?

Use $_COOKIE[]

Eric TF Bat said...

I agree with commie: anything in PHP with the word "magic" in it is doomed to (pardon my language) FAIL. Switch off that and the other childish hand-holding settings and just program defensively.

And yes, $_COOKIE is your friend.

Anonymous said...

Not a platform-specific bug, a programmer-specific bug.

Zend has advised you turn off the hand-holding settings for years now (they're off by default in PHP5).