-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRemoteCalls.php
More file actions
283 lines (245 loc) · 9.3 KB
/
Copy pathRemoteCalls.php
File metadata and controls
283 lines (245 loc) · 9.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<?php
namespace CleantalkSP\Common;
use CleantalkSP\SpbctWP\Helpers\IP;
use CleantalkSP\Variables\Request;
use CleantalkSP\SpbctWP\State;
class RemoteCalls
{
/**
* State object
*
* @var \CleantalkSP\SpbctWP\State
*/
protected $state;
/**
* Daughter class name
*
* @var string
*/
protected $class_name;
/**
* Is the remote call fires without token, is this remote call will be allowed?
*
* @var bool
*/
protected $without_token;
protected static $allowedActionsWithoutToken = [
'post_api_key',
];
const COOLDOWN = 10;
/**
* Timeout (seconds) for RC self-test requests.
* Keep low: expected response is immediate "OK".
*/
const TEST_REQUEST_TIMEOUT = 7;
/**
* How many times to attempt RC self-test before giving up.
*/
const TEST_REQUEST_ATTEMPTS = 3;
/**
* Checking if the current request is the Remote Call
*
* @return bool
*/
public static function check()
{
return Request::getString('spbc_remote_call_token')
? self::checkWithToken()
: self::checkWithoutToken();
}
public static function checkWithToken()
{
return Request::getString('spbc_remote_call_token') &&
Request::getString('spbc_remote_call_action') &&
in_array(Request::getString('plugin_name'), array('security', 'spbc'));
}
public static function checkWithoutToken()
{
global $spbc;
$rc_servers = [
'netserv3.cleantalk.org',
'netserv4.cleantalk.org',
];
return ! $spbc->key_is_ok &&
Request::getString('spbc_remote_call_action') &&
in_array(Request::getString('plugin_name'), array('security', 'spbc')) &&
in_array(IP::resolve(IP::get('remote_addr')), $rc_servers, true);
}
private static function isAllowedWithoutToken($rc)
{
return in_array($rc, self::$allowedActionsWithoutToken, true);
}
/**
* Execute corresponding method of RemoteCalls if exists
*
* @return void
*/
public function process()
{
$action = strtolower(Request::getString('spbc_remote_call_action'));
$token = strtolower(Request::getString('spbc_remote_call_token'));
$method = 'action__' . $action;
if (isset($this->state->remote_calls[$action])) {
$cooldown = isset($this->state->remote_calls[$action]['cooldown'])
? $this->state->remote_calls[$action]['cooldown']
: self::COOLDOWN;
// Return OK for test remote calls
if (Request::getString('test')) {
die('OK');
}
$is_locked = static::hasRateOverlimit(
(int)$cooldown,
$action,
(int)$this->state->remote_calls[$action]['last_call']
);
if (!$is_locked) {
$this->state->remote_calls[$action]['last_call'] = time();
$this->state->save('remote_calls', true, false);
// Check API key
if (
($this->state->data['key_is_ok'] !== false && $this->state->api_key !== '') &&
(
( $token === strtolower(md5($this->state->api_key)) ||
$token === strtolower(hash('sha256', $this->state->api_key)) ) ||
( $this->without_token && self::isAllowedWithoutToken($action) )
)
) {
// Flag to let plugin know that Remote Call is running.
$this->state->rc_running = true;
if (method_exists($this->class_name, $method)) {
// Perform action from a daughter class
$out = static::filter_before_action();
if (! $out) {
// Every remote call action handler should implement output or
// If out is empty(), the execution will continue
$out = static::$method();
}
} else {
$out = 'FAIL ' . json_encode(array('error' => 'UNKNOWN_ACTION_METHOD'));
}
} else {
$out = 'FAIL ' . json_encode(array('error' => 'WRONG_TOKEN'));
}
} else {
$out = 'FAIL ' . json_encode(array('error' => 'TOO_MANY_ATTEMPTS'));
}
} else {
$out = 'FAIL ' . json_encode(array('error' => 'UNKNOWN_ACTION'));
}
if ($out) {
die((string)$out);
}
}
/**
* @return bool|string[] This string[] return made for Psalm competition to avoid invalid inherited return type
*/
protected static function filter_before_action() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
{
return false;
}
public static function buildParameters($rc_action, $plugin_name, $api_key, $additional_params)
{
return array_merge(
array(
'spbc_remote_call_token' => md5($api_key),
'spbc_remote_call_action' => $rc_action,
'plugin_name' => $plugin_name,
),
$additional_params
);
}
/**
* Performs remote call to the current website
*
* @param string $host
* @param string $rc_action
* @param string $plugin_name
* @param string $api_key
* @param array $params
* @param array $patterns
* @param bool $do_check Perform check before main remote call or not
*
* @return bool|string[]
* @psalm-suppress PossiblyUnusedMethod
*/
public static function perform($host, $rc_action, $plugin_name, $api_key, $params, $patterns = array(), $do_check = true)
{
$params = static::buildParameters($rc_action, $plugin_name, $api_key, $params);
if ($do_check) {
$result__rc_check_website = static::performTest($host, $params, $patterns);
if (! empty($result__rc_check_website['error'])) {
return $result__rc_check_website;
}
}
$http = new \CleantalkSP\Common\HTTP\Request();
return $http
->setUrl($host)
->setData($params)
->setPresets($patterns)
->request();
}
/**
* Performs test remote call to the current website
* Expects 'OK' string as good response
*
* @param string $host
* @param array $params
* @param array $patterns
*
* @return array|bool|string
*/
public static function performTest($host, $params, $patterns = array())
{
// Delete async pattern to get the result in this process
$key = array_search('async', $patterns, true);
if ($key !== false) {
unset($patterns[$key]);
}
// Adding test flag
$params = array_merge($params, array('test' => 'test'));
$error_template = 'WRONG_SITE_RESPONSE TEST_ACTION FOR RC %s, ERROR: %s';
$error = null;
for ($attempt = 1; $attempt <= self::TEST_REQUEST_ATTEMPTS; $attempt++) {
$error = null;
$http = new \CleantalkSP\Common\HTTP\Request();
$options = defined('CURLOPT_TIMEOUT')
? array(CURLOPT_TIMEOUT => self::TEST_REQUEST_TIMEOUT)
: array('timeout' => self::TEST_REQUEST_TIMEOUT);
$result = $http
->setUrl($host)
->setData($params)
->setPresets($patterns)
// Prefer CURLOPT_* int keys: string 'timeout' is left in options by Request
// converter and breaks curl_setopt_array() on PHP 8+. Fallback to string
// name only when cURL constants are unavailable (no cURL extension).
->setOptions($options)
->request();
// Considering empty response as error
if ($result === '') {
$error = sprintf($error_template, $params['spbc_remote_call_action'], 'EMPTY RESPONSE');
// Wrap and pass error
} elseif (is_array($result) && ! empty($result['error'])) {
$error = sprintf($error_template, $params['spbc_remote_call_action'], $result['error']);
// Expects 'OK' string as good response otherwise - error
} elseif (is_string($result) && ! preg_match('@^.*?OK$@', $result)) {
$unexpected_response = 'UNEXPECTED RESPONSE: "' . json_encode(substr($result, 0, 400)) . '"';
$error = sprintf($error_template, $params['spbc_remote_call_action'], $unexpected_response);
}
if ($error === null) {
return $result;
}
}
return array('error' => $error);
}
/**
* Check if calls limit reached.
* @param int $cooldown timeframe in seconds
* @param string $_action action name
* @param int $_last_call last call timestamp
* @return bool True if difference between current timestamp and last call is greater than cooldown, false otherwise.
*/
public static function hasRateOverlimit($cooldown, $_action = '', $_last_call = 0)
{
return (time() - $_last_call) < $cooldown;
}
}