-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFirewall.class.php
2569 lines (2305 loc) · 77.8 KB
/
Firewall.class.php
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// vim: set ai ts=4 sw=4 ft=php:
namespace FreePBX\modules;
include __DIR__."/vendor/autoload.php";
class Firewall extends \FreePBX_Helpers implements \BMO {
private $network='';
private $zones='';
private static $firewalls;
public function __construct($freepbx = null) {
if ($freepbx == null)
throw new \Exception("Not given a FreePBX Object");
$this->FreePBX = $freepbx;
$this->db = $freepbx->Database;
$this->astman = $this->FreePBX->astman;
$this->astspooldir = $this->FreePBX->Config->get("ASTSPOOLDIR");
$this->astetcdir = $this->FreePBX->Config->get("ASTETCDIR");
$this->astlogdir = $this->FreePBX->Config->get("ASTLOGDIR");
$this->webuser = $this->FreePBX->Config->get('AMPASTERISKWEBUSER');
$this->webgroup = $this->FreePBX->Config->get("AMPASTERISKWEBGROUP");
}
/**
* setServices
*
* @param mixed $servicesObj
* @return void
*/
public function setServices($servicesObj){
self::$services = $servicesObj;
}
/**
* services
*
* @return void
*/
public function services() {
if (!self::$services) {
include 'Services.class.php';
self::$services = new Firewall\Services();
}
return self::$services;
}
public function setNetwork($networkObj){
$this->network = $networkObj;
}
public function network() {
if (!$this->network) {
include 'Network.class.php';
$this->network = new Firewall\Network();
}
return $this->network;
}
public function setZones($zoneObj){
$this->zones = $zoneObj;
}
public function zones() {
if (!$this->zones) {
include 'Zones.class.php';
$this->zones = new Firewall\Zones();
}
return $this->zones;
}
public function getTrustedZone($from){
$networkmaps = $this->FreePBX->Firewall->get_networkmaps();
$trusted = "";
foreach($networkmaps as $ip => $type){
if($type == $from){
$trusted .= (string) "$ip\n";
}
}
return $trusted;
}
/**
* setFirewall
*
* @param mixed $firewallObj
* @return void
*/
public function setFirewall($firewallObj){
self::$firewalls = $firewallObj;
}
/**
* firewall
*
* @return void
*/
public function getFirewall() {
if (!self::$firewalls) {
self::$firewalls = $this->FreePBX->Firewall;
}
return self::$firewalls;
}
public function intrusion_detection_status() {
exec('pgrep -f fail2ban-server', $out, $ret);
if ($ret == 0) {
return "stopped";
} else {
return "running";
}
}
public function getExtRegistered(){
/**
* Get all IP addresses of registered extensions.
* Whatever technololgies, SIP, PJSIP, IAX2
*/
$ip_reg = array();
$sip_driver = $this->astman->Command("sip show peers");
$pjsip_driver = $this->astman->Command("pjsip show endpoints");
$iax_driver = $this->astman->Command("iax2 show peers");
$sip_driver = (is_array($sip_driver)) && !empty($sip_driver["data"]) ? explode("\n",$sip_driver["data"]) : array();
$pjsip_driver = (is_array($pjsip_driver)) && !empty($pjsip_driver["data"]) ? explode("\n",$pjsip_driver["data"]) : array();
$iax_driver = (is_array($iax_driver)) && !empty($iax_driver["data"]) ? explode("\n",$iax_driver["data"]) : array();
foreach($sip_driver as $line => $content){
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $content, $ip_match) && strpos($content,"OK") !== false) {
$ip_reg[] = $ip_match[0];
}
}
foreach($pjsip_driver as $line => $content){
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $content, $ip_match) && strpos($content,"Avail") !== false) {
$ip_reg[] = $ip_match[0];
}
}
foreach($iax_driver as $line => $content){
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $content, $ip_match) && strpos($content,"OK") !== false) {
$ip_reg[] = $ip_match[0];
}
}
return implode("\n", array_unique($ip_reg));
}
public function get_astspooldir() {
return $this->astspooldir;
}
public function get_astetcdir() {
return $this->astetcdir;
}
public function get_astlogdir() {
return $this->astlogdir;
}
public static $dbDefaults = array("status" => false);
public static $filesCustomRules = array('ipv4' => '/etc/firewall-4.rules', 'ipv6' => '/etc/firewall-6.rules');
public static $filesLog = Null;
public static function logfile_init() {
$astlogdir = \FreePBX::Config()->get("ASTLOGDIR");
self::$filesLog = array('err' => $astlogdir.'/firewall.err', 'out' => $astlogdir.'/firewall.log');
}
private static $services = false;
public function install() {
// Upgrade at 13.0.47 - If the firewall is enabled, create the filesystem
// flag to say that it is.
if ($this->getConfig("status")) {
$file = "/etc/asterisk/firewall.enabled";
if (!file_exists($file)) {
touch($file);
chown($file, $this->webuser);
chgrp($file, $this->webgroup);
}
}
$this->setConfig("syncing", "no");
// 13.0.54 - Add cronjob to restart it if it crashes
$this->addCronJob();
$this->removeOldSyncJob();
$nt = \FreePBX::Notifications();
if($nt->exists("firewall", "1")) {
$nt->delete("firewall", "1");
}
$firewallDirectory = '/var/spool/asterisk/firewall/';
if (!file_exists($firewallDirectory)) {
mkdir($firewallDirectory);
chown($firewallDirectory, "asterisk");
chgrp($firewallDirectory, "asterisk");
chmod($firewallDirectory, 0755);
}
$interfaceZoneConfig = '/var/spool/asterisk/firewall/interface-zones.json';
if (!file_exists($interfaceZoneConfig)) {
touch($interfaceZoneConfig);
chown($interfaceZoneConfig, "asterisk");
chgrp($interfaceZoneConfig, "asterisk");
chmod($interfaceZoneConfig, 0755);
}
}
public function uninstall() {
// Disable the firewall when it's uninstalled,
// so if it is automatically reinstalled at some
// point, it doesn't start.
$this->setConfig("status", false);
@unlink("/etc/asterisk/firewall.enabled");
$o = \FreePBX::OOBE()->getConfig("completed");
if (is_array($o)) {
unset ($o['firewall']);
\FreePBX::OOBE()->setConfig("completed", $o);
$this->setConfig("oobeanswered", array());
}
$this->removeCronJob();
// Run hook uninstall, actions with special root permissions.
$this->uninstallHook();
}
public function get_networkmaps(){
return $this->getConfig("networkmaps");
}
public function backup() {}
public function restore($backup) {}
public function chownFreepbx() {
$this->fix_custom_rules_files();
$files = array(
array('type' => 'execdir',
'path' => __DIR__."/hooks",
'perms' => 0755),
array('type' => 'execdir',
'path' => __DIR__."/bin",
'perms' => 0755),
array('type' => 'execdir',
'path' => __DIR__."/phar",
'perms' => 0755)
);
return $files;
}
public function read_file($file, &$data) {
$data_return = false;
if (! empty($file)) {
if ( ( file_exists($file) ) && ( is_readable($file) ) ) {
if($fh = fopen($file,"r"))
{
while (($bufer = fgets($fh, 4096)) !== false) {
$data[] = $bufer;
}
fclose($fh);
$data_return = true;
}
}
}
return $data_return;
}
// INI - Advanced Custom Rules
public function check_protocol_custom_rules($protocolType=Null, $allow_empty=True) {
$data_return = true;
if ( ( empty($protocolType) ) && ( ! $allow_empty ) ) {
$data_return = false;
} else if ( ! empty($protocolType)) {
$data_return = array_key_exists($protocolType, self::$filesCustomRules);
}
return $data_return;
}
public function is_exist_custom_rules_files($protocolType=Null) {
$data_return = $this->check_protocol_custom_rules($protocolType);
if ($data_return) {
foreach (self::$filesCustomRules as $type => $file) {
if ( ( ! empty($protocolType) ) && ( strtolower($type) != strtolower($protocolType) ) ) {
continue;
}
if (! file_exists($file)) {
$data_return = false;
}
}
}
return $data_return;
}
public function is_good_owner_perms_custom_rules_files($protocolType=Null) {
$data_return = $this->check_protocol_custom_rules($protocolType);
if ($data_return) {
foreach (self::$filesCustomRules as $type => $file) {
if ( ( ! empty($protocolType) ) && ( strtolower($type) != strtolower($protocolType) ) ) {
continue;
}
if (! file_exists($file)) {
$data_return = false;
} else {
$owner_file = fileowner($file);
$perms_file = fileperms($file);
/*
* chown > 0 = root
* chmod > 33206 = 0666 (-rw-rw-rw-)
*/
if ( ( $owner_file != 0 ) || ( $perms_file != 33206 ) ) {
$data_return = false;
}
}
}
}
return $data_return;
}
public function read_file_custom_rules($protocolType=Null) {
$data_return = array();
if ( ( $this->check_protocol_custom_rules($protocolType, False) ) && ( $this->is_exist_custom_rules_files($protocolType) ) ) {
$file = self::$filesCustomRules[strtolower($protocolType)];
$this->read_file($file, $data_return);
}
return $data_return;
}
public function save_file_custom_rules($protocolType=Null, $data = "") {
$data_return = false;
if ( ( $this->check_protocol_custom_rules($protocolType, False) ) && ( $this->is_exist_custom_rules_files($protocolType) ) ) {
$file = self::$filesCustomRules[strtolower($protocolType)];
if (is_writable($file)) {
if($fh = fopen($file,"w"))
{
if (fwrite($fh, $data) !== FALSE) {
$data_return = true;
}
fclose($fh);
}
}
}
return $data_return;
}
public function check_custom_rules_files($protocolType=Null) {
if ( (! $this->is_exist_custom_rules_files($protocolType) ) || (! $this->is_good_owner_perms_custom_rules_files($protocolType) ) ) {
return false;
}
return true;
}
public function fix_custom_rules_files(&$log=Null) {
$detect_error = false;
foreach (self::$filesCustomRules as $file) {
$output[] = "<info>".sprintf(_("Check file '%s'"), $file)."</info>";
if (! file_exists($file)) {
$new_file = @fopen($file,"w+");
if($new_file == false) {
$errors= error_get_last();
freepbx_log(FPBX_LOG_ERROR, sprintf(_("Module Firewall - Check Rules - File '%s' not exist, error creating. Error Message: %s"), $file, $errors['message']));
$output[] = "<error>".sprintf(_("- Does not exist, creating file... ERROR!!\n >> Error Message: %s"), $errors['message'])."</error>";
continue;
} else {
freepbx_log(FPBX_LOG_INFO, sprintf(_("Module Firewall - Check Rules - File '%s' not exist, created OK!"), $file));
$output[] = "<info>"._("- Does not exist, creating file... OK!")."</info>";
}
fclose($new_file);
} else {
freepbx_log(FPBX_LOG_INFO, sprintf(_("Module Firewall - Check Rules - File '%s' exist... OK!"), $file));
}
$err_chmod = NULL;
$err_chown = NULL;
if (! @chmod($file, 0666)) {
$err_chmod = error_get_last();
}
if (! @chown($file, "root")) {
$err_chown = error_get_last();
}
if ((is_null($err_chmod)) && (is_null($err_chown))) {
freepbx_log(FPBX_LOG_INFO, sprintf(_("Module Firewall - Check Rules - Adjusting owner and permissions in file '%s'... OK!"), $file));
$output[] = "<info>"._("- Adjusting owner and permissions... OK!")."</info>";
}
if (! is_null($err_chmod)) {
$detect_error = true;
freepbx_log(FPBX_LOG_ERROR, sprintf(_("Module Firewall - Check Rules - Error adjusting permissions in file '%s'. Error Message: %s"), $file, $err_chmod['message']) );
$output[] = "<error>".sprintf(_("- Adjusting permissions... ERROR!\n >> Error Message: %s"), $err_chmod['message'])."</error>";
}
if (! is_null($err_chown)) {
$detect_error = true;
freepbx_log(FPBX_LOG_ERROR, sprintf(_("Module Firewall - Check Rules - Error adjusting owner in file '%s'. Error Message: %s"), $file, $err_chown['message']) );
$output[] = "<error>".sprintf(_("- Adjusting owner... ERROR!\n >> Error Message: %s"), $err_chown['message'])."</error>";
}
}
if (! is_null($log) ) {
if ( is_array($log) ) {
$log = array_merge($log, $output);
}
elseif (! empty($log) ) {
$log = array_merge(array($log), $output);
}
else {
$log = $output;
}
}
return !$detect_error;
}
public function read_file_custom_rules_ajax($protocolType) {
$data_return = array();
$data_return['status'] = false;
$data_return['protocol'] = "";
if ( isset($protocolType) ) {
$data_return['protocol'] = $protocolType;
if ($this->check_protocol_custom_rules($protocolType, False)) {
$data_return['status'] = true;
$data_return['data'] = $this->read_file_custom_rules($protocolType);
} else {
$data_return['code'] = 2;
$data_return['message'] = _("Protocol not valid!");
}
} else {
$data_return['code'] = 1;
$data_return['message'] = _("Protocol not selected!");
}
return $data_return;
}
public function save_file_custom_rules_ajax($protocolType, $data) {
$data_return = array();
$data_return['status'] = false;
$data_return['protocol'] = "";
if ( isset($protocolType) ) {
$data_return['protocol'] = $protocolType;
if ($this->check_protocol_custom_rules($protocolType, False)) {
if ( isset($data) ) {
if ( $this->save_file_custom_rules($protocolType, $data) ) {
$data_return['status'] = true;
} else {
$data_return['code'] = 4;
$data_return['message'] = _("Error saving data!");
}
}
else {
$data_return['code'] = 3;
$data_return['message'] = _("New rules unsent!");
}
} else {
$data_return['code'] = 2;
$data_return['message'] = _("Protocol not valid!");
}
} else {
$data_return['code'] = 1;
$data_return['message'] = _("Protocol not selected!");
}
return $data_return;
}
public function remove_custom_rules_files() {
$detect_error = false;
foreach (self::$filesCustomRules as $file) {
$err_unlink = null;
if (file_exists($file)) {
if (! @unlink($file)) {
$err_unlink = error_get_last();
freepbx_log(FPBX_LOG_ERROR, sprintf(_("Module Firewall - Remove File Rules - Error detected by deleting the file '%s'!. Error Message: %s"), $file, $err_chmod['message']));
$detect_error = true;
} else {
freepbx_log(FPBX_LOG_INFO, sprintf(_("Module Firewall - Remove File Rules - File '%s' deleted successfully."), $file));
}
}
}
return !$detect_error;
}
// END - Advanced Custom Rules
public function oobeHook() {
include __DIR__.'/OOBE.class.php';
$o = new Firewall\OOBE($this);
return $o->oobeRequest();
}
public function dashboardService() {
// Check to see if Firewall is enabled. Warn if it's not.
$status = array(
'title' => _("System Firewall"),
'order' => 3,
);
if ($this->getConfig("status")) {
$status = array_merge($status, $this->Dashboard()->genStatusIcon('ok', _("Firewall Active")));
} else {
$status = array_merge($status, $this->Dashboard()->genStatusIcon('error', _("Firewall Disabled")));
return array($status);
}
if ($this->isNotReady()) {
$status = array_merge($status, $this->Dashboard()->genStatusIcon('warning', _("Starting up")));
return array($status);
}
// Clobber the $status if it's not running
// We're meant to be running, check that the firewall service is running.
if (! $this->isRunning()) {
$status = array_merge($status, $this->Dashboard()->genStatusIcon('error', _("Firewall Service not running!")));
$status['order'] = 1;
}
// If there are any interfaces that are in 'Trusted', yell loudly about that, too
$trusted = array(
'title' => _("Firewall Configuration"),
'order' => 3
);
$foundtrustedint = false;
$foundnewint = false;
$error = false;
$ints = $this->getInterfaces();
foreach ($ints as $i => $conf) {
// Is it an alias? If so, ignore it, we can't set it anyway
if ($conf['config']['PARENT']) {
continue;
}
// Does this not have a zone?
if (!isset($conf['config']['ZONE'])) {
// If it's got IP addresses, it's new. Otherwise, we can just ignore it.
if ($conf['addresses']) {
$foundnewint = $i;
}
break;
}
$runningzone = $this->getZone($i);
if ($conf['config']['ZONE'] !== $runningzone) {
$error = $i;
break;
} elseif ($runningzone === "trusted") {
$foundtrustedint = $i;
break;
}
}
if ($error) {
$trusted = array_merge($trusted, $this->Dashboard()->genStatusIcon('error', _("Firewall Integrity Failed")));
$this->Notifications()->add_critical('firewall', 'zoneerror', _("Firewall Integrity Failed"),
sprintf(_("Interface %s is not in the correct zone. This can be caused by manual alterations of iptables, or, an unexpected error. Please restart the firewall service."), $error),
"?display=firewall",
true, // Reset on update.
true); // Can delete
return array($status, $trusted);
}
// No errors found. Remove zone errors, if there are any
$this->Notifications()->delete('firewall', 'zoneerror');
if ($foundnewint) { // Have we found a new interface?
$trusted = array_merge($trusted, $this->Dashboard()->genStatusIcon('error', _("New Interface Detected")));
$trusted['order'] = 1;
$this->Notifications()->add_critical('firewall', 'newint', _("New Interface Detected"),
sprintf(_("A new, unconfigured, network interface has been detected. Please assign interface '%s' to a zone."), $foundnewint),
"?display=firewall&page=about&tab=interfaces",
true, // Reset on update.
false); // Can delete
return array($status, $trusted);
} elseif ($foundtrustedint) { // If we've found a trusted interface, this is bad, yell.
$trusted = array_merge($trusted, $this->Dashboard()->genStatusIcon('error', _("Trusted Interface Detected")));
$trusted['order'] = 1;
// Add core notification
$this->Notifications()->add_critical('firewall', 'trustedint', _("Trusted Interface Detected"),
sprintf(_("A network interface that is assigned to the 'Trusted' zone has been detected. This is a misconfiguration. To ensure your system is protected from attacks, please change the default zone of interface '%s'."), $foundtrustedint),
"?display=firewall&page=about&tab=interfaces",
true, // Reset on update.
false); // Can delete
return array($status, $trusted);
} else {
// No errors with interfaces, so delete any old notifications
$this->Notifications()->delete('firewall', 'newint');
$this->Notifications()->delete('firewall', 'trustedint');
}
// Now we need to validate that we DO have a trusted network or host.
// If we dont', this should be a warning, not an error.
$nets = $this->getConfig("networkmaps");
if (!is_array($nets)) {
$nets = array();
}
$foundtrustednet = false;
foreach ($nets as $name => $zone) {
if ($zone === "trusted") {
$foundtrustednet = true;
break;
}
}
if ($foundtrustednet) {
// Yup, there's at least one!
$trusted = array_merge($trusted, $this->Dashboard()->genStatusIcon('ok', _("Trusted Management Network defined")));
} else {
$trusted = array_merge($trusted, $this->Dashboard()->genStatusIcon('warning', _("No Trusted Management Network")));
// Add core notification
$this->Notifications()->add_warning('firewall', 'trustednet', _("No Trusted Network or Host defined"),
_("No Trusted Network or Host has been defined. Every server should have a 'Trusted' host or network to ensure that in case of configuration error, the machine is still accessible."),
"?display=firewall&page=about&tab=networks",
true, // Reset on update.
true); // Can delete
}
return array($status, $trusted);
}
// Run a sysadmin-managed root hook.
public function runHook($hookname,$params = false) {
// Runs a new style Syadmin hook
if (!file_exists("/etc/incron.d/sysadmin")) {
throw new \Exception("Sysadmin RPM not up to date, or not a known OS. Can not start System Firewall. See http://bit.ly/fpbxfirewall");
}
$basedir = $this->get_astspooldir()."/incron";
if (!is_dir($basedir)) {
throw new \Exception("$basedir is not a directory");
}
// Does our hook actually exist?
if (!file_exists(__DIR__."/hooks/$hookname")) {
throw new \Exception("Hook $hookname doesn't exist");
}
// So this is the hook I want to run
$filename = "$basedir/firewall.$hookname";
// If we have a modern sysadmin_rpm, we can put the params
// INSIDE the hook file, rather than as part of the filename
if (file_exists("/etc/sysadmin_contents_max")) {
$fh = fopen("/etc/sysadmin_contents_max", "r");
if ($fh) {
$max = (int) fgets($fh);
fclose($fh);
}
} else {
$max = false;
}
if ($max > 65535 || $max < 128) {
$max = false;
}
// Do I have any params?
$contents = "";
if ($params) {
// Oh. I do. If it's an array, json encode and base64
if (is_array($params)) {
$b = base64_encode(gzcompress(json_encode($params)));
// Note we derp the base64, changing / to _, because this may be used as a filepath.
if ($max) {
if (strlen($b) > $max) {
throw new \Exception("Contents too big for current sysadmin-rpm. This is possibly a bug!");
}
$contents = $b;
$filename .= ".CONTENTS";
} else {
$filename .= ".".str_replace('/', '_', $b);
if (strlen($filename) > 200) {
throw new \Exception("Too much data, and old sysadmin rpm. Please run 'yum update'");
}
}
} elseif (is_object($params)) {
throw new \Exception("Can't pass objects to hooks");
} else {
// Cast it to a string if it's anything else, and then make sure
// it doesn't have any spaces.
$filename .= ".".preg_replace("/[[:blank:]]+/", "", (string) $params);
}
}
$fh = fopen($filename, "w+");
if ($fh === false) {
// WTF, unable to create file?
throw new \Exception("Unable to create hook trigger '$filename'");
}
// Put our contents there, if there are any.
fwrite($fh, $contents);
// As soon as we close it, incron does its thing.
fclose($fh);
// Wait for up to 10 seconds and make sure it's been deleted.
$maxloops = 20;
$deleted = false;
while ($maxloops--) {
if (!file_exists($filename)) {
$deleted = true;
break;
}
usleep(500000);
}
if (!$deleted) {
throw new \Exception("Hook file '$filename' was not picked up by Incron after 10 seconds. Is it not running?");
}
return true;
}
public function startFirewall() {
$this->runHook("firewall");
return 0;
}
public function stopFirewall() {
$this->runHook("stopfirewall");
return 0;
}
public function fixCustomRules($tiemout = 0) {
$this->runHook("fixcustomrules");
if ($tiemout > 0) {
$completed = false;
while ( $i <= $timeout ) {
$completed = $this->check_custom_rules_files();
if ( $completed ) { break; }
$i++;
sleep(1);
}
return $completed;
}
}
public function enableLeRules() {
// use sysadmin LetsEncrypt service port if defined
// else, we don't know which http service, so open all http
$as = $this->getAdvancedSettings();
if ($as['lefilter'] == "disabled") {
return true;
}
$leports = array();
$leservice = $this->getService('letsencrypt');
if (isset($leservice['fw'][0]['port'])) {
$leports[] = $leservice['fw'][0]['port'];
} else {
$allservices = $this->getServices();
unset($allservices['custom']); // ignore custom services
foreach ($allservices as $services) {
foreach($services as $service) {
$s = $this->getService($service);
if (!isset($s['disabled']) || !$s['disabled']) {
foreach ($s['fw'] as $fw) {
if (isset($fw['leport']) && $fw['leport']) {
$leports[] = $fw['port'];
}
}
}
}
}
}
return $this->runHook("updateipset", array('ipset' => 'lefilter', 'action' => 'add', 'ports' => $leports));
}
public function disableLeRules() {
$as = $this->getAdvancedSettings();
if ($as['lefilter'] == "disabled") {
return true;
}
return $this->runHook("updateipset", array('ipset' => 'lefilter', 'action' => 'flush'));
}
public function uninstallHook() {
$this->runHook("uninstall");
}
public function isEnabled() {
return $this->getConfig("status");
}
// If the machine is currently in safe mode, return true.
public function isNotReady() {
return file_exists("/var/run/firewalld.safemode");
}
// If the firewall service is running, it returns true.
public function isRunning() {
exec("pgrep -f hooks/voipfirewalld", $out, $ret);
return $ret == 0 ? true : false;
}
public function showLockoutWarning() {
if (!$this->isTrusted()) {
$thishost = $this->detectHost();
print "<div class='alert alert-warning' id='lockoutwarning'>";
print "<p>".sprintf(_("The client machine you are using to manage this server (<tt>%s</tt>) is <strong>not</strong> a member of the Trusted zone. It is highly recommended to add this client to your Trusted Zone to avoid accidental lockouts."), $thishost)."</p>";
print "<p><a href='?display=firewall&page=advanced&tab=shortcuts'>"._("You can add the host automatically here.")."</a></p>";
print "</div>";
}
}
public function showDisabled() {
// Firewall functions disabled
return load_view(__DIR__."/views/disabled.php", array("fw" => $this));
}
public function getRightNav($page) {
return load_view(__DIR__."/views/bootnav.php", array("fw" => $this, "thispage" => $page));
}
public function sysadmin_info(){
$module = \module_functions::create();
$result = $module->getinfo('sysadmin', MODULE_STATUS_ENABLED);
return (empty($result["sysadmin"])) ? '' : $result;
}
/**
* showIDPage for Sysadmin menu
* This page is displayed only if Firewall is disabled.
*
*
* @return string
*/
public function showIDPage(){
return __DIR__."/views/intrusion_detection.php";
}
/**
* getIDDataPage : Prepare everything for I.D page
* This page is shared with Firewall and Sysadmin module.
* The common data are there.
*
* @return array
*/
public function getIDDataPage(){
$asfw = $this->getAdvancedSettings();
$indetec = $this->FreePBX->Sysadmin->getIntrusionDetection();
$indetec["idregextip"] = $this->getConfig("idregextip") == "true" ? "Active" : "";
$indetec["trusted"] = $this->getConfig("trusted") == "true" ? "Active" : "";
$indetec["local"] = $this->getConfig("local") == "true" ? "Active" : "";
$indetec["other"] = $this->getConfig("other") == "true" ? "Active" : "";
$indetec["idstatus"] = $indetec["status"] == "stopped"? "style='display: none;'": "";
$indetec["legacy"] = $asfw["id_sync_fw"] == "legacy" ? "style='display: none;'": "";
if($indetec["legacy"] == ""){
$indetec["ids"]["fail2ban_whitelist"] = preg_replace('!\n+!', chr(10), $this->getConfig("dynamic_whitelist"));
}
$wl_filter = "^(\b(?:\d{1,3}\.){3}\d{1,3}\b)$"; // IPV4
$wl_filter .= "|^(\b(?:\d{1,3}\.){3}\d{1,3}\b)\/\d{1,2}$"; // IPV4 + subnet
$wl_filter .= "|^((\w|\d|[-\.]){1,})+(\w|\d|[-])$"; // Domains
$wl_filter .= "|^()$"; // Nothing (CR)
$wl_filter .= "|^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}"; // IPV6
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,7}:";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}";
$wl_filter .= "|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})";
$wl_filter .= "|:((:[0-9a-fA-F]{1,4}){1,7}|:)";
$wl_filter .= "|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}";
$wl_filter .= "|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]";
$wl_filter .= "|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]";
$wl_filter .= "|(2[0-4]";
$wl_filter .= "|1{0,1}[0-9]){0,1}[0-9])";
$wl_filter .= "|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]";
$wl_filter .= "|(2[0-4]";
$wl_filter .= "|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]";
$wl_filter .= "|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$";
$indetec["wl_filter"] = $wl_filter;
$indetec["id_sync_fw_legacy"] = $asfw["id_sync_fw"] == "legacy" ? "checked" : "";
$indetec["id_sync_fw_enabled"] = $asfw["id_sync_fw"] != "legacy" ? "checked" : "";
$indetec["id_service_enabled"] = $asfw["id_service"] == "enabled" ? "checked" : "";
$indetec["id_service_disabled"] = $asfw["id_service"] != "enabled" ? "checked" : "";
return $indetec;
}
public function showPage($page) {
if (strpos($page, ".") !== false) {
throw new \Exception("Invalid page name $page");
}
// Check to see if it's 'zones', which means it's an old notification.
if ($page == "zones") {
$page = "about";
$_REQUEST['tab'] = "interfaces";
}
$view = __DIR__."/views/page.$page.php";
if (!file_exists($view)) {
throw new \Exception("Can't find page $page");
}
return load_view($view, array("fw" => $this, "module_status" => $this->sysadmin_info()));
}
public function NSLookUp_Check($host =""){
@list($ip_part, $subnet_part) = explode("/",$host);
if (!filter_var($ip_part, \FILTER_VALIDATE_IP)) {
/**
* Is a hostname?
*/
if(preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $host) && preg_match("/^.{1,253}$/", $host) && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $host)){
try {
$dns_entries = dns_get_record($host, \DNS_A);
}
catch (Exception $e) {
dbug("NSLookUP exception error : ".$e->getMessage()."\n");
return false;
}
$ip = [];
foreach($dns_entries as $entry){
if(!empty($entry["ip"])){
$ip[] = $entry["ip"];
}
}
return $ip;
};
return false;
}
$ip = $ip_part;
if(!empty($subnet_part)){
$ip = $ip_part."/".$subnet_part;
}
$data[] = $ip;
return $data;
}
public function getipzone($from){
switch($from){
case "custom_whitelist":
$result = $this->getConfig("custom_whitelist");
break;
case "extregips":
$result = $this->getExtRegistered();
break;
case "trusted":
$result = $this->getTrustedZone("trusted");
break;
case "local":
$result = $this->getTrustedZone("internal");
break;
case "other":
$result = $this->getTrustedZone("other");
break;
case "hosts":
$result = $this->getConfig("whiteHosts");
break;
case "all":
$list = array();
if($this->getConfig("idregextip") == "true" ){
$list["Ext. Registered"] = explode("\n", $this->getExtRegistered());
}
if($this->getConfig("trusted") == "true"){
$list["Trusted"] = explode("\n", $this->getTrustedZone("trusted"));
}
if($this->getConfig("local") == "true"){
$list["Local"] = explode("\n", $this->getTrustedZone("internal"));
}
if($this->getConfig("other")== "true"){
$list["Other"] = explode("\n", $this->getTrustedZone("other"));
}
$customList = explode("\n",$this->getConfig("custom_whitelist"));
$list["Hosts"] = explode("\n",$this->getConfig("whiteHosts"));
if (isset($list["Trusted"]) && is_array($list["Trusted"]) && count($list["Trusted"]) >0) {
$trustedList = $list["Trusted"];
$customIpSet = array_flip($customList);
$trustedList = array_values(array_diff($trustedList, $customList));
$filteredTrustedList = array_filter($trustedList, function ($trustedEntry) use ($customIpSet) {
return !isset($customIpSet[explode("/", $trustedEntry)[0]]);
});
$list["Trusted"] = array_values($filteredTrustedList);
}
$list["Custom"] = $customList;
return $list;
default:
$result = "";
}
return preg_replace('!\n+!', chr(10), $result);
}
public function buildCustomWhitelist($wl){
/**
* Remove duplicated entries
*/
$currentwl = $this->getConfig("custom_whitelist");
$both = $currentwl."\n".$wl;
$both = preg_replace('!\n+!', chr(10), $both);
$both = explode("\n", $both);
foreach($both as $ip){