Two-Factor Authentication Series on Websec.io

January 16th, 2013 — 1:25pm

I’ve been running the websec.io site for a few months now and have written up articles on a pretty wide range of topics. Recently, though, I had a lot of fun working up a series of posts (three of them) about implementing two-factor authentication in your PHP applications. I went through three different methods (two API-based services and Google Authenticator) and wrote up articles about using them. These posts were also accompanied by some custom development work I posted over on Github. The idea was to lower the bar as far down as possible and make it dead easy to implement in any application.

They’ve all been posted on Packagist so they’re easy to install. Here’s the articles and the links to their respective code:

I also recently posted a script I was playing with to connect to the Twilio API and send an SMS message, but I never got around to writing something up. It’s not technically two-factor auth as it dosen’t hook into any user or authentication system, but it might be useful for someone wanting to try them out – here’s that code.

Hopefully you’ll find some use in these articles – I had fun doing them and I hope that seeing how easy it is to implement them (especially the Google option that’s independent of any service) you’ll consider them for your applications. And, of course, feel free to check out the other articles on websec.io for other goodies.

1 comment » | PHP, security, websec.io

Security in the Round

December 17th, 2012 — 12:59pm

My post for this year’s Web Advent was posted last night – Security in the Round. It’s a pretty high level look at something that’s easy for developers to forget about. To quote Bruce Schneier:

The mantra of any good security engineer is “Security is not a product, but a process.

It’s more than just designing strong cryptography into a system; it’s designing the entire system such that all security measures, including cryptography, work together.

It’s about people, networks, systems, hardware, processes….oh yeah, and the code. Don’t forget the bigger picture. I presented some about this (and other more PHP-related topics) at True North PHP, you can see the slides here.

Comment » | PHP, security

“It Depends”

November 30th, 2012 — 3:35am

In my research and writings that I’ve already done, I’ve noticed something about trying to share helpful security advice to fellow developers – you can provide all of the code examples and describe the threats all you want, but the problem really boils down to two words:

“It depends”

Much like other development-related issues, there’s a lot of things you have to take into consideration when thinking about the security of your application. Code security by itself is good, and there’s some best practices for that that have been shared all over the web. Unfortunately, this only paints a small part of the picture. Web applications, by their nature, are really complex systems composed of multiple pieces of software all running together to make this useful, functional service for its consumers. If you’re a PHP developer, there’s things you can do to help prevent common attacks (like XSS, CSRF or SQL injection to name some popular ones), but unless you look at the bigger picture, you’re getting a false sense of security.

“But I’m only responsible for the code!” you say. You like the idea that your code can be as secure as possible by filtering output, escaping user input and using defensive coding techniques. You commit your code, run your tests and happily go about your business, thinking things are good. Unfortunately, if you don’t consider the ecosystem your application lives in, chances are you missed something.

I’m not talking about code challenges here – preventing things like XSS or SQL injections is relatively easy (as long as you know what to do). The problems I’m talking about are things that may be true for one environment but not for another – things like:

  • Working with multiple databases and storing their credentials securely
  • Effective logging to a remote syslog server
  • Potentially protecting your data from a physical intrusion
  • Working with sensitive data
  • Bridging authentication/authorization across applications
  • Concurrency issues coming from multiple installations of the same application

While a lot of these kinds of concerns revolve around the architecture of the application, developers still need to keep them in mind when creating their applications. At the very least, you need to keep these kinds of concerns in mind when writing your code. Like anything else, there’s ways to structure the code to make things like this simpler to change. The trick is to keep things loosely coupled enough to make life simpler down the road.

Comment » | Development, Opinion, PHP, security, websec.io

Education in PHP Security – What’s Needed?

November 21st, 2012 — 3:28am

As anyone that’s been around the PHP community recently (within the last six to nine months) knows, Chris Hartjes has taken up the lead in an effort to increase awareness about unit testing – really testing in general – of PHP applications. He favors things like test-driven development and having good tests to back up and reinforce a good resulting product. I admire him for his efforts (including his book) and I wonder if this same movement could be used to help kickstart a security testing “revolution” in the PHP community too.

