Repository navigation
Expand file tree
/
Copy pathendpoint.php
More file actions
323 lines (281 loc) · 11.9 KB
/
Copy pathendpoint.php
File metadata and controls
323 lines (281 loc) · 11.9 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
<?php
/**
* Bootstrap-free endpoint, reached via /dispatch.php?p=cookie-consent&...
* (see public/dispatch.php - runs without the full app/session/Smarty
* bootstrap, just the SE_* path constants from config.php). Same mechanism
* as plugins/tracker/endpoint.php.
*
* Three jobs:
* - ?asset=<file>: serves the vendored CookieConsent v3 / iframemanager
* builds (assets/vendor/, both MIT-licensed) - plugins/ lives outside the
* public/ web root, so the files can't be linked directly.
* - ?embed_thumb=<service>&id=<video id>[&h=<hash>]&s=<signature>:
* YouTube/Vimeo thumbnail proxy, so the placeholder can show a preview
* image without the visitor's browser contacting the provider before
* consent. Only videos signed by global/iframe-filter.php (HMAC with the
* per-install secret) are fetched, so this can't be abused to fill the
* cache with arbitrary IDs.
* - ?consent_log=1 (POST, JSON body via navigator.sendBeacon): stores one
* consent log entry (proof of consent) - see cc_endpoint_consent_log().
*/
if (isset($_GET['consent_log'])) {
cc_endpoint_consent_log();
exit;
}
if (isset($_GET['embed_thumb'])) {
cc_endpoint_embed_thumb();
exit;
}
$requested = basename((string) ($_GET['asset'] ?? ''));
$allowed = [
'cookieconsent.umd.js' => 'application/javascript',
'cookieconsent.css' => 'text/css',
'iframemanager.js' => 'application/javascript',
'iframemanager.css' => 'text/css',
];
if ($requested === '' || !isset($allowed[$requested])) {
http_response_code(404);
exit;
}
$file = __DIR__.'/assets/vendor/'.$requested;
if (!is_file($file)) {
http_response_code(404);
exit;
}
header('Content-Type: '.$allowed[$requested].'; charset=utf-8');
// global/index.php always appends ?v=<plugin version>, so a plugin update
// that ships a newer library busts the cache - safe to cache immutably.
header('Cache-Control: public, max-age=31536000, immutable');
header('Content-Length: '.filesize($file));
readfile($file);
exit;
function cc_endpoint_embed_thumb(): void {
$service = (string) $_GET['embed_thumb'];
// Rebuild exactly the values global/iframe-filter.php signed - nothing
// else from the request is used.
$thumb = match ($service) {
'youtube' => ['id' => (string) ($_GET['id'] ?? '')],
'vimeo' => ['id' => (string) ($_GET['id'] ?? ''), 'h' => (string) ($_GET['h'] ?? '')],
default => null,
};
if ($thumb === null
|| ($service === 'youtube' && !preg_match('/^[A-Za-z0-9_-]{11}$/', $thumb['id']))
|| ($service === 'vimeo' && (!preg_match('/^\d{1,12}$/', $thumb['id']) || !preg_match('/^[A-Za-z0-9]{0,20}$/', $thumb['h'])))) {
http_response_code(404);
return;
}
$front_file = __DIR__.'/data/frontend.json';
$front = is_file($front_file) ? json_decode((string) file_get_contents($front_file), true) : null;
$secret = (string) ($front['embed_secret'] ?? '');
if (($front['embeds'][$service]['thumbnails'] ?? '') !== 'proxy' || $secret === '') {
http_response_code(404);
return;
}
require_once __DIR__.'/global/iframe-filter.php';
if (!hash_equals(cc_embed_thumb_signature($service, $thumb, $secret), (string) ($_GET['s'] ?? ''))) {
http_response_code(404);
return;
}
$dir = __DIR__.'/data/embed-thumbs/';
$file = $dir.$service.'-'.$thumb['id'].(($thumb['h'] ?? '') !== '' ? '-'.$thumb['h'] : '').'.img';
// Refresh monthly - a video's thumbnail can be changed by its owner.
if (!is_file($file) || filemtime($file) < time() - 30 * 86400) {
$image = $service === 'youtube'
? cc_endpoint_fetch_image('https://i.ytimg.com/vi/'.$thumb['id'].'/hqdefault.jpg')
: cc_endpoint_vimeo_thumb($thumb['id'], $thumb['h']);
if ($image !== null) {
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$tmp = $file.'.'.bin2hex(random_bytes(4)).'.tmp';
if (file_put_contents($tmp, $image) !== false) {
rename($tmp, $file);
}
}
}
$type = is_file($file) ? cc_endpoint_image_type((string) file_get_contents($file, false, null, 0, 16)) : null;
if ($type === null) {
http_response_code(404);
return;
}
header('Content-Type: '.$type);
header('Cache-Control: public, max-age=604800');
header('Content-Length: '.filesize($file));
readfile($file);
}
/**
* Consent log receiver. Runs on a public URL, so everything is validated
* and capped - but without storing or even looking at the visitor's IP:
* - same-origin only (Origin/Referer host must match the site's own host),
* - strict whitelist validation of every field, body max 8 KB,
* - max 20 entries per consent ID per day and 120 entries per minute
* overall, so the log can't be flooded with fabricated entries.
* Always answers 204/4xx without a body - nothing for the page to handle.
*/
function cc_endpoint_consent_log(): void {
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
$front_file = __DIR__.'/data/frontend.json';
$db_file = __DIR__.'/data/cookie-consent.sqlite3';
$front = is_file($front_file) ? json_decode((string) file_get_contents($front_file), true) : null;
if (empty($front['consent_log']['enabled']) || !is_file($db_file)) {
http_response_code(204);
return;
}
$source = (string) ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '');
$source_host = strtolower((string) parse_url($source, PHP_URL_HOST));
$own_host = strtolower(preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
if ($source_host === '' || $source_host !== $own_host) {
http_response_code(403);
return;
}
$data = json_decode((string) file_get_contents('php://input', false, null, 0, 8192), true);
$entry = is_array($data) ? cc_endpoint_validate_consent($data) : null;
if ($entry === null) {
http_response_code(400);
return;
}
try {
$pdo = new PDO('sqlite:'.$db_file, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_TIMEOUT => 3,
]);
$recent = (int) $pdo->query("SELECT COUNT(*) FROM consent_log WHERE ts >= datetime('now', '-60 seconds')")->fetchColumn();
$stmt = $pdo->prepare("SELECT COUNT(*) FROM consent_log WHERE consent_id = ? AND ts >= datetime('now', '-1 day')");
$stmt->execute([$entry['consent_id']]);
if ($recent >= 120 || (int) $stmt->fetchColumn() >= 20) {
http_response_code(429);
return;
}
$stmt = $pdo->prepare('INSERT INTO consent_log (consent_id, action, accept_type, categories, services, revision, lang, consent_ts, last_consent_ts, page)
VALUES (:consent_id, :action, :accept_type, :categories, :services, :revision, :lang, :consent_ts, :last_consent_ts, :page)');
$stmt->execute($entry);
// Retention cleanup now and then (~1% of writes) - the backend tab
// does it too, but a site whose admin never opens it still gets
// old entries removed.
$days = (int) ($front['consent_log']['retention_days'] ?? 1095);
if ($days > 0 && random_int(1, 100) === 1) {
$pdo->exec("DELETE FROM consent_log WHERE ts < datetime('now', '-".$days." days')");
}
} catch (Throwable $e) {
http_response_code(503);
return;
}
http_response_code(204);
}
/**
* @return array|null named INSERT parameters, or null if anything is off
*/
function cc_endpoint_validate_consent(array $d): ?array {
$key = '/^[a-z0-9_-]{1,50}$/';
$consent_id = (string) ($d['consentId'] ?? '');
$action = (string) ($d['action'] ?? '');
$accept_type = (string) ($d['acceptType'] ?? '');
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $consent_id)
|| !in_array($action, ['first', 'change'], true)
|| !in_array($accept_type, ['all', 'necessary', 'custom'], true)) {
return null;
}
$categories = $d['categories'] ?? [];
if (!is_array($categories) || count($categories) > 30) {
return null;
}
foreach ($categories as $c) {
if (!is_string($c) || !preg_match($key, $c)) {
return null;
}
}
$services = $d['services'] ?? [];
if (!is_array($services) || count($services) > 30) {
return null;
}
foreach ($services as $cat => $list) {
if (!preg_match($key, (string) $cat) || !is_array($list) || count($list) > 50) {
return null;
}
foreach ($list as $svc) {
if (!is_string($svc) || !preg_match($key, $svc)) {
return null;
}
}
}
$iso = fn($v) => is_string($v) && preg_match('/^\d{4}-\d{2}-\d{2}T[\d:.]+Z$/', $v) ? $v : null;
$lang = (string) ($d['lang'] ?? '');
$page = (string) ($d['page'] ?? '');
return [
'consent_id' => strtolower($consent_id),
'action' => $action,
'accept_type' => $accept_type,
'categories' => json_encode(array_values($categories)),
'services' => json_encode((object) $services),
'revision' => max(0, min(1000000, (int) ($d['revision'] ?? 0))),
'lang' => preg_match('/^[A-Za-z-]{2,15}$/', $lang) ? $lang : null,
'consent_ts' => $iso($d['consentTimestamp'] ?? null),
'last_consent_ts' => $iso($d['lastConsentTimestamp'] ?? null),
'page' => str_starts_with($page, '/') ? mb_substr($page, 0, 255) : null,
];
}
/**
* Vimeo has no fixed thumbnail URL scheme - ask its oEmbed API for it.
*/
function cc_endpoint_vimeo_thumb(string $id, string $hash): ?string {
$video_url = 'https://vimeo.com/'.$id.($hash !== '' ? '/'.$hash : '');
$json = cc_endpoint_fetch('https://vimeo.com/api/oembed.json?width=640&url='.rawurlencode($video_url));
$data = $json !== null ? json_decode($json, true) : null;
$thumb_url = (string) ($data['thumbnail_url'] ?? '');
// Only ever follow up to Vimeo's own image CDN.
$host = strtolower((string) parse_url($thumb_url, PHP_URL_HOST));
if (!str_starts_with($thumb_url, 'https://') || !preg_match('/(^|\.)vimeocdn\.com$/', $host)) {
return null;
}
return cc_endpoint_fetch_image($thumb_url);
}
function cc_endpoint_fetch_image(string $url): ?string {
$body = cc_endpoint_fetch($url);
// Must really be an image (magic bytes) - never cache an error page.
return $body !== null && cc_endpoint_image_type($body) !== null ? $body : null;
}
function cc_endpoint_image_type(string $bytes): ?string {
if (strncmp($bytes, "\xFF\xD8\xFF", 3) === 0) {
return 'image/jpeg';
}
if (strncmp($bytes, "\x89PNG", 4) === 0) {
return 'image/png';
}
if (strncmp($bytes, 'RIFF', 4) === 0 && substr($bytes, 8, 4) === 'WEBP') {
return 'image/webp';
}
return null;
}
/**
* @return string|null response body of a 200 response (max 2 MB), or null
*/
function cc_endpoint_fetch(string $url): ?string {
$body = null;
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
]);
$result = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (is_string($result) && $status === 200) {
$body = $result;
}
} else {
$context = stream_context_create(['http' => ['timeout' => 5, 'follow_location' => 0, 'ignore_errors' => true]]);
$result = @file_get_contents($url, false, $context);
$status_line = $http_response_header[0] ?? '';
if (is_string($result) && str_contains($status_line, ' 200')) {
$body = $result;
}
}
return $body !== null && strlen($body) <= 2 * 1024 * 1024 ? $body : null;
}