Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
Total | |
0.00% |
0 / 1 |
|
75.00% |
3 / 4 |
CRAP | |
96.88% |
31 / 32 |
DoubleSubmitCookieCsrfMiddleware | |
0.00% |
0 / 1 |
|
75.00% |
3 / 4 |
12 | |
96.88% |
31 / 32 |
__construct | |
0.00% |
0 / 1 |
5.01 | |
92.86% |
13 / 14 |
|||
setLogger | |
100.00% |
1 / 1 |
1 | |
100.00% |
2 / 2 |
|||
process | |
100.00% |
1 / 1 |
3 | |
100.00% |
12 / 12 |
|||
isValid | |
100.00% |
1 / 1 |
3 | |
100.00% |
4 / 4 |
1 | <?php declare(strict_types=1); |
2 | |
3 | namespace Taproot\IndieAuth\Middleware; |
4 | |
5 | use Nyholm\Psr7\Response; |
6 | use Psr\Http\Message\ServerRequestInterface; |
7 | use Psr\Http\Message\ResponseInterface; |
8 | use Psr\Http\Server\MiddlewareInterface; |
9 | use Psr\Http\Server\RequestHandlerInterface; |
10 | use Dflydev\FigCookies; |
11 | use Psr\Log\LoggerAwareInterface; |
12 | use Psr\Log\LoggerInterface; |
13 | use Psr\Log\NullLogger; |
14 | |
15 | use function Taproot\IndieAuth\generateRandomPrintableAsciiString; |
16 | |
17 | /** |
18 | * Double-Submit Cookie CSRF Middleware |
19 | * |
20 | * A PSR-15-compatible Middleware for stateless Double-Submit-Cookie-based CSRF protection. |
21 | * |
22 | * The `$attribute` property and first constructor argument sets the key by which the CSRF token |
23 | * is referred to in all parameter sets (request attributes, request body parameters, cookies). |
24 | * |
25 | * Generates a random token of length `$tokenLength` (default 128), and stores it as an attribute |
26 | * on the `ServerRequestInterface`. It’s also added to the response as a cookie. |
27 | * |
28 | * On requests which may modify state (methods other than HEAD, GET or OPTIONS), the request body |
29 | * and request cookies are checked for matching CSRF tokens. If they match, the request is passed on |
30 | * to the handler. If they do not match, further processing is halted and an error response generated |
31 | * from the `$errorResponse` callback is returned. Refer to the constructor argument for information |
32 | * about customising the error response. |
33 | * |
34 | * @link https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html |
35 | * @link https://github.com/zakirullin/csrf-middleware/blob/master/src/CSRF.php |
36 | */ |
37 | class DoubleSubmitCookieCsrfMiddleware implements MiddlewareInterface, LoggerAwareInterface { |
38 | const READ_METHODS = ['HEAD', 'GET', 'OPTIONS']; |
39 | const TTL = 60 * 20; |
40 | const ATTRIBUTE = 'csrf'; |
41 | const DEFAULT_ERROR_RESPONSE_STRING = 'Invalid or missing CSRF token!'; |
42 | const CSRF_TOKEN_LENGTH = 128; |
43 | |
44 | /** @var string $attribute */ |
45 | public $attribute; |
46 | |
47 | /** @var int $ttl */ |
48 | public $ttl; |
49 | |
50 | public $errorResponse; |
51 | |
52 | /** @var int $tokenLength */ |
53 | public $tokenLength; |
54 | |
55 | /** @var LoggerInterface $logger */ |
56 | public $logger; |
57 | |
58 | /** |
59 | * Constructor |
60 | * |
61 | * The `$errorResponse` parameter can be used to customse the error response returned when a |
62 | * write request has invalid CSRF parameters. It can take the following forms: |
63 | * |
64 | * * A `string`, which will be returned as-is with a 400 Status Code and `Content-type: text/plain` header |
65 | * * An instance of `ResponseInterface`, which will be returned as-is |
66 | * * A callable with the signature `function (ServerRequestInterface $request): ResponseInterface`, |
67 | * the return value of which will be returned as-is. |
68 | */ |
69 | public function __construct(?string $attribute=self::ATTRIBUTE, ?int $ttl=self::TTL, $errorResponse=self::DEFAULT_ERROR_RESPONSE_STRING, $tokenLength=self::CSRF_TOKEN_LENGTH, $logger=null) { |
70 | $this->attribute = $attribute ?? self::ATTRIBUTE; |
71 | $this->ttl = $ttl ?? self::TTL; |
72 | $this->tokenLength = $tokenLength ?? self::CSRF_TOKEN_LENGTH; |
73 | |
74 | if (!is_callable($errorResponse)) { |
75 | if (!$errorResponse instanceof ResponseInterface) { |
76 | if (!is_string($errorResponse)) { |
77 | $errorResponse = self::DEFAULT_ERROR_RESPONSE_STRING; |
78 | } |
79 | $errorResponse = new Response(400, ['content-type' => 'text/plain'], $errorResponse); |
80 | } |
81 | $errorResponse = function (ServerRequestInterface $request) use ($errorResponse) { return $errorResponse; }; |
82 | } |
83 | $this->errorResponse = $errorResponse; |
84 | |
85 | if (!$logger instanceof LoggerInterface) { |
86 | $logger = new NullLogger(); |
87 | } |
88 | $this->logger = $logger; |
89 | } |
90 | |
91 | public function setLogger(LoggerInterface $logger) { |
92 | $this->logger = $logger; |
93 | } |
94 | |
95 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { |
96 | // Generate a new CSRF token, add it to the request attributes, and as a cookie on the response. |
97 | $csrfToken = generateRandomPrintableAsciiString($this->tokenLength); |
98 | $request = $request->withAttribute($this->attribute, $csrfToken); |
99 | |
100 | if (!in_array(strtoupper($request->getMethod()), self::READ_METHODS) && !$this->isValid($request)) { |
101 | // This request is a write method with invalid CSRF parameters. |
102 | $response = call_user_func($this->errorResponse, $request); |
103 | } else { |
104 | $response = $handler->handle($request); |
105 | } |
106 | |
107 | // Add the new CSRF cookie, restricting its scope to match the current request. |
108 | $response = FigCookies\FigResponseCookies::set($response, FigCookies\SetCookie::create($this->attribute) |
109 | ->withValue($csrfToken) |
110 | ->withMaxAge($this->ttl) |
111 | ->withSecure($request->getUri()->getScheme() == 'https') |
112 | ->withDomain($request->getUri()->getHost()) |
113 | ->withPath($request->getUri()->getPath())); |
114 | |
115 | return $response; |
116 | } |
117 | |
118 | protected function isValid(ServerRequestInterface $request) { |
119 | if (array_key_exists($this->attribute, $request->getParsedBody() ?? [])) { |
120 | if (array_key_exists($this->attribute, $request->getCookieParams() ?? [])) { |
121 | // TODO: make sure CSRF token isn’t the empty string, possibly also check that it’s the same length |
122 | // as defined in $this->tokenLength. |
123 | return hash_equals($request->getParsedBody()[$this->attribute], $request->getCookieParams()[$this->attribute]); |
124 | } |
125 | } |
126 | return false; |
127 | } |
128 | } |