-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.php
More file actions
590 lines (494 loc) · 20.2 KB
/
index.php
File metadata and controls
590 lines (494 loc) · 20.2 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
/**
* HopTransfert
* A minimalist, single-file, secure PHP application for anonymous file sharing
*
* @author Fedir RYKHTIK; acclerated development with Claude.AI
* @version 1.0
* @requires PHP 8.1+
*/
// =============================================================================
// CONFIGURATION CONSTANTS
// =============================================================================
// Rate limiting
const DOWNLOAD_RATE_LIMIT_SECONDS = 5;
// File and directory paths
const DATA_DIR = __DIR__ . '/data';
const DOWNLOAD_DIR = __DIR__ . '/download';
const FILES_JSON = DATA_DIR . '/files.json';
const DOWNLOAD_LOG = DATA_DIR . '/download.log';
const ERROR_LOG = DATA_DIR . '/php_errors.log';
// File upload limits
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx', 'zip', 'rar'];
// Security
const PASSWORD_MIN_LENGTH = 6;
const HASH_SALT = 'your-secret-salt-here'; // change this
const CSRF_TOKEN_LENGTH = 16;
// Ressources control
const MAX_LOG_LINES = 5; // prevent log bloat
// =============================================================================
// ERROR HANDLING SETUP
// =============================================================================
// Configure error logging
ini_set('log_errors', 1);
ini_set('error_log', ERROR_LOG);
ini_set('display_errors', 0);
// Custom error handler
set_error_handler(function($severity, $message, $file, $line) {
error_log("Error [$severity]: $message in $file on line $line");
});
// =============================================================================
// INITIALIZATION
// =============================================================================
// Create required directories
if (!file_exists(DATA_DIR)) {
mkdir(DATA_DIR, 0755, true);
// Create .htaccess to protect data directory
$htaccess_content = "Deny from all\n";
file_put_contents(DATA_DIR . '/.htaccess', $htaccess_content);
}
if (!file_exists(DOWNLOAD_DIR)) {
mkdir(DOWNLOAD_DIR, 0755, true);
// Create .htaccess to protect download directory
$htaccess_content = "Deny from all\n";
file_put_contents(DOWNLOAD_DIR . '/.htaccess', $htaccess_content);
}
// Initialize files.json if it doesn't exist
if (!file_exists(FILES_JSON)) {
file_put_contents(FILES_JSON, json_encode([]));
}
// Initialize download.log if it doesn't exist
if (!file_exists(DOWNLOAD_LOG)) {
touch(DOWNLOAD_LOG);
}
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
/**
* Sanitize input data to prevent XSS and other attacks
*/
function sanitize_input($data) {
if (is_array($data)) {
return array_map('sanitize_input', $data);
}
return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}
/**
* Generate CSRF token
*/
function generate_csrf_token() {
if (session_status() === PHP_SESSION_NONE) {
// Configure secure session settings
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_samesite', 'Strict');
session_start();
}
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(CSRF_TOKEN_LENGTH));
}
return $_SESSION['csrf_token'];
}
/**
* Validate CSRF token
*/
function validate_csrf_token($token) {
if (session_status() === PHP_SESSION_NONE) {
// Configure secure session settings
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_samesite', 'Strict');
session_start();
}
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
/**
* Sanitize filename for headers to prevent HTTP Response Splitting
*/
function sanitize_filename_for_header($filename) {
// Remove any control characters and limit to ASCII printable chars
$filename = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $filename);
// Remove quotes and backslashes to prevent header injection
$filename = str_replace(['"', '\\', "\r", "\n"], '', $filename);
// Limit length to prevent excessively long headers
return mb_substr($filename, 0, 255);
}
/**
* Generate a UUID v4
*/
function generate_uuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
/**
* Get client IP address
*/
function get_client_ip() {
$ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
foreach ($ip_keys as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
// Handle comma-separated list of IPs
if (strpos($ip, ',') !== false) {
$ip = trim(explode(',', $ip)[0]);
}
// Validate IP
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}
/**
* Hash IP for GDPR compliance
*/
function hash_ip($ip) {
// normalize IPv4/IPv6
$normalized = inet_ntop(inet_pton($ip));
return hash('sha256', HASH_SALT . $normalized);
}
/**
* Check if IP is rate limited for downloads
*/
function is_rate_limited($ip) {
if (!file_exists(DOWNLOAD_LOG)) {
return false;
}
$hashed_ip = hash_ip($ip);
$current_time = time();
$fp = fopen(DOWNLOAD_LOG, 'r');
if (!$fp) return false;
while (($line = fgets($fp)) !== false) {
$parts = explode('|', trim($line));
if (count($parts) >= 2) {
[$log_ip, $timestamp] = $parts;
$timestamp = intval($timestamp);
if ($log_ip === $hashed_ip && ($current_time - $timestamp) < DOWNLOAD_RATE_LIMIT_SECONDS) {
fclose($fp);
return true;
}
}
}
fclose($fp);
return false;
}
/**
* Log download attempt
*/
function log_download($ip) {
$hashed_ip = hash_ip($ip);
$log_entry = $hashed_ip . '|' . time() . "\n";
// Append safely
file_put_contents(DOWNLOAD_LOG, $log_entry, FILE_APPEND | LOCK_EX);
// Keep log size under control
$lines = file(DOWNLOAD_LOG, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (count($lines) > MAX_LOG_LINES) {
$lines = array_slice($lines, -MAX_LOG_LINES); // keep recent only
file_put_contents(DOWNLOAD_LOG, implode("\n", $lines) . "\n", LOCK_EX);
}
}
/**
* Load files data from JSON
*/
function load_files_data() {
$json_content = file_get_contents(FILES_JSON);
return json_decode($json_content, true) ?: [];
}
/**
* Save files data to JSON
*/
function save_files_data($data) {
return file_put_contents(FILES_JSON, json_encode($data, JSON_PRETTY_PRINT), LOCK_EX);
}
/**
* Validate file extension
*/
function is_allowed_file_type($filename) {
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return in_array($extension, ALLOWED_EXTENSIONS);
}
/**
* Display error message and exit
*/
function display_error($message) {
error_log("User error: " . $message);
echo render_page("Error", "<div class='bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4'>$message</div>");
exit;
}
/**
* Display success message and exit
*/
function display_success($message) {
echo render_page("Success", "<div class='bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4'>$message</div>");
exit;
}
/**
* Render HTML page
*/
function render_page($title, $content) {
// Set security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Content-Security-Policy: default-src \'self\' cdn.tailwindcss.com; script-src \'self\' cdn.tailwindcss.com; style-src \'self\' \'unsafe-inline\' cdn.tailwindcss.com; img-src \'self\' data:; connect-src \'self\'');
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']);
return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$title - </title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
<div class="max-w-md w-full bg-white rounded-lg shadow-md p-6">
<h1 class="text-2xl font-bold text-center mb-6 text-gray-800"></h1>
$content
</div>
</body>
</html>
HTML;
}
// =============================================================================
// MAIN APPLICATION LOGIC
// =============================================================================
// Sanitize all input
$_GET = sanitize_input($_GET);
$_POST = sanitize_input($_POST);
// Route handling
if (isset($_GET['download'])) {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
handle_download($_GET['download'], $_POST['password'], $_POST['csrf_token'] ?? '');
} else {
show_download_form($_GET['download']);
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
handle_upload();
} else {
show_upload_form();
}
// =============================================================================
// ROUTE HANDLERS
// =============================================================================
/**
* Handle file upload
*/
function handle_upload() {
try {
// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Invalid request method');
}
// Validate CSRF token
$csrf_token = $_POST['csrf_token'] ?? '';
if (!validate_csrf_token($csrf_token)) {
throw new Exception('Invalid CSRF token. Please refresh the page and try again.');
}
// Check if file was uploaded
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
throw new Exception('No file uploaded or upload error occurred');
}
$file = $_FILES['file'];
$password = $_POST['password'] ?? '';
// Validate password
if (strlen($password) < PASSWORD_MIN_LENGTH) {
throw new Exception('Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters long');
}
// Validate file size
if ($file['size'] > MAX_FILE_SIZE) {
throw new Exception('File size exceeds maximum allowed size of ' . (MAX_FILE_SIZE / 1024 / 1024) . 'MB');
}
// Validate file type
if (!is_allowed_file_type($file['name'])) {
throw new Exception('File type not allowed. Allowed types: ' . implode(', ', ALLOWED_EXTENSIONS));
}
// Generate UUID and hash password
$uuid = generate_uuid();
$password_hash = password_hash($password, PASSWORD_DEFAULT);
// Save file with UUID name
$file_path = DOWNLOAD_DIR . '/' . $uuid;
if (!move_uploaded_file($file['tmp_name'], $file_path)) {
throw new Exception('Failed to save uploaded file');
}
// Add to files database
$files_data = load_files_data();
$files_data[$uuid] = [
'uuid' => $uuid,
'original_filename' => $file['name'],
'download_password_hash' => $password_hash,
'upload_timestamp' => time()
];
if (!save_files_data($files_data)) {
// Clean up uploaded file if database save fails
unlink($file_path);
throw new Exception('Failed to save file metadata');
}
// Generate links
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
$download_link = $base_url . '?download=' . urlencode($uuid);
$success_message = "
<p class='mb-4'>File uploaded successfully!</p>
<div class='space-y-4'>
<div>
<label class='block text-sm font-medium text-gray-700 mb-1'>Download Link:</label>
<input type='text' value='$download_link' class='w-full px-3 py-2 border border-gray-300 rounded-md text-sm' readonly onclick='this.select()'>
</div>
<div class='text-xs text-gray-600'>
<p><strong>Important:</strong> Share this link with the recipient. They will need the password you set to download.</p>
<p>The file will be automatically deleted after download.</p>
<p>Downloads are limited to 1 per minute per IP address.</p>
</div>
<a href='?' class='inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded'>Upload Another File</a>
</div>
";
display_success($success_message);
} catch (Exception $e) {
display_error($e->getMessage());
}
}
/**
* Show download form
*/
function show_download_form($uuid) {
// Validate UUID format
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid)) {
display_error('Invalid file ID');
return;
}
// Load files data to check if file exists
$files_data = load_files_data();
if (!isset($files_data[$uuid])) {
display_error('File not found or has been deleted');
return;
}
$file_info = $files_data[$uuid];
$original_filename = htmlspecialchars($file_info['original_filename']);
$csrf_token = generate_csrf_token();
$form = "
<div class='text-center mb-6'>
<h2 class='text-lg font-semibold text-gray-800 mb-2'>Download File</h2>
<p class='text-gray-600 mb-4'>File: <strong>$original_filename</strong></p>
</div>
<form method='post' class='space-y-4'>
<input type='hidden' name='csrf_token' value='" . htmlspecialchars($csrf_token) . "'>
<div>
<label for='password' class='block text-sm font-medium text-gray-700 mb-2'>Enter Download Password:</label>
<input type='password' id='password' name='password' required minlength='" . PASSWORD_MIN_LENGTH . "' class='w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500' autofocus>
<p class='text-xs text-gray-600 mt-1'>Enter the password provided by the file sender.</p>
</div>
<button type='submit' class='w-full bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-green-500'>Download File</button>
</form>
<div class='mt-6 text-xs text-gray-600 space-y-2'>
<p><strong>Note:</strong> The file will be automatically deleted after download.</p>
<p>Downloads are rate-limited to 1 per minute per IP address.</p>
</div>
";
echo render_page("Download File", $form);
}
/**
* Handle file download
*/
function handle_download($uuid, $token, $csrf_token) {
try {
// Validate CSRF token
if (!validate_csrf_token($csrf_token)) {
throw new Exception('Invalid CSRF token. Please refresh the page and try again.');
}
// Validate UUID format
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid)) {
throw new Exception('Invalid file ID');
}
// Check rate limiting
$client_ip = get_client_ip();
if (is_rate_limited($client_ip)) {
throw new Exception('Rate limit exceeded. Please wait before downloading another file.');
}
// Load files data
$files_data = load_files_data();
// Check if file exists in database
if (!isset($files_data[$uuid])) {
throw new Exception('File not found or has been deleted');
}
$file_info = $files_data[$uuid];
// Verify password
if (!password_verify($token, $file_info['download_password_hash'])) {
throw new Exception('Invalid download password');
}
$file_path = DOWNLOAD_DIR . '/' . $uuid;
// Check if physical file exists
if (!file_exists($file_path)) {
// Remove orphaned database entry
unset($files_data[$uuid]);
save_files_data($files_data);
throw new Exception('File not found or has been deleted');
}
// Log the download
log_download($client_ip);
// Serve the file
$original_filename = sanitize_filename_for_header($file_info['original_filename']);
$file_size = filesize($file_path);
// Set headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $original_filename . '"');
header('Content-Length: ' . $file_size);
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
// Output file contents
readfile($file_path);
// Delete file after successful download
unlink($file_path);
unset($files_data[$uuid]);
save_files_data($files_data);
exit;
} catch (Exception $e) {
display_error($e->getMessage());
}
}
/**
* Show upload form
*/
function show_upload_form() {
$max_size_mb = MAX_FILE_SIZE / 1024 / 1024;
$allowed_types = implode(', ', ALLOWED_EXTENSIONS);
$csrf_token = generate_csrf_token();
$form = "
<form method='post' enctype='multipart/form-data' class='space-y-4'>
<input type='hidden' name='csrf_token' value='" . htmlspecialchars($csrf_token) . "'>
<div>
<label for='file' class='block text-sm font-medium text-gray-700 mb-2'>Select File:</label>
<input type='file' id='file' name='file' required class='w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500'>
<p class='text-xs text-gray-600 mt-1'>Maximum size: {$max_size_mb}MB. Allowed types: $allowed_types</p>
</div>
<div>
<label for='password' class='block text-sm font-medium text-gray-700 mb-2'>Download Password:</label>
<input type='password' id='password' name='password' required minlength='" . PASSWORD_MIN_LENGTH . "' class='w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500'>
<p class='text-xs text-gray-600 mt-1'>Minimum " . PASSWORD_MIN_LENGTH . " characters. This password will be required to download the file.</p>
</div>
<button type='submit' class='w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-blue-500'>Upload File</button>
</form>
<div class='mt-6 text-xs text-gray-600 space-y-2'>
<p><strong>How it works:</strong></p>
<ul class='list-disc list-inside space-y-1'>
<li>Upload a file and set a download password</li>
<li>Share the download link with the intended recipient</li>
<li>Recipient enters the password to download the file</li>
<li>File is automatically deleted after download</li>
<li>Downloads are rate-limited to 1 per minute per IP</li>
</ul>
</div>
";
echo render_page("Upload File", $form);
}
?>