In my efforts to learn more about security best practices in PHP, I noticed that most of the PHP frameworks out there left it up to the developer to correctly handle input/output/etc themselves. Unfortunately, this has been a sticking point in PHP apps, so I decided to work on a microframework that was designed with security in mind.
This project is under a MIT license.
Please note: This framework is a work in progress and is serving as a resource to learn more about PHP and web application security. Use of this framework will not provide the perfect security for your application, nor should it be considered an ultimate resource for security best practices.
I'm a big fan of the Slim microframework, so anyone that's used that will feel at home with Shield. Here's some example code of it in use:
<?php
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/',function(){
echo 'website root! woo!';
});
$app->run();
The above example is super simple - all it does is handle (thanks to the included .htaccess file) the request for the root level route "/" as a GET request. When it matches the route, it executes the closure callback and echos out "website root! woo!" Easy right?
Let's take a look at something a bit more complicated to introduce you to a few other handy tools at your disposal:
<?php
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/',function() use ($app){
$app->filter->add('test','email');
echo 'from the URL: '.$app->input->get('test').'<br/>';
$app->view->set('test','<a href="https://github.com/enygma/shieldframework/blob/master/">foodles</a>');
return $app->view->render('index1 [test]');
});
$app->run();
First off, there's one key difference between this example and the first one. In this example we
pass in the $app
object itself so we have access to some special features. Here's a quick overview:
$app->view
: An instance of the View object that can be used to do some more complex view handling$app->filter
: A filtering object that lets you add and execute filters on the given data$app->input
: A feature to pull in values from the PHP superglobals ($_GET, $_POST, etc)$app->log
: A logging instance (what the framework uses too)$app->config
: Access to the configuration options, reading and writingThere's also one other thing that could help in more complex development - the DI container. The framework
makes heavy use of a Dependency Injection Container (DIC) to work with its resources. This is exposed
back to the user as well, so you can access $app->di
and use it to manage your own object instances as well.
Besides the ability for Shield to match exact routes (like /foo
), there's also a feature included allowing
you use regular expresions in your routing. For example:
<?php
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/foo([0-9]+)', function($matches) {
print_r($matches);
});
Shield will try to match exact routes first, but then fall back on the regex routing checks. In th eabove example
we're matching a route like /foo123
. You'll notice that the first argument for the method is the routing matches as
pulled from the preg_match PHP method. You can use whatever preg-based expression you
want to use and have the values returned to you in the $matches
value. So:
<?php
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/foo([0-9]+)', function($matches){
print_r($matches);
});
You would get Array ( [1] => 123 )
in the $matches
variable.
You can also use named parameters in your routes too:
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/params/[:t1]/[:t2]', function($matches){
return $app->view->render('First Parameter: '.$matches['t1']);
});
If your route is /params/123/456
you'll get:
Array ( [t1] => 123, [t2] => 456 )
in the $matches
variable.
NOTE: DO NOT directly use the values from this array - there is currently no filtering on these values so there is potential for exploitation.
You can also specify some configuration options linked directly to the route/closure combination. Here's an example:
<?php
include_once '../Shield/Shield.php';
$app = new Shield\Shield();
$app->get('/xml', function() use ($app){
return $app->view->render('<test>this is xml</test>');
}, array(
'view.content-type' => 'text/xml'
));
In the above example, we're overriding the view.content-type
setting, but only for the /
route, not everything. This gives us a bit more control over the application, making it easier to customize the request handling. Note this uses the dot notation to specify the value (the key). Most configuration options should be available for reconfiguration via this method.
The Shield
class is the main class you'll use and really only has a handful of methods:
run()
: execute the application, no parametersget()
and post()
. Two parameters: route and closure/callbackAccess the values loaded from the configuration file or set/read your own.
set($keyName,$value)
: Set a configuration valueget($keyName)
: Get a configuration valueload($path)
: Load the values from the path into the app (overwrites), default looks for "config.php"getConfig()
: Get all of the config options as an arraysetConfig($configArr)
: Set the array of options to the configuration (overwrites)Access to the dependency injection container (getting & setting)
register($obj,$alias)
: Register an object in the container, $alias
is optional. Uses classname as name
if not definedget($name)
: Get the object with the given name from the containerFilter values based on filter types (supported are: email, striptags). Filters are applied when get()
is called.
add($fieldName,$type)
: Add a filter of the $type
when the $fieldName
is fetchedfilter($fieldName,$value)
: Looks for the filter(s) on the object and executes them in order (FIFO) on the $value
NOTE: If no filters are specified, it will execute a "strip_tags" on the data by default.
The $type
parameter for the add()
method can either be a string for the filter type or it can be a \Closure that will
be given the value of the field as a parameter - for example:
<?php
$app->filter->add('myField', function($value) {
return 'returned: '.$value;
});
You must be sure to return from this closure, otherwise the filtering will return null.
Pull values from the PHP superglobals (filtered)
get($name)
: Pull from the $_GET, $name
is name of variablepost($name)
: Pull from the $_POST, $name
is name of the variablerequest($name)
: Pull from the $_REQUEST, $name
is name of the variablefiles($name)
: Pull from the $_FILES, $name
is the name of the variableserver($name)
: Pull from the $_SERVER, $name
is the name of the variableset($type,$name,$value)
: Push a $value
into the property $name
of $type
('session','get','post',etc)NOTE: Superglobals are unset following a creation of an Input object.
Logging to a file
log($msg,$level)
: Message to log to the file, $level
is optional (default "info")Handle output to the page
set($name,$value)
: Sets a variable into the view to be replaced in a templaterender($content)
: Renders and returns the content, any variables set to the object are replaced using the notation "[name]"NOTE: All values are escaped/filtered by default to prevent XSS. This can be overridden if desired.
A basic templating engine included in the framework. By default it looks for a file named with the string given (in views/) or falls back to a str_replace
method treating it as a string.
render($template)
: Either the name of the template file (no .php) or the string to use as a templateNOTE: If you choose to use the string as a template (no file), you must use the "[varName]" notation to get the values to substitute. Values can be set directly to the template instance (ex. $app->view->template->test = 'foo';
)
An optional config.php
file can be placed in the same root as your front controller (probably index.php
) so
it can be found by the framework. This configuration file is a PHP array returned with your settings. These values
can be accessed through the $di->get('Config')->get()
method call. Here's an example config:
<?php
return array(
'log_path' => '/tmp'
);
Additionally, you can use a "dotted notation" to find configuration options. So, for example, to find the value below:
<?php
return array(
'foo' => array(
'bar' => array(
'baz' => 'testing this'
)
)
);
You can use $app->config->get('foo.bar.baz');
to get the value "testing this".
log_path
: Set the default logging pathsession.path
: Set the path on the local filesystem to save the session files tosession.key
: Customize the key used for the session encryptionsession.lock
: Enable/disable session locking (binds session to the IP+User Agent to help prevent fixation)allowed_hosts
: Array of hosts allowed to make requests (whitelisting)force_https
: Allows you to force the use of HTTPS. Will redirect if enabled and HTTP is detectedFirst off, thanks for considering submitting changes for the project - help is always appreciated! If you're going to contribute to the project, here's a few simple steps to follow:
One of the "gold standards" in the web application security community is the infamous "Top Ten" list of common security issues that web apps have. Shield, being the nice framework that it is, tries to help protect you and your app from these problems. Here's how:
Chris Cornutt ccornutt@phpdeveloper.org