Custom Callbacks with Invoke

In putting the Invoke library to use I noticed something. While I could tell it to check for groups and permissions on the current user and limit HTTP methods on the request, there were more complex things I needed to check that weren’t part of these defaults. Now, I could just extend invoke to include match types for everything I needed (injecting a custom match class based on my needs) but I wanted something a bit more generic that I could use to call my own logic and return the pass/fail result.

So, I added in the “object.callback” match type that allows you to call a static method in your own code and perform the evaluation yourself. Here’s how it works. Say you have this configuration in your routes.yml file:

  protected: on
  callback: \App\MyUser::test

This tells Invoke that when the user requests the /foo URL, the protection should kick in. It then goes into the checks portion of the process. This sees the special callback option and looks the class and method to call. In this case, we’ve told it to try calling the test method \App\MyUser. This class needs to be autoloadable so that Invoke can directly call it and its static method. Yep, that’s right – it needs to be a static method but you’ll be provided with everything about the request in the incoming $data variable. Here’s what the method should look like:

public static function test(\Psecio\Invoke\Data $data)
  /* perform your evaluation here and return a boolean */

In the $data variable there, you’ll have access to the context of the application via some object properties:

  • user: The current InvokeUser instance (ideally where your user lies too)
  • resource: The resource that was requested (includes access to the requested URI)
  • route: This is the route match from Invoke’s configuration the current request matches. This contains the route regex match, the configuration options and any additional parameters passed along

For example, say you needed to get the parameters from the request to do further evaluation. You could fetch them through $data->resource->getParams() and get the associative array back.

Adding these callbacks makes the Invoke system a lot more flexible and allows you to create those custom match types without having to have whole other classes just to perform your checks.

Laravel Route Protection with Invoke

I started on a tool a while back to “scratch an itch” in a personal project to make it easier to protect endpoints based on the requested URL. The Invoke library makes it possible to detect the route requested and ensure a set of criteria are met to be sure a user can access a resource. This isn’t anything new or revolutionary, but it is something I couldn’t find separate and effectively decoupled from other tools. It’s loosely based on how Symfony (v1) does it’s route protection, right down to the .yaml file that it uses for configuration. In my case, I was using it in a Slim framework-based application to evaluate the current user to see if they had the required groups and permissions.

More recently, though, I’ve been messing with Laravel and since they’ve been putting a heavy emphasis on middleware, I thought I’d see how tough an integration might be. I wanted to use Invoke to check my Laravel user to see if they met my requirements. Fortunately, it turned out to be super easy.

Here’s how I did it – hopefully it can be useful for you. I’ll provide one caveat though: Laravel’s default auth handling only sets up users, not groups/permissions, so you’ll need a way to manage those but that’s outside the scope of this. You’ll see how it integrates in a bit.

First off, we need to get Invoke installed via Composer:

composer require psecio/invoke

Once that’s installed, we need to set up our middleware. This will go in with the rest of the default middleware in the app/Http/Middleware folder in your application. Create a file called InvokeMiddleware.php with this code:


namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth as Auth;

