The last couple posts have been around authorization, the act of determining if a given identity has access to a resource. We covered usage of role based access controls, as well as middleware that uses an RBAC.

In this post, we'll explore another option provided by Zend Framework, zend-permissions-acl, which implements Access Control Lists (ACL).

This post will follow the same basic format as the one covering zend-permissions-rbac, using the same basic examples.

Installing zend-permissions-acl

Just as you would any of our components, install zend-permissions-acl via Composer:

$ composer require zendframework/zend-permissions-acl

The component has no requirements at this time other than a PHP version of at least 5.5.


In ACL systems, we have three concepts:

  • a resource is something to which we control access.
  • a role is something that will request access to a resource.
  • Each resource has privileges for which access will be requested to specific roles.

As an example, an author might request to create (privilege) a blog post (resource); later, an editor (role) might request to edit (privilege) a blog post (resource).

The chief difference to RBAC is that RBAC essentially combines the resource and privilege into a single item. By separating them, you can create a set of discrete permissions for your entire application, and then create roles with multiple-inheritance in order to implement fine-grained permissions.


An ACL is created by instantiating the Acl class:

use Zend\Permissions\Acl\Acl;

$acl = new Acl();

Once that instance is available, we can start adding roles, resources, and privileges.

For this blog post, our ACL will be used for a content-based website.


Roles are added via the $acl->addRole() method. This method takes either a string role name, or a Zend\Permissions\Acl\Role\RoleInterface instance.

Let's start with a "guest" role, that only allows "read" permissions.

use Zend\Permissions\Acl\Role\GenericRole as Role;

// Create some roles
$guest = new Role('guest');

// OR

Referencing roles and resources

Roles are simply strings. We model them as objects in zend-permissions-acl in order to provide strong typing, but the only requirement is that they return a string role name. As such, when creating permissions, you can use either a role instance, or the equivalent name.

The same is true for resources, which we cover in a later section.

By default, zend-permissions-acl implements a whitelist approach. A whitelist denies access to everything unless it is explicitly whitelisted. (This is as opposed to a blacklist, where access is allowed to everything unless it is in the blacklist.) Unless you really know what you're doing we do not suggest toggling this; whitelists are widely regarded as a best practice for security.

What that means is that, out of the gate, while we can do some privilege assertions:

$acl->isAllowed('guest', 'blog', 'read');
$acl->isAllowed('guest', 'blog', 'write');

these will always return false, denying access. So, we need to start adding privileges.


Privileges are assigned using $acl->allow().

For the guest role, we'll allow the read privilege on any resource:

$acl->allow('guest', null, 'read');

The second argument to allow() is the resource (or resources); specifying null indicates the privilege applies to all resources. If we re-run the above assertions, we get the following:

$acl->isAllowed('guest', 'blog', 'read');  // true
$acl->isAllowed('guest', 'blog', 'write'); // false

Unknown roles or resources

One thing to note: if either the role or resource used with isAllowed() does not exist, this method raises an exception, specifically a Zend\Permissions\Acl\Exception\InvalidArgumentException, indicating the role or resource could not be found.

In many situations, this may not be what you want; you may want to handle non-existent roles and/or resources gracefully. You could do this in a couple ways. First, you can test to see if the role or resource exists before you check the permissions, using hasRole() and/or hasResource():

