-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.php
More file actions
264 lines (233 loc) · 9.96 KB
/
Copy pathsetup.php
File metadata and controls
264 lines (233 loc) · 9.96 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
<?php
declare(strict_types=1);
// Session must be started before any header() calls.
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Security Headers matching index.php
$cspNonce = bin2hex(random_bytes(16));
$cspHeader = "default-src 'self'; " .
"script-src 'self' 'nonce-{$cspNonce}'; " .
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " .
"font-src 'self' https://fonts.gstatic.com; " .
"img-src 'self' data: https:; " .
"connect-src 'self'; " .
"frame-ancestors 'self'; " .
"base-uri 'self'; " .
"form-action 'self';";
header("Content-Security-Policy: $cspHeader");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("Permissions-Policy: geolocation=(), camera=(), microphone=()");
// Prevent caching
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
/**
* WebyMail – First-run setup wizard
* Access this file directly (setup.php) before the application is configured.
* Once setup is complete, this file can be deleted or renamed.
*/
define('WEBYMAIL_ROOT', __DIR__);
spl_autoload_register(function (string $class): void {
$file = __DIR__ . '/src/' . $class . '.php';
if (file_exists($file)) {
require_once $file;
}
});
require_once __DIR__ . '/src/Config.php';
// Persist ?force=1 into the session so it survives POST redirects
// (form actions use ?action=setup which drops the force query param).
if (($_GET['force'] ?? '') === '1') {
$_SESSION['setup_force'] = true;
}
$isForced = !empty($_SESSION['setup_force']);
// If already set up, redirect to main app unless force setup is requested
if (Config::get('setup_complete') && !$isForced && ($_GET['action'] ?? '') !== 'setup') {
header('Location: index.php');
exit;
}
// Re-running setup on an already-configured installation (force=1) requires
// an active authenticated session to prevent unauthorised reconfiguration.
if ($isForced && Config::get('setup_complete')) {
spl_autoload_register(function (string $class): void {
$file = __DIR__ . '/src/' . $class . '.php';
if (file_exists($file)) {
require_once $file;
}
}, prepend: true);
$sessionObj = new Session();
$currentSession = $sessionObj->current();
if ($currentSession === null || (int)$currentSession['user_id'] !== 1) {
// No valid session or not the first user: abort and send the user to the normal login page
unset($_SESSION['setup_force']);
header('Location: index.php?action=login');
exit;
}
}
// Simple CSRF token for setup forms (session-bound, single token for the whole wizard)
if (empty($_SESSION['setup_csrf'])) {
$_SESSION['setup_csrf'] = bin2hex(random_bytes(32));
}
$setupCsrfToken = $_SESSION['setup_csrf'];
// Validate CSRF on every POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$submittedCsrf = $_POST['setup_csrf'] ?? '';
if (!hash_equals($setupCsrfToken, $submittedCsrf)) {
http_response_code(403);
die('Security token mismatch. Please go back and try again.');
}
}
$step = 'welcome';
$error = null;
$requirements = [];
$securityChecks = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$step = $_POST['step'] ?? 'welcome';
if ($step === 'requirements') {
$needed = ['imap', 'pdo_sqlite', 'openssl', 'mbstring', 'iconv'];
$allOk = true;
foreach ($needed as $ext) {
$ok = extension_loaded($ext);
$requirements[$ext] = $ok;
if (!$ok) $allOk = false;
}
if (!$allOk && !isset($_POST['ignore_requirements'])) {
$step = 'requirements';
} else {
$step = 'server';
}
} elseif ($step === 'server') {
// Just show server settings form
} elseif ($step === 'save') {
// Validate and save
$appName = trim($_POST['app_name'] ?? 'WebyMail');
$imapHost = trim($_POST['imap_host'] ?? '');
$imapPort = (int) ($_POST['imap_port'] ?? 993);
$imapSsl = !empty($_POST['imap_ssl']);
$smtpHost = trim($_POST['smtp_host'] ?? '');
$smtpPort = (int) ($_POST['smtp_port'] ?? 587);
$smtpSsl = !empty($_POST['smtp_ssl']);
$smtpTls = !empty($_POST['smtp_starttls']);
$captchaOn = !empty($_POST['captcha_enabled']);
$timezone = trim($_POST['timezone'] ?? 'Europe/Rome');
$hideServer = !empty($_POST['hide_server_on_login']);
$removeFavicon = !empty($_POST['remove_favicon']);
Config::set('app_name', $appName);
Config::set('imap_host', $imapHost);
Config::set('imap_port', $imapPort);
Config::set('imap_ssl', $imapSsl);
Config::set('smtp_host', $smtpHost);
Config::set('smtp_port', $smtpPort);
Config::set('smtp_ssl', $smtpSsl);
Config::set('smtp_starttls', $smtpTls);
Config::set('captcha_enabled', $captchaOn);
Config::set('2fa_enabled', true); // Always enabled by default, can be disabled in config.php manually if needed
Config::set('timezone', $timezone);
Config::set('hide_server_on_login', $hideServer);
Config::set('setup_complete', true);
Config::set('version', null); // Ensure version is removed from config.php
Config::set('update_url', Config::UPDATE_URL);
// Cleanup obsolete keys
Config::set('altcha_hmac_key', null);
Config::set('altcha_enabled', null);
if ($removeFavicon) {
Config::set('favicon_path', null);
}
// Handle Favicon upload
if (!empty($_FILES['favicon']['name']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES['favicon']['name'], PATHINFO_EXTENSION));
if (in_array($ext, ['ico', 'png', 'svg'])) {
$imgDir = __DIR__ . '/assets/img';
if (!is_dir($imgDir)) {
mkdir($imgDir, 0755, true);
}
$faviconPath = 'assets/img/favicon.' . $ext;
if (move_uploaded_file($_FILES['favicon']['tmp_name'], __DIR__ . '/' . $faviconPath)) {
Config::set('favicon_path', $faviconPath);
}
}
}
// Ensure data directory is writable
$dataDir = __DIR__ . '/data';
if (!is_dir($dataDir) && !mkdir($dataDir, 0750, true)) {
$error = 'Cannot create data/ directory. Please create it manually and make it writable.';
$step = 'server';
} else {
Config::save();
// Database backup before schema modifications (if database exists)
$dbPath = Config::resolveDbPath();
if (is_file($dbPath)) {
// Save backup in the same directory as the database
$backupDir = dirname($dbPath);
if (is_dir($backupDir) && is_writable($backupDir)) {
$backupFile = $backupDir . '/webymail_backup_' . date('Ymd_His') . '.db';
@copy($dbPath, $backupFile);
// Also copy WAL/SHM if they exist, to ensure a complete backup
foreach (['-wal', '-shm'] as $suffix) {
if (is_file($dbPath . $suffix)) {
@copy($dbPath . $suffix, $backupFile . $suffix);
}
}
// Maintain only 5 backups
Config::rotateBackups($backupDir, 5);
}
}
// Initialise the database (creates the SQLite file + schema)
try {
Database::getInstance();
} catch (Exception $e) {
error_log('Database initialisation failed during setup: ' . $e->getMessage());
$error = 'Database initialisation failed. Please confirm the data directory is writable and try again.';
$step = 'server';
}
if ($error === null) {
$step = 'security';
$sys = Config::checkSystem();
$securityChecks = $sys['security'];
}
}
} elseif ($step === 'finish') {
$step = 'done';
// Clear the force flag so the wizard cannot be re-entered without ?force=1
unset($_SESSION['setup_force'], $_SESSION['setup_csrf']);
// Move setup.php to the database directory for security (hardening)
$dbDir = dirname(Config::resolveDbPath());
if (is_dir($dbDir) && is_writable($dbDir)) {
@rename(__FILE__, $dbDir . DIRECTORY_SEPARATOR . 'setup.php');
} else {
@unlink(__FILE__);
}
} elseif ($step === 'fix_permissions') {
// Ensure a session is active so Config::checkSystem() can persist the
// result cache, preventing a stale "issues found" banner in the main app.
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Config::fixPermissions();
$step = 'security';
$sys = Config::checkSystem();
$securityChecks = $sys['security'];
} elseif ($step === 'move_database') {
$targetPath = trim($_POST['db_target_path'] ?? '');
if ($targetPath === '') {
$targetPath = Config::suggestSafeDbPath();
}
$result = Config::moveDatabase($targetPath);
if (!$result['ok']) {
$error = 'Failed to move database: ' . $result['error'];
}
$step = 'security';
$sys = Config::checkSystem();
$securityChecks = $sys['security'];
}
}
// Render
ob_start();
include __DIR__ . '/templates/setup.php';
$content = ob_get_clean();
$pageTitle = Config::get('app_name', 'WebyMail') . ' Setup';
$shellLayout = false;
include __DIR__ . '/templates/layout.php';