-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathinstall.php
More file actions
580 lines (508 loc) · 18.8 KB
/
install.php
File metadata and controls
580 lines (508 loc) · 18.8 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
<?php
if (!defined('FREEPBX_IS_AUTH')) { die('No direct script access allowed'); }
if (version_compare(PHP_VERSION, '7.4', '<')) {
out(sprintf(_("FreePBX Requires PHP Version 7.4 or Higher, you have: %s"),PHP_VERSION));
return false;
}
if(\FreePBX::Modules()->checkStatus("sysadmin")) {
touch("/var/spool/asterisk/incron/framework.logrotate");
}
$output = exec("node --version"); //v0.10.29
$output = str_replace("v","",trim($output ?? ' '));
if(empty($output)) {
out("NodeJS 8 or higher is not installed. This is now a requirement");
return false;
}
if(version_compare($output,'8.0.0',"<")) {
out(sprintf(_("NodeJS version is: %s requirement is %s or higher"),$output,'8.0.0'));
return false;
}
$engine_info = engine_getinfo();
$astversion = $engine_info['version'];
if (version_compare($astversion, "18", "lt") || version_compare($astversion, "24", "ge")) {
out(sprintf(_("<error>Error!</error>")));
out(sprintf(_("<error>Unsupported Version of %s </error>"), $astversion));
out(sprintf(_("<error>Supported Asterisk versions: 18, 19, 20, 21, 22</error>")));
exit(1);
}
out(sprintf(_("Determined Asterisk version to be: %s"), $astversion));
// HELPER FUNCTIONS:
function framework_print_errors($src, $dst, $errors) {
out("error copying files:");
out(sprintf(_("'cp -rf' from src: '%s' to dst: '%s'...details follow"), $src, $dst));
freepbx_log(FPBX_LOG_ERROR, sprintf(_("framework couldn't copy file to %s"),$dst));
foreach ($errors as $error) {
out("$error");
freepbx_log(FPBX_LOG_ERROR, _("cp error output: $error"));
}
}
function framework_repo_key_gpg_binary() {
$locations = array("/usr/bin/gpg", "/usr/bin/gpg2", "/usr/local/bin/gpg", "/usr/local/bin/gpg2");
foreach ($locations as $loc) {
if (!file_exists($loc) || filetype($loc) !== "file") {
continue;
}
return $loc;
}
throw new \Exception(_("Could not find gpg command!"));
}
function framework_repo_key_expiry_from_file($gpgBinary, $path) {
$result = [
'valid' => false,
'expires_in_days' => 0,
'expiry_date' => '',
'key_id' => '',
];
$output = [];
$returnVar = 0;
exec($gpgBinary . ' --show-keys ' . escapeshellarg($path) . ' 2>/dev/null', $output, $returnVar);
if ($returnVar !== 0 || empty($output)) {
return $result;
}
$expiryDate = null;
foreach ($output as $line) {
if (preg_match('/\[(?:expires|expired):\s*(\d{4}-\d{2}-\d{2})\]/', $line, $m)) {
$expiryDate = $m[1];
break;
}
if (preg_match('/^\s*([A-F0-9]{16,40})\s*$/', trim($line), $m)) {
$result['key_id'] = substr($m[1], -16);
}
}
if (!$expiryDate) {
return $result;
}
$expiryTs = strtotime($expiryDate);
if ($expiryTs === false) {
return $result;
}
$result['valid'] = true;
$result['expiry_date'] = $expiryDate;
$result['expires_in_days'] = (int) floor(($expiryTs - time()) / 86400);
return $result;
}
function framework_check_repo_key_expiry($gpgBinary) {
$result = [
'applicable' => false,
'needs_update' => false,
'expires_in_days' => 0,
'expiry_date' => '',
'key_id' => '',
];
$aptDir = dirname(FRAMEWORK_REPO_GPG_KEY_PATH);
if (!is_dir($aptDir)) {
return $result;
}
$result['applicable'] = true;
if (!file_exists(FRAMEWORK_REPO_GPG_KEY_PATH)) {
$result['needs_update'] = true;
return $result;
}
$direct = framework_repo_key_expiry_from_file($gpgBinary, FRAMEWORK_REPO_GPG_KEY_PATH);
if ($direct['valid']) {
$result['expiry_date'] = $direct['expiry_date'];
$result['expires_in_days'] = $direct['expires_in_days'];
$result['key_id'] = $direct['key_id'];
$result['needs_update'] = ($result['expires_in_days'] < FRAMEWORK_REPO_GPG_KEY_EXPIRY_UPDATE_DAYS);
return $result;
}
$result['needs_update'] = true;
return $result;
}
function framework_update_repo_key($gpgBinary) {
if (!file_exists('/etc/apt/trusted.gpg.d')) {
return [
'success' => false,
'message' => _('APT trusted key directory does not exist. This system may not use APT.'),
];
}
$response = \FreePBX::Curl()->get(FRAMEWORK_REPO_GPG_KEY_URL);
if (empty($response) || $response->status_code !== 200 || empty($response->body)) {
return [
'success' => false,
'message' => _('Failed to download GPG key.'),
];
}
$tmpKey = tempnam(sys_get_temp_dir(), 'fpbx-gpg-');
$tmpGpg = tempnam(sys_get_temp_dir(), 'fpbx-gpg-');
if ($tmpKey === false || $tmpGpg === false) {
return [
'success' => false,
'message' => _('Unable to create temporary files for GPG update.'),
];
}
$success = false;
$message = '';
try {
if (file_put_contents($tmpKey, $response->body) === false || !filesize($tmpKey)) {
$message = _('Failed to write downloaded GPG key.');
} else {
$output = [];
$exitCode = 0;
exec($gpgBinary . ' --dearmor --yes -o ' . escapeshellarg($tmpGpg) . ' ' . escapeshellarg($tmpKey) . ' 2>/dev/null', $output, $exitCode);
if ($exitCode !== 0 || !filesize($tmpGpg)) {
$message = sprintf(_('Failed to dearmor GPG key. Exit code: %s'), $exitCode);
} elseif (!@rename($tmpGpg, FRAMEWORK_REPO_GPG_KEY_PATH)) {
if (@copy($tmpGpg, FRAMEWORK_REPO_GPG_KEY_PATH)) {
@unlink($tmpGpg);
} else {
$message = _('Failed to install GPG key.');
}
}
if (empty($message)) {
@chmod(FRAMEWORK_REPO_GPG_KEY_PATH, 0644);
$success = true;
$message = _('GPG key updated successfully.');
}
}
} finally {
if (is_file($tmpKey)) {
@unlink($tmpKey);
}
if (is_file($tmpGpg)) {
@unlink($tmpGpg);
}
}
return [
'success' => $success,
'message' => $message,
];
}
function framework_check_and_update_repo_key($autoUpdate = false, $outputCallback = null) {
$result = [
'checked' => true,
'applicable' => false,
'needed_update' => false,
'updated' => false,
'success' => false,
'message' => '',
];
$gpgBinary = framework_repo_key_gpg_binary();
$gpgStatus = framework_check_repo_key_expiry($gpgBinary);
$result['applicable'] = $gpgStatus['applicable'];
if (!$gpgStatus['applicable']) {
return $result;
}
if (!$gpgStatus['needs_update']) {
$result['success'] = true;
return $result;
}
$result['needed_update'] = true;
if ($autoUpdate) {
$result['updated'] = true;
$updateResult = framework_update_repo_key($gpgBinary);
$result['success'] = $updateResult['success'];
$result['message'] = $updateResult['message'];
}
return $result;
}
global $amp_conf;
// default php will check local path, or should we add that in?
//include "libfreepbx.install.php";
$debug = false;
$dryrun = false;
/** verison_compare that works with freePBX version numbers
* included here because there are some older versions of functions.inc.php that do not have
* it included as it was added during 2.3.0beta1
*/
if (!function_exists('version_compare_freepbx')) {
function version_compare_freepbx($version1, $version2, $op = null) {
$version1 = str_replace("rc","RC", strtolower($version1));
$version2 = str_replace("rc","RC", strtolower($version2));
if (!is_null($op)) {
return version_compare($version1, $version2, $op);
} else {
return version_compare($version1, $version2);
}
}
}
if (!defined('FRAMEWORK_REPO_GPG_KEY_URL')) {
define('FRAMEWORK_REPO_GPG_KEY_URL', 'http://deb.freepbx.org/gpg/aptly-pubkey.asc');
}
if (!defined('FRAMEWORK_REPO_GPG_KEY_PATH')) {
define('FRAMEWORK_REPO_GPG_KEY_PATH', '/etc/apt/trusted.gpg.d/freepbx.gpg');
}
if (!defined('FRAMEWORK_REPO_GPG_KEY_EXPIRY_UPDATE_DAYS')) {
define('FRAMEWORK_REPO_GPG_KEY_EXPIRY_UPDATE_DAYS', 30);
}
/* This is here to catch some errors in an 11->12 upgrade, specifically
* with dashboard changes. These used to be part of dashboard, but have
* been moved to framework. As dashboard was never REMOVED, the symlinks
* were never removed either. We'll just sneak them in now.
*/
$wr = $amp_conf['AMPWEBROOT'];
$files = glob($wr."/*");
foreach($files as $file) {
$name = basename($file);
if($name == "r1z") {
unlink($file);
}
if(preg_match("/[0-9a-f]{32}\.php/i",$name)) {
unlink($file);
}
}
if (is_link("$wr/admin/images/notify_critical.png")) {
unlink("$wr/admin/images/notify_critical.png");
}
if (is_link("$wr/admin/images/notify_security.png")) {
unlink("$wr/admin/images/notify_security.png");
}
$cleanups = array("$wr/admin/xml.php", "$wr/.xml.php", "$wr/admin/libraries/pest/index.php",
"$wr/restapps/.-", "$wr/restapps/.htaccess", "/var/lib/asterisk/images/...");
foreach ($cleanups as $f) {
if (file_exists($f)) {
// If we can't unlink the file, we want it to throw an error here
$ret = @unlink($f);
if (!$ret) {
throw new \Exception("Known bad file '$f' found, unable to remove. Critical security error.");
}
}
}
// Known bad contents of extensions_custom.conf
$knownbad = array (
"4fa57266a3fc2d63ae83ca793b53c5d686b67780b0b5c74ee25b498555a04320" => "thanku-outcall",
);
$ecc = @file_get_contents("/etc/asterisk/extensions_custom.conf");
$ecchash = hash("sha256", $ecc);
if (isset($knownbad[$ecchash])) {
date_default_timezone_set("UTC");
$ecc = "# Known bad file found (".$knownbad[$ecchash]." - $ecchash)\n# Removed automatically by framework ".date("Y-m-d H:i:s")." UTC\n";
file_put_contents("/etc/asterisk/extensions_custom.conf", $ecc);
out("WARNING: Known bad extensions_custom.conf automatically replaced (contained ".$knownbad[$ecchash].")");
}
// Prune any invalid files in assets or images
if (is_dir("$wr/admin/assets")) {
$obj = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("$wr/admin/assets", FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($obj as $name => $o) {
// There shouldn't be any php files in this diretory
if (preg_match('/php$/', $name)) {
unlink($name);
}
}
unset($obj);
}
if (is_dir("$wr/admin/images")) {
$obj = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("$wr/admin/images", FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($obj as $name => $o) {
// There shouldn't be any php files in this diretory
if (preg_match('/php$/', $name)) {
unlink($name);
}
}
unset($obj);
}
// Remove any bogus files in views, too
if (is_dir("$wr/admin/views")) {
$obj = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("$wr/admin/views", FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($obj as $name => $o) {
// There shouldn't be any php files in this diretory
if (preg_match('/\/(index|config|ajax).php$/', $name)) {
unlink($name);
}
}
unset($obj);
}
if (function_exists("sql")) {
$result = sql("SELECT * FROM freepbx_settings WHERE `keyword` = 'AUTHTYPE'",'getRow',DB_FETCHMODE_ASSOC);
if (isset($result['hidden']) && $result['hidden'] == 0) {
sql("UPDATE freepbx_settings SET `hidden` = 1 WHERE `keyword` = 'AUTHTYPE'");
}
}
if ($amp_conf['AUTHTYPE'] == 'webserver' || $amp_conf['AUTHTYPE'] == 'none') {
$kv = \FreePBX::Framework()->getConfig('AUTH_NOTIFICATION_HIDDEN');
if (!\FreePBX::Notifications()->exists('framework', 'WEBSERVER_AUTH') && empty($kv)) {
\FreePBX::Notifications()->add_error('framework', 'WEBSERVER_AUTH', _("Security Notice: Authentication Update Recommended"), _("Your system is using ".$amp_conf['AUTHTYPE']." authentication for the Authorization Type (Advanced Settings) option, which may offer reduced security compared to the default method.\n\nTo revert to the default authentication, run:\n\nfwconsole setting AUTHTYPE usermanager\n\nIf this configuration is intentional, you may continue using it.\n\nFor more details, see <a href=\"https://github.com/FreePBX/security-reporting/security/advisories?state=published\" target=\"_blank\">GHSA-9jvh-mv6x-w698</a>."), '', false, true);
\FreePBX::Framework()->setConfig('AUTH_NOTIFICATION_HIDDEN', 1);
}
}
/*
* Framework install script
*/
$base_source = dirname(__FILE__) . "/amp_conf";
$htdocs_source = $base_source . "/htdocs/.";
$bin_source = $base_source . "/bin/*";
$agibin_source = $base_source . "/agi-bin/*";
if (!file_exists(dirname($htdocs_source))) {
out(sprintf(_("No directory %s, install script not needed"),dirname($htdocs_source)));
return true;
}
// These are required by libfreepbx.install.php library for upgrade routines
//
define("UPGRADE_DIR", dirname(__FILE__)."/upgrades/");
define("MODULE_DIR", $amp_conf['AMPWEBROOT'].'/modules/');
$htdocs_dest = $amp_conf['AMPWEBROOT'];
$bin_dest = isset($amp_conf['AMPBIN']) ? $amp_conf['AMPBIN'] : '/var/lib/asterisk/bin';
$agibin_dest = isset($amp_conf['ASTAGIDIR']) ? $amp_conf['ASTAGIDIR']:'/var/lib/asterisk/agi-bin';
$msg = _("installing files to %s..");
$out = array();
outn(sprintf($msg, $htdocs_dest));
exec("cp -rf $htdocs_source $htdocs_dest 2>&1",$out,$ret);
if ($ret != 0) {
framework_print_errors($htdocs_source, $htdocs_dest, $out);
out(_("done, see errors below"));
} else {
out(_("done"));
}
unset($out);
outn(sprintf($msg, $bin_dest));
exec("cp -rf $bin_source $bin_dest 2>&1",$out,$ret);
if ($ret != 0) {
framework_print_errors($bin_source, $bin_dest, $out);
out(_("done, see errors below"));
} else {
exec("chmod +x $bin_dest/*");
out(_("done"));
}
unset($out);
outn(sprintf($msg, $agibin_dest));
exec("cp -rf $agibin_source $agibin_dest 2>&1",$out,$ret);
if ($ret != 0) {
framework_print_errors($agibin_source, $agibin_dest, $out);
out(_("done, see errors below"));
} else {
exec("chmod +x $agibin_dest/*");
out(_("done"));
}
/*TODO: (Requirment for #4733)
*
* 1. Update publish.pl to grab a copy of amportal and put it somehwere.
* 2. If we have access to do an md5sum on AMPSBIN/amportal do it and
* compare to the local copy.
* 3. If the md5sum is different or we couldn't check, put amportal in AMPBIN
* 4. If we decided they need a new one, then write out a message that they
* should run amportal to update it.
*/
require_once(__DIR__.'/installlib/installer.class.php');
$installer = new \FreePBX\Install\Installer();
$installer->install_upgrades(getversion());
// We run this each time so that we can add settings if need be
// without requiring a major version bump
//
$installer->freepbx_settings_init(true);
// We now delete the files, this makes sure that if someone had an unprotected system where they have not enabled
// the .htaccess files or otherwise allowed direct access, that these files are not around to possibly cause problems
//
out(_("framework file install done, removing packages from module"));
$rem_files[] = $base_source;
$rem_files[] = dirname(__FILE__) . "/upgrades";
$rem_files[] = dirname(__FILE__) . "/start_asterisk";
$rem_files[] = dirname(__FILE__) . "/install";
$rem_files[] = dirname(__FILE__) . "/installlib";
foreach ($rem_files as $target) {
unset($out);
exec("rm -rf $target 2>&1",$out,$ret);
if ($ret != 0) {
out(sprintf(_("an error occured removing the packaged file/directory: %s"), $target));
} else {
out(sprintf(_("file/directory: %s removed successfully"), $target));
}
}
//This seems like a really freaky race condition because we have previously called the out function
//But I digress, just reinclude the file
if (!$amp_conf['DISABLE_CSS_AUTOGEN'] && !function_exists('compress_framework_css')) {
outn(_("Compressing Web Files"));
if(!class_exists('compress')) {
require_once($dirname . '/libraries/compress.class.php');
}
compress::web_files();
out(_("Done"));
}
if (!$amp_conf['DISABLE_CSS_AUTOGEN'] && function_exists('compress_framework_css')) {
outn(_("Compressing Framework CSS..."));
compress_framework_css();
out(_("Done"));
}
if(!file_exists(dirname(__FILE__).'/module.xml')) {
out(_('Cant Find Framework XML'));
return false;
}
//This is also run in moduleadmin class
//why? well because in developer mode this file doesnt exist, only the
//module.xml exists so we have to do it in multiple places. yaaaaay :-|
$fwxml = simplexml_load_file(dirname(__FILE__).'/module.xml');
//setversion to whatever is in framework.xml forever for here on out.
$fwver = (string)$fwxml->version;
if(!empty($fwver)) {
outn(_("Setting Framework Version..."));
$installer->set_version($fwver);
if($installer->get_version() != $fwver) {
out(_('Internal Error. Function install_getversion did not match the Framework version, even after it was suppose to be applied'));
return false;
} else {
out(_("Done"));
}
} else {
out(_('Version from Framework was empty, cant continue'));
return false;
}
//sbin is not set correctly starting in 2.9, this is a stop-gap till we fix the installer in 13
exec('export PATH=/usr/local/sbin:$PATH && which -a amportal',$output, $return_var);
$file = null;
foreach($output as $f) {
if(!is_link($f)) {
$file = $f;
break;
}
}
if(!empty($file)) {
$sbin = dirname($file);
if(is_dir($sbin) && ($amp_conf['AMPSBIN'] !== $sbin)) {
$freepbx_conf =& freepbx_conf::create();
out(sprintf(_("Setting sbin to the correct location of: %s"),$sbin));
$freepbx_conf->set_conf_values(array("AMPSBIN" => $sbin), true,true);
}
}
//need to invalidate module_xml at this point
if(function_exists("sql")) {
outn(_("Running SQL cleanup..."));
sql("DELETE FROM module_xml WHERE id = 'modules'");
// Remove potential bogus accounts - 2016-09-08
sql("DELETE FROM `ampusers` where `username` regexp 'Alex\d*'");
// Remove potential bogus accounts - 2016-09-16
sql("DELETE FROM `ampusers` where `username` = 'adm'");
// Remove any attacks from cronmanager
sql("DELETE FROM `cronmanager` WHERE `command` LIKE '%php%'");
out(_("Done"));
}
if(method_exists(\FreePBX::create()->View,'getScripts')) {
outn(_("Building Packaged Scripts..."));
\FreePBX::View()->getScripts();
out(_("Done"));
}
// Make sure our GPG keys are up to date
outn(_("Refreshing GPG Keys..."));
try {
\FreePBX::GPG()->refreshKeys();
out(_("Done"));
} catch (\Exception $e) {
out(sprintf(_("Error updating GPG Keys: %s"), $e->getMessage()));
}
outn(_("Checking and updating Sangoma Debian Repository GPG Key..."));
framework_check_and_update_repo_key(true);
out(_("Done."));
try {
$gpgBinary = framework_repo_key_gpg_binary();
$gpgStatus = framework_check_repo_key_expiry($gpgBinary);
$nt = \FreePBX::create()->Notifications;
$nt->delete('framework', 'GPG_KEY_EXPIRY');
if ($gpgStatus['applicable'] && $gpgStatus['needs_update']) {
out(_("Sangoma Debian Repository GPG Key Update Failed"));
$days = (int) $gpgStatus['expires_in_days'];
$displayText = $days < 0 ? _("Sangoma Debian Repository GPG Key Expired") : _("Sangoma Debian Repository GPG Key Expiring Soon");
$extendedText = $days < 0
? sprintf(_("The GPG key used to verify packages from deb.freepbx.org repository expired %d days ago (on %s). Repository updates will fail until the key is updated. Please update the key by running the command : \"fwconsole util updategpgkey\" from CLI."), abs($days), $gpgStatus['expiry_date'] ?: _("unknown"))
: sprintf(_("The GPG key used to verify packages from deb.freepbx.org will expire in %d days on %s .To prevent repository authentication issues, please update the key by running the command: \"fwconsole util updategpgkey\" from CLI."), $days, $gpgStatus['expiry_date'] ?: _("unknown"));
$nt->add_error('framework', 'GPG_KEY_EXPIRY', $displayText, $extendedText, false, false, true);
}
} catch (\Exception $e) {
// Ignore notification updates if GPG isn't available.
}