/
pfblockerng.inc
11056 lines (9521 loc) · 358 KB
/
pfblockerng.inc
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
/*
* pfblockerng.inc
*
* part of pfSense (https://www.pfsense.org)
* Copyright (c) 2015-2023 Rubicon Communications, LLC (Netgate)
* Copyright (c) 2015-2023 BBcan177@gmail.com
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once('config.lib.inc');
require_once('util.inc');
require_once('functions.inc');
require_once('pkg-utils.inc');
require_once('pfsense-utils.inc');
require_once('globals.inc');
require_once('services.inc');
require_once('service-utils.inc');
if (file_exists('/usr/local/pkg/pfblockerng/pfblockerng_extra.inc')) {
require_once('/usr/local/pkg/pfblockerng/pfblockerng_extra.inc'); // 'include functions' not yet merged into pfSense
}
global $g, $pfb;
if (!is_array($pfb)) {
$pfb = array();
}
// Folders
$pfb['dbdir'] = "{$g['vardb_path']}/pfblockerng";
$pfb['aliasdir'] = "{$g['vardb_path']}/aliastables";
$pfb['logdir'] = "{$g['varlog_path']}/pfblockerng";
$pfb['etdir'] = "{$pfb['dbdir']}/ET";
$pfb['nativedir'] = "{$pfb['dbdir']}/native";
$pfb['denydir'] = "{$pfb['dbdir']}/deny";
$pfb['matchdir'] = "{$pfb['dbdir']}/match";
$pfb['permitdir'] = "{$pfb['dbdir']}/permit";
$pfb['origdir'] = "{$pfb['dbdir']}/original";
$pfb['dnsdir'] = "{$pfb['dbdir']}/dnsbl";
$pfb['dnsorigdir'] = "{$pfb['dbdir']}/dnsblorig";
$pfb['dnsalias'] = "{$pfb['dbdir']}/dnsblalias";
$pfb['geoipshare'] = '/usr/local/share/GeoIP';
$pfb['ccdir'] = '/usr/local/share/GeoIP/cc';
$pfb['ccdir_tmp'] = '/tmp/geoip_cc';
$pfb['dnsbl_tmp'] = '/tmp/dnsbl_tmp';
$pfb['dnsbl_tmpdir'] = '/tmp/DNSBL_TMP';
// Application Paths
$pfb['grep'] = '/usr/bin/grep';
$pfb['ggrep'] = '/usr/local/bin/ggrep'; // textproc/gnugrep
$pfb['awk'] = '/usr/bin/awk';
$pfb['cut'] = '/usr/bin/cut';
$pfb['sed'] = '/usr/bin/sed';
$pfb['cat'] = '/bin/cat';
$pfb['ls'] = '/bin/ls';
$pfb['pfctl'] = '/sbin/pfctl';
// Folder Array
$pfb['folder_array'] = array( "{$pfb['dbdir']}", "{$pfb['logdir']}", "{$pfb['ccdir']}", "{$pfb['origdir']}", "{$pfb['nativedir']}",
"{$pfb['denydir']}", "{$pfb['matchdir']}","{$pfb['permitdir']}", "{$pfb['aliasdir']}",
"{$pfb['dnsdir']}", "{$pfb['dnsorigdir']}", "{$pfb['dnsalias']}");
// Files
$pfb['log'] = "{$pfb['logdir']}/pfblockerng.log";
$pfb['dnslog'] = "{$pfb['logdir']}/dnsbl.log";
$pfb['dnsreplylog'] = "{$pfb['logdir']}/dns_reply.log";
$pfb['ip_blocklog'] = "{$pfb['logdir']}/ip_block.log";
$pfb['ip_permitlog'] = "{$pfb['logdir']}/ip_permit.log";
$pfb['ip_matchlog'] = "{$pfb['logdir']}/ip_match.log";
$pfb['unilog'] = "{$pfb['logdir']}/unified.log";
$pfb['errlog'] = "{$pfb['logdir']}/error.log";
$pfb['pyerrlog'] = "{$pfb['logdir']}/py_error.log";
$pfb['extraslog'] = "{$pfb['logdir']}/extras.log";
$pfb['dnsbl_parse_err'] = "{$pfb['logdir']}/dnsbl_parsed_error.log";
$pfb['master'] = "{$pfb['dbdir']}/masterfile";
$pfb['supptxt'] = "{$pfb['dbdir']}/pfbsuppression.txt";
$pfb['dnsbl_supptxt'] = "{$pfb['dbdir']}/pfbdnsblsuppression.txt";
$pfb['geoip_isos'] = "{$pfb['dbdir']}/geoip.txt";
$pfb['dnsbl_info'] = '/var/unbound/pfb_py_dnsbl.sqlite';
$pfb['dnsbl_resolver'] = '/var/unbound/pfb_py_resolver.sqlite';
$pfb['dnsbl_cache'] = '/var/unbound/pfb_py_cache.sqlite';
$pfb['asn_cache'] = "{$pfb['dbdir']}/asn_cache.sqlite";
$pfb['ip_cache'] = "{$pfb['dbdir']}/ip_cache.sqlite";
$pfb['asn_list'] = '/pfblockerng/pfblockerng_asn.txt'; // used by Ajax function in pfBlockerNG.js
$pfb['script'] = '/usr/local/pkg/pfblockerng/pfblockerng.sh';
$pfb['feeds'] = '/usr/local/www/pfblockerng/pfblockerng_feeds.json';
$pfb['aliasarchive'] = '/usr/local/etc/aliastables.tar.bz2';
$pfb['dnsbl_tld_txt'] = "{$pfb['dnsdir']}/DNSBL_TLD.txt";
$pfb['dnsbl_tld_data'] = '/usr/local/pkg/pfblockerng/dnsbl_tld';
$pfb['dnsbl_conf'] = '/var/unbound/pfb_dnsbl_lighty.conf';
$pfb['dnsbl_cert'] = '/var/unbound/dnsbl_cert.pem';
$pfb['unbound_py_conf'] = '/var/unbound/pfb_unbound.ini';
$pfb['unbound_py_wh'] = '/var/unbound/pfb_py_whitelist.txt';
$pfb['unbound_py_data'] = '/var/unbound/pfb_py_data.txt';
$pfb['unbound_py_zone'] = '/var/unbound/pfb_py_zone.txt';
$pfb['unbound_py_ss'] = '/var/unbound/pfb_py_ss.txt';
$pfb['unbound_py_count']= '/var/unbound/pfb_py_count';
$pfb['dnsbl_safesearch'] = '/usr/local/pkg/pfblockerng/pfb_dnsbl.safesearch.conf';
$pfb['dnsbl_youtube_restrict'] = '/usr/local/pkg/pfblockerng/pfb_dnsbl.youtube_restrict.conf';
$pfb['dnsbl_youtube_restrictmoderate'] = '/usr/local/pkg/pfblockerng/pfb_dnsbl.youtube_restrictmoderate.conf';
$pfb['dnsbl_doh'] = '/usr/local/pkg/pfblockerng/pfb_dnsbl.doh.conf';
// tmp files
$pfb['geoip_tmp'] = '/tmp/pfb_continent';
$pfb['ip_unlock'] = '/tmp/ip_unlock';
$pfb['dnsbl_tld_remove'] = '/tmp/dnsbl_tld_remove';
$pfb['dnsbl_add'] = '/tmp/dnsbl_add';
$pfb['dnsbl_add_zone'] = '/tmp/dnsbl_add_zone';
$pfb['dnsbl_add_data'] = '/tmp/dnsbl_add_data';
$pfb['dnsbl_remove'] = '/tmp/dnsbl_remove';
$pfb['dnsbl_remove_zone'] = '/tmp/dnsbl_remove_zone';
$pfb['dnsbl_remove_data'] = '/tmp/dnsbl_remove_data';
$pfb['dnsbl_unlock'] = '/tmp/dnsbl_unlock';
$pfb['states_tmp'] = '/tmp/pfb_states';
// Unbound files and folders
$pfb['dnsbl_file'] = '/var/unbound/pfb_dnsbl'; // Filename Extension not referenced
$pfb['dnsbldir'] = '/var/unbound';
// Array definitions
$pfb['continents'] = array ( 'Top Spammers' => 'pfB_Top',
'Africa' => 'pfB_Africa',
'Antarctica' => 'pfB_Antarctica',
'Asia' => 'pfB_Asia',
'Europe' => 'pfB_Europe',
'North America' => 'pfB_NAmerica',
'Oceania' => 'pfB_Oceania',
'South America' => 'pfB_SAmerica',
'Proxy and Satellite' => 'pfB_PS'
);
$pfb['continent_list'] = array_flip(array('pfB_Africa', 'pfB_Antarctica', 'pfB_Asia', 'pfB_Europe', 'pfB_NAmerica', 'pfB_Oceania', 'pfB_SAmerica', 'pfB_Top'));
// Base rule array
$pfb['base_rule_reg'] = array('ipprotocol' => 'inet');
// Floating rules, base rule array
$pfb['base_rule_float'] = array('quick' => 'yes', 'floating' => 'yes', 'ipprotocol' => 'inet');
// Define Arrays for managing the IP mastefile
foreach (array('existing', 'actual') as $pftype) {
$pfb[$pftype]['match'] = array();
$pfb[$pftype]['permit'] = array();
$pfb[$pftype]['deny'] = array();
$pfb[$pftype]['native'] = array();
$pfb[$pftype]['dnsbl'] = array();
}
// Default cURL options
$pfb['curl_defaults'] = array( CURLOPT_USERAGENT => 'pfSense/pfBlockerNG cURL download agent-' . system_get_uniqueid(),
CURLOPT_SSL_CIPHER_LIST => 'TLSv1.3, TLSv1.2',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FILETIME => true,
CURLOPT_TCP_NODELAY => true,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_AUTOREFERER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_NONE,
CURLOPT_FORBID_REUSE => true,
CURLOPT_SSL_ENABLE_ALPN => true,
CURLOPT_SSL_ENABLE_NPN => true,
);
// RFC7231 HTTP response codes
$pfb['rfc7231'] = array(
1 => 'Unsupported Protocol', 2 => 'Early Initilization failed', 3 => 'Malformed URL',
4 => 'Requested feature not found', 5 => 'Could not Resolve Proxy', 6 => 'Could not Resolve Host',
7 => 'Failed to connect', 8 => 'Failed to parse data', 9 => 'Denied access',
10 => 'FTP failed', 11 => 'FTP password failure', 12 => 'FTP Accept timeout',
13 => 'FTP PASV failure', 14 => 'FTP 227 Format failure', 15 => 'FTP Host lookup failure',
16 => 'HTTP2 framing layer failure', 17 => 'FTP Could not set transfer mode', 18 => 'File Transfer failure',
19 => 'FTP weird reply', 20 => 'Obsolete error', 21 => 'FTP quote command error',
22 => 'HTTP Returned Error code', 23 => 'Write Error', 24 => 'Obsolete error',
25 => 'FTP failted starting upload', 26 => 'Read Error', 27 => 'Memory allocation request error',
28 => 'Operation timed out', 29 => 'Obsolete error', 30 => 'FTP Port command failure',
31 => 'FTP REST failure', 32 => 'Obsolete error', 33 => 'Range Request failure',
34 => 'HTTP Post error', 35 => 'SSL Connect error', 37 => 'Could not read file',
38 => 'LDAP Cannot bind', 39 => 'LDAP Search failed', 40 => 'Obsolete error',
41 => 'Function not found', 42 => 'Aborted by callback', 43 => 'Bad parameter',
44 => 'Obsolete error', 45 => 'Interface failure', 46 => 'Obsolete error',
47 => 'Too many redirects', 48 => 'Unknown option', 49 => 'Setopt Syntax error',
50 => 'Obsolete error', 51 => 'Obsolete error', 52 => 'Curl got nothing',
53 => 'SSL Engine not found', 54 => 'SSL Engine failure', 55 => 'Failed sending data',
56 => 'Failure receving data', 57 => 'Obsolete error', 58 => 'Local client certificate error',
59 => 'Cipher error', 60 => 'SSL certificate error', 61 => 'Transfer encoding error',
62 => 'Obsolete error', 63 => 'Maximum file size exceeded', 64 => 'FTP SSL level failure',
65 => 'Rewinding operation failed', 66 => 'SSL Engine failure', 67 => 'Login Denied',
68 => 'TFTP server not found', 69 => 'TFTP permission error', 70 => 'Out of disk space on server',
71 => 'Illegal TFTP operation', 72 => 'Unknown TFTP transfer ID', 73 => 'File already exists',
74 => 'TFTP no such user', 75 => 'Obsolete error', 76 => 'Obsolete error',
77 => 'SSL CA certificate error', 78 => 'Remote file not found', 79 => 'SSH connection failure',
80 => 'SSH connection failure', 81 => 'Socket is not ready', 82 => 'CRL Bad File error',
83 => 'SSL Issurer failure', 84 => 'FTP PRET failure', 85 => 'RTSP CSeq number error',
86 => 'RTSP Session mismatch', 87 => 'FTP Bad file list', 88 => 'Chunk callback error',
89 => 'No connection available', 90 => 'Pin Key match failure', 91 => 'Invalid Certificate status',
92 => 'HTTP/2 framing error', 93 => 'Recursive API call error', 94 => 'Authentication error',
95 => 'HTTP/3 layer error', 94 => 'Authentication function error', 95 => 'HTTP/3 layer error',
96 => 'QUIC connect error', 97 => 'Proxy handshake error', 98 => 'SSL Client certificate required',
99 => 'Unrecoveranle Poll error',
100 => '100 Continue', 101 => '101 Switching Protocols', 102 => '102 Processing',
200 => '200 OK', 201 => '201 Created', 202 => '202 Accepted',
203 => '203 Non-Authoritative Info', 204 => '204 No Content', 205 => '205 Reset Content',
206 => '206 Partial Content', 207 => '207 Multi-Status', 208 => '208 Already Reported',
226 => '226 IM Used',
300 => '300 Multiple Choices', 301 => '301 Moved Permanently', 302 => '302 Found',
303 => '303 See Other', 304 => '304 Not Modified', 305 => '305 Use Proxy',
306 => '306 Switch Proxy', 307 => '307 Temporary Redirect', 308 => '308 Permanent Redirect',
400 => '400 Bad Request', 401 => '401 Unauthorized', 402 => '402 Payment Required',
403 => '403 Forbidden', 404 => '404 Not Found', 405 => '405 Method Not Allowed',
406 => '406 Not Acceptable', 407 => '407 Proxy Authentication Required', 408 => '408 Request Timeout',
409 => '409 Conflict', 410 => '410 Gone', 411 => '411 Length Required',
412 => '412 Precondition Failed', 413 => '413 Request Entity Too Large', 414 => '414 Request-URI Too Long',
415 => '415 Unsupported Media Type', 416 => '416 Requested Range Not Satisfiable', 417 => '417 Expectation Failed',
418 => '418 Im a teapot', 419 => '419 Authentication Timeout', 420 => '420 Method Failure',
421 => '421 Misdirected Request', 422 => '422 Unprocessable Entity', 423 => '423 Locked',
424 => '424 Failed Dependency', 426 => '426 Upgrade Required', 428 => '428 Precondition Required',
429 => '429 Too Many Requests', 431 => '431 Request Header Fields Large', 440 => '440 Login Timeout',
444 => '444 No Response', 449 => '449 Retry With', 450 => '450 Blocked Windows Parental Controls',
451 => '451 Unavailable Legal Reasons', 494 => '494 Request Header too Large', 495 => '495 Cert Error',
496 => '496 No Cert', 497 => '497 HTTP to HTTPS', 498 => '498 Token expired/invalid',
499 => '499 Client Closed Request',
500 => '500 Internal Server Error', 501 => '501 Not Implemented', 502 => '502 Bad Gateway',
503 => '503 Service Unavailable', 504 => '504 Gateway Timeout', 505 => '505 HTTP Version Not Supported',
506 => '506 Variant Also Negotiates', 507 => '507 Insufficient Storage', 508 => '508 Loop Detected',
509 => '509 Bandwidth Limit Exceeded', 510 => '510 Not Extended', 511 => '511 Network Authentication Required',
521 => '521 Web Server is down', 598 => '598 Network read timeout error', 599 => '599 Network connect timeout error',
520 => 'CF 520 Unknown Error', 521 => 'CF 521 Web Server is Down', 522 => 'CF 522 Connection Timed Out',
523 => 'CF 523 Origin is Unreachable', 524 => 'CF 524 A Timeout Occured', 525 => 'CF 525 SSL Handshake Failed',
526 => 'CF 526 Invalid SSL Certificate',527 => 'CF 527 Railgun Error'
);
// File download Mime-Types
$pfb['mime_types'] = array_flip(array( 'inode/x-empty',
'text/plain',
'text/html',
'text/xml',
'text/csv',
'application/csv',
'application/json',
'application/x-tar',
'application/gzip',
'application/x-gzip',
'application/x-bzip2',
'application/zip'));
// pfb_filter constants
define('PFB_FILTER_HTML', 1);
define('PFB_FILTER_URL', 2);
define('PFB_FILTER_WORD', 3);
define('PFB_FILTER_WORD_DOT', 4);
define('PFB_FILTER_TLD', 5);
define('PFB_FILTER_DOMAIN', 6);
define('PFB_FILTER_HOSTNAME', 7);
define('PFB_FILTER_IPV4', 8);
define('PFB_FILTER_IP', 9);
define('PFB_FILTER_ALPHA', 10);
define('PFB_FILTER_ALNUM', 11);
define('PFB_FILTER_NUM', 12);
define('PFB_FILTER_CSV', 13);
define('PFB_FILTER_CSV_WHOIS', 14);
define('PFB_FILTER_CSV_CRON', 15);
define('PFB_FILTER_FILE_MIME_COMPARE', 16);
define('PFB_FILTER_FILE_MIME', 17);
define('PFB_FILTER_FILE_MIME_COMPRESSED', 18);
define('PFB_FILTER_ATYPE', 19);
define('PFB_FILTER_HEX_COLOR', 20);
define('PFB_FILTER_ON_OFF', 21);
// Function to filter/sanitize user input
function pfb_filter($input, $type, $reference='Unknown', $default='', $escape=FALSE) {
global $pfb;
$header = "\n PFB_FILTER - {$type} | {$reference} [ NOW ]";
$return_type = $default;
if (in_array($type, array(PFB_FILTER_URL, PFB_FILTER_FILE_MIME_COMPARE, PFB_FILTER_FILE_MIME, PFB_FILTER_FILE_MIME_COMPRESSED))) {
$return_type = FALSE;
}
if (!in_array($type, array(PFB_FILTER_ON_OFF, PFB_FILTER_NUM))) {
if (empty($input) || is_null($input)) {
return $return_type;
}
}
// Check for control characters
if (is_array($input)) {
foreach ($input as $vline) {
if (preg_match("/[\p{C}]+/", $vline)) {
pfb_logger("{$header} Control characters found [ " . htmlspecialchars($vline) . " ]", 6);
return $return_type;
}
}
}
else {
if (preg_match("/[\p{C}]+/", $input)) {
pfb_logger("{$header} Control characters found [ " . htmlspecialchars($input) . " ]", 6);
return $return_type;
}
}
$result = FALSE;
switch ($type) {
case PFB_FILTER_HTML:
$result = htmlspecialchars(trim($input));
break;
case PFB_FILTER_URL:
// Validate URL input
$is_RSYNC = FALSE;
if (strpos($input, '::') !== FALSE && !$escape) {
$rsync = explode('::', $input);
if (count($rsync) == 2 && !empty($rsync[0]) && filter_var($rsync[0], FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
$is_RSYNC = TRUE;
}
}
if ($is_RSYNC || filter_var($input, FILTER_VALIDATE_URL)) {
if ($is_RSYNC) {
$data = array('host' => $rsync[0], 'path' => $rsync[1]);
} else {
$data = parse_url($input);
if (!in_array($data['scheme'], array('http', 'https', 'rsync', 'ftp'))) {
pfb_logger("{$header} Invalid URL Scheme [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
}
}
$validate_list = '';
if (!$data || !is_array($data)) {
pfb_logger("{$header} Invalid URL (missing data) [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
} elseif (!isset($data['host']) || empty($data['host'])) {
pfb_logger("{$header} Invalid URL (missing hostname) [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
} elseif (is_ipaddr($data['host'])) {
$validate_list = array(array('type' => 'IP', 'data' => $data['host']));
} else {
$validate_list = resolve_host_addresses("{$data['host']}.");
}
$pfsense_configured = FALSE;
if (!empty($validate_list) && is_array($validate_list)) {
foreach ($validate_list as $validate) {
if ($validate['type'] == 'CNAME' && !empty($validate['data'])) {
if (is_ipaddr($validate['data'])) {
$cname_list = resolve_host_addresses($validate['data']);
} else {
$cname_list = resolve_host_addresses("{$validate['data']}.");
}
if (!empty($cname_list) && is_array($cname_list)) {
foreach ($cname_list as $cname) {
if (!empty($cname['data']) && is_ipaddr_configured($cname['data'])) {
$pfsense_configured = TRUE;
break 2;
}
}
}
}
if (!empty($validate['data']) && is_ipaddr_configured($validate['data'])) {
$pfsense_configured = TRUE;
break;
}
}
}
else {
// Cannot resolve host
pfb_logger("{$header} Invalid URL (cannot resolve) [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
}
$path = pathinfo($data['path'], PATHINFO_DIRNAME);
// Validate only pfSense URLS (localfile check and Alerts Tab refresh)
if ($escape) {
if ($pfsense_configured ||
($data['host'] == '127.0.0.1') ||
($data['host'] == '::1')) {
// Allow '/usr/local/www'
if ($path == '/') {
return TRUE;
}
}
if ($reference == 'alerts refresh') {
pfb_logger("{$header} Invalid URL (alerts tab) [ " . htmlspecialchars($input) . " ]", 6);
}
return FALSE;
}
// pfSense URL
if (($pfsense_configured) ||
($data['host'] == '127.0.0.1') ||
($data['host'] == '::1')) {
// Allow '/usr/local/www'
if ($path == '/') {
return TRUE;
}
pfb_logger("{$header} Invalid URL (not allowed) [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
}
// all other remote URLs no path validation
return TRUE;
}
// Local file path validation
else {
$path = pathinfo($input, PATHINFO_DIRNAME) . '/';
$allowed_path = array_flip(array( '/var/db/pfblockerng/',
'/var/db/pfblockerng/deny/',
'/var/db/pfblockerng/permit/',
'/var/db/pfblockerng/match/',
'/var/db/pfblockerng/native/',
'/var/db/pfblockerng/original/',
'/var/db/pfblockerng/dnsbl/',
'/var/db/pfblockerng/dnsblorig/',
'/var/db/pfblockerng/ET/',
'/var/db/pfblockerng/ut1/',
'/var/db/pfblockerng/shallalist/',
'/usr/local/www/',
'/usr/local/share/GeoIP/',
'/usr/local/share/GeoIP/cc/' ));
if (isset($allowed_path[$path])) {
return TRUE;
}
}
pfb_logger("\n[PFB_FILTER - {$type}] Invalid URL (not allowed2) [ " . htmlspecialchars($input) . " ]", 6);
return FALSE;
break;
case PFB_FILTER_WORD:
// Validate for 'Any word character (letter, number, underscore)'
if (!preg_match("/\W/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_WORD_DOT:
// Validate for '(letter, number, underscore, dash) dot (letter, number, underscore, dash)'
if (preg_match("/^[a-zA-Z0-9_\-]+\.{1}[a-zA-Z0-9_\-]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_TLD:
// Validate TLD
if (preg_match("/^[a-zA-Z0-9_\.\-]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_DOMAIN:
// Validate domain
if ((strpos($input, '.') !== FALSE) && // Exclude no dots
(strpos($input, '..') === FALSE) && // Exclude double dot
(strlen($input) < 255) && // Validate length of domain (Max 255 chars)
(pfb_validate_domain_labels($input) !== FALSE) && // Validate length of labels (Max of 63 chars)
(preg_match("/^[a-zA-Z0-9_\.\-]+$/", $input))) { // Exclude any other characters
$result = TRUE;
}
if ($result) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_HOSTNAME:
// Validate hostname
if (is_hostname($input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_IPV4:
// Validate IPv4
if (is_ipaddrv4($input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_IP:
// Validate any IP address v4/v6
if (is_ipaddr($input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_ALPHA:
// Validate input is alphabetic only
if (ctype_alpha($input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_ALNUM:
// Validate input is alphanumeric only
if (ctype_alnum($input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_NUM:
// Validate input is number only
if (preg_match("/^[0-9]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_CSV:
// Validate CSV string
if (preg_match("/^[a-zA-Z0-9,_-]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_CSV_WHOIS:
// Validate Whoisconvert string
if (preg_match("/^[a-zA-Z0-9,\._\-]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_CSV_CRON:
// Validate CSV string (cron hour setting)
if ($input == '*' || preg_match("/^[0-9,]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_FILE_MIME_COMPARE:
// Validate mime-type
// $input [0] path/file, [1] mime-type to be validated against
if (isset($retval)) {
unset($retval);
}
if (isset($output)) {
unset($output);
}
if (!file_exists($input[0])) {
pfb_logger("{$header} Invalid Mime-type (file missing): [" . htmlspecialchars($input[0]) . "|" . htmlspecialchars($input[1]) . "]", 2);
return FALSE;
}
exec("/usr/bin/file -b --mime-type " . escapeshellarg($input[0]) . " 2>&1", $output, $retval);
if ($retval != 0 || empty($output[0]) || $output[0] !== $input[1]) {
pfb_logger("{$header} Invalid Mime-type: [" . htmlspecialchars($input[0]) . "|" . htmlspecialchars($input[1]) . "]", 2);
return FALSE;
}
return TRUE;
break;
case PFB_FILTER_FILE_MIME:
// Validate File Mime-types
// $input [0] path/file escaped, [1] path/file [2] URL
if (isset($retval)) {
unset($retval);
}
if (isset($output)) {
unset($output);
}
if (!file_exists($input[1])) {
pfb_logger("{$header} Downloaded file not found: [" . htmlspecialchars($input[0]) . "|" . htmlspecialchars($input[1]) . "]", 2);
return FALSE;
}
exec("/usr/bin/file -b --mime-type {$input[0]} 2>&1", $output, $retval);
if ($retval != 0 || empty($output[0]) || !isset($pfb['mime_types'][$output[0]])) {
// Exceptions
$hostname = parse_url($input[2], PHP_URL_HOST);
if ($output[0] == 'text/x-asm' &&
($hostname == 'easylist-downloads.adblockplus.org' || $hostname == 'easylist.to' )) {
$output[0] = 'text/plain';
}
else {
pfb_logger("\n[PFB_FILTER - {$type}] Failed or invalid Mime Type: [" . htmlspecialchars($output[0]) . "|" . htmlspecialchars($retval) . "]", 2);
unlink_if_exists($input[1]);
return FALSE;
}
}
$result = htmlspecialchars($output[0]);
break;
case PFB_FILTER_FILE_MIME_COMPRESSED:
// Validate File Mime-types in compressed files
// $input [0] path/file escaped, [1] path/file [2] URL
if (isset($retval)) {
unset($retval);
}
if (isset($output)) {
unset($output);
}
if (!file_exists($input[1])) {
pfb_logger("{$header} Downloaded file not found: [" . htmlspecialchars($input[0]) . "|" . htmlspecialchars($input[1]) . "]", 2);
return FALSE;
}
exec("/usr/bin/file -bZ --mime-type {$input[0]} 2>&1", $output, $retval);
if ($retval != 0 || empty($output[0]) || !isset($pfb['mime_types'][$output[0]])) {
pfb_logger("{$header} Failed or invalid Mime Type Compressed: [" . htmlspecialchars($output[0]) . "|" . htmlspecialchars($retval) . "]", 2);
unlink_if_exists($input[1]);
return FALSE;
}
$result = htmlspecialchars($output[0]);
break;
case PFB_FILTER_ATYPE:
// Validate atype entry in category_edit.php
if (preg_match("/^[a-zA-Z0-9\.|_]+$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_HEX_COLOR:
// Alerts Tab - Hex code validation
if ($input == 'none' || preg_match("/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/", $input)) {
$result = htmlspecialchars($input);
}
break;
case PFB_FILTER_ON_OFF:
// Validate on or off
if ($input == 'on' || $input == '') {
$result = htmlspecialchars($input);
} else {
pfb_logger("{$header} Invalid on/off [ " . htmlspecialchars($input) . " ]", 6);
}
break;
default:
pfb_logger("{$header} Type invalid [ " . htmlspecialchars($input) . " ]", 6);
break;
}
if ($result && $escape) {
$result = escapeshellarg($result);
}
// Log validation errors
if (!empty($input) && empty($result) &&
!in_array($type, array(PFB_FILTER_URL, PFB_FILTER_FILE_MIME_COMPARE, PFB_FILTER_FILE_MIME, PFB_FILTER_FILE_MIME_COMPRESSED, PFB_FILTER_ON_OFF, PFB_FILTER_NUM))) {
// Exceptions
if (in_array($reference, array( 'DNSBL_Download'))) {
//
} else {
pfb_logger("{$header} Failed validation [ " . htmlspecialchars($input) . " ]", 6);
}
}
return $result == FALSE ? $default : $result;
}
// Validate length of labels (Max of 63 chars)
function pfb_validate_domain_labels($input) {
$labels = explode('.', $input);
if (!empty($labels) && is_array($labels)) {
foreach ($labels as $label) {
if (strlen($label) > 63) {
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
// [ $pfb ] pfBlockerNG global array. This needs to be called to get the updated settings.
function pfb_global() {
global $g, $config, $pfb;
// Create folders if not exist.
foreach ($pfb['folder_array'] as $folder) {
safe_mkdir("{$folder}", 0755);
}
// Reload config.xml to get any recent changes
$config = parse_config(true);
init_config_arr(array('installedpackages', 'pfblockerng', 'config', 0));
init_config_arr(array('installedpackages', 'pfblockerngipsettings', 'config', 0));
init_config_arr(array('installedpackages', 'pfblockerngdnsblsettings', 'config', 0));
init_config_arr(array('installedpackages', 'pfblockerngblacklist'));
init_config_arr(array('installedpackages', 'pfblockerngglobal'));
// General variables
$pfb['config'] = config_get_path('installedpackages/pfblockerng/config/0');
$pfb['ipconfig'] = config_get_path('installedpackages/pfblockerngipsettings/config/0');
$pfb['dnsblconfig'] = config_get_path('installedpackages/pfblockerngdnsblsettings/config/0');
$pfb['blconfig'] = config_get_path('installedpackages/pfblockerngblacklist');
$pfb['config_global'] = config_get_path('installedpackages/pfblockerngglobal');
$pfb['enable'] = $pfb['config']['enable_cb']; // Enable/Disable of pfBlockerNG
$pfb['keep'] = $pfb['config']['pfb_keep']; // Keep blocklists on pfBlockerNG Disable
$pfb['interval'] = $pfb['config']['pfb_interval'] ?: '1'; // Hour cycle for scheduler
// Validate Cron settings
if (!is_numeric($pfb['interval'])) {
$pfb['interval'] = '1';
}
foreach (array( 'pfb_min' => 'min', // User defined CRON start minute
'pfb_hour' => 'hour', // Start hour of the scheduler
'pfb_dailystart' => '24hour' // Start hour of the 'Once a day' schedule
) as $conf_value => $pfb_value) {
$pfb_variable = $pfb['config'][$conf_value] ?: '0';
if (!is_numeric($pfb_variable)) {
$pfb[$pfb_value] = '0';
} else {
$pfb[$pfb_value] = $pfb_variable;
}
}
$pfb['supp'] = $pfb['ipconfig']['suppression']; // Enable Suppression
$pfb['cc'] = $pfb['ipconfig']['database_cc']; // Disable Country database CRON updates
$pfb['maxmind_locale'] = $pfb['ipconfig']['maxmind_locale'] ?: 'en'; // MaxMind Localized Language setting
$pfb['asn_reporting'] = $pfb['ipconfig']['asn_reporting'] ?: 'disabled'; // ASN Reporting
$pfb['maxmind_key'] = pfb_filter($pfb['ipconfig']['maxmind_key'], PFB_FILTER_WORD, 'pfb_global'); // Maxmind License Key
$pfb['dnsbl'] = $pfb['dnsblconfig']['pfb_dnsbl']; // Enabled state of DNSBL
$pfb['dnsbl_vip_type'] = $pfb['dnsblconfig']['pfb_dnsvip_type'] ?: 'ipalias'; // Virtual IP type
$pfb['dnsbl_vip_vhid'] = isset($pfb['dnsblconfig']['pfb_dnsvip_vhid']) ? $pfb['dnsblconfig']['pfb_dnsvip_vhid'] : ''; // Virtual IP Carp VHID
$pfb['dnsbl_vip_base'] = isset($pfb['dnsblconfig']['pfb_dnsvip_base']) ? $pfb['dnsblconfig']['pfb_dnsvip_base'] : ''; // Virtual IP Carp advbase
$pfb['dnsbl_vip_skew'] = isset($pfb['dnsblconfig']['pfb_dnsvip_skew']) ? $pfb['dnsblconfig']['pfb_dnsvip_skew'] : ''; // Virtual IP Carp skew
$pfb['dnsbl_vip_pass'] = isset($pfb['dnsblconfig']['pfb_dnsvip_pass']) ? $pfb['dnsblconfig']['pfb_dnsvip_pass'] : ''; // Virtual IP Carp password (if required)
$pfb['dnsbl_iface'] = $pfb['dnsblconfig']['dnsbl_interface']?: 'lo0'; // VIP Local Interface setting
$pfb['dnsbl_vip'] = $pfb['dnsblconfig']['pfb_dnsvip'] ?: ''; // Virtual IP local address
$pfb['dnsbl_v6'] = $pfb['dnsblconfig']['pfb_dnsblv6'] ?: ''; // Enable/Disable DNSBL IPv6
$pfb['dnsbl_port'] = $pfb['dnsblconfig']['pfb_dnsport']; // Lighttpd web server http port setting
$pfb['dnsbl_port_ssl'] = $pfb['dnsblconfig']['pfb_dnsport_ssl']; // Lighttpd web server https port setting
$pfb['dnsbl_alexa'] = $pfb['dnsblconfig']['alexa_enable']; // TOP1M whitelist
$pfb['dnsbl_alexatype'] = $pfb['dnsblconfig']['alexa_type'] ?: 'tranco'; // TOP1M type (Tranco, Alexa or Cisco)
$pfb['dnsbl_res_cache'] = $pfb['dnsblconfig']['pfb_cache']; // DNSBL Option to backup/restore Resolver cache
$pfb['dnsbl_sync'] = $pfb['dnsblconfig']['pfb_dnsbl_sync']; // Live Updates to Resolver without a Reload
$pfb['dnsbl_global_log']= $pfb['dnsblconfig']['global_log'] ?: ''; // Global Logging/Blocking mode
$pfb['dnsbl_python'] = $pfb['dnsblconfig']['pfb_python']; // DNSBL Resolver python integration
$pfb['dnsbl_mode'] = $pfb['dnsblconfig']['dnsbl_mode']; // DNSBL Mode (Unbound/python mode)
$pfb['dnsbl_py_reply'] = $pfb['dnsblconfig']['pfb_py_reply']; // DNSBL Resolver python DNS Reply logging
$pfb['dnsbl_py_block'] = $pfb['dnsblconfig']['pfb_py_block']; // DNSBL Resolver python blocking mode
$pfb['dnsbl_hsts'] = $pfb['dnsblconfig']['pfb_hsts']; // DNSBL Resolver python block HSTS via Null Block mode
$pfb['dnsbl_idn'] = $pfb['dnsblconfig']['pfb_idn']; // DNSBL Resolver python block IDN domains
$pfb['dnsbl_regex'] = $pfb['dnsblconfig']['pfb_regex']; // DNSBL Resolver python regex
$pfb['dnsbl_regex_list']= $pfb['dnsblconfig']['pfb_regex_list']; // DNSBL Resolver python regex list
$pfb['dnsbl_cname'] = $pfb['dnsblconfig']['pfb_cname']; // DNSBL Resolver python CNAME Validation
$pfb['dnsbl_pytld'] = $pfb['dnsblconfig']['pfb_pytld']; // DNSBL Resolver python TLD Allow option
$pfb['dnsbl_py_nolog'] = $pfb['dnsblconfig']['pfb_py_nolog']; // DNSBL Resolver python - Log events via DNSBL Webserver vs python
$pfb['dnsbl_noaaaa'] = $pfb['dnsblconfig']['pfb_noaaaa']; // DNSBL Resolver python no AAAA
$pfb['dnsbl_noaaaa_list']=$pfb['dnsblconfig']['pfb_noaaaa_list']; // DNSBL Resolver python no AAAA list
$pfb['dnsbl_gp'] = $pfb['dnsblconfig']['pfb_gp']; // DNSBL Resolver python - DNSBL Bypass
$pfb['dnsbl_gp_bypass_list'] = $pfb['dnsblconfig']['pfb_gp_bypass_list']; // DNSBL Resolver python - List of Local IPs to bypass DNSBL
// DNSBL Resolver mode (Unbound/Python)
$pfb['dnsbl_py_blacklist'] = FALSE;
if ($pfb['dnsbl_mode'] == 'dnsbl_python' && $pfb['dnsbl_py_block'] == 'on') {
$pfb['dnsbl_py_blacklist'] = TRUE;
}
// SafeSearch
init_config_arr(array('installedpackages', 'pfblockerngsafesearch'));
$pfb['safesearch_enable'] = config_get_path('installedpackages/pfblockerngsafesearch/safesearch_enable', 'Disable');
$pfb['safesearch_youtube'] = config_get_path('installedpackages/pfblockerngsafesearch/safesearch_youtube', 'Disable');
$pfb['safesearch_doh'] = config_get_path('installedpackages/pfblockerngsafesearch/safesearch_doh', 'Disable');
$pfb['safesearch_doh_list'] = explode(',', config_get_path('installedpackages/pfblockerngsafesearch/safesearch_doh_list', ''));
// DNSBL SafeSearch
$pfb['dnsbl_safe_search'] = FALSE;
if ($pfb['safesearch_enable'] !== 'Disable' ||
$pfb['safesearch_youtube'] !== 'Disable' ||
$pfb['safesearch_doh'] !== 'Disable') {
$pfb['dnsbl_safe_search'] = TRUE;
}
// External DNS Server for TLD drill and CNAME Queries
$pfb['extdns'] = pfb_filter($pfb['config_global']['pfbextdns'], PFB_FILTER_IPV4, 'pfb_global', '8.8.8.8');
// Unbound chroot cmd
$pfb['chroot_cmd'] = "/usr/sbin/chroot -u unbound -g unbound / /usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf";
// Define SQLite3 parameters
$pfb['sqlite_timeout'] = 100000;
// Max daily download failure threshold (default to '0' unlimited failures)
$pfb['skipfeed'] = $pfb['config']['skipfeed'] != '' ? $pfb['config']['skipfeed'] : 0;
if (config_path_enabled('unbound')) {
$pfb['unbound_state'] = 'on';
} else {
$pfb['unbound_state'] = '';
}
// cURL - system proxy server setttings, if configured
if (!empty(config_get_path('system/proxyurl'))) {
$pfb['curl_defaults'][CURLOPT_PROXY] = config_get_path('system/proxyurl');
if (!empty(config_get_path('system/proxyport'))) {
$pfb['curl_defaults'][CURLOPT_PROXYPORT] = config_get_path('system/proxyport');
}
if (!empty(config_get_path('system/proxyuser')) && !empty(config_get_path('system/proxypass'))) {
$pfb['curl_defaults'][CURLOPT_PROXYAUTH] = 'CURLAUTH_ANY | CURLAUTH_ANYSAFE';
$pfb['curl_defaults'][CURLOPT_PROXYUSERPWD] = config_get_path('system/proxyuser') . ':' . config_get_path('system/proxypass');
}
}
else {
$pfb['curl_defaults'][CURLOPT_TCP_FASTOPEN] = true;
}
// Set pfBlockerNG to disabled on 're-install'
if (isset($pfb['install']) && $pfb['install']) {
$pfb['enable'] = $pfb['dnsbl'] = '';
$pfb['install'] = FALSE;
}
}
pfb_global();
// Function to get pfBlockerNG package version
function pfb_pkg_ver() {
$pkg_ver = 'v??';
foreach (config_get_path('installedpackages/package', []) as $pkg_info_data) {
if (strpos($pkg_info_data['name'], 'pfBlockerNG') !== FALSE) {
$pkg_ver = 'v' . $pkg_info_data['version'];
break;
}
}
return $pkg_ver;
}
// Firewall Filter Service
function pfb_filter_service() {
$rc = array();
$rc['file'] = 'pfb_filter.sh';
$rc['start'] = <<<EOF
# Check if pfBlockerNG is enabled
pfbcheck="\$(/usr/local/sbin/read_xml_tag.sh string installedpackages/pfblockerng/config/enable_cb)"
if [ "\${pfbcheck}" != 'on' ]; then
exit
fi
# Ensure all processes are stopped
rc_stop
# clog is not required for pfSense 2.5 and above
filter_type='tail_pfb'
if [ -e "/usr/local/sbin/clog_pfb" ]; then
filter_type='clog_pfb'
fi
# Compare php/php_pfb versions
php_path='/usr/local/bin'
phpver="\$(/usr/bin/stat \${php_path}/php | cut -d '/' -f1)"
if [ -e "\${php_path}/php_pfb" ]; then
phppfbver="\$(/usr/bin/stat \${php_path}/php_pfb | cut -d '/' -f1)"
else
phppfbver=''
fi
# Create new hard link for php_pfb on version mismatch
if [ "\${phpver}" != "\${phppfbver}" ]; then
if [ -e "\${php_path}/php_pfb" ]; then
tmpfile="\$(/usr/bin/mktemp /tmp/pfb_php.XXXXXX)"
/bin/mv "\${php_path}/php_pfb" "\${tmpfile}"
fi
/bin/ln "\${php_path}/php" "\${php_path}/php_pfb"
fi
# Start pfBlockerNG Firewall filter Daemon
if [ -e '/var/log/filter.log' ]; then
/usr/bin/logger -p daemon.info -t "\${filter_type}" "[pfBlockerNG] Firewall Filter Service started"
if [ "\${filter_type}" == 'clog_pfb' ]; then
/usr/local/sbin/clog_pfb -f /var/log/filter.log | /usr/local/bin/php_pfb -f /usr/local/pkg/pfblockerng/pfblockerng.inc filterlog &
else
/usr/bin/tail_pfb -n0 -F /var/log/filter.log | /usr/local/bin/php_pfb -f /usr/local/pkg/pfblockerng/pfblockerng.inc filterlog &
fi
fi
EOF;
$rc['stop'] = <<<EOF
# clog is not required for pfSense 2.5 and above
filter_type='tail_pfb'
if [ -e "/usr/local/sbin/clog_pfb" ]; then
filter_type='clog_pfb'
fi
# Terminate pfBlockerNG Firewall filter Daemon (clog) and filter Daemon, if found
/usr/bin/logger -p daemon.info -t "\${filter_type}" "[pfBlockerNG] Firewall Filter Service stopped"
/usr/bin/logger -p daemon.info -t php_pfb "[pfBlockerNG] filterlog daemon stopped"
pidnum="\$(/bin/ps -wax | /usr/bin/grep '[c]log_pfb -f /var/log/filter.log\|[t]ail_pfb -n0 -F /var/log/filter.log\|[p]fblockerng.inc filterlog' | /usr/bin/awk '{print \$1}')"
if [ ! -z "\${pidnum}" ]; then
for i in \${pidnum}; do
/bin/kill -9 "\${i}"
done
fi
EOF;
write_rcfile($rc);
}
// DNSBL Service
function pfb_dnsbl_service() {
$rc = array();
$rc['file'] = 'pfb_dnsbl.sh';
$rc['start'] = <<<EOF
# Check if DNSBL is enabled
dnsblcheck="\$(/usr/local/sbin/read_xml_tag.sh string installedpackages/pfblockerngdnsblsettings/config/pfb_dnsbl)"
if [ "\${dnsblcheck}" != 'on' ]; then
exit
fi
# Ensure all processes are stopped
rc_stop
# Start DNSBL Lighttpd webserver (Unbound/Python mode) and DNSBL HTTPS Daemon (Unbound mode only)
if [ -e '/var/unbound/pfb_dnsbl_lighty.conf' ]; then
/usr/bin/logger -p daemon.info -t lighttpd_pfb "[pfBlockerNG] DNSBL Webserver started"
/usr/local/sbin/lighttpd_pfb -f /var/unbound/pfb_dnsbl_lighty.conf
fi
# Check if Unbound mode is enabled
unbound_mode="\$(/usr/local/sbin/read_xml_tag.sh string installedpackages/pfblockerngdnsblsettings/config/dnsbl_mode)"
# Start DNSBL Resolver queries Daemon
if [ "\${unbound_mode}" == 'dnsbl_unbound' ]; then
/usr/local/bin/php -f /usr/local/pkg/pfblockerng/pfblockerng.inc queries &
elif [ ! -e '/var/unbound/pfb_unbound.py' ]; then
cp /usr/local/pkg/pfblockerng/pfb_unbound.py /var/unbound/pfb_unbound.py
cp /usr/local/pkg/pfblockerng/pfb_unbound_include.inc /var/unbound/pfb_unbound_include.inc
cp /usr/local/pkg/pfblockerng/pfb_py_hsts.txt /var/unbound/pfb_py_hsts.txt
/usr/local/sbin/pfSctl -c 'service reload dns'
fi
EOF;
$rc['stop'] = <<<EOF
# Terminate DNSBL Lighttpd webserver, if found
/usr/bin/logger -p daemon.info -t lighttpd_pfb "[pfBlockerNG] DNSBL Webserver stopped"
pidnum="\$(/bin/pgrep lighttpd_pfb)"
if [ ! -z "\${pidnum}" ]; then
/usr/bin/killall lighttpd_pfb
fi
# Terminate DNSBL queries Daemon, if found
pidnum="\$(/bin/ps -wax | /usr/bin/grep '[p]fblockerng.inc queries' | /usr/bin/awk '{print \$1}')"
if [ ! -z "\${pidnum}" ]; then
for i in \${pidnum}; do
/bin/kill -9 "\${i}"
done
fi
EOF;
write_rcfile($rc);
}
// Create Firewall filter service
if (!file_exists('/usr/local/etc/rc.d/pfb_filter.sh')) {
pfb_filter_service();
}
// Create DNSBL service
if (!file_exists('/usr/local/etc/rc.d/pfb_dnsbl.sh')) {
pfb_dnsbl_service();
}
// clog is not required for pfSense 2.5 and above
if (substr(trim(file_get_contents('/etc/version')), 0, 3) > '2.5' && file_exists('/usr/local/sbin/clog_pfb')) {
unlink_if_exists('/usr/local/sbin/clog_pfb');
unlink_if_exists('/usr/bin/tail_pfb');
link('/usr/bin/tail', '/usr/bin/tail_pfb');
restart_service('pfb_filter');
}
// Commandline arguments for daemons
if (isset($argv[1])) {
// DNSBL Lighttpd HTTPS daemon (Collects HTTPS events from the Lighttpd dnsbl_error.log)
if ($argv[1] == 'dnsbl') {