For a long time, PHP has had an unfortunate reputation as being an insecure language to develop web-based applications in. The language itself has very few built-in security features and favors offering the ability to plug in techniques and tools of their own to make things secure. Unfortunately, this leaves a lot of the beginner level applications wide open to potential attacks. Developers aren’t immediately given options to do things like filter their data or secure the data they’re storing in their sessions. Most developers that I know that are just starting out with PHP don’t even know these sorts of things need to be done. They blindly accept user data and expect that nothing other than what they’re wanting will come through. Sadly, this sort of thing has lead to this insecure reputation – bad code written by inexperienced users. One of PHP’s best attributes is its low learning curve…and also its worst.

Many developers don’t even realize the need for security in the code they write until it’s too late. One day they wake up and – either because something they’ve written has been hacked or they read an article that talks about it – realize that they’ve been blind about protecting themselves and their data from Those People out on the web. This usually seems to happen about the time that most of them discover frameworks and how useful they can be. They start poking around what the framework has to offer and come across things like access control, user authentication and yes, maybe even secure session handling. A switch is flipped and the developer reacts in one of two ways – they take it as a charge to get better about their secure coding practices or they freak out and start going crazy with filtering, encryption and escaping.

Back to my original point – I wonder if it’s possible to take this momentum that Chris has gotten going and use it to encourage more testing for the security of applications up front. I’ve been doing what I can over on websec.io to try to help educate developers about things like secure coding practices, common infosec terms and information about securing their applications from would-be attackers, but it’s not enough. It’s not even a blip on the radar in what is a very serious matter that should be a consideration for all PHP developers.

Testing application security early, whether it be through the use of something like skipfish or a static code scanning tool, can save you time in the long run, just as unit testing your code helps track down and eliminate bugs faster. I want to promote early testing for security issues in applications and the mitigation of them, but I’m not sure how to reach developers in a way that they’ll listen.

Pádraic Brady has started up an effort to create a guide to some of the most common issues PHP developers might face and it’s off to a good start. I wonder if there’s more that can be done to help improve the security awareness in the PHP ecosystem, though. It seems like there’s a lot of content floating around out there that’s from the “stone age” of PHP security practices (filter input, escape output, blah blah blah) and not much about real-world, advanced threats that relate to PHP applications and current web technologies.

What would you like to see in a security resource that could help you, as a developer, make your code more secure? Do things like articles/tutorials encourage you to take a good long look at your code and try to “think like an attacker” or would more real-time interaction (screencasts or webinars) do more to help? I’m interested to see what the community thinks is a good approach to this.

Security is an important topic, no matter the language you’re working with. PHP just has more of an uphill battle than some other languages – help me make it a little bit easier.

13 comments » | Community, PHP, security

Websec.io (for the Security Minded Developer)

October 5th, 2012 — 5:14pm

If you follow me on Twitter you know I’ve been working on a new project for a bit now. I wanted it to gather up a bit of steam before I posted about it here…and it’s about that time.

I started up Websec.io with the hopes that it could provide articles about current trends in web security and look forward to some of the things coming down the line. Given that I’m a PHP developer by trade, a lot of the content is PHP-focused right now. I hope that in the future it can branch out. It will always stay developer-focused. As Pádraic Brady mentioned in a recent post of his, security isn’t just something to be considered from the outside in (preventing attackers and their requests). It’s also required for the developers of the applications to keep security principles in mind when developing their features.

By following some of the ideas behind the Defense in Depth theory, developers can harden their applications to make it harder for would-be attackers to find those gaps. If a developer’s doing their job right, they’re thinking like an attacker at the same time as writing code.

This, hopefully, is where Websec.io can help out. With developer-centric articles, my hope is that it can not only raise awareness about the large security knowledge gap most developers seem to have but can also provide some good solutions for them in the future.

There’s already quite a few articles posted over there (including some from other authors like Jeremy Cook and David Müller) on a wide range of topics like:

I’ve recently posted a tutorial showing how to use a new offering in the security space from Mozilla – their Persona service – with PHP and jQuery