class InvokeMiddleware
     * Handle an incoming request and validate against Invoke rules
     * @param \Illuminate\Http\Request $request
     * @param \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        $en = new \Psecio\Invoke\Enforcer(app_path().'/../config/routes.yml');
        $user = Auth::user();

        $allowed = $en->isAuthorized(
            new \App\InvokeUser($user),
            new \Psecio\Invoke\Resource($request->path())

        if ($allowed !== true) {
            return response('Unauthorized.', 401);

        return $next($request);

You’ll see there’s a reference to an InvokeUser class in there. Let’s make that next. In app/InvokeUser.php put this code:


namespace App;

class InvokeUser implements \Psecio\Invoke\UserInterface
	private $user;

	public function __construct($user)
		$this->user = $user;

	public function getGroups()
		// This is where you fetch groups
		return [];

	public function getPermissions()
		// This is where you fetch permissions
		return [];

	public function isAuthed()
		return ($this->user !== null);


Then, to turn it on, edit your app/Http/Kernel.php class and add this to the list of $middleware:


Viola, you’re set to go using Invoke. Now, the next step is to define your rules. You’ll notice in the middleware above we’re loading the config/routes.yml configuration file for our rules. Let’s make one of those with a super simple example. In app/config/routes.yml put:

  protected: on

This configuration is telling Invoke that, when you hit the base URL of your application (“/”) it’s protected. This means that it requires a logged in user. If you’ve just added this to your application and try to load the main page without a user, you’ll be given the unhappy “Forbidden” message instead of your lovely site. It’s the check in InvokeUser::isAuthed that evaluates for this, checking to see if the user is null (no valid logged in user).

That’s it…it’s a pretty simple integration to get just get bare minimum up and running. If you’re interested in how to add group and permission checking to this, forge ahead and keep reading.

So we have our basic yaml configuration file with protection turned on. Say we wanted to add in group and permission checks too. I’ve already talked some about this kind of handling in a different post but I’ve more recently simplified it even more, no longer requiring extra classes in the mix.

Let’s start by changing our configuration file to tell Invoke that we want to be sure the user is in the “admin” group and has a permission of “delete_user” to access the /admin/user/delete resource:

  protected: on
  groups: [admin]
  permissions: [delete_user]

When you fire off the page request for that URL, Invoke will try to call the InvokeUser::getGroups and InvokeUser::getPermissions methods to return the user’s current permission set. Before it required you to use classes that implemented the InvokeGroup and InvokePermission interfaces for each group/permission. I streamlined this since it’s really only evaluating string matches and allowed those methods to either return a set of objects or of strings. Let’s update the InvokeUser class to hard-code in some groups/permissions for return:


namespace App;

class InvokeUser implements \Psecio\Invoke\UserInterface
        /** ...more code... */

	public function getGroups()
		return ['admin','froods'];

	public function getPermissions()
		return ['delete_user','view_user','update_user'];
        /** ...more code... */

Ideally you’d be fetching these groups and permissions from some role-based access control system (maybe, say Gatekeeper) and returning real values. These hard-coded values will work for now.

Since the user has all the requirements, Invoke is happy and they’re able to move along and delete all the users they want.

I’ve tried to keep the class as simple as possible to use and I’m definitely open to suggestions. There’s a few additions I’d though about including adding HTTP method matching (different rules for POST than GET) and other match types than just groups and permissions. Let me know if you’d like to see something else included in Invoke – I’d love to chat!

Why Drupal’s Bug Bounty is Important

The Drupal project has just announced a bug bounty program where they’re offering sums between $50-1000 USD for anyone who finds and reports a security issue with Drupal 8:

Drupal 8 is nearing release, and with all the big architectural changes it brings, we want to ensure D8 upholds the same level of security as our previous releases. That’s where you come in!

The security team is using monies from the D8 Accelerate fund to pay for valid security issues found in Drupal 8, from now until August 31, 2015 (open to extension). This program is open for participation by anyone.

One thing to note, they’re only looking for Drupal 8 issues here, not problems in past editions (I’m sure they’d still appreciate them being reported though). There’s some stipulations they list where the vulnerability doesn’t count including someone with Administer level access and several other very specific kinds of issues. I’m assuming they’ve already run some pretty extensive testing on those, though, otherwise they would’ve been included in the list of allowed vulnerabilities.

A mention of the bug bounty was posted over on the /r/php subreddit earlier and there’s already some good feedback about it. There’s two points that I want to touch on as to why Drupal announcing this bounty is a major and important thing for the entire PHP community, not just Drupal.

First off, it sends a message to the wider world of developers that it’s time to take (PHP) security seriously. PHP’s had a less than stellar reputation when it comes to security. Fortunately it seems like things are getting better and more developers are working towards building secure applications. Security is a hot topic everywhere, not just in development communities and it’s starting to rub off on PHP devs. This bold move from the Drupal organization takes that up to the next level. It’s essentially telling everyone that uses Drupal or has any kind of contact with it, that they’re taking the security of their systems seriously and are “putting their money where their mouth is” to encourage as much participation as possible.

Bold moves like this are what get people’s attention too, even people not in the PHP community. Bug bounties have become a pretty common place thing in the security world, for software and hardware alike. By posting this bounty Drupal has shown that they (and vicariously PHP) are ready to move up and join with the security community as a whole to make their software more secure. Not only does this look good for Drupal but it looks good for PHP too, elevating the status of the language back to a “major contender” in the security circles.

Second, it helps pave the way for other projects to do the same. Most PHP projects tend to be smaller, not only in size but in complexity. There’s only a handful that most PHP developers can immediately list that are larger and have really stood the test of time. Keep in mind, I’m not talking about corporate applications or services here. I’m talking about PHP-based applications like Drupal, WordPress or Joomla that can be used as a platform to build other things. For the most part, their PHP brethren trend more towards the smaller side. Some of the most popular packages on Packagist are smaller libraries and frameworks, not applications as a whole.

There are some larger projects, though. Frameworks like the Zend Framework and Symfony have put their own emphasis on security, having internal groups or just contributors handling the vulnerability discovery and disclosure. Drupal has done things similarly in the past, but with the posting of this bounty, they’ve set a precedent for other projects to follow. It’s an unfortunate fact but in the Real World, time spent on a project (that’s not for work) falls into two categories:

  1. You do it for passion, either because the project is “yours” and you want to see it thrive or
  2. You do it because you’ll get something back out of it, either financial or in terms of much needed features

Bug bounties, pretty obviously, fall into that second category. Being able to pay out that financial compensation for work done bug hunting could be enough to tip people over from the “eh, I could” mentality to the “that’s worth my time” world. Don’t get me wrong, I’m not saying that developers are only interested in the money…far from it. I’m only saying that bounties like this gather more attention and show that the project believes in itself enough to have people commit time, either free or for work, to hunting down bugs.

I do want to touch on a third (bonus!) point too, while I have you here. While bounties like this are good for projects that have a budget, it sort of rules it out for those smaller projects where it’s just a one person team (or just a few people). In general these kinds of projects have little to no budget associated with them and don’t have spare cash on hand to pay out for bugs found or fixed. Unfortunately, there’s not too much in the way of options on this one. I’ve seen differing opinions on the payout amounts too. Some people think that the payout should relate to the severity of the bug, but the project just may not be able to afford that. People could feel slighted by the low compensation for their time which could in turn reflect poorly on the project overall. It’s a tough line…

There is one option out there that might be a good fit for your smaller project, though. The site has integrated an interesting concept of a “fundraiser” for open source projects. The idea is that a project could raise the finds in a Kickstarter-like fashion and use it to pay out bounties (or really however they might see fit). While it’s a good idea in theory, smaller projects that don’t have much exposure are still going to have a hard time raising any funds to make the bounties a realistic thing.

I don’t have a good answer here, unfortunately. I think with so much of the PHP world turing to smaller packages, it’s a tough problem to figure out. I’m all ears if you can think of any other options or even services that might help. I’d love to help make bug bounties a more wide-spread thing in the PHP world. I feel like, done correctly, they can only help to make the PHP ecosystem a better, more secure place.

Gatekeeper & Policies

I’ve been working on a system for a while now, inspired by the work that was done on the Sentry project, to provide a role-based access control system that was not only more well-maintained but also built on the foundation they provided to add in some new features. My “little project” Gatekeeper has really grown over time and (I think) really evolved into something that’s quite useful.

With this progression in mind, I’ve recently added another new feature that sits on top of the permissions and groups system that allows you to create reusable policies. Policies are a common concept when it comes to access control. They can make performing complex operations a lot simpler and, in the case of how it’s implemented here, make it much more reusable across the entire system (or multiple systems). Checking user permissions and groups is a relatively simple operation if you’re just doing one or two checks. You’d end up with something like this:

use \Psecio\Gatekeeper\Gatekeeper as g;

$user = g::findUserById(1);
if ($user->inGroup("group1") && $user->hasPermission("perm1")) {
    echo "Good to go!";


In this case, the check is relatively simple but there’s one think that any DRY code advocate could tell you – this exact check would need to be reproduced throughout the entire application exactly as stated to ensure the evaluation is the same. Even worse, if the requirements changed you’d have to work across the entire application and replace all instances with the new logic.

This is where policies can come in very handy. With the functionality that Gatekeeper includes, they’re dead simple to use too. The key is in their use of the Symfony Expression Language component. This language allows you to define text strings that represent logic and allow for more complex and self-contained evaluation. Enough talk, let’s see how we can use these policies to perform the same check as above.

// First we'll make the policy - this only needs to be done once
    'name' => 'admin-test1',
    'expression' => '"group1" in user.groups.getName() and "perm1" in user.permissions.getName()',
    'description' => 'See if a user has "permission1" and is in "group1"'

// Now, we need to evaluate the user against the policy
if (Gatekeeper::evaluatePolicy('admin-test1', $user) === true) {
    echo 'They have the permission! Rock on!';


It’s a little more verbose than the previous example, but you can see how it would fetch the permissions and groups for the user and check it against the set of names. In this case the getName function is a magic method that filters the collection and returns a set of the name property values as an array. This way it can be used with the incheck. Once the policy is in place, then any time you need to perform that evaluation, all you need to do is call the evaluatePolicy method with the information and it will always execute the same logic making it super portable and DRY.

I also mentioned how it helps with changing requirements. All you’d need to do here is change the policy contents (the expression string) and all of the code already in place will now evaluate with that new logic with no code changes required. Easy, huh?

I hope this functionality will be useful if you’re a Gatekeeper user or, if you’re not, may give you a reason to check it out. I’m also interested to hear if you think this might make for a good stand-alone component, abstracted out from the Gatekeeper system. It’s integrated right now because of the known model/relationship structure but it’s not hard to pull it out and make it abstract enough to use for other systems.

PHP, Security & PSR-9/PSR-10

Late yesterday afternoon the PSR-9 and PSR-10 drafts were moved into master on the php-fig/standards repository, moving them along to the next step and to get the wider perspective of the main PHP-FIG group’s opinions on it.

What are PSR-9 and PSR-10, you ask? Here’s a brief summary so far:

At the end of last year (2014) Lukas Smith made a proposal to the PHP-FIG group for a standard that would make reporting security issues with PHP projects and libraries a much more structured thing. The general idea is that a standardized document (or documents?) in a project’s repository would provide information about current and past security issues in a well-defined structure that could have some automated tooling around it. Much discussion was had around what the proposal actually entailed and how it would integrate with the goals of the PHP-FIG process. As work progressed on it, a few others besides Lukas came on-board to help flesh out the standard and work out the kinks, including myself.

It wasn’t long before we realized that, while having a standardized method for reporting vulnerabilities was good there also needed to be a way to discover this documentation for a given project (more than just a “look for this file” kind of thing). So, the original PSR-9 was split, giving us the security advisory reporting standard (PSR-9) and the security disclosure workflow (PSR-10) to make discovery of the reports easier. Both PSRs have received the votes needed for entrance and consideration and, as I mentioned, work is moving forward on them in the wider PHP-FIG group.

So, what are the standards? Well, I’m not going to just copy and paste from the documents (you can find those here if you’re interested) but I will give a quick overview of what they contain and their goals.

Note: these standards are by no means complete so this information is a bit subject to change. I just wanted to share their current state though.


The main goal of the PSR-9 standard is to provide structure around the documentation a project provides to the wider community around security vulnerabilities that have been found (and fixed) and those that are still pending. The idea is that any given user could look at the document and have a security-centric view into where the project currently stands. Right now, with the exception of those participating in the security-advisories database, most projects make it a bit of a run around to try to figure out what issues have come up and what problems have been fixed. Sometimes it’s reported in the Changelog, other times it’s in the mailing lists and other times you just have to know what to search for in the project’s issue tracker to get the list. This PSR-9 aims to eliminate a lot of this hassle and give a single source for the information.

The security-advisories database has provided a great start around this same kind of information but with PSR-9 the burden of reporting this information falls on the project, not a single source. We’re not aiming to replace that database by any means, though. We just want to empower the projects to share the information in a vetted, well-defined way. The PSR-9 proposal provides a lot more context around the security issues too.

This information includes:

  • An entry for each vulnerability that includes a short summary, published date, link to more information and a unique reference ID
  • CWE and/or CVE information, if possible (not all vulnerabilities are reported as CVEs)
  • What versions the issue affects
  • Current status of the issue
  • A description of the remediation if resolved
  • A low/medium/high severity rating based on the impact to the project’s users

We discussed the versioning of this resource (multiple files) so new vulnerabilities could be added and a “history” of sorts could be tracked over time but nixed that idea in favor of a single file that would just evolve over time. A lot of this vulnerability metadata is similar to information currently reported by other projects, so it’s not too far of a stretch to see this dropped into a structured, easy to find document. Speaking of which, this brings me to the next proposal…


Where PSR-9 is about the structured vulnerability list, PSR-10 is about the discovery of said document. As we worked through the original PSR-9 ideas, we found that reporting the vulnerabilities was one thing and having a structured way to access the documentation was another. One is more about the concrete thing, the document, and the other is more around process.

The PSR-10 proposal isn’t quite as fleshed out at the moment, but there are a few main points that give us a starting place:

  • The document that represents the data for a project’s PSR-9 disclosure should live somewhere the project can directly reference it, such as the project’s website or other documentation page. This is the ideal place as it removes ambiguity around which version of the document is the “master”.
  • Projects may opt to have the source in their version control system with the caveat that it should be publicly facing (not require a checkout) and that the “master” branch should be visibly documented.
  • Projects would be allowed to split up the information by the version number of the release but, as this can get much more confusing quickly, it would need to be well documented

We discussed just having the document in the version controlled repository of the project, but this leads to other issues including the definition of which branch is the “master” for the document and how to deal with private repositories (remember, the goal is public disclosure). Ultimately is was worked out that a public-facing resource was the best option. One suggestion includes a custom “link” tag with a relation value of “php-vuln-disclosures” to help with automated discovery.

We’re all excited about these two standards moving forward and look forward to the feedback the wider PHP-FIG group can provide around them. Things will be developing a bit more quickly now (it was slow going mainly because of holidays and other personal issues around the end of the year) and our hopes are that these two standards can evolve and be worked out as soon as possible.

Keep an eye on the proposals as they evolve. I’d love to get any feedback on them or suggestions based on your own experiences that would help make things even better.

Speaking at AppSec USA 2015

It’s always good to step outside of your usual bubble and try something new every once and a while. I recently took this step and submitted for the AppSec USA 2015 conference happening in San Francisco on September. My topic? PHP security, naturally but it’s to a much more diverse audience. At PHP conferences its easy to take a lot of things for granted. You’re able to assume that most of the people in the room are developers and understand what PHP’s all about and have at least a little experience with it. At AppSec I don’t really have that guarantee so it’ll be interesting to see how it turns out.

Here’s my prospectus for those that are interested:

PHP Security, Redefined

Let’s be honest, PHP has had a rocky history with security. Over the years the language has been highly criticized for it’s lack of a focus on security and secure development practices. In more recent years, however, a resurgence has happened in the language and community, bringing secure development back into focus. With PHP 7 on the horizon, the language is making even more strides to improve some of its wayward ways of the past and reinvent itself. I’ll share practical code examples, tools, libraries and best practices that are making it easier than ever to keep PHP applications safe.

Come along with me as I guide you through both the language improvements and community encouragement making PHP a more secure place.

I’m hoping that, while the talk is more specifically about PHP security, that it will also be a good platform to help some in the information security community shatter some of their own misconceptions about PHP (ones that are probably stuck in the late PHP 4 to early PHP 5 days). I’m excited to get to talk about PHP7 too which, if all goes well, should be in its final stages by the time the conference rolls around in September.

When I got the acceptance email, I felt that same feeling down in the pit of my stomach I felt when I first was accepted to php[tek] so many years ago. Now it’s a good feeling, though – one that’s more excitement than worry, more encouragement than stress.

Social Security

Let me preface this by saying I think that sharing knowledge and experiences is a great thing. I love that there’s so many tutorials out there from people showing good practices in security and things they’ve learned along the way. Unfortunately, this is the same place where I see a major downfall. This kind of “social security” is a problem and it needs fixing so secure application development can really thrive.

Technology is great, especially PHP. Sure, there’ll be haters out there and they’ll throw stones at the glass house that is PHP hoping to break down the walls and push it off away from the public eye and into the “Not A Real Language” world. Fortunately, this will never happen especially with more recent improvements to the language and its consistent popularity among web developers. PHP is both easy to pick up but difficult to master, especially when it comes to the security of the applications written with it. Along with this low barrier for entry comes people sharing things either in tutorials or just articles that they’ve found to be useful or think is a good practice. The web is littered with articles like these, some being a bit more factual than others. *This is where the real problem is.*

Well-meaning developers post tutorials about things like preventing XSS with just htmlspecialchars or only fixing SQL injection with prepared statements and bound parameters. While these are good practices in themselves, they’re not the only thing that needs to be done to prevent these issues. Security is a complicated subject and there’s no one answer to any problem. Usually a robust solution involves multiple layers (defense in depth anyone?) to ensure the problem doesn’t pop up again or in another location. Even worse are the numerous older articles posted around the internet that have bad or old information. Sadly I see some of these that are *years* old being recommended as good resources to learn from.

I see two kinds of resources out there:

  • Those that are posts from individuals or groups and are wholly maintained by them
  • community resources such as the OWASP wiki

I’ve done some picking on OWASP in the past about the quality of their PHP materials and what seems to be their general feel around PHP and PHP-centric security. This time, though, I don’t want to talk as much about their content itself but about the process they follow for generating that content.

I appreciate what OWASP is going for application security, I really do, but I think the “everyone can edit” mentality of their content is very flawed. I know it’s just not feasible for a single organization largely made up of volunteers to manage and audit all of the content on their site. I get that, I really do, but when I see people referring to PHP resources that haven’t been updated since 2006 or 2007 it makes me cringe. And, because of the visibility of the group, those are the resources people find and recommend not knowing any different.

I think this is the crux of my opinion – having resources where anyone can contribute and not auditing those resources is a “Bad Thing” in my book. Unfortunately, in the case of the masses of tutorials posted out on the web, there’s not much that can be done about that. Those are there to stay and search engines will continue to ensure they show in results regardless of their quality or relevance to the current state of things.

I’m not saying I want people to stop contributing here, I just think there needs to be a balance. There’s a lot of regurgitation of the same kinds of advice out there (“let’s rehash the Top 10 again…”) but there’s also a lot of more innovative content that gets deeper into PHP security matters beyond just the prevention of the most common issues. In my experience, PHP developers are becoming more and more savvy about the security of their applications (even if it is a “negative deliverable” so to speak) and require tips and techniques beyond these simple ten point checklists.

Unfortunately, there’s just not a good answer here. As long as the web continues to be a free for all in terms of posting content developers will keep posting the same things or they’ll post bad suggestions (or ones that just don’t make any sense). The only thing I can think to do is to offer advice to those doing research or reading through PHP security content to ensure they’re getting the best information they can:

  1. Check the article date. If it’s older than 9-12 months, close the tab and move on. That’s not content you need to be reading.
  2. If the content talks about “preventing the most common vulnerabilities” in PHP applications, chances are it’s just another Top 10 article. If you know those already, skip it.
  3. Favor articles with links from things other than search engine results. If you come across an article from a recommendation on another non-linkbait site chances are the content is at least mildly useful.
  4. Consider the source. Do a little research on the author, if they don’t have much of a presence on the web around PHP-related things either take the advice with a large grain of salt or move on.
  5. Look for things that are well-written. Chances are if something is easy to understand or provides plenty of technical detail (and less hand waving “do this not that”) you’ve found something worth reading through.

These are just guidelines, obviously. Ultimately it’s up to your best judgement and research skills to determine the validity of the content and if it applies to your situation.