if (! $acl->hasRole($foo)) {
    // failed, due to missing role
if (! $acl->hasResource($bar)) {
    // failed, due to missing resource
if (! $acl->isAllowed($foo, $bar, $privilege)) {
    // failed, due to invalid privilege

Alternately, wrap the isAllowed() call in a try/catch block:

try {
    if (! $acl->isAllowed($foo, $bar, $privilege)) {
        // failed, due to missing privileges
} catch (AclInvalidArgumentException $e) {
      // failed, due to missing role or resource

Personally, I don't like to use exceptions for application flow, so I recommend the first solution. That said, in most cases, you will be working with a role instance that you've just added to the ACL, and should only perform assertions against known resources.


Now let's add some actual resources. These are almost exactly like roles in terms of usage: you create a ResourceInterface instance to pass to the ACL, or, more simply, a string; resources are added via the $acl->addResource() method.

use Zend\Permissions\Acl\Resource\GenericResource as Resource;

$resource = new Resource('blog');

// OR:

A resource is anything to which you want to apply permissions. In the remaining examples of this post, we'll use a "blog" as the resource, and provide a variety of permissions related to it.


Let's say we want to build on our previous examples, and create an "editor" role that also incorporates the permissions of the "guest" role, and adds a "write" permission to the "blog" resource.

Unlike RBAC, roles themselves contain no information about inheritance; instead, the ACL takes care of that when you add the role to the ACL:

$editor = new Role('editor');
$acl->addRole($editor, $guest); // OR:
$acl->addRole($editor, 'guest');

The above creates a new role, editor, which inherits the permissions of our guest role. Now, let's add a privilege allowing editors to write to our blog:

$acl->allow('editor', 'blog', 'write');

With this in place, let's do some assertions:

$acl->isAllowed('editor', 'blog', 'write'); // true
$acl->isAllowed('editor', 'blog', 'read');  // true
$acl->isAllowed('guest',  'blog', 'write'); // false

Another role might be a "reviewer" who can "moderate" content:

$acl->addRole('reviewer', 'guest');
$acl->allow('reviewer', 'blog', 'moderate');

$acl->isAllowed('reviewer', 'blog', 'moderate'); // true
$acl->isAllowed('reviewer', 'blog', 'write');    // false; editor only!
$acl->isAllowed('reviewer', 'blog', 'read');     // true
$acl->isAllowed('guest',    'blog', 'moderate'); // false

Let's create another, an "admin" who can do all of the above, but also has permissions for "settings":

$acl->addRole('admin', ['guest', 'editor', 'reviewer']);
$acl->allow('admin', 'blog', 'settings');

$acl->isAllowed('admin',    'blog', 'settings'); // true
$acl->isAllowed('admin',    'blog', 'write');    // true
$acl->isAllowed('admin',    'blog', 'moderate'); // true
$acl->isAllowed('admin',    'blog', 'read');     // true
$acl->isAllowed('editor',   'blog', 'settings'); // false
$acl->isAllowed('reviewer', 'blog', 'settings'); // false
$acl->isAllowed('guest',    'blog', 'write');    // false

Note that the addRole() call here provides an array of roles as the second value this time; when called this way, the new role will inherit the privileges of every role listed; this allows for multiple-inheritance at the role level.

Resource inheritance

Resource inheritance works exactly the same as Role inheritance! Add one or more parent resources when calling addResource() on the ACL, and any privileges assigned to that parent resource will also apply to the new resource.

As an example, I could have a "news" section in my website that has the same privilege and role schema as my blog:

$acl->addResource('news', 'blog');

Fun with privileges!

Privileges are assigned using allow(). Interestingly, like addRole() and addResource(), the role and resource arguments presented may be arrays of each; in fact, so can the privileges themselves!

As an example, we could do the following:

    ['reviewer', 'editor'],
    ['blog', 'homepage'],
    ['write', 'maintenance']

This would assign the "write" and "maintenance" privileges on each of the "blog" and "homepage" resources to the "reviewer" and "editor" roles! Due to inheritance, the "admin" role would also gain these privileges.

Creating your ACL

When should you create your ACL, exactly? And should it contain all roles and permissions?

Typically, you will create a finite number of application or domain permissions. In our above examples, we could omit the blog resource and apply the ACL only within the blog domain (for example, only within a module of a zend-mvc or Expressive application); alternately, it could be an application-wide ACL, with resources segregated by specific domain within the application.

In either case, you will generally:

  • Create a finite set of well-known roles, resources, and privileges as a global or per-domain ACL.
  • Create a custom role for the current user, typically inheriting from the set of well-known roles.
  • Validate the current user against the ACL.

Unlike RBAC, you typically will not add custom permissions for a user. The reason for this is due to the complexity of storing the combination of roles, resources, and privileges in a database. Storing roles is trivial:

user_id fullname roles
mario Mario editor,reviewer

You could then create the role by splitting the roles field and assigning each as parents:

$acl->addRole($user->getId(), explode(',', $user->getRoles());

However, for fine-grained permissions, you would essentially need an additional lookup table mapping the user to a resource and list of privileges:

user_id resource privileges
mario blog update,delete
mario news update

While it can be done, it's resource and code intensive.

Putting it all together, let's say the user "mario" has logged in, with the role "editor"; further, let's assume that the identity instance for our user implements RoleInterface. If our ACL is already populated per the above examples, I might do the following:

$acl->addRole($mario, $mario->getRoles());

$acl->isAllowed($mario, 'blog', 'settings'); // false; admin only!
$acl->isAllowed($mario, 'blog', 'write');    // true; all editors
$acl->isAllowed($mario, 'blog', 'read');     // true; all guests

Now, let's say we've gone to the work of creating the join table necessary for storing user ACL information; we might have something like the following to further populate the ACL:

foreach ($mario->getPrivileges() as $resource => $privileges) {
    $acl->allow($mario, $resource, explode(',', $privileges));

We could then do the following assertions:

$acl->isAllowed($mario,   'blog', 'update'); // true
$acl->isAllowed('editor', 'blog', 'update'); // false; mario only!
$acl->isAllowed($mario,   'blog', 'delete'); // true
$acl->isAllowed('editor', 'blog', 'delete'); // false; mario only!

Custom assertions

Fine-grained as the privilege system can be, sometimes it's not enough.

As an example, we may want to implement a rule that the creator of a content item in our website always has rights to edit the item. How would we implement that with the above system?

zend-permissions-acl allows you to do so via dynamic assertions. Such assertions are classes that implement Zend\Permissions\Acl\Assertion\AssertionInterface, which defines a single method:

namespace Zend\Permissions\Assertion;

use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Resource\ResourceInterface;
use Zend\Permissions\Acl\Role\RoleInterface;

interface AssertionInterface
     * @return bool
    public function assert(
        Acl $acl,
        RoleInterface $role = null,
        ResourceInterface $resource = null,
        $privilege = null

For the sake of this example, let's assume:

  • We cast our identity to a RoleInterface instance after retrieval.
  • The content item is represented as an object.
  • The object has a method getCreatorUsername() that will return the same username as we might have in our custom identity from the previous example.
  • If the username is the same as the custom identity, allow any privileges.

Because we have PHP 7 at our disposal, we'll create the assertion as an anonymous class:

use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Assertion\AssertionInterface;
use Zend\Permissions\Acl\Resource\ResourceInterface;
use Zend\Permissions\Acl\Role\RoleInterface;

$assertion = new class ($identity, $content) implements AssertionInterface {
    private $content;
    private $identity;

    public function __construct(RoleInterface $identity, $content)
        $this->identity = $identity;
        $this->content = $content;

     * @return bool
    public function assert(
        Acl $acl,
        RoleInterface $role = null,
        ResourceInterface $resource = null,
        $privilege = null
    ) {
        if (null === $role || $role->getRoleId() !== $this->identity->getRoleId()) {
            return false;

        if (null === $resource || 'blog' !== $resource->getResourceId()) {
            return false;

        return $this->identity->getRoleId() === $this->content->getCreatorUsername();

// Attach the assertion to all roles on the blog resource;
// custom assertions are provided as a fourth argument to allow().
$acl->allow(null, 'blog', null, $assertion);

$acl->isAllowed('mario', 'blog', 'edit'); // returns true if $mario created $content

The above creates a new assertion that will trigger for the "blog" resource when a privilege we do not already know about is queried. In that particular case, if the creator of our content is the same as the current user, it will return true, allowing access!

By creating such assertions in-place with data retrieved at runtime, you can achieve an incredible amount of flexibility for your ACLs.

Wrapping up

zend-permissions-acl provides a huge amount of power, and the ability to provide both role and resource inheritance can vastly simplify setup of complex ACLs. Additionally, the privilege system provides much-needed granularity.

If you wanted to use ACLs in middleware, the usage is quite similar to zend-permissions-rbac: inject your ACL instance in your middleware, retrieve your user identity (and thus role) from the request, and perform queries against the ACL using the current middleware or route as a resource, and either the HTTP method or the domain action you will perform as the privilege.

The main difficulty with zend-permissions-acl is that there is no 1:1 relationship between a role and a privilege, which makes storing ACL information in a database more complex. If you find yourself struggling with that fact, you may want to use RBAC instead.

Hopefully these last few posts provide you with the information you need to start adding authentication and authorization to any PHP application you're writing!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.


In a previous post, we demonstrated how to authenticate a middleware application in PHP. In this post we will continue the discussion, showing how to manage authorizations.

We will start from an authenticated user and demonstrate how to allow or disable actions for specific users. We will collect users by groups and we will use a Role-Based Access Control (RBAC) system to manage the authorizations.

To implement RBAC, we will consume zendframework/zend-permissions-rbac.

If you are not familiar with RBAC and the usage of zend-permissions-rbac, you can read our previous blog post on the subject.

Getting started

This article assumes you have already created the Auth module, as described in our previous post on authentication. For the purposes of our application, we'll create a new module, Permission, in which we'll put our classes, middleware, and general configuration.

First, if you have not already, install the tooling support:

$ composer require --dev zendframework/zend-expressive-tooling

Next, we'll create the Permission module:

$ ./vendor/bin/expressive module:create Permission

With that out of the way, we can get started.


As already mentioned, we will reuse the Auth module created in our previous post. We will reuse the Auth\Action\AuthAction::class to get the authenticated user's data.


In order to manage authorization, we will use a RBAC system using the user's role. A user's role is a string that represents the permission level; as an example, the role administrator might provide access to all permissions.

In our scenario, we want to allow or disable access of specific routes to a role or set of roles. Each route represents a permission in RBAC terminology.

We can use zendframework/zend-permissions-rbac to manage the RBAC system using a PHP configuration file storing the list of roles and permissions. Using zend-permissions-rbac, we can also manage permissions inheritance.

For instance, imagine implementing a blog application; we might define the following roles:

  • administrator
  • editor
  • contributor

A contributor can create, edit, and delete only the posts created by theirself. The editor can create, edit, and delete all posts and publish posts (that means enabling public view of a post in the web site). The administrator can perform all actions, including changing the blog's configuration.

This is a perfect use case for using permission inheritance. In fact, the administrator role would inherit the permissions of the editor, and the editor role inherits the permissions of the contributor.

To manage the previous scenario, we can use the following configuration file:

// In src/Permission/config/rbac.php:

return [
    'roles' => [
        'administrator' => [],
        'editor'        => ['admin'],
        'contributor'   => ['editor'],
    'permissions' => [
        'contributor' => [
        'editor' => [
        'administrator' => [

In this file we have specified 3 roles, including the inheritance relationship using an array of role names. The parent of administator is an empty array, meaning no parents.

The permissions are configured using the permissions key. Each role has the list of permissions, specified with an array of route names.

All the roles can access the route admin.dashboard and admin.posts. The editor role can also access admin.publish. The administrator can access all the roles of contributor and editor. Moreover, only the administrator can access the admin.settings route.

We used the route names as RBAC permissions because in this way we can allow URL and HTTP methods using a single resource name. Moreover, in Expressive we have a config/routes.php file containing all the routes and we can easily use it to add authorization, as we did for authentication.

Authorization middleware

Now that we have the RBAC configuration in place, we can create a middleware that performs the user authorization verifications.

We can create an AuthorizationAction middleware in our Permission module as follows:

// in src/Permission/src/Action/AuthorizationAction.php:

namespace Permission\Action;

use Auth\Action\AuthAction;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as MiddlewareInterface;
use Permission\Entity\Post as PostEntity;
use Permission\Service\PostService;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Expressive\Router\RouteResult;
use Zend\Permissions\Rbac\AssertionInterface;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\RoleInterface;

class AuthorizationAction implements MiddlewareInterface
    private $rbac;
    private $postService;

    public function __construct(Rbac $rbac, PostService $postService)
        $this->rbac        = $rbac;
        $this->postService = $postService;

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
        $user = $request->getAttribute(AuthAction::class, false);
        if (false === $user) {
            return new EmptyResponse(401);

        // if a post attribute is present and user is contributor
        $postUrl = $request->getAttribute('post', false);
        if (false !== $postUrl && $user['role'] === 'contributor') {
            $post = $this->postService->getPost($postUrl);
            $assert = new class ($user['username'], $post) implements AssertionInterface {
                private $post;
                private $username;

                public function __construct(string $username, PostEntity $post)
                    $this->username = $username;
                    $this->post     = $post;

                public function assert(Rbac $rbac)
                    return $this->username === $this->post->getAuthor();

        $route     = $request->getAttribute(RouteResult::class);
        $routeName = $route->getMatchedRoute()->getName();
        if (! $this->rbac->isGranted($user['role'], $routeName, $assert ?? null)) {
            return new EmptyResponse(403);

        return $delegate->process($request);

If the user is not present, the AuthAction::class attribute will be false. In this case we are returning a 401 error, indicating we have an unauthenticated user, and halting execution.

If a user is returned from AuthAction::class attribute, this means that we have an authenticated user.

The authentication is performed by the Auth\Action\AuthAction class that stores the AuthAction::class attribute in the request. See the previous post for more information.

This middleware performs the authorization check using isGranted($role, $permission) where $role is the user's role ($user['role']) and $permission is the route name, retrieved by the RouteResult::class attribute. If the role is granted, we continue the execution flow with the delegate middleware. Otherwise, we stop the execution with a 403 error, indicating lack of authorization.

We manage also the case when the user is a contributor and there is a post attribute in the request (e.g. /admin/posts/{post}). That means someone is performing some action on a specific post. To perform this action, we require that the owner of the post should be the same as the authenticated user.

This will prevent a contributor to change the content of a post if he/she is not the author. We managed this special case using a dynamic assertion, built using an anonymous class; it checks if the authenticated username is the same of the author's post. We used a general PostEntity class with a getAuthor() function.

In order to retrieve for the route name, we used the RouteResult::class attribute provided by Expressive. This attribute facilitates access to the matched route.

The AuthorizationAction middleware requires the Rbac and the PostService dependencies. The first is an instance of Zend\Permissions\Rbac\Rbac and the second is a general service to manage blog posts, i.e. a class that performs some lookup to retrieve the post data from a database.

To inject these dependencies, we use an AuthorizationFactory like the following:

namespace Permission\Action;

use Interop\Container\ContainerInterface;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\Role;
use Permission\Service\PostService;
use Exception;

class AuthorizationFactory
    public function __invoke(ContainerInterface $container)
        $config = $container->get('config');
        if (! isset($config['rbac']['roles'])) {
            throw new Exception('Rbac roles are not configured');
        if (!isset($config['rbac']['permissions'])) {
            throw new Exception('Rbac permissions are not configured');

        $rbac = new Rbac();

        // roles and parents
        foreach ($config['rbac']['roles'] as $role => $parents) {
            $rbac->addRole($role, $parents);

        // permissions
        foreach ($config['rbac']['permissions'] as $role => $permissions) {
            foreach ($permissions as $perm) {
        $post = $container->get(PostService::class);

        return new AuthorizationAction($rbac, $post);

This factory class builds the Rbac object using the configuration file stored in src/Permission/config/rbac.php. We read all the roles and the permissions following the order in the array. It is important to enable the creation of missing roles in the Rbac object using the function setCreateMissingRoles(true). This is required to be sure to create all the roles even if we add it out of order. For instance, without this setting, the following configuration will throw an exception:

return [
    'roles' => [
        'contributor'   => ['editor'],
        'editor'        => ['administrator'],
        'administrator' => []

because the editor and the administrator roles are specified as parents of other roles before they were created.

Finally, we can configure the Permission module adding the following dependencies:

// In src/Permission/src/ConfigProvider.php:

// Update the following methods:
public function __invoke()
    return [
        'dependencies' => $this->getDependencies(),
        'rbac'         => include __DIR__ . '/../config/rbac.php',

public function getDependencies()
    return [
        'factories' => [
            Service\PostService::class => Service\PostFactory::class,
            Action\AuthorizationAction::class => Action\AuthorizationFactory::class,

Configure the route for authorization

To enable authorization on a specific route, we need to add the Permission\Action\AuthorizationAction middleware in the route, as follows:

$app->get('/admin/dashboard', [
], 'admin.dashboard');

This is an example of the GET /admin/dashboard route with admin.dashboard as the name. We add AuthAction and AuthorizationAction before execution of the DashboardAction. The order of the middleware array is important; authentication must happen first, and authorization must happen before executing the dashboard middleware.

Add the AuthorizationAction middleware to all routes requiring authorization.


This article, together with the one related to the authentication middleware, demonstrates how to accomodate authentication and authorization within middleware in PHP.

We showed how to create two separate Expressive modules, Auth and Permission, to provide authentication and authorization using zend-authentication and zend-permissions-rbac.

We showed also the usage of a dynamic assertion for specific permissions based on the role and username of an authenticated user.

The blog use case proposed in this article is quite simple, but the architecture used can be applied also in complex scenario, to manage permissions based on different requirements.

In the future we will talk again about authentication and authorization, since this is a very important aspect of web applications.

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.


ZF2016-04: Potential remote code execution in zend-mail via Sendmail adapter

When using the zend-mail component to send email via the Zend\Mail\Transport\Sendmail transport, a malicious user may be able to inject arbitrary parameters to the system sendmail program. The attack is performed by providing additional quote characters within an address; when unsanitized, they can be interpreted as additional command line arguments, leading to the vulnerability.

The following example demonstrates injecting additional parameters to the sendmail binary via the From address:

use Zend\Mail;

$mail = new Mail\Message();
$mail->setBody('This is the text of the email.');

// inject additional parameters to sendmail command line
$mail->setFrom('"AAA\" params injection"@domain', 'Sender\'s name');

$mail->addTo('hacker@localhost', 'Name of recipient');

$transport = new Mail\Transport\Sendmail();

The attack works because zend-mail filters the email addresses using the RFC 3696 specification, where the string "AAA\" params injection"@domain is considered a valid address. This validation is provided using the zend-validator component with the following parameters:

    Zend\Validator\Hostname::ALLOW_DNS | Zend\Validator\Hostname::ALLOW_LOCAL

The above accepts local domain with any string specified by double quotes as the local part. While this is valid per RFC 3696, due to the fact that sender email addresses are provided to the sendmail binary via the command line, they create the vulnerability described above.

Action Taken

To fix the issue, we added a transport-specific email filter for the From header in the Sendmail transport adapter. The filter checks for the sequence \" in the local part of the email From address.

$from = $headers->get('From');
if ($from) {
    foreach ($from->getAddressList() as $address) {
        if (preg_match('/\\\"/', $address->getEmail())) {
            throw new Exception\RuntimeException("Potential code injection in From header");

The patch resolving the vulnerability is available in:

  • zend-mail, starting in version 2.7.2
  • zend-mail, 2.4.11
  • Zend Framework, 2.4.11

Zend Framework 2.5 and 3.0 versions will receive the update automatically, as executing composer update in proejcts using these versions will update to zend-mail 2.7.2+.


The Zend Framework team thanks the following for identifying the issues and working with us to help protect its users:

  • The independent security researcher Dawid Golunski, who reported the vulnerability to Beyond Security’s SecuriTeam Secure Disclosure program;
  • Enrico Zimuel, who provided the patch.


The Zend Framework community is pleased to announce the immediate availability of Zend Framework 1.12.20! Packages and installation instructions are available at:


This release includes a single security patch, reported as ZF2016-03, for SQL injection vulnerabilities in the Zend_Db_Select::order() and Zend_Db_Select::group() methods. If you use these, we recommend updating immedaitely.

To see the complete set of issues resolved for 1.12.20, please visit the changelog:

End of Life

As announced previously, Zend Framework 1 will reach its end of life on 28 September 2016, and only receive security fixes between now and that date. Past that point, we will offer custom bug and security fixes for Zend Framework 1 on-demand only to Enterprise users of Zend Server.

Thank You!

Many thanks to Enrico Zimuel for his efforts in developing the security patch for this release!


ZF2016-03: Potential SQL injection in ORDER and GROUP functions of ZF1

The implementation of ORDER BY and GROUP BY in Zend_Db_Select remained prone to SQL injection when a combination of SQL expressions and comments were used. This security patch provides a comprehensive solution that identifies and removes comments prior to checking validity of the statement to ensure no SQLi vectors occur.

The implementation of ORDER BY and GROUP BY in Zend_Db_Select of ZF1 is vulnerable by the following SQL injection:

$db = Zend_Db::factory(/* options here */);
$select = new Zend_Db_Select($db);
$select->order("MD5(\"a(\");DELETE FROM p2; #)"); // same with group()

The above $select will render the following SQL statement:


instead of the correct one:

SELECT "p".* FROM "p" ORDER BY "MD5(""a("");DELETE FROM p2; #)" ASC

This security fix can be considered an improvement of the previous ZF2016-02 and ZF2014-04 advisories.

As a final consideration, we recommend developers either never use user input for these operations, or filter user input thoroughly prior to invoking Zend_Db. You can use the Zend_Db_Select::quoteInto() method to filter the input data, as shown in this example:

$db    = Zend_Db::factory(...);
$input = "MD5(\"a(\");DELETE FROM p2; #)"; // user input can be an attack
$order = $db->quoteInto("SQL statement for ORDER", $input);

$select = new Zend_Db_Select($db);
$select->order($order); // same with group()

Action Taken

We fixed the reported SQL injection by removing comments from the SQL statement before passing it to either the order() or group() methods; this patch effectively solves any comment-based SQLi vectors.

We used the following regex to remove comments from a SQL statement:

    (([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
    |(                   # $3 : Match comments
        (?:\#|--).*?$    # - Single line comments
        |                # - Multi line (nested) comments
         /\*             #   . comment open marker
            (?: [^/*]    #   . non comment-marker characters
                |/(?!\*) #   . ! not a comment open
                |\*(?!/) #   . ! not a comment close
                |(?R)    #   . recursive case
            )*           #   . repeat eventually
        \*\/             #   . comment close marker
    )\s*                 # Trim after comments
    |(?<=;)\s+           # Trim after semi-colon

The patch is available starting in Zend Framework 1.12.20.

Other Information

This SQL injection attack does not affect Zend Framework 2 and 3 versions because the implementations of Zend\Db\Sql\Select::order() and Zend\Db\Sql\Select::group() do not manage parenthetical expressions.


The Zend Framework team thanks the following for identifying the issues and working with us to help protect its users:

  • Hiroshi Tokumaru (HASH Consulting Corp.), who discovered the issue;
  • Masanobu Katagi (Japan Computer Emergency Response Team Coordination Center), who reported the issue;
  • Enrico Zimuel, who provided the patch.


Recently, we released zend-crypt 3.1.0, the cryptographic component from Zend Framework. This last version includes a hybrid cryptosystem, a feature that can be used to implement end-to-end encryption schema in PHP.

A hybrid cryptosystem is a cryptographic mechanism that uses symmetric encyption (e.g. AES) to encrypt a message, and public-key cryptography (e.g. RSA) to protect the encryption key. This methodology guarantee two advantages: the speed of a symmetric algorithm and the security of public-key cryptography.

Before we talk about the PHP implementation, let's explore the hybrid mechanism in more detail. Below is a diagram demonstrating a hybrid encryption schema:

Encryption schema

A user (the sender) wants to send a protected message to another user (the receiver). He/she generates a random session key (one-time pad) and uses this key with a symmetric algorithm to encrypt the message (in the figure, Block cipher represents an authenticated encryption algorithm). At the same time, the sender encrypts the session key using the public key of the receiver. This operation is done using a public-key algorithm, e.g., RSA. Once the encryption is done, the sender can send the encrypted session key along with the encrypted message to the receiver. The receiver can decrypt the session key using his/her private key, and consequently decrypt the message.

This idea of combining together symmetric and asymmetric (public-key) encryption can be used to implement end-to-end encryption (E2EE). An E2EE is a communication system that encrypts messages exchanged by two users with the property that only the two users can decrypt the message. End-to-end encryption has become quite popular in the last years with the usage in popular software, and particularly messaging systems, such as WhatsApp. More generally, when you have a software used by many users, end-to-end encryption can be used to protect information exchanged by users. Only the users can access (decrypt) exchanged information; even the administrator of the system is not able to access this data.

Build end-to-end encryption in PHP

We want to implement end-to-end encryption for a web application with user authentication. We will use zend-crypt 3.1.0 to implement our cryptographic schemas. This component of Zend Framework uses the OpenSSL extension for PHP for its cryptographic primitives.

The first step is to create public and private keys for each users. Typically, this step can be done when the user credentials are created. To generare the pairs of keys, we can use Zend\Crypt\PublicKey\RsaOptions. Below is an example demonstrating how to generate public and private keys to store in the filesystem:

use Zend\Crypt\PublicKey\RsaOptions;
use Zend\Crypt\BlockCipher;

$username = 'alice';
$password = 'test'; // user's password

// Generate public and private key
$rsaOptions = new RsaOptions();
    'private_key_bits' => 2048
$publicKey  = $rsaOptions->getPublicKey()->toString();
$privateKey = $rsaOptions->getPrivateKey()->toString();

// store the public key in a .pub file
file_put_contents($username . '.pub', $publicKey);

// encrypt and store the private key in a file
$blockCipher = BlockCipher::factory('openssl', array('algo' => 'aes'));
file_put_contents($username, $blockCipher->encrypt($privateKey));

In the above example, we generated a private key of 2048 bits. If you are wondering why not 4096 bits, this is questionable and depends on the real use case. For the majority of applications, 2048 is still a good key size, at least until 2030. If you want more security and you don't care about the additional CPU time, you can increase the key size to 4096. We suggest reading the following blog posts for more information on key key size:

We did not generate the private key using a passphrase; this is because the OpenSSL extension of PHP does not support AEAD (Authenticated Encrypt with Associated Data) mode yet; AEAD mode will be supported starting in PHP 7.1, which should release this autumn.

The default passphrase encryption algorithm for OpenSSL is des-ede3-cbc using PBKDF2 with 2048 iterations for generating the encryption key from the user's password. Even if this encryption algorithm is quite good, the number of iterations of PBKDF2 is not optimal; zend-crypt improves on this in a variety of ways, out-of-the-box. As demonstrated above, we use Zend\Crypt\BlockCipher to encrypt the private key; this class provides encrypt-then-authenticate using the AES-256 algorithm for encryption and HMAC-SHA-256 for authentication. Moreover, BlockCipher uses the PBKDF2 algorithm to derivate the encryption key from the user's key (password). The default number of iterations for PBKDF2 is 5000, and you can increase it using the BlockCipher::setKeyIteration() method.

In the example, we stored the public and private keys in two files named, respectively, $ and $username. Because the private file is encrypted, using the user's password, it can be access only by the user. This is a very important aspect for the security of the entire system (we take for granted that the web application stores the hashes of the user's passwords using a secure algorithm such as bcrypt).

Once we have the public and private keys for the users, we can start using the hybrid cryptosystem provided by zend-crypt. For instance, imagine Alice wants to send an encrypted message to Bob:

use Zend\Crypt\Hybrid;
use Zend\Crypt\BlockCipher;

$sender   = 'alice';
$receiver = 'bob';
$password = 'test'; // bob's password

$msg = sprintf('A secret message from %s!', $sender);

// encrypt the message using the public key of the receiver
$publicKey  = file_get_contents($receiver . '.pub');
$hybrid     = new Hybrid();
$ciphertext = $hybrid->encrypt($msg, $publicKey);

// send the ciphertext to the receiver

// decrypt the private key of bob
$blockCipher = BlockCipher::factory('openssl', ['algo' => 'aes']);
$privateKey = $blockCipher->decrypt(file_get_contents($receiver));

$plaintext = $hybrid->decrypt($ciphertext, $privateKey);

printf("%s\n", $msg === $plaintext ? "The message is: $msg" : 'Error!');

The above example demonstrates encrypting information between two users. Of course, in this case, the sender (Alice) knows the message because she wrote it. More in general, if we need to store a secret between multiple users, we need to specify the public keys to be used for encryption.

The hybrid component of zend-crypt supports encrypting messages for multiple recipients. To do so, pass an array of public keys in the $publicKey parameter of Zend\Crypt\Hybrid::encrypt($data, $publicKey).

Below demonstrates encrypting a file for two users, Alice and Bob.

use Zend\Crypt\Hybrid;
use Zend\Crypt\BlockCipher;

$data    = file_get_contents('path/to/file/to/protect');
$pubKeys = [
  'alice' => file_get_contents(''),
  'bob'   => file_get_contents('')

$hybrid     = new Hybrid();

// Encrypt using the public keys of both alice and bob
$ciphertext = $hybrid->encrypt($data, $pubKeys);

file_put_contents('file.enc', $ciphertext);

$blockCipher = BlockCipher::factory('openssl', ['algo' => 'aes']);

$passwords = [
  'alice' => 'password of Alice',
  'bob'   => 'password of Bob'

// decrypt using the private keys of alice and bob, one at time
foreach ($passwords as $id => $pass) {
  $privateKey = $blockCipher->decrypt(file_get_contents($id));
  $plaintext  = $hybrid->decrypt($ciphertext, $privateKey, null, $id);
  printf("%s for %s\n", $data === $plaintext ? 'Decryption ok' : 'Error', $id);

For decryption, we used a hard coded password for the users. Usually, the user's password is provided during the login process of a web application and should not be stored as permanent data; for instance, the user's password can be saved in a PHP session variable for temporary usage. If you use sessions to save the user's password, ensure that data is protected; the PHP-Secure-Session library or the Suhosin PHP extension will help you do so.

To decrypt the file we used the Zend\Crypt\Hybrid::decrypt() function, where we specified the $privateKey, a null passphrase, and finally the $id of the privateKey. This parameters are necessary to find the correct key to use in the header of the encrypted message.


We are pleased to announce the immediate availability of Apigility 1.4.0!

This is our first minor release in over a year, and our largest, feature-wise, to date!

Zend Framework 3 Support

Six weeks ago, we announce Zend Framework 3 availablility. Our efforts since then have been focused on making all Apigility modules forwards compatible with version 3 releases of Zend Framework components. This touched on every Apigility component, and required the addition of a couple new components as well to help with migration.

This update also means that Apigility has adopted the same minimum supported PHP version as Zend Framework itself: 5.6. If you are using an earlier version of PHP, we recommend updating as soon as possible, as earlier versions are no longer supported by the PHP project.

The main takeaway to know is: you can upgrade your existing Apigility applications now, and they will continue to work, albeit with a number of bugfixes and new features!

Upgrade script

Additionally, once you've verified your application is working, we have provided a script to update your application to take advantage of Zend Framework v3 components and reduce the overall dependency footprint of your application!

$ ./vendor/bin/apigility-upgrade-to-1.5

(The 1.5 here refers to the internal version of the zf-apigility-admin module, in which this script is defined.)

Once you've run that script, you will be pinned to version 3 Zend Framework component releases, and no longer have a dependency on the full ZF metapackage.

There are other things you can do as well to modernize your application, and we have created a comprehensive migration document for 1.4 detailing the changes.

New Apigility skeleton

We decided to mondernize the Apigility skeleton in the same way that we updated the Zend Framework skeleton application. In particular:

  • Adopting PSR-4 directory structure for the shipped Application module.
  • Providing unit tests for the shipped Application module.
  • Removal of i18n features.
  • Enabling PSR-4 Apigility module structure by default.
  • Enabling usage of short array syntax in Apigility-generated configuration files by default.
  • Enabling usage of ::class notation in Apigility-generated configuration files by default.
  • Usage of zfcampus/zf-asset-manager for asset management by default.
  • Addition of zfcampus/zf-composer-autoloading as a development requirement, to facilitate enabling Composer-based autoloading of your Apigility (or Zend Framework) modules.
  • Addition of zendframework/zend-component-installer, to automate registration of ZF components and modules with Apigility applications.
  • Addition of several Composer scripts for working with development mode, serving your application via the PHP built-in web server, and running QA tools.
  • New vagrant and docker-compose configuration based on Ubuntu 16.04 and PHP 7.

The new skeleton updates Apigility applications to use modern approaches to PHP application structure, and provides better tooling around usage of virtual machines and containers in the development workflow.


This release wraps new releases of every Apigility module. Notable features of these modules include:

  • zf-apigility
    • Support in ZF\Apigility\Application for handling PHP 7 Throwables.
  • zf-apigility-admin
    • Extracts all factories defined in the Module class to their own classes.
    • Extracts all listeners defined in the Module class to their own classes.
    • Adds a patchList() stub to the REST resource class template, so that it is present by default.
    • Adds support for working with modules using PSR-4 directory format, and the ability to generate PSR-4-style modules.
    • Adds a vendor script, apigility-upgrade-to-1.5, for upgrading an existing Apigility application so that it may use Zend Framework component v3 releases.
    • Adds the ability to generate all configuration files using short array syntax and ::class notation.
    • Adds a new API endpoint for reporting the current Apigility skeleton version.
  • zf-apigility-admin-ui
    • Displays the current Apigility skeleton version as returned by the zf-apigility-admin API.
    • Uses full controller service names when interacting with the zf-apigility-admin API; this resolves some lingering UI issues due to version mismatch.
    • Adds a "field type" input to new field entries, allowing you to provide this information via the UI (previously the information could only be provided by manually updating configuration files). This allows communicating field type information to documentation systems such as Swagger.
    • Numerous UI fixes, particularly with regards to sidebar behavior.
  • zf-apigility-documentation
    • Adds support for displaying documentation of APIs in nested PHP namespaces.
    • Adds support for transforming Markdown documentation to HTML, and enables it by default.
    • Displays field types, if provided, by default.
  • zf-apigility-provider
    • Deprecates the Module class. You no longer need to list the ZF\Apigility\Provider module in your application module configuration.
  • zf-configuration
    • Adds a new configuration switch, zf-configuration.class_name_scalars, allowing you to configure whether or not generated configuration will use ::class notation.
  • zf-console
    • Adds the ability to substitute your own dispatcher via the ZF\Console\DispatcherInterface
    • Adds the ability to disable output of the application banner.
    • Adds the ability to compose a container-interop container with the dispatcher, which allows providing service names as console handlers.
    • The exception handler now catches PHP 7 Throwable instances as well.
  • zf-content-validation
    • Adds support for mapping input filters to GET requests. This feature is not yet supported in the admin UI, however.
  • zf-hal
    • Adds an interface, concrete classes, and configuration for allowing alternate "self" and generic link generation strategies. As such, usage of the server url and url helpers with the Hal plugin is now deprecated.
    • Adds service factories for the two link extraction services, allowing the ability to provide alternate facilities if needed.
    • Adds a new method to the Hal plugin, resetEntityHashStack(); this can be used when rendering multiple responses or payloads within the same request cycle to allow re-use of the same entity instances.
  • zf-http-cache
    • Adds ETag support, with configurable hashing.
    • Adds more capabilities aroudn matching routed controllers.
  • zf-oauth2
    • Adds support for the ext/mongodb extension.
    • Adds token revocation suport.

New modules

Two new modules were added to Apigility:

  • zfcampus/zf-asset-manager uses configuration from rwoverdijk/assetmanager to expose asset directories in the document root of your application. It acts as a Composer plugin, and copies configured asset directories under your public/ directory, adding an entry to that directory's .gitignore file to prevent checking those files into version control. Updates to modules are honored, and removal of a module will remove the files from your source tree.
  • zfcampus/zf-composer-autoloading will add an autoloading entry to your Composer configuration for the module you specify, and then update autoloading rules locally. This package can be used with any Zend Framework application!

Doctrine support

At this time, Doctrine support for Apigility has not yet been updated. Contributors and collaborators are working with the Doctrine team to ensure the various Zend Framework modules they maintain are updated to work with Zend Framework component v3 releases, while working in parallel on zf-apigility-doctrine and zf-doctrine-querybuilder. We hope to announce support for these in the next few weeks.

Upgrading to the latest versions of Apigility modules, however, should allow you to continue using Doctrine features; you will simply be constrained to Zend Framework component v2 releases.

Thank You!

We had a number of contributors to this release, but wish to call out two individuals in particular:

  • Adam Grabek provided the initial pull requests implementing Zend Framework v3 support for around a half-dozen or more modules, and maintained a checklist monitoring progress.
  • Michal (webimpress) Bundyra provided a number of compatibility patches, bugfixes, features, and, most notably, innumerable hours of testing and collaboration towards finalizing the skeleton changes.

To everyone who has contributed patches, features, feedback, and documentation: thank you!


The Zend Framework community is pleased to announce the immediate availability of Zend Framework 1.12.19! Packages and installation instructions are available at:


This release includes a single security patch, reported as ZF2016-02, for SQL injection vulnerabilities in the Zend_Db_Select::order() and Zend_Db_Select::group() methods. If you use these, we recommend updating immedaitely.

To see the complete set of issues resolved for 1.12.2, please visit the changelog:

Thank You!

Many thanks to all contributors to this release!


ZF2016-02: Potential SQL injection in ORDER and GROUP statements of Zend_Db_Select

The implementation of ORDER BY and GROUP BY in Zend_Db_Select of ZF1 is vulnerable by the following SQL injection:

$db = Zend_Db::factory(/* options here */);
$select = new Zend_Db_Select($db);
$select->order("MD5(\"(\");DELETE FROM p2; #)"); // same with group()

The above $select will render the following SQL statement:


instead of the correct one:

SELECT `p`.* FROM `p` ORDER BY "MD5("""");DELETE FROM p2; #)" ASC

This security fix can be considered as an improvement of the previous ZF2014-04.

Action Taken

We fixed the reported SQL injection using two regular expressions for the order() and the group() methods in Zend_Db_Select, created as the class constants REGEX_COLUMN_EXPR_ORDER and REGEX_COLUMN_EXPR_GROUP, respectively. These are defined as:


This regexp is different from the previous REGEX_COLUMN_EXPR, which used the character patterm [\w]*; we now require at least one word boundary ([\w]+).

The patch is available starting in Zend Framework 1.12.19.

Other Information

This SQL injection attack does not affect Zend Framework 2 and 3 versions because the implementations of Zend\Db\Sql\Select::order() and Zend\Db\Sql\Select::group() do not manage parenthetical expressions.


The Zend Framework team thanks the following for identifying the issues and working with us to help protect its users:

  • Peter O'Callaghan, who discovered and reported the issue;
  • Enrico Zimuel, who provided the patch.


After 17 months of effort, hundreds of releases, tens of thousands of commits by hundreds of contributors, and millions of installs, we're pleased to announce the immediate availability of Zend Framework 3.

What is Zend Framework 3?

For Zend Framework 2 MVC users, the differences are subtle:

  • Increased performance; we've measured up to 4X faster applications under PHP 5, and even better performance under PHP 7!
  • PHP 7 support.
  • A focus on de-coupling packages, to allow re-use in a greater number of contexts. In some cases, this has meant the creation of new packages that either split concerns, or provide integration between multiple components.
  • A focus on documentation. Documentation is now included within each component repository, allowing us to block contributions for lack of documentation, as well as automate deployment of documentation. See our new documentation site for the results.

Migration from version 2 to version 3 was at the top of our minds, and we have provided a number of forwards compatibility features over the course of ZF3 development, and written migration guides to help you navigate the changes.

If you are already familiar with our MVC, or want to get started with it, we have created a new version of the skeleton application that ships with minimal dependencies, and provides a number of convenience features including the ability to select optional packages at installation, as well as auto-register components and modules when adding them to your application. Read more about the skeleton in the documentation.

For newcomers to the framework, we have been working on our package architecture, and attempting to make each package installable with a minimal amount of dependencies, to allow usage in any project, from Zend Framework MVC applications to other popular frameworks such as Laravel and Symfony. All components are now developed independently, with their own release schedules, allowing us to ship bugfixes and new features more frequently. This change has allowed us to tag multiple hundreds of releases in the past year!

The Zend Framework 3 initiatives also included a number of new features, primarily around PSR-7 (HTTP Message interfaces) support. These include:

Yes, you read that correctly: Zend Framework now ships with a microframework as a parallel offering to its MVC full-stack framework! For users new to Zend Framework who are looking for a place to dive in, we recommend Expressive, as we feel PSR-7 middleware represents the future of PHP application development.

The release today is a new beginning for the framework, returning to its original mission: a strong component library, with opt-in MVC features.

Join our community today; we're available on the #zftalk Freenode IRC channel, and via our component repositories (for discussing issues and development).

— The Zend Framework Team —

Look for follow-up posts on this blog soon, detailing some of the new features!