If you’re interested in learning a bit more about how you as a developer can be “security minded” in your development, you should head over and check it out. It’s also open for submissions, so feel free to let me know if you’d like to contribute!

1 comment » | PHP, security, websec.io

Intro to Shield (A Security-Minded Microframework)

August 2nd, 2012 — 5:27pm

Recently I’ve become more interested in something that, despite the wealth of resources out there, still seems to be lacking in a lot of web-based applications – good security. I’m not talking just about the “filter input, escape output” kinds of things. I’m digging a little deeper than that and looking and encryption, hashing, authentication methods and network/server configurations that could open your app wide open to malicious people.

So, in an effort to learn more about the security for PHP based applications, I’ve started up a new project that I hope can serve as a good tool (and maybe a guide) to those looking to create secure applications – the Shield microframework. It’s a small framework in the spirit of Slim framework that has a focus on security aspects and tries to help keep the user’s app a little safer by including things like:

  • Output filtering on all values (preventing XSS)
  • Logging on all actions
  • Input filtering functionality for accessing all superglobal information
  • Uses PHP’s own filtering for data sanitization
  • Encrypted session handling (RIJNDAEL_256/MCRYPT_MODE_CBC, uses IV)
  • Custom cookie handling (including httpOnly)
  • Customized error handling to avoid exposing filesystem information
  • Basic templating/view system
  • IP-based access control

It’s an open source project and it’s already seen some great contributions from people all across the community. I wanted to provide a quick guide to getting started with this handy little framework so you could give it a shot in your own apps.

  • 1. First off, you’ll need to download the framework from github: https://github.com/enygma/shieldframework
  • 2. Once you’ve got it, check out the `app/index.php` file for an example of how to use it (pretty easy, right?)

At its most basic, all you need to do is make a route for the default page (this assumes you’re putting it in that same `app/` directory:

<?php
include_once '../Shield/Shield.php';
$app = new Shield();

$app->get('/',function() use ($app){
    echo 'It works!';
});

$app->run();
?>

That’s really all there is to it…this sets up a route for handling the main page of your app and echoes out the “It works!” message when you hit the page. You might see some other warnings and errors pop up about various settings and directories too. These are there to help you make things more secure, so be sure to make an effort to correct them.

There’s a lot more interesting things you can do with the frame work (it’s all in the README in the checkout) to work with filtering of user input, setting up custom filters, using the View object to add values to and display a rendered view and more.

I hope to make this project even better over time while trying to keep it small and flexible. I’m always looking for new ideas to help make it more secure and user friendly, so if you have any suggestions, please either leave them in the comments or email them over!.

8 comments » | framework, PHP, Shield

Introducing JsQuickFix

June 22nd, 2012 — 9:32am

Fans of PHPDeveloper.org (@phpdeveloper) or the PHPQuickFix (@phpquickfix) news feeds to keep up with some of the latest things in the PHP community, but looking for something a bit more on the Javascript side are in luck.

To compliment the PHPQuickFix site/twitter account, I’ve started up a Javascript-centric feed of hand-picked items I find in my reading that look useful/interesting/are more than just fluff – JsQuickFix (and @jsquickfix on Twitter).

This uses the same setup I have for the PHPQuickFix feed:

  • using GimmeBar as a data source
  • a simple PHP script to generate an RSS feed of the latest assets
  • Twitterfeed to pull the latest from this feed and post to Twitter

I use the Chrome extension that adds a GimmeBar icon to my toolbar and makes adding new links to these services a few simple clicks away.

To accomplish this, though, I had to shift over to using Collections instead of just pointing it at my main GimmeBar Public feed. Here’s the two collections that will grow in the future:

Enjoy! :)

1 comment » | Community, javascript, jsquickfix, PHP, phpquickfix

Innovation’s Not The “Ah-Hah!”

May 25th, 2012 — 10:29pm

