-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.php
More file actions
681 lines (573 loc) · 19.9 KB
/
deploy.php
File metadata and controls
681 lines (573 loc) · 19.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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<?php
/**
* PHP Terminal Production Deployment Script
* Automated deployment and configuration
*/
class ProductionDeployer
{
private $config;
private $logFile;
public function __construct()
{
$this->logFile = __DIR__ . '/phpterminal/logs/deployment.log';
$this->config = [
'backup_before_deploy' => true,
'run_tests' => true,
'optimize_performance' => true,
'set_permissions' => true,
'enable_security' => true,
'create_admin_user' => true
];
}
/**
* Run full deployment
*/
public function deploy()
{
$this->log('Starting production deployment...');
try {
// Pre-deployment checks
$this->preDeploymentChecks();
// Create backup if enabled
if ($this->config['backup_before_deploy']) {
$this->createBackup();
}
// Run tests if enabled
if ($this->config['run_tests']) {
$this->runTests();
}
// Optimize performance
if ($this->config['optimize_performance']) {
$this->optimizePerformance();
}
// Set proper permissions
if ($this->config['set_permissions']) {
$this->setPermissions();
}
// Enable security features
if ($this->config['enable_security']) {
$this->enableSecurity();
}
// Create admin user
if ($this->config['create_admin_user']) {
$this->createAdminUser();
}
// Post-deployment verification
$this->postDeploymentVerification();
$this->log('Deployment completed successfully!');
return ['success' => true, 'message' => 'Deployment completed successfully'];
} catch (Exception $e) {
$this->log('Deployment failed: ' . $e->getMessage());
return ['success' => false, 'error' => $e->getMessage()];
}
}
/**
* Pre-deployment checks
*/
private function preDeploymentChecks()
{
$this->log('Running pre-deployment checks...');
// Check PHP version
if (version_compare(PHP_VERSION, '7.4.0', '<')) {
throw new Exception('PHP 7.4+ required, found ' . PHP_VERSION);
}
// Check required extensions
$required = ['json', 'mbstring', 'openssl', 'curl', 'zip', 'gd'];
$missing = [];
foreach ($required as $ext) {
if (!extension_loaded($ext)) {
$missing[] = $ext;
}
}
if (!empty($missing)) {
throw new Exception('Missing required extensions: ' . implode(', ', $missing));
}
// Check disk space
$free = disk_free_space(__DIR__);
if ($free < 100 * 1024 * 1024) { // 100MB
throw new Exception('Insufficient disk space');
}
// Check write permissions
$directories = [
'phpterminal/logs',
'phpterminal/cache',
'phpterminal/uploads',
'phpterminal/backups'
];
foreach ($directories as $dir) {
$fullPath = __DIR__ . '/' . $dir;
if (!is_dir($fullPath)) {
if (!mkdir($fullPath, 0755, true)) {
throw new Exception("Cannot create directory: $dir");
}
}
if (!is_writable($fullPath)) {
throw new Exception("Directory not writable: $dir");
}
}
$this->log('Pre-deployment checks passed');
}
/**
* Create backup before deployment
*/
private function createBackup()
{
$this->log('Creating backup...');
$backupDir = __DIR__ . '/phpterminal/backups';
$timestamp = date('Y-m-d_H-i-s');
$backupName = "pre_deployment_backup_{$timestamp}";
$backupPath = $backupDir . '/' . $backupName;
// Create backup directory
if (!is_dir($backupPath)) {
mkdir($backupPath, 0755, true);
}
// Backup critical files
$criticalFiles = [
'phpterminal.php',
'phpterminal/config/config.php',
'phpterminal/core/Application.php',
'phpterminal/templates/terminal.html',
'phpterminal/media/styles/phpterminal.css',
'phpterminal/media/scripts/terminal.js'
];
foreach ($criticalFiles as $file) {
$source = __DIR__ . '/' . $file;
$dest = $backupPath . '/' . $file;
if (file_exists($source)) {
$destDir = dirname($dest);
if (!is_dir($destDir)) {
mkdir($destDir, 0755, true);
}
copy($source, $dest);
}
}
// Compress backup
$this->compressDirectory($backupPath, $backupPath . '.tar.gz');
$this->log("Backup created: $backupName");
}
/**
* Run deployment tests
*/
private function runTests()
{
$this->log('Running deployment tests...');
// Test configuration
$configPath = __DIR__ . '/phpterminal/config/config.php';
if (!file_exists($configPath)) {
throw new Exception('Configuration file not found');
}
// Test application loading
try {
require_once $configPath;
require_once __DIR__ . '/phpterminal/core/Application.php';
} catch (Exception $e) {
throw new Exception('Application loading failed: ' . $e->getMessage());
}
// Test file permissions
$testFile = __DIR__ . '/phpterminal/logs/test_' . time() . '.log';
if (!file_put_contents($testFile, 'test')) {
throw new Exception('Cannot write to logs directory');
}
unlink($testFile);
$this->log('Deployment tests passed');
}
/**
* Optimize performance
*/
private function optimizePerformance()
{
$this->log('Optimizing performance...');
// Create optimized .htaccess
$htaccessContent = $this->generateOptimizedHtaccess();
file_put_contents(__DIR__ . '/.htaccess', $htaccessContent);
// Create opcache configuration
$opcacheConfig = $this->generateOpcacheConfig();
file_put_contents(__DIR__ . '/phpterminal/config/opcache.ini', $opcacheConfig);
// Optimize CSS and JS
$this->optimizeAssets();
$this->log('Performance optimization completed');
}
/**
* Set proper file permissions
*/
private function setPermissions()
{
$this->log('Setting file permissions...');
$permissions = [
'phpterminal/logs' => 0755,
'phpterminal/cache' => 0755,
'phpterminal/uploads' => 0755,
'phpterminal/backups' => 0755,
'phpterminal/config' => 0755,
'phpterminal/core' => 0755,
'phpterminal/bin' => 0755,
'phpterminal/templates' => 0755,
'phpterminal/media' => 0755,
'phpterminal.php' => 0644,
'.htaccess' => 0644
];
foreach ($permissions as $path => $perm) {
$fullPath = __DIR__ . '/' . $path;
if (file_exists($fullPath) || is_dir($fullPath)) {
chmod($fullPath, $perm);
}
}
$this->log('File permissions set');
}
/**
* Enable security features
*/
private function enableSecurity()
{
$this->log('Enabling security features...');
// Create security configuration
$securityConfig = $this->generateSecurityConfig();
file_put_contents(__DIR__ . '/phpterminal/config/security.php', $securityConfig);
// Create security monitor
$securityMonitor = $this->generateSecurityMonitor();
file_put_contents(__DIR__ . '/phpterminal/security/monitor.php', $securityMonitor);
// Enable security headers
$this->enableSecurityHeaders();
$this->log('Security features enabled');
}
/**
* Create admin user
*/
private function createAdminUser()
{
$this->log('Creating admin user...');
$adminConfig = [
'username' => 'admin',
'password' => $this->generateSecurePassword(),
'email' => 'admin@localhost',
'created_at' => date('Y-m-d H:i:s'),
'role' => 'administrator'
];
$adminFile = __DIR__ . '/phpterminal/config/admin.json';
file_put_contents($adminFile, json_encode($adminConfig, JSON_PRETTY_PRINT));
$this->log('Admin user created');
$this->log('Admin credentials: ' . $adminConfig['username'] . ' / ' . $adminConfig['password']);
}
/**
* Post-deployment verification
*/
private function postDeploymentVerification()
{
$this->log('Running post-deployment verification...');
// Test application startup
$testUrl = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/phpterminal.php';
$response = $this->testUrl($testUrl);
if (!$response || strpos($response, 'PHP Terminal') === false) {
throw new Exception('Application startup test failed');
}
// Test admin dashboard
$adminUrl = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/phpterminal/admin/dashboard.php';
$adminResponse = $this->testUrl($adminUrl);
if (!$adminResponse || strpos($adminResponse, 'Admin Dashboard') === false) {
$this->log('Warning: Admin dashboard not accessible');
}
$this->log('Post-deployment verification completed');
}
/**
* Generate optimized .htaccess
*/
private function generateOptimizedHtaccess()
{
return '# PHP Terminal - Optimized Configuration
# Generated by deployment script
# Security Headers
<IfModule mod_headers.c>
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Frame-Options DENY
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Header always set Content-Security-Policy "default-src \'self\'; script-src \'self\' \'unsafe-inline\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:; font-src \'self\'; connect-src \'self\'; frame-ancestors \'none\';"
</IfModule>
# Disable directory browsing
Options -Indexes
# Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
</IfModule>
# Browser caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType font/woff "access plus 1 month"
ExpiresByType font/woff2 "access plus 1 month"
</IfModule>
# PHP settings
php_value upload_max_filesize 10M
php_value post_max_size 20M
php_value max_execution_time 30
php_value memory_limit 128M
php_value display_errors Off
php_value log_errors On
# Session security
php_value session.cookie_httponly 1
php_value session.cookie_secure 1
php_value session.use_only_cookies 1
php_value session.cookie_samesite Strict
# Disable dangerous functions
php_value disable_functions "exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source"
# Protect sensitive files
<FilesMatch "\.(env|log|sql|bak|backup|old|orig|tmp)$">
Order allow,deny
Deny from all
</FilesMatch>
# Protect configuration files
<FilesMatch "^(config|\.env|\.htaccess|\.htpasswd)">
Order allow,deny
Deny from all
</FilesMatch>
# Protect cache and logs directories
<DirectoryMatch "^(cache|logs|uploads)/">
Order allow,deny
Deny from all
</DirectoryMatch>
# Prevent access to PHP files in media directory
<Directory "media/">
<Files "*.php">
Order allow,deny
Deny from all
</Files>
</Directory>
# Rate limiting
<IfModule mod_evasive24.c>
DOSHashTableSize 2048
DOSPageCount 3
DOSPageInterval 1
DOSSiteCount 50
DOSSiteInterval 1
DOSBlockingPeriod 600
</IfModule>
# Custom error pages
ErrorDocument 404 /phpterminal.php
ErrorDocument 403 /phpterminal.php
ErrorDocument 500 /phpterminal.php';
}
/**
* Generate opcache configuration
*/
private function generateOpcacheConfig()
{
return '; PHP Terminal - OPcache Configuration
; Generated by deployment script
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.save_comments=1
opcache.enable_file_override=1';
}
/**
* Optimize assets
*/
private function optimizeAssets()
{
// Minify CSS
$cssFile = __DIR__ . '/phpterminal/media/styles/phpterminal.css';
if (file_exists($cssFile)) {
$css = file_get_contents($cssFile);
$css = preg_replace('/\s+/', ' ', $css);
$css = str_replace(['; ', ' {', '{ ', ' }', '} '], [';', '{', '{', '}', '}'], $css);
file_put_contents($cssFile, $css);
}
// Minify JS
$jsFile = __DIR__ . '/phpterminal/media/scripts/terminal.js';
if (file_exists($jsFile)) {
$js = file_get_contents($jsFile);
$js = preg_replace('/\s+/', ' ', $js);
$js = str_replace(['; ', ' {', '{ ', ' }', '} '], [';', '{', '{', '}', '}'], $js);
file_put_contents($jsFile, $js);
}
}
/**
* Generate security configuration
*/
private function generateSecurityConfig()
{
return '<?php
/**
* PHP Terminal Security Configuration
* Generated by deployment script
*/
// Security settings
define(\'PHPTERM_SECURITY_ENABLED\', true);
define(\'PHPTERM_RATE_LIMIT_ENABLED\', true);
define(\'PHPTERM_RATE_LIMIT_REQUESTS\', 100);
define(\'PHPTERM_RATE_LIMIT_WINDOW\', 60);
define(\'PHPTERM_SESSION_TIMEOUT\', 3600);
define(\'PHPTERM_MAX_LOGIN_ATTEMPTS\', 5);
define(\'PHPTERM_LOCKOUT_DURATION\', 300);
// Allowed commands
define(\'PHPTERM_ALLOWED_COMMANDS\', [
\'ls\', \'cd\', \'pwd\', \'cat\', \'mkdir\', \'rmdir\', \'touch\', \'rm\',
\'cp\', \'mv\', \'chmod\', \'clear\', \'man\', \'phpversion\', \'ini_get\'
]);
// Path restrictions
define(\'PHPTERM_RESTRICTED_PATHS\', [
\'/etc/\', \'/proc/\', \'/sys/\', \'/dev/\', \'/root/\', \'/home/\'
]);
// File type restrictions
define(\'PHPTERM_ALLOWED_EXTENSIONS\', [
\'txt\', \'log\', \'php\', \'html\', \'css\', \'js\', \'json\', \'xml\',
\'md\', \'yml\', \'yaml\', \'ini\', \'conf\', \'config\'
]);
';
}
/**
* Generate security monitor
*/
private function generateSecurityMonitor()
{
return '<?php
/**
* PHP Terminal Security Monitor
* Generated by deployment script
*/
namespace PHPTerminal\Security;
class SecurityMonitor
{
private $logFile;
private $maxAttempts;
private $lockoutDuration;
public function __construct()
{
$this->logFile = __DIR__ . \'/../logs/security.log\';
$this->maxAttempts = 5;
$this->lockoutDuration = 300;
}
public function logEvent($event, $details = [])
{
$timestamp = date(\'Y-m-d H:i:s\');
$ip = $this->getClientIP();
$userAgent = $_SERVER[\'HTTP_USER_AGENT\'] ?? \'Unknown\';
$logEntry = [
\'timestamp\' => $timestamp,
\'ip\' => $ip,
\'event\' => $event,
\'details\' => $details,
\'user_agent\' => $userAgent,
\'session_id\' => session_id()
];
$logLine = json_encode($logEntry) . "\n";
file_put_contents($this->logFile, $logLine, FILE_APPEND | LOCK_EX);
}
private function getClientIP()
{
$ipKeys = [\'HTTP_X_FORWARDED_FOR\', \'HTTP_X_REAL_IP\', \'HTTP_CLIENT_IP\', \'REMOTE_ADDR\'];
foreach ($ipKeys as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
if (strpos($ip, \',\') !== false) {
$ip = trim(explode(\',\', $ip)[0]);
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER[\'REMOTE_ADDR\'] ?? \'Unknown\';
}
}
';
}
/**
* Enable security headers
*/
private function enableSecurityHeaders()
{
// Security headers are already included in the .htaccess file
$this->log('Security headers enabled');
}
/**
* Test URL
*/
private function testUrl($url)
{
$context = stream_context_create([
'http' => [
'timeout' => 10,
'method' => 'GET',
'header' => 'User-Agent: PHP Terminal Deployer'
]
]);
return @file_get_contents($url, false, $context);
}
/**
* Compress directory
*/
private function compressDirectory($source, $destination)
{
$phar = new PharData($destination);
$phar->buildFromDirectory($source);
$phar->compress(Phar::GZ);
// Remove uncompressed directory
$this->removeDirectory($source);
}
/**
* Remove directory recursively
*/
private function removeDirectory($dir)
{
if (!is_dir($dir)) {
return;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $file) {
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
/**
* Generate secure password
*/
private function generateSecurePassword($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[random_int(0, strlen($chars) - 1)];
}
return $password;
}
/**
* Log deployment activity
*/
private function log($message)
{
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] $message\n";
file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
echo $logEntry;
}
}
// Run deployment if called directly
if (basename(__FILE__) === basename($_SERVER['SCRIPT_NAME'])) {
$deployer = new ProductionDeployer();
$result = $deployer->deploy();
if ($result['success']) {
echo "\n✅ Deployment completed successfully!\n";
echo "🚀 PHP Terminal is ready for production!\n";
} else {
echo "\n❌ Deployment failed: " . $result['error'] . "\n";
exit(1);
}
}