-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
570 lines (478 loc) · 18.4 KB
/
auth.php
File metadata and controls
570 lines (478 loc) · 18.4 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
<?php
/**
* 用户认证管理类
*/
require_once __DIR__ . '/includes/security_headers.php';
require_once __DIR__ . '/includes/Config.php';
require_once __DIR__ . '/includes/functions.php';
class Auth {
private const MAX_USERNAME_LENGTH = 64;
private const MAX_PASSWORD_LENGTH = 1024;
private const MIN_PASSWORD_LENGTH = 12;
/**
* 启动会话
*/
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 = netwatch_is_https_request();
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;
}
/**
* 验证用户凭据
* @param string $username 用户名
* @param string $password 明文密码
* @return bool 凭据是否合法
*/
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 (self::isPasswordStrengthEnforced() && !self::isStrongPassword($password)) {
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;
}
/**
* 是否启用登录密码强度校验
* @return bool true=启用,false=关闭
*/
private static function isPasswordStrengthEnforced(): bool {
if (defined('ENFORCE_LOGIN_PASSWORD_STRENGTH')) {
return ENFORCE_LOGIN_PASSWORD_STRENGTH === true;
}
return true;
}
/**
* 校验密码复杂度是否满足策略要求
* @param string $password 明文密码
* @return bool 是否满足最小长度和复杂度要求
*/
private static function isStrongPassword(string $password): bool {
if (strlen($password) < self::MIN_PASSWORD_LENGTH) {
return false;
}
$hasUpper = preg_match('/[A-Z]/', $password) === 1;
$hasLower = preg_match('/[a-z]/', $password) === 1;
$hasNumber = preg_match('/\d/', $password) === 1;
$hasSpecial = preg_match('/[^a-zA-Z\d]/', $password) === 1;
return $hasUpper && $hasLower && $hasNumber && $hasSpecial;
}
/**
* 用户登录
* @param string $username 用户名
* @param string $password 明文密码
* @return bool|string 成功返回 true,失败返回 false,Session 写入异常时返回错误码字符串
*/
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()])) {
$cookieParams = session_get_cookie_params();
setcookie(session_name(), '', [
'expires' => time() - 3600,
'path' => $cookieParams['path'] ?? '/',
'domain' => $cookieParams['domain'] ?? '',
'secure' => (bool) ($cookieParams['secure'] ?? false),
'httponly' => (bool) ($cookieParams['httponly'] ?? true),
'samesite' => $cookieParams['samesite'] ?? 'Lax'
]);
}
// 销毁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(false);
return false;
}
// 更新最后活动时间
$_SESSION['last_activity'] = time();
return true;
}
/**
* 检查会话是否过期
* @return bool true=已过期,false=未过期
*/
public static function isSessionExpired(): bool {
if (!isset($_SESSION['last_activity'])) {
return true;
}
$timeout = (int) config('security.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;
}
/**
* 获取剩余会话时间(秒)
* @return int 剩余秒数;未登录或无活动记录时返回 0
*/
public static function getRemainingSessionTime(): int {
if (!isset($_SESSION['last_activity'])) {
return 0;
}
$timeout = (int) config('security.session_timeout', 3600);
$elapsed = time() - $_SESSION['last_activity'];
return max(0, $timeout - $elapsed);
}
/**
* 生成CSRF Token
* @return string CSRF Token
* @throws \Exception random_bytes 失败时抛出异常
*/
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
* @param string $token 前端提交的 CSRF Token
* @return bool 是否校验通过
*/
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();
}
/**
* 要求用户登录(重定向到登录页面)
* @return void
*/
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::isLoginEnabled()) {
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo 'Not Found';
exit;
}
}
if (!self::isLoggedIn()) {
// 如果是AJAX/JSON请求,返回JSON响应
if (netwatch_request_expects_json_response()) {
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 目录请求
* @return bool 当前请求是否指向 Debug 目录
*/
private static function isDebugRequestPath(): bool {
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
return stripos($scriptName, '/Debug/') !== false || stripos($scriptName, '\\Debug\\') !== false;
}
/**
* 是否为生产环境(默认按生产环境处理,避免误暴露调试工具)
* @return bool true=生产环境,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);
}
/**
* 获取登录页面路径(支持从子目录调用)
* @return string 登录页相对路径
*/
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
* @return string 安全的站内重定向路径
*/
public static function getRedirectUrl(): string {
self::startSession();
$redirectUrl = (string) ($_SESSION['redirect_after_login'] ?? '/');
unset($_SESSION['redirect_after_login']);
if ($redirectUrl === '' || $redirectUrl === '/') {
return '/';
}
if (preg_match('/[\x00-\x1F\x7F]/', $redirectUrl) === 1) {
return '/';
}
if (preg_match('/^[a-z][a-z0-9+\-.]*:/i', $redirectUrl) === 1) {
return '/';
}
if (strncmp($redirectUrl, '//', 2) === 0 || strncmp($redirectUrl, '\\\\', 2) === 0) {
return '/';
}
if ($redirectUrl[0] !== '/') {
return '/';
}
return $redirectUrl;
}
/**
* 检测存储空间是否足够
* @return array{status:string,message:string,free_percent?:float,free_mb?:float} 存储空间检查结果
*/
public static function checkStorageSpace(): array {
$sessionPath = self::resolveSessionStoragePath();
if (!is_dir($sessionPath) || !is_readable($sessionPath) || !is_writable($sessionPath)) {
return [
'status' => 'warning',
'message' => 'Session 存储目录不可读或不可写:' . $sessionPath
];
}
if (self::isSessionPathStrictCheckEnabled()) {
$worldWritable = self::isWorldWritablePath($sessionPath);
if ($worldWritable === true) {
return [
'status' => 'warning',
'message' => 'Session 存储目录权限过宽(对所有用户可写),建议收紧目录权限:' . $sessionPath
];
}
}
// 检查磁盘空间
$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)
];
}
/**
* 解析 Session 存储目录路径
* @return string Session 目录绝对路径
*/
private static function resolveSessionStoragePath(): string {
$sessionPath = trim((string) session_save_path());
if ($sessionPath === '') {
return sys_get_temp_dir();
}
if (strpos($sessionPath, ';') !== false) {
$parts = explode(';', $sessionPath);
$last = trim((string) end($parts));
if ($last !== '') {
return $last;
}
}
return $sessionPath;
}
/**
* 是否启用 Session 目录严格权限检查
* @return bool true=启用,false=关闭
*/
private static function isSessionPathStrictCheckEnabled(): bool {
if (defined('SESSION_PATH_STRICT_CHECK')) {
return (bool) SESSION_PATH_STRICT_CHECK;
}
return true;
}
/**
* 判断目录是否对所有用户可写且无 sticky bit 保护
* @param string $path 待检查目录路径
* @return bool|null true=存在风险,false=安全,null=当前平台或权限信息不可判定
*/
private static function isWorldWritablePath(string $path): ?bool {
if (DIRECTORY_SEPARATOR !== '/') {
return null;
}
$perms = @fileperms($path);
if ($perms === false) {
return null;
}
$worldWritable = (($perms & 0x0002) === 0x0002);
if (!$worldWritable) {
return false;
}
$stickyBitSet = (($perms & 0x0200) === 0x0200);
if ($stickyBitSet) {
return false;
}
return true;
}
}