After reading through his “Confessions of a Public Speaker” (as a beginning speaker, I learned some good things from this one – I’d suggest it if you do any kind of speaking) I was anxious to check out some of Scott Berkun’s other books. The topics of some of the others didn’t really appeal to me, but the one that’s caught my attention recently is his “Myths of Innovation” book. I’m maybe a third of the way through it right now, and there’s one thing that keeps resonating in my mind as I go through it. In a previous chapter, he makes the point that innovation, despite what the history books and popular culture would have us assume – it’s less of an “Ah-hah!” and more of a “Finally!”.

See, most of the common stories of innovators out there leave out something that’s very important – the reference frame of their lives. They don’t provide a larger picture of who someone is (like Einstein or Newton) and how all of their work, everything they’ve done in their career led up to the discoveries that they’re known for.

I think this is important to remember as software developers, too. All of us start projects and never finish them, it’s just a fact of life in the world of a coder. We find something that we either think is the “Next Big Idea” or something that we’ll find amazingly useful and latch onto it, giving it our all for a week, maybe a month. Nine times out of ten, though, that project falls by the wayside. Now, don’t get me wrong, there’s some folks out there that do a great job with anything they touch, but for the average developer, it’s all about hacking away at the latest “shiny”.

Sometimes it’s about the technology (“everyone’s learning Backbone.js, why shouldn’t I?”) and other times there’s a bit of pride that kicks in (“I could do this so much better if…”) but there’s always one thing to remember. It doesn’t matter if the project you’re working on goes anywhere. Remember this. Just like some of the great innovators of the past, it takes a lot of dedication and work to get to be the “Ah-hah Guy” that wows the world with something new and amazing. Don’t forget that the code of the Next Great App isn’t just going to fly from your fingertips.

Work hard at your craft and it will pay off. Maybe not in fame and glory, maybe in making real, useful contributions to the culture and technology around you. Don’t stop trying to innovate, don’t focus on the failures and, above all, keep learning and keep doing.

4 comments » | Community, Development, Opinion, PHP

Composer Dependency Woes

May 15th, 2012 — 5:35pm

I spent the better part of this afternoon trying to figure out why a Composer installation wasn’t working and finally figured out the problem…it wasn’t mine.

First, a little context – I’m currently working on a testing presentation for some folks at work and I wanted to show them how to work with the Behat testing tool to create some handy functional/integration tests for our framework-based apps. I threw together a little framework (yes yes, I know) and got the PHPUnit tests set up and running in no time. When it came to the Behat tests, though, no matter what I did, I was still having a problem:

PHP Fatal error:  Class 'GoutteClient' not found in /www/htdocs/testing-examples/app/vendor/behat/mink/src/Behat/Mink/Driver/Goutte/Client.php on line 13

