1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FFCMS\Traits; |
4
|
|
|
|
5
|
|
|
use FFMVC\Helpers; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Check for CSRF code (see counterpart CSRF code in app/app.php) |
10
|
|
|
* and dns blacklist check |
11
|
|
|
* |
12
|
|
|
* If a config key called 'security.csrf' is true, will redirect the client |
13
|
|
|
* to the supplied url (or homepage if not). The URL can be a full internal URL |
14
|
|
|
* or an f3 url alias. |
15
|
|
|
*/ |
16
|
|
|
trait SecurityController |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Create an internal URL |
20
|
|
|
* Uses method from |
21
|
|
|
* @see \FFCMS\Helpers\UrlHelper |
22
|
|
|
* @param string $url |
23
|
|
|
* @param array $params |
24
|
|
|
*/ |
25
|
|
|
abstract public function url(string $url, array $params = []): string; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Check for CSRF token, reroute if failed, otherwise generate new csrf token |
29
|
|
|
* Call this method from a controller method class to check and then set a new csrf token |
30
|
|
|
* then include $f3-get('csrf') as a hidden type in your form to be submitted |
31
|
|
|
* |
32
|
|
|
* @param string $url if csrf check fails |
33
|
|
|
* @param array $params for querystring |
34
|
|
|
* @return boolean true/false if csrf enabled |
35
|
|
|
*/ |
36
|
|
|
public function csrf(string $url = '@index', array $params = []): bool |
37
|
|
|
{ |
38
|
|
|
$f3 = \Base::instance(); |
39
|
|
|
if (empty($f3->get('security.csrf'))) { |
40
|
|
|
return false; |
41
|
|
|
} |
42
|
|
|
// redirect user if it's not a POST request |
43
|
|
|
if ('POST' !== $f3->get('VERB')) { |
44
|
|
|
$f3->reroute($url); |
45
|
|
|
} |
46
|
|
|
$csrf = $f3->get('csrf'); |
47
|
|
|
if ($csrf === false) { |
48
|
|
|
$url = $this->url($url, $params); |
49
|
|
|
$f3->reroute($url); |
50
|
|
|
return; |
51
|
|
|
} else { |
52
|
|
|
$csrf = Helpers\Str::salted(Helpers\Str::random(16), Helpers\Str::random(16), Helpers\Str::random(16)); |
53
|
|
|
$f3->set('csrf', $csrf); |
54
|
|
|
$f3->set('SESSION.csrf', $csrf); |
55
|
|
|
$f3->expire(0); |
56
|
|
|
} |
57
|
|
|
return true; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Check ip-address is blacklisted, halt, if-so |
63
|
|
|
* |
64
|
|
|
* @return bool |
65
|
|
|
*/ |
66
|
|
|
public function dnsbl(): bool |
67
|
|
|
{ |
68
|
|
|
$f3 = \Base::instance(); |
69
|
|
|
$cache = \Cache::instance(); |
70
|
|
|
$ip = $f3->get('IP'); |
71
|
|
|
$f3->set('DNSBL', $f3->get('security.dnsbl')); |
72
|
|
|
if (!$cache->exists($ip, $isBlacklisted)) { |
73
|
|
|
$isBlacklisted = $f3->blacklisted($ip); |
74
|
|
|
$cache->set($ip, $isBlacklisted, $f3->get('ttl.blacklist')); |
75
|
|
|
} |
76
|
|
|
if (false !== $isBlacklisted) { |
77
|
|
|
printf(_("Your ip-address '%s' is blacklisted!"), $ip); |
78
|
|
|
$f3->halt(); |
79
|
|
|
} |
80
|
|
|
return true; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
} |
84
|
|
|
|