-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.php
More file actions
418 lines (365 loc) · 12.2 KB
/
Copy pathsecurity.php
File metadata and controls
418 lines (365 loc) · 12.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
<?php
/**
* Sigma SMS A2P — Security Functions
* Rate limiting, input validation, and security utilities
*/
/**
* Rate Limiter
* Prevents brute force and abuse
*/
class RateLimiter {
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
/**
* Check if action is rate limited
* @param string $identifier User ID, IP, or unique identifier
* @param string $action Action type (login, api_call, etc.)
* @param int $maxAttempts Maximum attempts allowed
* @param int $windowSeconds Time window in seconds
* @return bool True if rate limit exceeded
*/
public function isRateLimited(string $identifier, string $action, int $maxAttempts = 5, int $windowSeconds = 300): bool {
$stmt = $this->pdo->prepare("
SELECT COUNT(*) FROM rate_limits
WHERE identifier = ? AND action = ?
AND created_at >= DATE_SUB(NOW(), INTERVAL ? SECOND)
");
$stmt->execute([$identifier, $action, $windowSeconds]);
$count = $stmt->fetchColumn();
return $count >= $maxAttempts;
}
/**
* Record an attempt
*/
public function recordAttempt(string $identifier, string $action): void {
$stmt = $this->pdo->prepare("
INSERT INTO rate_limits (identifier, action, created_at)
VALUES (?, ?, NOW())
");
$stmt->execute([$identifier, $action]);
// Clean old records (older than 1 hour)
$this->pdo->query("DELETE FROM rate_limits WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR)");
}
/**
* Get remaining attempts
*/
public function getRemainingAttempts(string $identifier, string $action, int $maxAttempts = 5, int $windowSeconds = 300): int {
$stmt = $this->pdo->prepare("
SELECT COUNT(*) FROM rate_limits
WHERE identifier = ? AND action = ?
AND created_at >= DATE_SUB(NOW(), INTERVAL ? SECOND)
");
$stmt->execute([$identifier, $action, $windowSeconds]);
$count = $stmt->fetchColumn();
return max(0, $maxAttempts - $count);
}
/**
* Clear rate limit for identifier
*/
public function clearLimit(string $identifier, string $action): void {
$stmt = $this->pdo->prepare("DELETE FROM rate_limits WHERE identifier = ? AND action = ?");
$stmt->execute([$identifier, $action]);
}
}
/**
* Input Sanitizer
*/
class InputSanitizer {
/**
* Sanitize string input
*/
public static function sanitizeString(string $input, int $maxLength = 255): string {
$input = trim($input);
$input = strip_tags($input);
$input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
return substr($input, 0, $maxLength);
}
/**
* Sanitize phone number
*/
public static function sanitizePhone(string $phone): string {
// Remove all non-digit and non-plus characters
$phone = preg_replace('/[^0-9+]/', '', $phone);
// Ensure + is only at the start
$phone = '+' . str_replace('+', '', $phone);
return substr($phone, 0, 20);
}
/**
* Sanitize email
*/
public static function sanitizeEmail(string $email): string {
$email = trim(strtolower($email));
return filter_var($email, FILTER_SANITIZE_EMAIL);
}
/**
* Validate email
*/
public static function isValidEmail(string $email): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
/**
* Validate phone number
*/
public static function isValidPhone(string $phone): bool {
return preg_match('/^\+[1-9]\d{1,14}$/', $phone);
}
/**
* Sanitize URL
*/
public static function sanitizeUrl(string $url): string {
return filter_var($url, FILTER_SANITIZE_URL);
}
/**
* Validate URL
*/
public static function isValidUrl(string $url): bool {
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
/**
* Sanitize integer
*/
public static function sanitizeInt($value, int $min = PHP_INT_MIN, int $max = PHP_INT_MAX): int {
$value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$value = (int)$value;
return max($min, min($max, $value));
}
/**
* Sanitize float
*/
public static function sanitizeFloat($value, float $min = PHP_FLOAT_MIN, float $max = PHP_FLOAT_MAX): float {
$value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$value = (float)$value;
return max($min, min($max, $value));
}
}
/**
* SQL Injection Prevention
* Always use prepared statements, but this adds extra layer
*/
class SQLSanitizer {
/**
* Escape identifier (table/column name)
*/
public static function escapeIdentifier(string $identifier): string {
// Remove any backticks and escape
$identifier = str_replace('`', '', $identifier);
// Only allow alphanumeric and underscore
if (!preg_match('/^[a-zA-Z0-9_]+$/', $identifier)) {
throw new InvalidArgumentException('Invalid identifier');
}
return '`' . $identifier . '`';
}
/**
* Validate ORDER BY direction
*/
public static function sanitizeOrderDirection(string $direction): string {
$direction = strtoupper(trim($direction));
return in_array($direction, ['ASC', 'DESC']) ? $direction : 'ASC';
}
}
/**
* XSS Prevention
*/
class XSSProtection {
/**
* Clean HTML output
*/
public static function clean(string $input): string {
return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Clean for JavaScript context
*/
public static function cleanJS(string $input): string {
return json_encode($input, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
}
/**
* Clean for URL context
*/
public static function cleanURL(string $input): string {
return urlencode($input);
}
}
/**
* Password Security
*/
class PasswordSecurity {
/**
* Validate password strength
*/
public static function isStrongPassword(string $password): array {
$errors = [];
if (strlen($password) < 8) {
$errors[] = 'Password must be at least 8 characters long';
}
if (!preg_match('/[A-Z]/', $password)) {
$errors[] = 'Password must contain at least one uppercase letter';
}
if (!preg_match('/[a-z]/', $password)) {
$errors[] = 'Password must contain at least one lowercase letter';
}
if (!preg_match('/[0-9]/', $password)) {
$errors[] = 'Password must contain at least one number';
}
if (!preg_match('/[^A-Za-z0-9]/', $password)) {
$errors[] = 'Password must contain at least one special character';
}
return [
'valid' => empty($errors),
'errors' => $errors
];
}
/**
* Hash password
*/
public static function hash(string $password): string {
return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}
/**
* Verify password
*/
public static function verify(string $password, string $hash): bool {
return password_verify($password, $hash);
}
}
/**
* Session Security
*/
class SessionSecurity {
/**
* Regenerate session ID
*/
public static function regenerate(): void {
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id(true);
}
}
/**
* Validate session
*/
public static function validate(): bool {
// Check if session has user agent
if (!isset($_SESSION['user_agent'])) {
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
}
// Verify user agent hasn't changed
if ($_SESSION['user_agent'] !== ($_SERVER['HTTP_USER_AGENT'] ?? '')) {
return false;
}
// Check session timeout (24 hours)
if (isset($_SESSION['last_activity'])) {
if (time() - $_SESSION['last_activity'] > 86400) {
return false;
}
}
$_SESSION['last_activity'] = time();
return true;
}
/**
* Destroy session securely
*/
public static function destroy(): void {
$_SESSION = [];
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/');
}
session_destroy();
}
}
/**
* IP Security
*/
class IPSecurity {
/**
* Get real client IP
*/
public static function getClientIP(): string {
$headers = [
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_X_FORWARDED_FOR',
'HTTP_X_REAL_IP',
'REMOTE_ADDR'
];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
$ip = $_SERVER[$header];
// Handle comma-separated IPs (X-Forwarded-For)
if (strpos($ip, ',') !== false) {
$ips = explode(',', $ip);
$ip = trim($ips[0]);
}
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
}
}
}
return '0.0.0.0';
}
/**
* Check if IP is in whitelist
*/
public static function isWhitelisted(string $ip, array $whitelist): bool {
return in_array($ip, $whitelist);
}
/**
* Check if IP is in blacklist
*/
public static function isBlacklisted(string $ip, array $blacklist): bool {
return in_array($ip, $blacklist);
}
}
/**
* File Upload Security
*/
class FileUploadSecurity {
private static $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
private static $maxFileSize = 5242880; // 5MB
/**
* Validate uploaded file
*/
public static function validateUpload(array $file): array {
$errors = [];
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = 'File upload error: ' . $file['error'];
return ['valid' => false, 'errors' => $errors];
}
if ($file['size'] > self::$maxFileSize) {
$errors[] = 'File size exceeds maximum allowed (5MB)';
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, self::$allowedExtensions)) {
$errors[] = 'File type not allowed';
}
// Check MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
$allowedMimes = [
'image/jpeg', 'image/png', 'image/gif',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];
if (!in_array($mimeType, $allowedMimes)) {
$errors[] = 'Invalid file MIME type';
}
return [
'valid' => empty($errors),
'errors' => $errors,
'extension' => $ext,
'mime_type' => $mimeType
];
}
/**
* Generate safe filename
*/
public static function generateSafeFilename(string $originalName): string {
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$basename = pathinfo($originalName, PATHINFO_FILENAME);
$basename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $basename);
$basename = substr($basename, 0, 50);
return $basename . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
}
}