forked from slimphp/Slim-Csrf
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 0994bd8
Showing
10 changed files
with
437 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
vendor | ||
composer.lock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
language: php | ||
|
||
php: | ||
- 5.4 | ||
- 5.5 | ||
- 5.6 | ||
- 7.0 | ||
- hhvm | ||
|
||
before_script: composer install | ||
|
||
script: phpunit --coverage-text |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# How to Contribute | ||
|
||
## Pull Requests | ||
|
||
1. Fork this repository | ||
2. Create a new branch for each feature or improvement | ||
3. Send a pull request from each feature branch | ||
|
||
It is very important to separate new features or improvements into separate feature branches, and to send a pull request for each branch. This allows me to review and pull in new features or improvements individually. | ||
|
||
## Style Guide | ||
|
||
All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). | ||
|
||
## Unit Testing | ||
|
||
All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses phpunit for testing. | ||
|
||
[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
Copyright (c) 2012-2015 Josh Lockhart | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is furnished | ||
to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
# Slim Framework CSRF Protection | ||
|
||
[![Build Status](https://travis-ci.org/slimphp/Slim-Csrf.svg?branch=master)](https://travis-ci.org/slimphp/Slim-Csrf) | ||
|
||
This repository contains a Slim Framework CSRF protection middleware. CSRF protection applies to all unsafe HTTP requests (POST, PUT, DELETE, PATCH). | ||
|
||
You can fetch the latest CSRF token's name and value from the Request object with its `getAttribute()` method. By default, the CSRF token's name is stored in the `csrf_name` attribute, and the CSRF token's value is stored in the `csrf_value` attribute. | ||
|
||
## Install | ||
|
||
Via Composer | ||
|
||
``` bash | ||
$ composer require slim/csrf | ||
``` | ||
|
||
Requires Slim 3.0.0 or newer. | ||
|
||
## Usage | ||
|
||
```php | ||
// Start PHP session | ||
session_start(); | ||
|
||
$app = new \Slim\App(); | ||
|
||
// Register middleware | ||
$app->add(new \Slim\Csrf\Guard); | ||
|
||
$app->get('/foo', function ($req, $res, $args) { | ||
// CSRF token name and value | ||
$name = $req->getAttribute('csrf_name'); | ||
$value = $req->getAttribute('csrf_value'); | ||
|
||
// Render HTML form hidden input with this | ||
// CSRF token name and value. | ||
}); | ||
|
||
$app->post('/bar', function ($req, $res, $args) { | ||
// CSRF protection successful if you reached | ||
// this far. | ||
}) | ||
|
||
$app->run(); | ||
``` | ||
|
||
## Testing | ||
|
||
``` bash | ||
$ phpunit | ||
``` | ||
|
||
## Contributing | ||
|
||
Please see [CONTRIBUTING](CONTRIBUTING.md) for details. | ||
|
||
## Security | ||
|
||
If you discover any security related issues, please email [email protected] instead of using the issue tracker. | ||
|
||
## Credits | ||
|
||
- [Josh Lockhart](https://github.com/codeguy) | ||
- [All Contributors](../../contributors) | ||
|
||
## License | ||
|
||
The MIT License (MIT). Please see [License File](LICENSE.md) for more information. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
{ | ||
"name": "slim/csrf", | ||
"type": "library", | ||
"description": "Slim Framework CSRF protection middleware", | ||
"keywords": ["slim","framework","middleware","csrf"], | ||
"homepage": "http://slimframework.com", | ||
"license": "MIT", | ||
"authors": [ | ||
{ | ||
"name": "Josh Lockhart", | ||
"email": "[email protected]", | ||
"homepage": "http://joshlockhart.com" | ||
} | ||
], | ||
"require": { | ||
"php": ">=5.4.0", | ||
"pimple/pimple": "~3.0", | ||
"psr/http-message": "~0.9" | ||
}, | ||
"require-dev": { | ||
"slim/slim": "dev-develop" | ||
}, | ||
"autoload": { | ||
"psr-4": { | ||
"Slim\\Csrf\\": "src" | ||
} | ||
}, | ||
"autoload-dev": { | ||
"psr-4": { | ||
"Slim\\Csrf\\Tests\\": "tests" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
|
||
<phpunit backupGlobals="false" | ||
backupStaticAttributes="false" | ||
colors="true" | ||
convertErrorsToExceptions="true" | ||
convertNoticesToExceptions="true" | ||
convertWarningsToExceptions="true" | ||
processIsolation="false" | ||
stopOnFailure="false" | ||
syntaxCheck="false" | ||
bootstrap="tests/bootstrap.php" | ||
> | ||
<testsuites> | ||
<testsuite name="Slim Test Suite"> | ||
<directory>tests/</directory> | ||
</testsuite> | ||
</testsuites> | ||
|
||
<filter> | ||
<whitelist> | ||
<directory>src/</directory> | ||
</whitelist> | ||
</filter> | ||
</phpunit> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
<?php | ||
namespace Slim\Csrf; | ||
|
||
use Psr\Http\Message\RequestInterface; | ||
use Psr\Http\Message\ResponseInterface; | ||
|
||
/** | ||
* CSRF protection middleware based | ||
* on the OWASP example linked below. | ||
* | ||
* @link https://www.owasp.org/index.php/PHP_CSRF_Guard | ||
*/ | ||
class Guard | ||
{ | ||
/** | ||
* Prefix for CSRF parameters (omit trailing "_" underscore) | ||
* | ||
* @var string | ||
*/ | ||
protected $prefix; | ||
|
||
/** | ||
* CSRF storage | ||
* | ||
* @var null|array|ArrayAccess | ||
*/ | ||
protected $storage; | ||
|
||
/** | ||
* Create new CSRF guard | ||
* | ||
* @param string $prefix | ||
* @param null|array|ArrayAccess $storage | ||
*/ | ||
public function __construct($prefix = 'csrf', $storage = null) | ||
{ | ||
$this->prefix = rtrim($prefix, '_'); | ||
if (is_array($storage) || $storage instanceof \ArrayAccess) { | ||
$this->storage = $storage; | ||
} else { | ||
if (!isset($_SESSION)) { | ||
throw new \RuntimeException('CSRF middleware failed. Session not found.'); | ||
} | ||
$this->storage = &$_SESSION; | ||
} | ||
} | ||
|
||
/** | ||
* Invoke middleware | ||
* | ||
* @param RequestInterface $request PSR7 request object | ||
* @param ResponseInterface $response PSR7 response object | ||
* @param callable $next Next middleware callable | ||
* | ||
* @return ResponseInterface PSR7 response object | ||
*/ | ||
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) | ||
{ | ||
// Validate POST, PUT, DELETE, PATCH requests | ||
if (in_array($request->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) { | ||
$body = $request->getParsedBody(); | ||
$body = $body ? (array)$body : []; | ||
$name = isset($body[$this->prefix . '_name']) ? $body[$this->prefix . '_name'] : false; | ||
$value = isset($body[$this->prefix . '_value']) ? $body[$this->prefix . '_value'] : false; | ||
if (!$name || !$value || !$this->validateToken($name, $value)) { | ||
return $response->withStatus(400); | ||
} | ||
} | ||
|
||
// Generate new CSRF token | ||
$name = $this->prefix . mt_rand(0, mt_getrandmax()); | ||
$value = $this->createToken(); | ||
$this->saveToStorage($name, $value); | ||
$request = $request->withAttribute($this->prefix . '_name', $name) | ||
->withAttribute($this->prefix . '_value', $value); | ||
|
||
return $next($request, $response); | ||
} | ||
|
||
/** | ||
* Validate CSRF token from current request | ||
* against token value stored in $_SESSION | ||
* | ||
* @param string $name CSRF name | ||
* @param string $value CSRF token value | ||
* | ||
* @return bool | ||
*/ | ||
protected function validateToken($name, $value) | ||
{ | ||
$token = $this->getFromStorage($name); | ||
if ($token === false) { | ||
return false; | ||
} elseif ($token === $value) { | ||
$result = true; | ||
} else { | ||
$result = false; | ||
} | ||
$this->removeFromStorage($name); | ||
|
||
return $result; | ||
} | ||
|
||
/** | ||
* Create CSRF token value | ||
* | ||
* @return string | ||
*/ | ||
protected function createToken() | ||
{ | ||
if (function_exists("hash_algos") && in_array("sha512", hash_algos())) { | ||
$token = hash("sha512", mt_rand(0, mt_getrandmax())); | ||
} else { | ||
$token = ' '; | ||
for ($i = 0; $i < 128; ++$i) { | ||
$rVal = mt_rand(0, 35); | ||
if ($rVal < 26) { | ||
$cVal = chr(ord('a') + $rVal); | ||
} else { | ||
$cVal = chr(ord('0') + $rVal - 26); | ||
} | ||
$token .= $cVal; | ||
} | ||
} | ||
|
||
return $token; | ||
} | ||
|
||
/** | ||
* Save token to storage | ||
* | ||
* @param string $name CSRF token name | ||
* @param string $value CSRF token value | ||
*/ | ||
protected function saveToStorage($name, $value) | ||
{ | ||
$this->storage[$name] = $value; | ||
} | ||
|
||
/** | ||
* Get token from storage | ||
* | ||
* @param string $name CSRF token name | ||
* | ||
* @return string|bool CSRF token value or `false` if not present | ||
*/ | ||
protected function getFromStorage($name) | ||
{ | ||
return isset($this->storage[$name]) ? $this->storage[$name] : false; | ||
} | ||
|
||
/** | ||
* Remove token from storage | ||
* | ||
* @param string $name CSRF token name | ||
*/ | ||
protected function removeFromStorage($name) | ||
{ | ||
$this->storage[$name] = ' '; | ||
unset($this->storage[$name]); | ||
} | ||
} |
Oops, something went wrong.