-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
422 lines (352 loc) · 13.9 KB
/
auth.php
File metadata and controls
422 lines (352 loc) · 13.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
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
<?php
/**
* 用户认证管理类
*/
require_once __DIR__ . '/includes/security_headers.php';
class Auth {
private const MAX_USERNAME_LENGTH = 64;
private const MAX_PASSWORD_LENGTH = 1024;
/**
* 启动会话
*/
public static function startSession(): void {
if (session_status() === PHP_SESSION_NONE) {
if (!headers_sent()) {
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
(!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) ||
(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') ||
(!empty($_SERVER['HTTP_CF_VISITOR']) && strpos($_SERVER['HTTP_CF_VISITOR'], 'https') !== false);
ini_set('session.cookie_secure', $isHttps ? '1' : '0');
$cookieParams = session_get_cookie_params();
session_set_cookie_params([
'lifetime' => $cookieParams['lifetime'] ?? 0,
'path' => $cookieParams['path'] ?? '/',
'domain' => $cookieParams['domain'] ?? '',
'secure' => $isHttps,
'httponly' => true,
'samesite' => 'Lax'
]);
}
session_start();
}
}
/**
* 检查是否启用登录功能
*/
public static function isLoginEnabled(): bool {
return defined('ENABLE_LOGIN') && ENABLE_LOGIN === true;
}
/**
* 验证用户凭据
*/
public static function validateCredentials(string $username, string $password): bool {
if (
strlen($username) === 0 ||
strlen($username) > self::MAX_USERNAME_LENGTH ||
strlen($password) === 0 ||
strlen($password) > self::MAX_PASSWORD_LENGTH
) {
return false;
}
if (!defined('LOGIN_USERNAME')) {
return false;
}
if ($username !== LOGIN_USERNAME) {
return false;
}
// 仅允许密码哈希校验
if (defined('LOGIN_PASSWORD_HASH') && is_string(LOGIN_PASSWORD_HASH) && LOGIN_PASSWORD_HASH !== '') {
return password_verify($password, LOGIN_PASSWORD_HASH);
}
error_log('[NetWatch][SECURITY] LOGIN_PASSWORD_HASH is required. Plaintext LOGIN_PASSWORD is no longer supported.');
return false;
}
/**
* 用户登录
*/
public static function login(string $username, string $password): bool|string {
self::startSession();
if (self::validateCredentials($username, $password)) {
// 尝试设置session数据
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $username;
$_SESSION['login_time'] = time();
$_SESSION['last_activity'] = time();
// 强制写入session数据到存储
session_write_close();
// 重新启动session并验证数据是否成功写入
self::startSession();
// 检查session数据是否成功保存
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true ||
!isset($_SESSION['username']) || $_SESSION['username'] !== $username) {
// Session写入失败,清理可能的残留数据
$_SESSION = array();
return 'session_write_failed';
}
// 登录成功后重新生成Session ID,防止会话固定攻击
if (session_status() === PHP_SESSION_ACTIVE) {
try {
session_regenerate_id(true);
} catch (\Exception $e) {
error_log('[NetWatch] session_regenerate_id 失败: ' . $e->getMessage());
}
}
if (file_exists(__DIR__ . '/includes/AuditLogger.php')) {
require_once __DIR__ . '/includes/AuditLogger.php';
AuditLogger::log('login', 'user', $username);
}
return true;
}
return false;
}
/**
* 用户登出
* @param bool $redirect 是否重定向到登录页面(CLI/测试场景可设为false)
*/
public static function logout(bool $redirect = true): void {
self::startSession();
$username = $_SESSION['username'] ?? null;
if (file_exists(__DIR__ . '/includes/AuditLogger.php')) {
require_once __DIR__ . '/includes/AuditLogger.php';
AuditLogger::log('logout', 'user', $username);
}
// 清除所有session数据
$_SESSION = [];
// 删除session cookie
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/');
}
// 销毁session
session_destroy();
// CLI 模式或明确不重定向时,仅清理 session 不做 header/exit
if (php_sapi_name() === 'cli' || !$redirect) {
return;
}
// 重定向到登录页面(使用根目录路径)
$loginPath = self::getLoginPath();
header('Location: ' . $loginPath);
exit;
}
/**
* 检查用户是否已登录
*/
public static function isLoggedIn(): bool {
// 如果未启用登录功能,直接返回true
if (!self::isLoginEnabled()) {
return true;
}
self::startSession();
// 检查是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
return false;
}
// 检查会话是否超时
if (self::isSessionExpired()) {
self::logout();
return false;
}
// 更新最后活动时间
$_SESSION['last_activity'] = time();
return true;
}
/**
* 检查会话是否过期
*/
public static function isSessionExpired(): bool {
if (!isset($_SESSION['last_activity'])) {
return true;
}
$timeout = defined('SESSION_TIMEOUT') ? SESSION_TIMEOUT : 3600;
return (time() - $_SESSION['last_activity']) > $timeout;
}
/**
* 获取当前登录用户名
*/
public static function getCurrentUser(): ?string {
self::startSession();
return $_SESSION['username'] ?? null;
}
/**
* 获取登录时间
*/
public static function getLoginTime(): ?int {
self::startSession();
return $_SESSION['login_time'] ?? null;
}
/**
* 获取剩余会话时间(秒)
*/
public static function getRemainingSessionTime(): int {
if (!isset($_SESSION['last_activity'])) {
return 0;
}
$timeout = defined('SESSION_TIMEOUT') ? SESSION_TIMEOUT : 3600;
$elapsed = time() - $_SESSION['last_activity'];
return max(0, $timeout - $elapsed);
}
/**
* 生成CSRF Token
*/
public static function generateCsrfToken(): string {
self::startSession();
$tokenLifetime = 3600; // CSRF Token有效期1小时
// 检查是否需要轮换(不存在或已过期)
if (!isset($_SESSION['csrf_token']) ||
!isset($_SESSION['csrf_token_time']) ||
(time() - $_SESSION['csrf_token_time']) > $tokenLifetime) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$_SESSION['csrf_token_time'] = time();
}
return $_SESSION['csrf_token'];
}
/**
* 验证CSRF Token
*/
public static function validateCsrfToken(string $token): bool {
self::startSession();
if (!isset($_SESSION['csrf_token'])) {
return false;
}
return hash_equals($_SESSION['csrf_token'], $token);
}
/**
* 获取当前CSRF Token
*/
public static function getCsrfToken(): string {
self::startSession();
return $_SESSION['csrf_token'] ?? self::generateCsrfToken();
}
/**
* 要求用户登录(重定向到登录页面)
*/
public static function requireLogin(): void {
if (self::isDebugRequestPath()) {
$debugEnabled = defined('ENABLE_DEBUG_TOOLS') && ENABLE_DEBUG_TOOLS === true;
$allowInProduction = defined('ALLOW_DEBUG_TOOLS_IN_PRODUCTION') && ALLOW_DEBUG_TOOLS_IN_PRODUCTION === true;
if (!$debugEnabled || (self::isProductionEnvironment() && !$allowInProduction)) {
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo 'Not Found';
exit;
}
}
if (!self::isLoggedIn()) {
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$isXmlHttpRequest = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
$acceptsJson = !empty($accept) && (strpos($accept, 'application/json') !== false);
$acceptsHtml = !empty($accept) && (strpos($accept, 'text/html') !== false);
$hasAjaxParam = isset($_GET['ajax']) && ($_GET['ajax'] === '1' || $_GET['ajax'] === 'true' || $_GET['ajax'] === 1);
// 如果是AJAX/JSON请求,返回JSON响应
if ($isXmlHttpRequest || $hasAjaxParam || ($acceptsJson && !$acceptsHtml)) {
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
echo json_encode([
'error' => 'unauthorized',
'message' => '请先登录'
]);
exit;
}
// 保存当前页面URL,登录后重定向
$currentUrl = $_SERVER['REQUEST_URI'];
if ($currentUrl !== '/login.php') {
$_SESSION['redirect_after_login'] = $currentUrl;
}
// 重定向到登录页面(使用根目录路径)
$loginPath = self::getLoginPath();
header('Location: ' . $loginPath);
exit;
}
}
/**
* 是否是 Debug 目录请求
*/
private static function isDebugRequestPath(): bool {
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
return stripos($scriptName, '/Debug/') !== false || stripos($scriptName, '\\Debug\\') !== false;
}
/**
* 是否为生产环境(默认按生产环境处理,避免误暴露调试工具)
*/
private static function isProductionEnvironment(): bool {
$appEnv = defined('APP_ENV') ? strtolower((string)APP_ENV) : 'production';
return !in_array($appEnv, ['local', 'dev', 'development', 'test', 'testing'], true);
}
/**
* 获取登录页面路径(支持从子目录调用)
*/
private static function getLoginPath(): string {
// 获取当前脚本相对于网站根目录的路径
$scriptName = $_SERVER['SCRIPT_NAME'];
$scriptDir = dirname($scriptName);
// 计算到根目录的相对路径
if ($scriptDir === '/' || $scriptDir === '\\') {
return 'login.php';
}
// 计算需要返回的层级数
$levels = substr_count($scriptDir, '/');
$relativePath = str_repeat('../', $levels) . 'login.php';
return $relativePath;
}
/**
* 获取登录后重定向URL
*/
public static function getRedirectUrl(): string {
self::startSession();
$redirectUrl = $_SESSION['redirect_after_login'] ?? '/';
unset($_SESSION['redirect_after_login']);
// Ensure we return a valid URL path
if ($redirectUrl === '/' || empty($redirectUrl)) {
return '/';
}
// Remove any leading slashes to prevent double slashes
return '/' . ltrim($redirectUrl, '/');
}
/**
* 检测存储空间是否足够
*/
public static function checkStorageSpace(): array {
$sessionPath = session_save_path();
if (empty($sessionPath)) {
$sessionPath = sys_get_temp_dir();
}
// 检查磁盘空间
$freeBytes = disk_free_space($sessionPath);
$totalBytes = disk_total_space($sessionPath);
if ($freeBytes === false || $totalBytes === false) {
return [
'status' => 'unknown',
'message' => '无法检测存储空间'
];
}
$freePercent = ($freeBytes / $totalBytes) * 100;
if ($freePercent < 1) {
return [
'status' => 'critical',
'message' => '存储空间严重不足(剩余 ' . round($freePercent, 2) . '%),可能导致登录失败',
'free_percent' => $freePercent,
'free_mb' => round($freeBytes / 1024 / 1024, 2)
];
} elseif ($freePercent < 5) {
return [
'status' => 'warning',
'message' => '存储空间不足(剩余 ' . round($freePercent, 2) . '%)',
'free_percent' => $freePercent,
'free_mb' => round($freeBytes / 1024 / 1024, 2)
];
}
return [
'status' => 'ok',
'message' => '存储空间充足',
'free_percent' => $freePercent,
'free_mb' => round($freeBytes / 1024 / 1024, 2)
];
}
}
?>