No matter how I tried to configure the composer install, it always gave me this message. I tried everything I could think of and, finally, at the suggestion of Rafael Dohms, checked out the github repository for the Goutte client (a href=”http://github.com/fabpot/goutte”>here). As it turns out, in the past day or so, there’s been a large change where Fabien implemented composer support on the repo.

Apparently this was what broke things – thankfully not something obvious I was missing.

So, how did I solve it so I could see the lovely green of passing tests again? Well, if you’re familiar with composer, you know there’s a composer.lock file that’s created after you install. When you run the “composer install” and it fetches from “fabpot/goutte”:”*”, you get this latest version that has the issues. A quick modification of the composer.lock file takes care of that though:

{
    "package": "fabpot/goutte",
    "version": "master-dev",
    "source-reference": "5ecceb7c28a428fb93f283982cc4f5edfd96630b"
},

See that “source-reference” setting? Well, that can either point to the branch or version you want to pull from or it can point to a specific commit. In my case, I just pulled the hash for the commit before all of the changes and dropped it in there. Then it’s just a matter of running a “composer install” to get the code from this commit instead. Don’t run an update though – that will wipe out your manual changes to the lock file and you’ll be back to square one.

Hope this helps someone out there who might be dealing with a similar issue regarding brokenness on an external lib!

3 comments » | Composer, PHP

Quick and Dirty REST Security (or Hashes For All!)

May 14th, 2012 — 5:44pm

So in working up a new RESTful service I’ve been tinkering with, I wanted to provide some kind of “authentication” system for it. I started to look into OAuth, but got a bit overwhelmed by everything that was involved with it. Looking for something a bit more lightweight (and simpler to implement a bit more quickly) I came across this older article with a suggestion of a private key/hash combination. I figured that could do the job nicely for a first shot, so I set to implementing it.

On the Server Side

I’m using the FuelPHP framework for this one, but that’s really only giving me a structure to work in and pull the request information from. This would work in most major frameworks (and even outside of one if you you’re a “do it my way” kind of developer). First off, let’s start with the controller side:

<?php
class Controller_User extends Controller_Rest
{
    protected function validateHash()
    {
        $request = file_get_contents('php://input');
        $requestHeaders = apache_request_headers();

        if (!isset($requestHeaders['X-Auth']) || !isset($requestHeaders['X-Auth-Hash'])) {
            $this->response('fail!',401);
        } else {
            // we have the headers - let's match!
            $user = Model_User::find()->where('public_key',$requestHeaders['X-Auth'])->get_one();

            if ($user !== null) {
                $hash = hash_hmac('sha256',$request,$user->private_key);
                return ($hash == $requestHeaders['X-Auth-Hash']) ? true : false;
            } else {
                return false;
            }
        }
    }

    public function post_index()
    {
        // return the user details here....
    }

    public function router($resource, array $arguments)
    {
        if ($this->validateHash() == false) {
            $resource = 'error';
            $arguments = array('Not Authorized',401);
        }

        parent::router($resource,$arguments);
    }
}
?>

There’s a lot going on here, so let me walk you through each of the steps:

  1. First off, we’re making a RESTful service, so we’re going to extend the Controller_Rest that Fuel comes with. It has some handy special routing. Our POST request in the example below would try to hit the “post_index” method and have its hashes checked in the process.
  2. Next up is the “validateHash” method – this is where the hard work happens:
    • The request and headers are read into variables for easier use ($request and $requestHeaders).
    • It then checks to be sure that both of our required headers are set (X-Auth and X-Auth-Hash). There’s nothing magical about these header names, so they can be switched out depending on need and naming preference.
    • If they’re there, the next step is to find the user based on the public key that was sent. This value is okay to openly share because, without the private key to correctly hash the data, your requests will fail.
    • The hash_hmac function is then used (with the “sha256″ hash type) to regenerate the hash off of the contents of the request and the private key on the found user.
  3. If all goes well, the request continues on and the “post_index” method is used. If it fails, however, the check in the “route” method of the controller makes a switch. It changes the currently requested resource to “/error/index” instead of what the user wants. This seamlessly shows the user a “Not Authorized” error message (401) if the hash checking fails.

A Client Example

Now, to help make it a bit clearer, here’s an example little script showing a curl request using the hashes:

<?php

$privateKey = 'caa68fb2160b428bd1e7d78fcf0ce2d5';
$publicKey  = '01fa456c4e2a2bc13e5c0c4977297fbb';

$data = '{"username":"happyFunBall"}';
$hash = hash_hmac('sha256',$data,$privateKey);

$headers = array(
    'X-Auth: '.$publicKey,
    'X-Auth-Hash: '.$hash
);

$ch = curl_init('http://mysite.localhost:8080/user');

curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$result = curl_exec($ch);
curl_close($ch);

print_r($result);
echo "nn";
?>

You can see that both the public and private keys are specified (but on the PHP side, not visible to the user) and are sent as the “X-Auth*” headers as a part of the request. In this case, we’re POSTing to the “/user/enygma” resource and creating a user. To create the value to put into $hash, we use the same “sha256″ hashing method and salt it with the private key. This value – the result of the data+private key hashing – is then passed to the service who uses the controller code from above to validate that it’s correct.

It’s not a true “login” process, but it can help to validate that a piece of information known only to the user (the private key) and never shared directly, is known and matches the requests that the user sends.

You can find the code for this in this gist if you’d like something a bit more readable: https://gist.github.com/2697434

6 comments » | FuelPHP, PHP, REST

Back to top