forked from poppyred/1.6.x
/
exec.postfix.iptables.php
executable file
·1132 lines (879 loc) · 45.2 KB
/
exec.postfix.iptables.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
$_GET["filelogs"]="/var/log/artica-postfix/iptables.debug";
$_GET["filetime"]="/etc/artica-postfix/croned.1/".basename(__FILE__).".time";
if(preg_match("#--verbose#",implode(" ",$argv))){$GLOBALS["VERBOSE"]=true;$GLOBALS["debug"]=true;}
if($GLOBALS["VERBOSE"]){ini_set('display_errors', 1); ini_set('html_errors',0);ini_set('display_errors', 1);ini_set('error_reporting', E_ALL);}
if(posix_getuid()<>0){die("Cannot be used in web server mode\n\n");}
include_once(dirname(__FILE__) . '/ressources/class.users.menus.inc');
include_once(dirname(__FILE__) . '/ressources/class.mysql.inc');
include_once(dirname(__FILE__) . '/ressources/class.user.inc');
include_once(dirname(__FILE__) . '/ressources/class.ini.inc');
include_once(dirname(__FILE__) . '/ressources/class.ldap.inc');
include_once(dirname(__FILE__) . '/ressources/class.iptables-chains.inc');
include_once(dirname(__FILE__) . '/ressources/class.main_cf.inc');
include_once(dirname(__FILE__) . '/ressources/class.baseunix.inc');
include_once(dirname(__FILE__) . '/framework/class.unix.inc');
include_once(dirname(__FILE__) . '/framework/frame.class.inc');
$sock=new sockets();
$GLOBALS["EnablePostfixAutoBlock"]=trim($sock->GET_INFO("EnablePostfixAutoBlock"));
if(!is_numeric($GLOBALS["EnablePostfixAutoBlock"])){$GLOBALS["EnablePostfixAutoBlock"]=1;}
if($GLOBALS["VERBOSE"]){echo "EnablePostfixAutoBlock:: {$GLOBALS["EnablePostfixAutoBlock"]}\n";}
if($argv[1]=='--compile'){Compile_rules();die();}
if($argv[1]=='--parse-queue'){parsequeue();die();}
if($argv[1]=='--no-check'){$_GET["nocheck"]=true;}
if($argv[1]=='--parse-sql'){ParseLastEvents();die();}
if($argv[1]=='--delete-all-iptables'){DeleteAllIpTablesRules();die();}
if($argv[1]=='--test-white'){$iptablesClass=new iptables_chains();$GLOBALS["IPTABLES_WHITELISTED"]=$iptablesClass->LoadWhiteLists();$iptablesClass->isWhiteListed($argv[2]);die();}
if($argv[1]=='--export-drop'){ExportDrop();die();}
if($argv[1]=='--transfert-white'){ParseResolvMX();die();}
if($argv[1]=='--upgrade-white'){UpgradeWhiteList();die();}
if($argv[1]=='--ipdeny'){ipdeny();die();}
if($argv[1]=='--perso'){perso();die();}
if($argv[1]=='--nginx'){FW_NGINX_RULES();die();}
if($argv[1]=='--spamhaus'){FW_SPAMHAUS_RULES();die();}
if($GLOBALS["VERBOSE"]){echo "Parsing ".@implode(" ", $argv)."\n";}
if(!Build_pid_func(__FILE__,"MAIN")){writelogs(basename(__FILE__).":Already executed.. aborting the process",basename(__FILE__),__FILE__,__LINE__);die();}
parsequeue();
if($GLOBALS["EnablePostfixAutoBlock"]<>1){
iptables_delete_all();
events("This feature is currently disabled ({$GLOBALS["EnablePostfixAutoBlock"]})");die();
}
die();
//iptables -L OUTPUT --line-numbers
//iptables -A INPUT -s 65.55.44.100 -p tcp --destination-port 25 -j DROP;
function DeleteAllIpTablesRules(){
$unix=new unix();
$iptables=$unix->find_program("iptables");
shell_exec("$iptables -F");
shell_exec("$iptables -F");
shell_exec("$iptables -t nat -F");
shell_exec("$iptables -t mangle -F");
shell_exec("$iptables -X");
}
function ArrayIPTables(){
$pattern="#INPUT\s+-s\s(.+?)\/.+?--dport 25.+?ArticaInstantPostfix#";
$cmd="/sbin/iptables-save > /etc/artica-postfix/iptables.conf";
system($cmd);
events("ArrayIPTables:: loading current ipTables list");
$datas=explode("\n",@file_get_contents("/etc/artica-postfix/iptables.conf"));
if(!is_array($datas)){return null;}
while (list ($num, $ligne) = each ($datas) ){
if(preg_match($pattern,$ligne,$re)){
$array[$re[1]]=$re[1];
}else{
}
}
events("ArrayIPTables:: loading current ipTables list ". count($array). " rules");
return $array;
}
function iptables_delete_all(){
$unix=new unix();
$iptables_save=$unix->find_program("iptables-save");
$iptables_restore=$unix->find_program("iptables-restore");
events("Exporting datas iptables-save > /etc/artica-postfix/iptables.conf");
system("$iptables_save > /etc/artica-postfix/iptables.conf");
$data=file_get_contents("/etc/artica-postfix/iptables.conf");
$datas=explode("\n",$data);
$pattern="#.+?ArticaInstantPostfix#";
while (list ($num, $ligne) = each ($datas) ){
if($ligne==null){continue;}
if(preg_match($pattern,$ligne)){continue;}
events("skip rule $ligne from deletion");
$conf=$conf . $ligne."\n";
}
events("restoring datas iptables-restore < /etc/artica-postfix/iptables.new.conf");
file_put_contents("/etc/artica-postfix/iptables.new.conf",$conf);
system("$iptables_restore < /etc/artica-postfix/iptables.new.conf");
}
function iptables_ipdeny_delete_all(){
$unix=new unix();
$iptables_save=$unix->find_program("iptables-save");
$iptables_restore=$unix->find_program("iptables-restore");
events("Exporting datas iptables-save > /etc/artica-postfix/iptables.conf");
system("$iptables_save > /etc/artica-postfix/iptables.conf");
$data=file_get_contents("/etc/artica-postfix/iptables.conf");
$datas=explode("\n",$data);
$pattern="#.+?ArticaIpDeny#";
$c=0;
while (list ($num, $ligne) = each ($datas) ){
if($ligne==null){continue;}
if(preg_match($pattern,$ligne)){$c++;continue;}
events("skip rule $ligne from deletion");
$conf=$conf . $ligne."\n";
}
echo "Ban country $c removed rules...\n";
events("restoring datas iptables-restore < /etc/artica-postfix/iptables.new.conf");
file_put_contents("/etc/artica-postfix/iptables.new.conf",$conf);
system("$iptables_restore < /etc/artica-postfix/iptables.new.conf");
}
function iptables_perso_delete_all(){
$unix=new unix();
$iptables_save=$unix->find_program("iptables-save");
$iptables_restore=$unix->find_program("iptables-restore");
events("Exporting datas iptables-save > /etc/artica-postfix/iptables.conf");
system("$iptables_save > /etc/artica-postfix/iptables.conf");
$data=file_get_contents("/etc/artica-postfix/iptables.conf");
$datas=explode("\n",$data);
$pattern="#.+?ArticaPersoRules#";
$c=0;
while (list ($num, $ligne) = each ($datas) ){
if($ligne==null){continue;}
if(preg_match($pattern,$ligne)){$c++;continue;}
events("skip rule $ligne from deletion");
$conf=$conf . $ligne."\n";
}
echo "Ban country $c removed rules...\n";
events("restoring datas iptables-restore < /etc/artica-postfix/iptables.new.conf");
file_put_contents("/etc/artica-postfix/iptables.new.conf",$conf);
system("$iptables_restore < /etc/artica-postfix/iptables.new.conf");
}
function iptables_nginx_delete_all(){
$unix=new unix();
$iptables_save=$unix->find_program("iptables-save");
$iptables_restore=$unix->find_program("iptables-restore");
events("Exporting datas iptables-save > /etc/artica-postfix/iptables.conf");
system("$iptables_save > /etc/artica-postfix/iptables.conf");
$data=file_get_contents("/etc/artica-postfix/iptables.conf");
$datas=explode("\n",$data);
$pattern="#.+?ArticaInstantNginx#";
$c=0;
while (list ($num, $ligne) = each ($datas) ){
if($ligne==null){continue;}
if(preg_match($pattern,$ligne)){$c++;continue;}
events("skip rule $ligne from deletion");
$conf=$conf . $ligne."\n";
}
echo "Ban country $c removed rules...\n";
events("restoring datas iptables-restore < /etc/artica-postfix/iptables.new.conf");
file_put_contents("/etc/artica-postfix/iptables.new.conf",$conf);
system("$iptables_restore < /etc/artica-postfix/iptables.new.conf");
}
function iptables_spamhaus_delete_all(){
$unix=new unix();
$iptables_save=$unix->find_program("iptables-save");
$iptables_restore=$unix->find_program("iptables-restore");
events("Exporting datas iptables-save > /etc/artica-postfix/iptables.conf");
system("$iptables_save > /etc/artica-postfix/iptables.conf");
$data=file_get_contents("/etc/artica-postfix/iptables.conf");
$datas=explode("\n",$data);
$pattern="#.+?SpamHaus#";
$c=0;
while (list ($num, $ligne) = each ($datas) ){
if($ligne==null){continue;}
if(preg_match($pattern,$ligne)){$c++;continue;}
events("skip rule $ligne from deletion");
$conf=$conf . $ligne."\n";
}
echo "Ban country $c removed rules...\n";
events("restoring datas iptables-restore < /etc/artica-postfix/iptables.new.conf");
file_put_contents("/etc/artica-postfix/iptables.new.conf",$conf);
system("$iptables_restore < /etc/artica-postfix/iptables.new.conf");
}
function perso($NoOtherRules=false){
$unix=new unix();
if(!$NoOtherRules){
$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
$pid=@file_get_contents($pidfile);
if($unix->process_exists($pid)){echo "Already running pid $pid\n";return;}
}
$iptables=$unix->find_program("iptables");
$iptablesClass=new iptables_chains();
iptables_perso_delete_all();
$sock=new sockets();
$GlobalIptablesEnabled=$sock->GET_INFO("GlobalIptablesEnabled");
if(!is_numeric($GlobalIptablesEnabled)){$GlobalIptablesEnabled=1;}
if($GlobalIptablesEnabled<>1){return;}
/*
* ----------------- ALLOW -----------------------------------------------
*/
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' AND allow=1 AND service='MANUAL'";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
$ligne["multiples_ports"]=trim($ligne["multiples_ports"]);
$port=" --destination-port {$ligne["local_port"]}";
if($ligne["local_port"]==-1){
if($ligne["multiples_ports"]==null){continue;}
$port=" -m multiport --dports {$ligne["multiples_ports"]}";
}
if($ligne["local_port"]==0){$port=null;}
if($ligne["log"]==1){
$log=" -j LOG --log-prefix \"FW_IN OK: \"";
}
events("LOG {$ligne["serverip"]} ACCEPT INBOUND PORT $port");
progress(35,"Building logging rules for $ip");
$ipsource_cmdline="-s $ip";
if(preg_match("#Range:(.+)#", $ip,$re)){$ipsource_cmdline=" -m iprange --src-range {$re[1]}";}
if($ligne["log"]==1){
$commands[]="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j LOG --log-prefix \"FW_IN OK: \" -m comment --comment \"ArticaPersoRules\"";
}
$commands[]="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j ACCEPT -m comment --comment \"ArticaPersoRules\"";
}
/*
* ----------------- DENY -----------------------------------------------
*/
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' AND allow=0 AND service='MANUAL'";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
$GLOBALS["IPTABLES_WHITELISTED"]=$iptablesClass->LoadWhiteLists();
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
$ligne["multiples_ports"]=trim($ligne["multiples_ports"]);
$port=" --destination-port {$ligne["local_port"]}";
if($iptablesClass->isWhiteListed($ip)){continue;}
if($ligne["local_port"]==-1){
if($ligne["multiples_ports"]==null){continue;}
$port=" -m multiport --dports {$ligne["multiples_ports"]}";
}
if($ligne["local_port"]==0){$port=null;}
events("LOG {$ligne["serverip"]} REJECT INBOUND PORT $port");
progress(35,"Building logging rules for $ip");
$ipsource_cmdline="-s $ip";
if(preg_match("#Range:(.+)#", $ip,$re)){$ipsource_cmdline=" -m iprange --src-range {$re[1]}";}
if($ligne["log"]==1){
$commands[]="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j LOG --log-prefix \"FW_IN DROP: \" -m comment --comment \"ArticaPersoRules\"";
}
$commands[]="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j DROP -m comment --comment \"ArticaPersoRules\"";
}
if(is_array($commands)){
if($GLOBALS["VERBOSE"]){echo count($commands)." should be performed:\n";
while (list ($index, $line) = each ($commands) ){echo $line."\n";}return;}
while (list ($index, $line) = each ($commands) ){
shell_exec($line);
}
}
if(!$NoOtherRules){Compile_rules(true);}
}
function FW_NGINX_RULES($aspid=false){
// --------------------------------------------------------------------------------------------------------
$unix=new unix();
$commands=array();
if(!$aspid){
$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
$pid=$unix->get_pid_from_file($pidfile);
if($unix->process_exists($pid,basename(__FILE__))){
$time=$unix->PROCCESS_TIME_MIN($pid);
if($GLOBALS["VERBOSE"]){echo "Already pid $pid running since {$time}Mn\n";}
return;
}
}
iptables_nginx_delete_all();
$iptables=$unix->find_program("iptables");
$iptablesClass=new iptables_chains();
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' AND allow=0 AND service='ArticaInstantNginx'";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
if(!isset($GLOBALS["IPTABLES_WHITELISTED"])){
$GLOBALS["IPTABLES_WHITELISTED"]=$iptablesClass->LoadWhiteLists();
}
if($GLOBALS["VERBOSE"]){echo "FW_NGINX_RULES:".mysql_num_rows($results)." item(s)\n";}
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
$ligne["multiples_ports"]=trim($ligne["multiples_ports"]);
$port=" --destination-port {$ligne["local_port"]}";
if($iptablesClass->isWhiteListed($ip)){
if($GLOBALS["VERBOSE"]){echo "$ip is whitelisted...\n";}
continue;}
if($ligne["local_port"]==-1){
if($ligne["multiples_ports"]==null){
if($GLOBALS["VERBOSE"]){echo "FW_NGINX_RULES: multiples_ports ???\n";}
continue;}
$port=" -m multiport --dports {$ligne["multiples_ports"]}";
}
if($ligne["local_port"]==0){$port=null;}
if($GLOBALS["VERBOSE"]){echo "FW_NGINX_RULES: {$ligne["serverip"]} REJECT INBOUND PORT $port\n";}
events("LOG {$ligne["serverip"]} REJECT INBOUND PORT $port");
$ipsource_cmdline="-s $ip";
if(preg_match("#Range:(.+)#", $ip,$re)){$ipsource_cmdline=" -m iprange --src-range {$re[1]}";}
if($ligne["log"]==1){
$commands[]="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j LOG --log-prefix \"FW_IN DROP: \" -m comment --comment \"ArticaInstantNginx\"";
}
$iptablerules="$iptables -A INPUT $ipsource_cmdline -p tcp$port -j DROP -m comment --comment \"ArticaInstantNginx\"";
if($GLOBALS["VERBOSE"]){echo "FW_NGINX_RULES: $iptablerules\n";}
$commands[]=$iptablerules;
}
if($GLOBALS["VERBOSE"]){echo count($commands)." should be performed\n";}
if(is_array($commands)){
while (list ($index, $line) = each ($commands) ){
$results=array();
exec($line,$results);
if($GLOBALS["VERBOSE"]){echo $line."\n".@implode("\n", $results);}
}
}
if(!$aspid){
$cachefile="/etc/artica-postfix/IPTABLES_INPUT";
shell_exec("$iptables -L --line-numbers -n >$cachefile 2>&1");
}
}
function FW_SPAMHAUS_RULES($aspid=false){
// --------------------------------------------------------------------------------------------------------
$unix=new unix();
$commands=array();
$sock=new sockets();
$EnableSpamhausDROPList=$sock->GET_INFO("EnableSpamhausDROPList");
if(!is_numeric($EnableSpamhausDROPList)){$EnableSpamhausDROPList=0;}
if(!$aspid){
$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
$pid=$unix->get_pid_from_file($pidfile);
if($unix->process_exists($pid,basename(__FILE__))){
$time=$unix->PROCCESS_TIME_MIN($pid);
if($GLOBALS["VERBOSE"]){echo "Already pid $pid running since {$time}Mn\n";}
return;
}
}
if($EnableSpamhausDROPList==0){iptables_spamhaus_delete_all();return;}
iptables_spamhaus_delete_all();
$iptables=$unix->find_program("iptables");
$iptablesClass=new iptables_chains();
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' AND allow=0 AND service='SpamHaus'";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
if(!isset($GLOBALS["IPTABLES_WHITELISTED"])){
$GLOBALS["IPTABLES_WHITELISTED"]=$iptablesClass->LoadWhiteLists();
}
if($GLOBALS["VERBOSE"]){echo "FW_SPAMHAUS_RULES:".mysql_num_rows($results)." item(s)\n";}
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
if($iptablesClass->isWhiteListed($ip)){
if($GLOBALS["VERBOSE"]){echo "$ip is whitelisted...\n";}
continue;}
events("LOG {$ligne["serverip"]} REJECT INBOUND $ip");
//echo "iptables -A input -s $cidr -d 0/0 -j REJECT\n";
//echo "iptables -A output -s 0/0 -d $cidr -j REJECT\n";
if($ligne["log"]==1){
$commands[]="$iptables -A INPUT -s $ip -j LOG --log-prefix \"FW_IN DROP: \" -m comment --comment \"SpamHaus\"";
}
$iptablerules="$iptables -A INPUT -s $ip -d 0/0 -j REJECT -m comment --comment \"SpamHaus\"";
if($GLOBALS["VERBOSE"]){echo "FW_SPAMHAUS_RULES: $iptablerules\n";}
$commands[]=$iptablerules;
$iptablerules="$iptables -A OUTPUT -s 0/0 -d $ip -j REJECT -m comment --comment \"SpamHaus\"";
if($GLOBALS["VERBOSE"]){echo "FW_SPAMHAUS_RULES: $iptablerules\n";}
$commands[]=$iptablerules;
}
if($GLOBALS["VERBOSE"]){echo count($commands)." should be performed\n";}
if(is_array($commands)){
while (list ($index, $line) = each ($commands) ){
$results=array();
exec($line,$results);
if($GLOBALS["VERBOSE"]){echo $line."\n".@implode("\n", $results);}
}
}
if(!$aspid){
$cachefile="/etc/artica-postfix/IPTABLES_INPUT";
shell_exec("$iptables -L --line-numbers -n >$cachefile 2>&1");
}
}
function ipdeny(){
$unix=new unix();
$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
$pid=@file_get_contents($pidfile);
if($unix->process_exists($pid,basename(__FILE__))){echo "Already running pid $pid\n";return;}
if($GLOBALS["VERBOSE"]){echo "iptables_ipdeny_delete_all()\n";}
iptables_ipdeny_delete_all();
$sock=new sockets();
$EnableIpBlocks=$sock->GET_INFO("EnableIpBlocks");
if($EnableIpBlocks<>1){return ;}
$sql="SELECT * FROM ipblocks_set";
$q=new mysql();
$list=array("af"=>"afghanistan","al"=>"albania","dz"=>"algeria","as"=>"samoa","ad"=>"andorra","ao"=>"angola","ai"=>"anguilla","ag"=>"barbuda","ar"=>"argentina","am"=>"armenia","aw"=>"aruba","au"=>"australia","at"=>"austria","az"=>"azerbaijan","bs"=>"bahamas","bh"=>"bahrain","bd"=>"bangladesh","bb"=>"barbados","by"=>"belarus","be"=>"belgium","bz"=>"belize","bj"=>"benin","bm"=>"bermuda","bt"=>"bhutan","bo"=>"bolivia","ba"=>"herzegovina","bw"=>"botswana","br"=>"brazil","io"=>"territory","bn"=>"darussalam","bg"=>"bulgaria","bf"=>"faso","bi"=>"burundi","kh"=>"cambodia","cm"=>"cameroon","ca"=>"canada","ky"=>"islands","cf"=>"republic","cl"=>"chile","cn"=>"china","co"=>"colombia","cd"=>"the","ck"=>"islands","cr"=>"rica","ci"=>"ivoire","hr"=>"croatia","cu"=>"cuba","cy"=>"cyprus","cz"=>"republic","dk"=>"denmark","dj"=>"djibouti","do"=>"republic","ec"=>"ecuador","eg"=>"egypt","sv"=>"salvador","er"=>"eritrea","ee"=>"estonia","et"=>"ethiopia","fo"=>"islands","fj"=>"fiji","fi"=>"finland","fr"=>"france","gf"=>"guiana","pf"=>"polynesia","ga"=>"gabon","gm"=>"gambia","ge"=>"georgia","de"=>"germany","gh"=>"ghana","gi"=>"gibraltar","gr"=>"greece","gl"=>"greenland","gd"=>"grenada","gu"=>"guam","gt"=>"guatemala","gw"=>"bissau","gy"=>"guyana","ht"=>"haiti","hn"=>"honduras","hk"=>"kong","hu"=>"hungary","is"=>"iceland","in"=>"india","id"=>"indonesia","ir"=>"of","iq"=>"iraq","ie"=>"ireland","il"=>"israel","it"=>"italy","jm"=>"jamaica","jp"=>"japan","jo"=>"jordan","kz"=>"kazakhstan","ke"=>"kenya","ki"=>"kiribati","kr"=>"of","kw"=>"kuwait","kg"=>"kyrgyzstan","la"=>"republic","lv"=>"latvia","lb"=>"lebanon","ls"=>"lesotho","lr"=>"liberia","ly"=>"jamahiriya","li"=>"liechtenstein","lt"=>"lithuania","lu"=>"luxembourg","mo"=>"macao","mk"=>"of","mg"=>"madagascar","mw"=>"malawi","my"=>"malaysia","mv"=>"maldives","ml"=>"mali","mt"=>"malta","mr"=>"mauritania","mu"=>"mauritius","mx"=>"mexico","fm"=>"of","md"=>"of","mc"=>"monaco","mn"=>"mongolia","ma"=>"morocco","mz"=>"mozambique","mm"=>"myanmar","na"=>"namibia","nr"=>"nauru","np"=>"nepal","nl"=>"netherlands","an"=>"antilles","nc"=>"caledonia","nz"=>"zealand","ni"=>"nicaragua","ne"=>"niger","ng"=>"nigeria","nu"=>"niue","nf"=>"island","mp"=>"islands","no"=>"norway","om"=>"oman","pk"=>"pakistan","pw"=>"palau","ps"=>"occupied","pa"=>"panama","pg"=>"guinea","py"=>"paraguay","pe"=>"peru","ph"=>"philippines","pl"=>"poland","pt"=>"portugal","pr"=>"rico","qa"=>"qatar","ro"=>"romania","ru"=>"federation","rw"=>"rwanda","kn"=>"nevis","lc"=>"lucia","ws"=>"samoa","sm"=>"marino","sa"=>"arabia","sn"=>"senegal","sc"=>"seychelles","sl"=>"leone","sg"=>"singapore","sk"=>"slovakia","si"=>"slovenia","sb"=>"islands","za"=>"africa","es"=>"spain","lk"=>"lanka","sd"=>"sudan","sr"=>"suriname","sz"=>"swaziland","se"=>"sweden","ch"=>"switzerland","sy"=>"republic","tw"=>"china","tj"=>"tajikistan","tz"=>"of","th"=>"thailand","tg"=>"togo","to"=>"tonga","tt"=>"tobago","tn"=>"tunisia","tr"=>"turkey","tm"=>"turkmenistan","tv"=>"tuvalu","ug"=>"uganda","ua"=>"ukraine","ae"=>"emirates","gb"=>"kingdom","us"=>"states","uy"=>"uruguay","uz"=>"uzbekistan","vu"=>"vanuatu","ve"=>"venezuela","vn"=>"nam","vg"=>"british","ye"=>"yemen","zm"=>"zambia","zw"=>"zimbabwe");
$results=$q->QUERY_SQL($sql,'artica_backup');
if(!$q->ok){echo "<H2>$q->mysql_error</H2><code>$sql</code>";}
while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
echo "Ban country {$list[$ligne["country"]]} {$ligne["country"]}\n";
ipdeny_perform($ligne["country"]);
}
}
function ipdeny_perform($country){
$unix=new unix();
$iptables=$unix->find_program("iptables");
$sql="SELECT * FROM ipblocks_db WHERE country='$country'";
$list=array("af"=>"afghanistan","al"=>"albania","dz"=>"algeria","as"=>"samoa","ad"=>"andorra","ao"=>"angola","ai"=>"anguilla","ag"=>"barbuda","ar"=>"argentina","am"=>"armenia","aw"=>"aruba","au"=>"australia","at"=>"austria","az"=>"azerbaijan","bs"=>"bahamas","bh"=>"bahrain","bd"=>"bangladesh","bb"=>"barbados","by"=>"belarus","be"=>"belgium","bz"=>"belize","bj"=>"benin","bm"=>"bermuda","bt"=>"bhutan","bo"=>"bolivia","ba"=>"herzegovina","bw"=>"botswana","br"=>"brazil","io"=>"territory","bn"=>"darussalam","bg"=>"bulgaria","bf"=>"faso","bi"=>"burundi","kh"=>"cambodia","cm"=>"cameroon","ca"=>"canada","ky"=>"islands","cf"=>"republic","cl"=>"chile","cn"=>"china","co"=>"colombia","cd"=>"the","ck"=>"islands","cr"=>"rica","ci"=>"ivoire","hr"=>"croatia","cu"=>"cuba","cy"=>"cyprus","cz"=>"republic","dk"=>"denmark","dj"=>"djibouti","do"=>"republic","ec"=>"ecuador","eg"=>"egypt","sv"=>"salvador","er"=>"eritrea","ee"=>"estonia","et"=>"ethiopia","fo"=>"islands","fj"=>"fiji","fi"=>"finland","fr"=>"france","gf"=>"guiana","pf"=>"polynesia","ga"=>"gabon","gm"=>"gambia","ge"=>"georgia","de"=>"germany","gh"=>"ghana","gi"=>"gibraltar","gr"=>"greece","gl"=>"greenland","gd"=>"grenada","gu"=>"guam","gt"=>"guatemala","gw"=>"bissau","gy"=>"guyana","ht"=>"haiti","hn"=>"honduras","hk"=>"kong","hu"=>"hungary","is"=>"iceland","in"=>"india","id"=>"indonesia","ir"=>"of","iq"=>"iraq","ie"=>"ireland","il"=>"israel","it"=>"italy","jm"=>"jamaica","jp"=>"japan","jo"=>"jordan","kz"=>"kazakhstan","ke"=>"kenya","ki"=>"kiribati","kr"=>"of","kw"=>"kuwait","kg"=>"kyrgyzstan","la"=>"republic","lv"=>"latvia","lb"=>"lebanon","ls"=>"lesotho","lr"=>"liberia","ly"=>"jamahiriya","li"=>"liechtenstein","lt"=>"lithuania","lu"=>"luxembourg","mo"=>"macao","mk"=>"of","mg"=>"madagascar","mw"=>"malawi","my"=>"malaysia","mv"=>"maldives","ml"=>"mali","mt"=>"malta","mr"=>"mauritania","mu"=>"mauritius","mx"=>"mexico","fm"=>"of","md"=>"of","mc"=>"monaco","mn"=>"mongolia","ma"=>"morocco","mz"=>"mozambique","mm"=>"myanmar","na"=>"namibia","nr"=>"nauru","np"=>"nepal","nl"=>"netherlands","an"=>"antilles","nc"=>"caledonia","nz"=>"zealand","ni"=>"nicaragua","ne"=>"niger","ng"=>"nigeria","nu"=>"niue","nf"=>"island","mp"=>"islands","no"=>"norway","om"=>"oman","pk"=>"pakistan","pw"=>"palau","ps"=>"occupied","pa"=>"panama","pg"=>"guinea","py"=>"paraguay","pe"=>"peru","ph"=>"philippines","pl"=>"poland","pt"=>"portugal","pr"=>"rico","qa"=>"qatar","ro"=>"romania","ru"=>"federation","rw"=>"rwanda","kn"=>"nevis","lc"=>"lucia","ws"=>"samoa","sm"=>"marino","sa"=>"arabia","sn"=>"senegal","sc"=>"seychelles","sl"=>"leone","sg"=>"singapore","sk"=>"slovakia","si"=>"slovenia","sb"=>"islands","za"=>"africa","es"=>"spain","lk"=>"lanka","sd"=>"sudan","sr"=>"suriname","sz"=>"swaziland","se"=>"sweden","ch"=>"switzerland","sy"=>"republic","tw"=>"china","tj"=>"tajikistan","tz"=>"of","th"=>"thailand","tg"=>"togo","to"=>"tonga","tt"=>"tobago","tn"=>"tunisia","tr"=>"turkey","tm"=>"turkmenistan","tv"=>"tuvalu","ug"=>"uganda","ua"=>"ukraine","ae"=>"emirates","gb"=>"kingdom","us"=>"states","uy"=>"uruguay","uz"=>"uzbekistan","vu"=>"vanuatu","ve"=>"venezuela","vn"=>"nam","vg"=>"british","ye"=>"yemen","zm"=>"zambia","zw"=>"zimbabwe");
$q=new mysql();
$results=$q->QUERY_SQL($sql,'artica_backup');
while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
$cmd="$iptables -A INPUT -s {$ligne["cdir"]} -p tcp -j LOG --log-prefix \"IPDENY {$list["$country"]} - $country DROP: \" -m comment --comment \"ArticaIpDeny\"";
$commands[]=$cmd;
}
if($GLOBALS["VERBOSE"]){echo count($commands)." should be performed\n";}
if(is_array($commands)){
while (list ($index, $line) = each ($commands) ){
$results=array();
exec($line,$results);
if($GLOBALS["VERBOSE"]){echo $line."\n".@implode("\n", $results);}
}
}
echo "Ban country {$list["$country"]} $country ". count($commands)." entries done\n";
}
function Compile_rules_whitelist(){
$sock=new sockets();
$q=new mysql();
$sql="SELECT * FROM postfix_whitelist_con";
progress(10,"Query rules");
$results=$q->QUERY_SQL($sql,"artica_backup");
if(!$q->ok){writelogs("mysql error $q->mysql_error [$q->mysql_admin/$q->mysql_password]",__CLASS__.'/'.__FUNCTION__,__FILE__,__LINE__);return array();}
$unix=new unix();
$iptables=$unix->find_program("iptables");
$InstantIptablesEventAll=$sock->GET_INFO("InstantIptablesEventAll");
if(!is_numeric($InstantIptablesEventAll)){$InstantIptablesEventAll=1;}
if($GLOBALS["VERBOSE"]){echo "InstantIptablesEventAll=$InstantIptablesEventAll\n";}
$log="-j LOG --log-prefix \"SMTP DROP: \" ";
$c=0;
progress(25,"Building logging rules");
while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["ipaddr"];
$c++;
if(trim($ip)==null){continue;}
$cmd[]="$iptables -A INPUT -s $ip -p tcp --destination-port 25 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ip -p tcp --destination-port 587 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ip -p tcp --destination-port 465 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ip -p tcp --destination-port 80 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ip -p tcp --destination-port 443 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
}
$sql="SELECT * FROM crossroads_smtp";
$results=$q->QUERY_SQL($sql,"artica_backup");
if(!$q->ok){writelogs("mysql error $q->mysql_error [$q->mysql_admin/$q->mysql_password]",__CLASS__.'/'.__FUNCTION__,__FILE__,__LINE__);return array();}
while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
$ipaddrSource=$ligne["ipaddr"];
$arrayConf=unserialize($ligne["parameters"]);
$instancesParams=$arrayConf["INSTANCES_PARAMS"];
while (list ($ip, $none) = each ($arrayConf["INSTANCES"]) ){
$cmd[]="$iptables -A INPUT -s $ipaddrSource -p tcp --destination-port 25 -d $ip -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ipaddrSource -p tcp --destination-port 587 -d $ip -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -s $ipaddrSource -p tcp --destination-port 465 -d $ip -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
}
}
if($InstantIptablesEventAll==1){
$cmd[]="$iptables -A INPUT -p tcp --destination-port 25 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -p tcp --destination-port 587 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -p tcp --destination-port 465 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
}
$cmd[]="$iptables -A INPUT -p tcp --destination-port 587 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -p tcp --destination-port 25 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -p tcp --destination-port 465 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
if(is_array($cmd)){
while (list ($index, $line) = each ($cmd) ){
if($GLOBALS["VERBOSE"]){echo $line."\n";}
shell_exec($line);
}
}
$unix->send_email_events("$c whitelisted addresses compiled in the SMTP Firewall",
"$c items has been accepted to pass trough 25,587,465 ports", "postfix");
progress(90,"Building rules done...");
progress(100,"Building rules done...");
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." done....\n";}
}
function Compile_rules_postfix_limitToNets(){
$unix=new unix();
$iptables=$unix->find_program("iptables");
$main=new main_cf();
$sock=new sockets();
$PostfixBadNettr=unserialize(base64_decode($sock->GET_INFO("PostfixBadNettr")));
$cmd[]="$iptables -A INPUT -s 127.0.0.1 -p tcp --destination-port 25 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
while (list ($num, $ipaddrSource) = each ($main->array_mynetworks) ){
if(isset($PostfixBadNettr[$ipaddrSource])){continue;}
$cmd[]="$iptables -A INPUT -s $ipaddrSource -p tcp --destination-port 25 -j ACCEPT -m comment --comment \"ArticaInstantPostfix\"";
}
$cmd[]="$iptables -A INPUT -p tcp --destination-port 25 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
$cmd[]="$iptables -A INPUT -p tcp --destination-port 25 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
if(is_array($cmd)){
while (list ($index, $line) = each ($cmd) ){
if($GLOBALS["VERBOSE"]){echo $line."\n";}
shell_exec($line);
}
}
}
function Compile_rules($NoPersoRules=false){
progress(5,"Cleaning rules");
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." line:".__LINE__."\n";}
iptables_delete_all();
$sock=new sockets();
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." line:".__LINE__."\n";}
$PostFixLimitToNets=$sock->GET_INFO("PostFixLimitToNets");
if(!is_numeric($PostFixLimitToNets)){$PostFixLimitToNets=0;}
$EnablePostfixAutoBlockWhiteListed=$sock->GET_INFO("EnablePostfixAutoBlockWhiteListed");
if(!is_numeric($EnablePostfixAutoBlockWhiteListed)){$EnablePostfixAutoBlockWhiteListed=0;}
$GlobalIptablesEnabled=$sock->GET_INFO("GlobalIptablesEnabled");
if(!is_numeric($GlobalIptablesEnabled)){$GlobalIptablesEnabled=1;}
if($GlobalIptablesEnabled<>1){if($GLOBALS["VERBOSE"]){echo "GlobalIptablesEnabled <> 1, aborting...\n";}return;}
if(!$NoPersoRules){perso(true);}
FW_PERSO_RULES();
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." line:".__LINE__."\n";}
if($EnablePostfixAutoBlockWhiteListed==1){Compile_rules_whitelist();}
if($GLOBALS["VERBOSE"]){echo "FW_NGINX_RULES\n\n";}
FW_NGINX_RULES(true);
FW_SPAMHAUS_RULES(true);
if($PostFixLimitToNets==1){
Compile_rules_postfix_limitToNets();
return;
}
$unix=new unix();
$iptables=$unix->find_program("iptables");
$sock=new sockets();
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." line:".__LINE__."\n";}
$iptablesClass=new iptables_chains();
if($GLOBALS["VERBOSE"]){echo __FUNCTION__." line:".__LINE__."\n";}
$InstantIptablesEventAll=$sock->GET_INFO("InstantIptablesEventAll");
if(!is_numeric($InstantIptablesEventAll)){$InstantIptablesEventAll=1;}
if($GLOBALS["VERBOSE"]){echo "InstantIptablesEventAll=$InstantIptablesEventAll\n";}
if($GLOBALS["EnablePostfixAutoBlock"]<>1){progress(100,"Building rules done...");return;}
events("Query iptables rules from mysql");
progress(10,"Query rules");
progress(25,"Building logging rules");
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' and log=1 AND allow=0 AND local_port=25";
if($GLOBALS["VERBOSE"]){echo $sql."\n";}
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
$GLOBALS["IPTABLES_WHITELISTED"]=$iptablesClass->LoadWhiteLists();
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
if($iptablesClass->isWhiteListed($ip)){
if($GLOBALS["VERBOSE"]){echo "$ip is whitelisted\n";}
continue;
}
events("LOG {$ligne["serverip"]} REJECT INBOUND PORT 25");
progress(35,"Building logging rules for $ip");
$cmd="$iptables -A INPUT -s $ip -p tcp --destination-port 25 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
$commands[]=$cmd;
}
progress(40,"Building rules...");
$c=0;
$sql="SELECT * FROM iptables WHERE disable=0 AND flux='INPUT' AND allow=0 AND local_port=25";
if($GLOBALS["VERBOSE"]){echo $sql."\n";}
$results=$q->QUERY_SQL($sql,"artica_backup");
progress(55,"Building rules...");
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
if($iptablesClass->isWhiteListed($ip)){continue;}
$c++;
events("ADD REJECT {$ligne["serverip"]} INBOUND PORT 25");
progress(60,"Building rules for $ip...");
if($InstantIptablesEventAll==1){
if($GLOBALS["VERBOSE"]){echo "$ip -> LOG\n";}
$cmd="$iptables -A INPUT -s $ip -p tcp --destination-port 25 -j LOG --log-prefix \"SMTP DROP: \" -m comment --comment \"ArticaInstantPostfix\"";
$commands[]=$cmd;
}
$cmd="$iptables -A INPUT -s $ip -p tcp --destination-port 25 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$commands[]=$cmd;
}
if($GLOBALS["VERBOSE"]){
echo count($commands)." should be performed\n";
return;
}
if(is_array($commands)){
while (list ($index, $line) = each ($commands) ){
shell_exec($line);
}
}
$unix->send_email_events("$c banned addresses compiled in the SMTP Firewall",
"$c items has been banned from 25,587,465 ports", "postfix");
progress(90,"Building rules done...");
progress(100,"Building rules done...");
$nohup=$unix->find_program("nohup");
$cachefile="/etc/artica-postfix/IPTABLES_INPUT";
shell_exec("$nohup $iptables -L --line-numbers -n >$cachefile 2>&1 &");
}
function FW_PERSO_RULES(){
$tf=array();
if(!is_file("/etc/artica-postfix/FW_PERSO_RULES")){return;}
$tF=explode("\n",@file_get_contents("/etc/artica-postfix/FW_PERSO_RULES"));
if(count($tF)==0){return;}
while (list ($index, $line) = each ($tF) ){
if(trim($line==null)){continue;}
if(!preg_match("#iptables\s+#", $line)){continue;}
shell_exec($line);
}
}
function progress($pourc,$text){
if($GLOBALS["VERBOSE"]){echo "$pourc% $text\n";}
$file="/usr/share/artica-postfix/ressources/logs/compile.iptables.progress";
$ini=new Bs_IniHandler();
$ini->set("PROGRESS","pourc",$pourc);
$ini->set("PROGRESS","text",$text);
$ini->saveFile($file);
chmod($file,0777);
}
function events($text){
$pid=getmypid();
$date=date('Y-m-d H:i:s');
$logFile=$_GET["filelogs"];
$size=filesize($logFile);
if($size>1000000){unlink($logFile);}
$f = @fopen($logFile, 'a');
@fwrite($f, "$date [$pid] $text\n");
@fclose($f);
}
function load_whitelist(){
$array=array();
$q=new mysql();
$sql="SELECT * FROM postfix_whitelist_con";
$results=$q->QUERY_SQL($sql,"artica_backup");
$q->QUERY_SQL($sql,"artica_backup");
if(!$q->ok){echo "$q->mysql_error\n";}
while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
$array[$ligne["ipaddr"]]=$ligne["ipaddr"];
}
$sql="SELECT serverip FROM iptables WHERE disable=1 AND flux='INPUT'";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_backup");
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$ip=$ligne["serverip"];
$array[$ip]=$ip;
}
$array["127.0.0.1"]="127.0.0.1";
return $array;
}
function parsequeue(){
$unix=new unix();
$iptables=$unix->find_program("iptables");
$q=new mysql();
$q->Check_iptables_table();
$ini=new Bs_IniHandler();
$ini->loadFile('/etc/artica-postfix/settings/Daemons/PostfixAutoBlockResults');
if($GLOBALS["VERBOSE"]){echo "Scanning /var/log/artica-postfix/smtp-hack\n";}
foreach (glob("/var/log/artica-postfix/smtp-hack/*.hack") as $filename) {
if($GLOBALS["VERBOSE"]){echo "Scanning $filename\n";}
$basename=basename($filename);
$array=unserialize(@file_get_contents($filename));
$IP=$array["IP"];
if($IP=="127.0.0.1"){@unlink($filename);continue;}
$server_name=gethostbyaddr($IP);
$matches=$array["MATCHES"];
$EVENTS=$array["EVENTS"];
$date=$array["DATE"];
if($GLOBALS["VERBOSE"]){echo "$basename: servername:$server_name IP=[$IP]\n";}
$cmd="$iptables -A INPUT -s $IP -p tcp --destination-port 25 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$iptablesClass=new iptables_chains();
$iptablesClass->serverip=$IP;
$iptablesClass->servername=$server_name;
$iptablesClass->rule_string=$cmd;
$iptablesClass->EventsToAdd=$EVENTS;
if($iptablesClass->addPostfix_chain()){
if($GLOBALS["VERBOSE"]){echo "Add IP:Addr=<$IP>, servername=<{$server_name}> to mysql\n";}
$ini->set($IP,"events",$matches);
$ini->set($IP,"iptablerule",$cmd);
$ini->set($IP,"hostname",$server_name);
if($GLOBALS["VERBOSE"]){echo "delete $filename\n";}
@unlink($filename);
}
$cmd="$iptables -A INPUT -s $IP -p tcp --destination-port 587 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$iptablesClass=new iptables_chains(587);
$iptablesClass->serverip=$IP;
$iptablesClass->servername=$server_name;
$iptablesClass->rule_string=$cmd;
$iptablesClass->EventsToAdd=$EVENTS;
$iptablesClass->addPostfix_chain();
$cmd="$iptables -A INPUT -s $IP -p tcp --destination-port 465 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$iptablesClass=new iptables_chains();
$iptablesClass->serverip=$IP;
$iptablesClass->servername=$server_name;
$iptablesClass->rule_string=$cmd;
$iptablesClass->EventsToAdd=$EVENTS;
$iptablesClass->addPostfix_chain(465);
}
$filestr=$ini->toString();
file_put_contents("/etc/artica-postfix/settings/Daemons/PostfixAutoBlockResults",$filestr);
}
function ParseLastEvents(){
$timefile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".time";
$timeF=file_time_min($timefile);
if($timeF<240){
if($GLOBALS["VERBOSE"]){echo "$timeF minutes, need to wait 240\n";}
return;
}
@file_put_contents($timefile,"#");
$unix=new unix();
$iptables=$unix->find_program("iptables");
if($GLOBALS["VERBOSE"]){echo "Loading Whitelist\n";}
$whitelist=load_whitelist();
if($GLOBALS["VERBOSE"]){echo "Loading Whitelist ". count($whitelist). " items\n";}
$sock=new sockets();
$PostfixInstantIptablesLastDays=$sock->GET_INFO("PostfixInstantIptablesLastDays");
$PostfixInstantIptablesMaxEvents=$sock->GET_INFO("PostfixInstantIptablesMaxEvents");
if(!is_numeric($PostfixInstantIptablesLastDays)){$PostfixInstantIptablesLastDays=7;}
if(!is_numeric($PostfixInstantIptablesMaxEvents)){$PostfixInstantIptablesMaxEvents=50;}
$sql="SELECT COUNT(ipaddr) as tcount,ipaddr,smtp_err,hostname
FROM mail_con_err_stats WHERE zDate<DATE_SUB(NOW(),INTERVAL 1 DAY)
AND zDate>=DATE_SUB(NOW(),INTERVAL $PostfixInstantIptablesLastDays DAY)
GROUP BY ipaddr,smtp_err,hostname ORDER BY COUNT(ipaddr) DESC";
$q=new mysql();
$results=$q->QUERY_SQL($sql,"artica_events");
$newarray=array();
while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){
$count_events=$ligne["tcount"];
if($count_events<3){break;}
$ipaddr=$ligne["ipaddr"];
$error=$ligne["smtp_err"];
$server_name=$ligne["hostname"];
if($whitelist[$server_name]){echo "Whitelisted $server_name\n";continue;}
if($whitelist[$ipaddr]){echo "Whitelisted $ipaddr\n";continue;}
$newarray[$ipaddr]["HOST"]=$server_name;
$newarray[$ipaddr]["EVENTS_TEXT"][]="$server_name [$ipaddr] - $count_events $error";
if(isset($newarray[$ipaddr])){
$newarray[$ipaddr]["EVENTS"]=$newarray[$ipaddr]["EVENTS"]+$count_events;
}else{
$newarray[$ipaddr]["EVENTS"]=$newarray[$ipaddr]["EVENTS"];
}
}
if(!is_array($newarray)){return;}
$newarray2=$newarray;
while (list ($ipaddr, $ligne) = each ($newarray) ){
$count=$ligne["EVENTS"];
if($count<$PostfixInstantIptablesMaxEvents){
unset($newarray2[$ipaddr]);
//if($GLOBALS["VERBOSE"]){echo "skipping $ipaddr {$ligne["HOST"]} $count events\n";}
continue;
}
}
if($GLOBALS["VERBOSE"]){echo count($newarray2)." items -> Array:newarray2\n";}
if(count($newarray2)==0){return;}
$ipCount=0;
while (list ($ipaddr, $ipaddrARR) = each ($newarray2) ){
$sql="SELECT rulemd5 FROM iptables WHERE serverip='$ipaddr' AND local_port='25'";
$ligne=mysql_fetch_array($q->QUERY_SQL($sql,"artica_backup"));
if($ligne["rulemd5"]<>null){
if($GLOBALS["VERBOSE"]){
echo "Skip $ipaddr already added\n";
}
continue;
}
$EVENTS="{$ipaddrARR["EVENTS"]} refused connexions:\n".@implode("\n",$ipaddrARR["EVENTS_TEXT"]);
$cmd="$iptables -A INPUT -s $ipaddr -p tcp --destination-port 25 -j DROP -m comment --comment \"ArticaInstantPostfix\"";
$iptablesClass=new iptables_chains();
$iptablesClass->serverip=$ipaddr;
$iptablesClass->servername=$server_name;
$iptablesClass->rule_string=$cmd;
$iptablesClass->EventsToAdd=$EVENTS;
if(!$iptablesClass->addPostfix_chain()){$FAILED="FAILED TO add $ipaddr ";}
$notifs[]=$EVENTS;
shell_exec($cmd);
if($GLOBALS["VERBOSE"]){echo $cmd."\n";}
$ipCount++;
}
if($ipCount>0){
$unix->send_email_events("Instant Iptables $ipCount addresse(s) added",
"Calculation since $PostfixInstantIptablesLastDays days and for $PostfixInstantIptablesMaxEvents minimal blocks events\n".
@implode("\n",$notifs),"postfix");
}
}
function ExportDrop(){
if($GLOBALS["EnablePostfixAutoBlock"]<>1){
if($GLOBALS["VERBOSE"]){echo "EnablePostfixAutoBlock={$GLOBALS["EnablePostfixAutoBlock"]}, aborting..\n";}
return;}
$pidpath="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
$pid=@file_get_contents($pidpath);
$unix=new unix();
if($unix->process_exists($pid)){
if($GLOBALS["VERBOSE"]){echo "Already executed $pid\n";}
return;
}
@file_put_contents($pidpath,getmypid());
$grep=$unix->find_program("grep");
$tail=$unix->find_program("tail");
$syslog=$unix->LOCATE_SYSLOG_PATH();
$NICE=$unix->EXEC_NICE();
$syslogSize=$unix->file_size($syslog);
if($syslogSize>512000000){