This repository has been archived by the owner on Jan 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 246
/
squid.inc
executable file
·2358 lines (2089 loc) · 83.8 KB
/
squid.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
/*
squid.inc
part of pfSense (https://www.pfSense.org/)
Copyright (C) 2006-2009 Scott Ullrich
Copyright (C) 2006 Fernando Lemos
Copyright (C) 2012 Martin Fuchs
Copyright (C) 2012-2014 Marcello Coutinho
Copyright (C) 2013 Gekkenhuis
Copyright (C) 2015 ESF, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once('config.inc');
require_once('globals.inc');
require_once('notices.inc');
require_once('pfsense-utils.inc');
require_once('pkg-utils.inc');
require_once('services.inc');
require_once('service-utils.inc');
require_once('util.inc');
require_once('xmlrpc.inc');
require_once('xmlrpc_client.inc');
if (!function_exists("filter_configure")) {
require_once("filter.inc");
}
$shortcut_section = "squid";
global $pfs_version;
$pfs_version = substr(trim(file_get_contents("/etc/version")), 0, 3);
if ($pfs_version == "2.1" || $pfs_version == "2.2") {
define('SQUID_BASE', '/usr/pbi/squid-' . php_uname("m"));
define('SQUID_LOCALBASE', SQUID_BASE . "/local");
define('SQUID_UID', 'proxy');
define('SQUID_GID', 'proxy');
} else {
define('SQUID_BASE', '/usr/local');
define('SQUID_LOCALBASE', '/usr/local');
define('SQUID_UID', 'squid');
define('SQUID_GID', 'squid');
}
define('SQUID_CONFBASE', SQUID_LOCALBASE .'/etc/squid');
define('SQUID_CONFFILE', SQUID_CONFBASE . '/squid.conf');
define('SQUID_ACLDIR', '/var/squid/acl');
define('SQUID_PASSWD', '/var/etc/squid.passwd');
define('SQUID_SSL_DB', '/var/squid/lib/ssl_db');
$valid_acls = array();
$uname = posix_uname();
if ($uname['machine'] == 'amd64') {
ini_set('memory_limit', '250M');
}
/* Squid reverse proxy */
require_once('/usr/local/pkg/squid_reverse.inc');
/* Squid javascript helpers */
require_once('/usr/local/pkg/squid_js.inc');
/* Squid antivirus intergration features helpers */
require_once('/usr/local/pkg/squid_antivirus.inc');
/*
* Utility functions
*/
/* Handle base64 encoding and linebreaks in textarea configuration fields */
function sq_text_area_decode($text) {
return preg_replace('/\r\n/', "\n", base64_decode($text));
}
/* Get interface IP and netmask for Squid interfaces */
function squid_get_real_interface_address($iface) {
if (!function_exists("get_interface_ip")) {
require_once("interfaces.inc");
}
return array(get_interface_ip($iface), gen_subnet_mask(get_interface_subnet($iface)));
}
/* Check whether ACL is valid */
function squid_is_valid_acl($acl) {
global $valid_acls;
if (!is_array($valid_acls)) {
return;
}
return in_array($acl, $valid_acls);
}
/* Recursively change ownership of directories */
function squid_chown_recursive($dir, $user, $group) {
if (empty($dir) || ($dir == '/') || ($dir == '/usr/local') || !is_dir($dir)) {
log_error(gettext("[squid] Attempted to chown an invalid directory: '{$dir}'"));
return;
}
chown($dir, $user);
chgrp($dir, $group);
$handle = opendir($dir);
if ($handle) {
while (($item = readdir($handle)) !== false) {
if (!empty($item) && ($item != ".") && ($item != "..")) {
$path = "{$dir}/{$item}";
// Recurse unless it's the cache dir, that is slow and rarely necessary.
if (is_dir($path) && (basename($dir) != "cache")) {
squid_chown_recursive($path, $user, $group);
} elseif (is_file($path)) {
chown($path, $user);
chgrp($path, $group);
}
}
}
} else {
log_error(gettext("[squid] squid_chown_recursive() call failed; permissions not set for directory: '{$dir}'"));
}
}
/* Check whether Squid is enabled */
function squid_enabled() {
global $config, $proxy_enabled;
$proxy_enabled = false;
if (is_array($config['installedpackages']['squid']['config'])) {
// check whether Squid is enabled ...
if ($config['installedpackages']['squid']['config'][0]['enable_squid'] == "on") {
// ... and has at least one interface configured ...
if (!empty($config['installedpackages']['squid']['config'][0]['active_interface'])) {
$proxy_enabled = true;
// ... or whether Squid reverse proxy is enabled
} elseif (squid_reverse_enabled()) {
$proxy_enabled = true;
}
}
}
return $proxy_enabled;
}
/* Get list of certificates for SSL proxy */
function squid_get_server_certs() {
global $config;
$cert_arr = array();
$cert_arr[] = array('refid' => 'none', 'descr' => 'none');
foreach ($config['cert'] as $cert) {
$cert_arr[] = array('refid' => $cert['refid'], 'descr' => $cert['descr']);
}
return $cert_arr;
}
/* Handle root CA certificates bundle */
function squid_check_ca_hashes() {
global $config, $g;
// check certificates
$cert_count = 0;
if (is_dir(SQUID_LOCALBASE . '/share/certs')) {
if ($handle = opendir(SQUID_LOCALBASE . '/share/certs')) {
while (false !== ($file = readdir($handle))) {
if (preg_match ("/\d+.0/", $file)) {
$cert_count++;
}
}
closedir($handle);
}
}
if ($cert_count < 10) {
conf_mount_rw();
// create ca-root hashes from ca-root-nss package
log_error("[squid] Creating root certificate bundle hashes from the Mozilla Project...");
$cas = file(SQUID_LOCALBASE . '/share/certs/ca-root-nss.crt');
$cert = 0;
foreach ($cas as $ca) {
if (preg_match("/--BEGIN CERTIFICATE--/", $ca)) {
$cert = 1;
}
if ($cert == 1) {
$crt .= $ca;
}
if (preg_match("/-END CERTIFICATE-/", $ca)) {
file_put_contents("/tmp/cert.pem", $crt, LOCK_EX);
$cert_hash = array();
exec("/usr/bin/openssl x509 -hash -noout -in /tmp/cert.pem", $cert_hash);
file_put_contents(SQUID_LOCALBASE . "/share/certs/" . $cert_hash[0] . ".0", $crt, LOCK_EX);
$crt = "";
$cert = 0;
}
}
}
}
/*
* Squid cache setup
*/
/* Create Squid disk cache directories */
function squid_dash_z($cache_action = 'none') {
global $config;
// We need cache configured after initial package install
if (!is_array($config['installedpackages']['squidcache']['config'])) {
log_error("[squid] 'Local Cache' not configured, disk cache will be disabled.");
log_error("[squid] Please, configure and save 'Local Cache' settings before enabling Squid proxy.");
return;
}
if (is_array($config['installedpackages']['squidcache'])) {
$cachesettings = $config['installedpackages']['squidcache']['config'][0];
} else {
$cachesettings = array();
}
$cachedir = ($cachesettings['harddisk_cache_location'] ? $cachesettings['harddisk_cache_location'] : '/var/squid/cache');
$numdirs = ($cachesettings['level1_subdirs'] ? $cachesettings['level1_subdirs'] : 16);
if (is_dir($cachedir)) {
$currentdirs = count(glob("{$cachedir}/*", GLOB_ONLYDIR));
} else {
$currentdirs = 0;
}
// If the cache system is null, there is no need to initialize the (irrelevant) cache dir.
// If it already exists, delete it.
if ($cachesettings['harddisk_cache_system'] == "null") {
if (is_dir($cachedir)) {
if (substr($cachedir, 0, 11) === "/var/squid/") {
log_error("[squid] Deleting cache dir '{$cachedir}' since 'Hard Disk Cache System' is set to null...");
// cannot nuke disk cache while Squid is running
squid_stop_monitor();
if (is_service_running('squid')) {
stop_service("squid");
}
@rename($cachedir, "{$cachedir}.old");
mwexec_bg("/bin/rm -rf {$cachedir}.old");
squid_restart_services();
} else {
log_error("[squid] 'Hard Disk Cache System' is set to null.");
log_error("[squid] Will NOT delete cache dir '{$cachedir}' since it is not located under /var/squid. Delete manually if required.");
}
}
return;
}
// Re-create the cachedir if clean is forced by manually,
// or if the cachedir changed, or level1_subdirs don't exist or the number of level1_subdirs changed
if ($cache_action == "clean" || !is_dir($cachedir) || !is_dir($cachedir . '/00') || $numdirs != $currentdirs) {
// cannot nuke disk cache while Squid is running
squid_stop_monitor();
if (is_service_running('squid')) {
stop_service("squid");
}
if (is_dir($cachedir)) {
if (substr($cachedir, 0, 11) === "/var/squid/") {
@rename($cachedir, "{$cachedir}.old");
mwexec_bg("/bin/rm -rf {$cachedir}.old");
} else {
log_error("[squid] Will NOT delete cache dir '{$cachedir}' since it is not located under /var/squid. Delete manually if required.");
}
}
squid_create_cachedir();
squid_restart_services();
}
}
/* Helper function for squid_dash_z() */
function squid_create_cachedir() {
global $config;
if (is_array($config['installedpackages']['squidcache'])) {
$cachesettings = $config['installedpackages']['squidcache']['config'][0];
} else {
$cachesettings = array();
}
$cachedir = ($cachesettings['harddisk_cache_location'] ? $cachesettings['harddisk_cache_location'] : '/var/squid/cache');
if (!is_dir($cachedir)) {
log_error("[squid] Creating cache dir '{$cachedir}' ...");
safe_mkdir($cachedir, 0755);
@chown($cachedir, SQUID_UID);
@chgrp($cachedir, SQUID_GID);
}
if (!is_dir($cachedir . '/00')) {
log_error("[squid] Creating Squid cache subdirs in {$cachedir} ...");
mwexec(SQUID_BASE. "/sbin/squid -z -f " . SQUID_CONFFILE);
// Double check permissions here, should be safe to recurse cache dir if it's small here.
squid_chown_recursive($cachedir, SQUID_UID, SQUID_GID);
}
if (file_exists("/var/squid/cache/swap.state")) {
chown("/var/squid/cache/swap.state", SQUID_UID);
chgrp("/var/squid/cache/swap.state", SQUID_GID);
chmod("/var/squid/cache/swap.state", 0666);
}
}
/*
* rc scripts, services and cronjobs
*/
/* Handle cronjob install/uninstall */
function squid_install_cron($should_install) {
if (platform_booting()) {
return;
}
$cron_cmd = SQUID_BASE . "/sbin/squid -k rotate -f " . SQUID_CONFFILE;
/*
* This is here to prevent Squid from filling disk completely on misconfigured boxes.
* When 'Hard Disk Cache System' is set to null, the script silently returns, no need to check here.
* Otherwise, swapstate_check.php will only clear the disk cache on the following conditions:
* - if the swap.state file is taking up more than 75% of disk space,
* - or the drive is 90% full and swap.state is larger than 1GB.
*/
$swapstate_cmd = "/usr/local/pkg/swapstate_check.php";
if (($should_install) && (squid_enabled())) {
log_error("[squid] Adding cronjobs ...");
install_cron_job("{$cron_cmd}", $should_install, "0", "0", "*", "*", "*", "root");
install_cron_job("{$swapstate_cmd}", $should_install, "15", "0", "*", "*", "*", "root");
} else {
log_error("[squid] Removing cronjobs ...");
install_cron_job("{$cron_cmd}", false);
install_cron_job("{$swapstate_cmd}", false);
}
}
/* Create /usr/local/etc/rc.d/squid.sh rc script */
function squid_write_rcfile() {
/* Declare a variable for the SQUID_CONFFILE constant. */
/* Then the variable can be referenced easily in the heredoc text that generates the rc file. */
$squid_conffile_var = SQUID_CONFFILE;
$squid_base = SQUID_BASE;
$rc = array();
$rc['file'] = 'squid.sh';
$rc['start'] = <<< EOD
#/sbin/sysctl net.inet.ip.portrange.reservedhigh=0
if [ -z "`/bin/ps auxw | /usr/bin/grep "[s]quid " | /usr/bin/awk '{print $2}'`" ]; then
{$squid_base}/sbin/squid -f {$squid_conffile_var}
fi
EOD;
$rc['stop'] = <<< EOD
{$squid_base}/sbin/squid -k shutdown -f {$squid_conffile_var}
# Just to be sure...
sleep 5
if [ -n "`/bin/ps auxw | /usr/bin/grep "[s]quid " | /usr/bin/awk '{print $2}'`" ]; then
{$squid_base}/sbin/squid -k kill -f {$squid_conffile_var}
fi
if [ -x /usr/bin/ipcs ]; then
# http://man.chinaunix.net/newsoft/squid/Squid_FAQ/FAQ-22.html#ss22.8
/usr/bin/ipcs | /usr/bin/grep '^[mq]' | /usr/bin/awk '{printf "ipcrm -%s %s\\n", $1, $2}' | /bin/sh
fi
/usr/bin/killall -9 squid 2>/dev/null
/usr/bin/killall pinger 2>/dev/null
EOD;
conf_mount_rw();
write_rcfile($rc);
conf_mount_ro();
}
/* Start sqp_monitor.sh watchdog script */
function squid_start_monitor() {
if (squid_enabled()) {
if (!exec("/bin/ps auxw | /usr/bin/grep '[s]qpmon'")) {
log_error("[squid] Starting a proxy monitor script");
mwexec_bg("/usr/local/etc/rc.d/sqp_monitor.sh start");
}
sleep(1);
} else {
log_error("[squid] Squid is disabled. Not starting a proxy monitor script");
}
}
/* Stop sqp_monitor.sh watchdog script */
function squid_stop_monitor() {
/* kill any running proxy alarm scripts */
if (exec("/bin/ps auxw | /usr/bin/grep '[s]qpmon'")) {
log_error("[squid] Stopping any running proxy monitors");
mwexec("/usr/local/etc/rc.d/sqp_monitor.sh stop");
}
sleep(1);
}
/* Start and/or stop services according to Squid configuration */
function squid_restart_services() {
global $config;
// do not (re)start squid services on boot
if (platform_booting()) {
return;
}
if (squid_enabled()) {
/* kill any running proxy alarm scripts */
squid_stop_monitor();
if (!is_service_running('squid')) {
log_error("[squid] Starting service...");
mwexec(SQUID_BASE . "/sbin/squid -f " . SQUID_CONFFILE);
} else {
log_error("[squid] Reloading for configuration sync...");
mwexec(SQUID_BASE . "/sbin/squid -k reconfigure -f " . SQUID_CONFFILE);
}
// sleep for a couple seconds to give squid a chance to fire up fully.
for ($i = 0; $i < 10; $i++) {
if (!is_service_running('squid')) {
sleep(1);
}
}
/* restart proxy alarm scripts */
squid_start_monitor();
} else {
/* Squid is disabled - kill any running proxy alarm scripts and stop Squid services */
squid_stop_monitor();
if (is_service_running('squid')) {
log_error("[squid] Stopping service...");
stop_service("squid");
}
}
}
/*
* Squid package install/uninstall
*/
function squid_install_command() {
global $config, $g;
/* Set storage system for nanobsd */
if (!is_array($config['installedpackages']['squidcache'])) {
$config['installedpackages']['squidcache'] = array();
}
if ($g['platform'] == "nanobsd") {
$config['installedpackages']['squidcache']['config'][0]['harddisk_cache_system'] = 'null';
}
// migrate configuration from old versions
squid_upgrade_config();
/* make sure pinger is executable and suid root */
// XXX: Bug #5114
if (file_exists(SQUID_LOCALBASE . "/libexec/squid/pinger")) {
chgrp(SQUID_LOCALBASE . "/libexec/squid/pinger", SQUID_GID);
}
// another PBI hack
if (SQUID_BASE != '/usr/local' && file_exists('/usr/local/bin/check_ip.php') && !file_exists(SQUID_BASE . '/bin/check_ip.php')) {
symlink("/usr/local/bin/check_ip.php", SQUID_BASE . "/bin/check_ip.php");
}
// create squid rcfile
squid_write_rcfile();
// create squid monitor rcfile
write_rcfile(array(
"file" => "sqp_monitor.sh",
"start" => "/usr/local/pkg/sqpmon.sh &",
"stop" => "/bin/ps awux | /usr/bin/grep \"sqpmon\" | /usr/bin/grep -v \"grep\" | /usr/bin/grep -v \"php\" | /usr/bin/awk '{ print $2 }' | /usr/bin/xargs kill")
);
// antivirus intergration
squid_antivirus_install_command();
foreach (array(SQUID_CONFBASE, SQUID_ACLDIR, SQUID_SSL_DB) as $dir) {
safe_mkdir($dir, 0755);
squid_chown_recursive($dir, SQUID_UID, SQUID_GID);
}
if (!file_exists(SQUID_CONFBASE . '/mime.conf') && file_exists(SQUID_CONFBASE . '/mime.conf.default')) {
copy(SQUID_CONFBASE . '/mime.conf.default', SQUID_CONFBASE . '/mime.conf');
}
// remove unwanted PBI rc script
unlink_if_exists("/usr/local/etc/rc.d/squid");
// remove broken cronjobs possibly left over after 'Clear Cache on Log Rotate' misfeature
install_cron_job("/usr/local/pkg/swapstate_check.php clean;", false);
install_cron_job("/bin/rm /var/squid/cache/swap.state;", false);
}
function squid_deinstall_command() {
global $config, $g, $keep;
/* remove cronjobs */
squid_install_cron(false);
/* kill all running services */
mwexec('/usr/local/etc/rc.d/sqp_monitor.sh stop');
mwexec("/bin/ps awux | /usr/bin/egrep -i '[s]quid -f|\([s]quid\)' | /usr/bin/awk '{ print $2 }' | /usr/bin/xargs kill");
mwexec("/bin/ps awux | /usr/bin/grep '[d]iskd' | /usr/bin/awk '{ print $2 }' | /usr/bin/xargs kill");
mwexec("/bin/ps awux | /usr/bin/grep '[d]nsserver' | /usr/bin/awk '{ print $2 }' | /usr/bin/xargs kill");
mwexec("/bin/ps awux | /usr/bin/grep '[u]nlinkd' | /usr/bin/awk '{ print $2 }' | /usr/bin/xargs kill");
/* delete rc scripts */
unlink_if_exists('/usr/local/etc/rc.d/sqp_monitor.sh');
unlink_if_exists('/usr/local/etc/rc.d/squid.sh');
/* clean up created directories if 'Keep Settings/Data' is disabled */
if (is_array($config['installedpackages']['squidcache'])) {
$cachesettings = $config['installedpackages']['squidcache']['config'][0];
} else {
$cachesettings = array();
}
$cachedir = ($cachesettings['harddisk_cache_location'] ? $cachesettings['harddisk_cache_location'] : '/var/squid/cache');
if (is_array($config['installedpackages']['squid'])) {
$squidsettings = $config['installedpackages']['squid']['config'][0];
} else {
$squidsettings = array();
}
$logdir = ($squidsettings['log_dir'] ? $squidsettings['log_dir'] : '/var/squid/logs');
$keep = ($squidsettings['keep_squid_data'] ? true : false);
if (!$keep) {
if (is_dir("{$cachedir}")) {
if (substr($cachedir, 0, 11) === "/var/squid/") {
mwexec_bg("/bin/rm -rf {$cachedir}");
} else {
log_error("[squid] Will NOT delete Squid cache dir '{$cachedir}' since it is not located under /var/squid. Delete manually if required.");
}
}
if (is_dir("{$logdir}")) {
if (substr($logdir, 0, 11) === "/var/squid/") {
mwexec("/bin/rm -rf {$logdir}");
} else {
log_error("[squid] Will NOT delete Squid log dir '{$logdir}' since it is not located under /var/squid. Delete manually if required.");
}
}
$dirs = array("/var/run/squid", "/var/squid");
foreach ($dirs as $dir) {
if (is_dir("{$dir}")) {
mwexec("/bin/rm -rf {$dir}");
}
}
}
// remove antivirus integration features
squid_antivirus_deinstall_command();
filter_configure();
/* Remove package settings from config if 'Keep Settings/Data' is disabled */
if (!$keep) {
log_error("[squid] Removing all Squid settings since 'Keep Settings/Data' is disabled...");
if (is_array($config['installedpackages']['squid'])) {
unset($config['installedpackages']['squid']);
}
if (is_array($config['installedpackages']['squidantivirus'])) {
unset($config['installedpackages']['squidantivirus']);
}
if (is_array($config['installedpackages']['squidauth'])) {
unset($config['installedpackages']['squidauth']);
}
if (is_array($config['installedpackages']['squidcache'])) {
unset($config['installedpackages']['squidcache']);
}
if (is_array($config['installedpackages']['squidnac'])) {
unset($config['installedpackages']['squidnac']);
}
if (is_array($config['installedpackages']['squidreverse'])) {
unset($config['installedpackages']['squidreverse']);
}
if (is_array($config['installedpackages']['squidreversegeneral'])) {
unset($config['installedpackages']['squidreversegeneral']);
}
if (is_array($config['installedpackages']['squidreversepeer'])) {
unset($config['installedpackages']['squidreversepeer']);
}
if (is_array($config['installedpackages']['squidreverseredir'])) {
unset($config['installedpackages']['squidreverseredir']);
}
if (is_array($config['installedpackages']['squidreverseuri'])) {
unset($config['installedpackages']['squidreverseuri']);
}
if (is_array($config['installedpackages']['squidsync'])) {
unset($config['installedpackages']['squidsync']);
}
if (is_array($config['installedpackages']['squidtraffic'])) {
unset($config['installedpackages']['squidtraffic']);
}
if (is_array($config['installedpackages']['squidremote'])) {
unset($config['installedpackages']['squidremote']);
}
if (is_array($config['installedpackages']['squidusers'])) {
unset($config['installedpackages']['squidusers']);
}
}
}
/* Migrate configuration from god knows which Squid package versions */
/* None of these ever existed with Squid 3.4 package and this cruft should be most likely just removed */
function squid_upgrade_config() {
global $config, $pfs_version;
/* migrate existing csv config fields */
if (is_array($config['installedpackages']['squidauth']['config'])) {
$settingsauth = $config['installedpackages']['squidauth']['config'][0];
}
if (is_array($config['installedpackages']['squidcache']['config'])) {
$settingscache = $config['installedpackages']['squidcache']['config'][0];
}
if (is_array($config['installedpackages']['squidnac']['config'])) {
$settingsnac = $config['installedpackages']['squidnac']['config'][0];
}
if (is_array($config['installedpackages']['squid']['config'])) {
$settingsgen = $config['installedpackages']['squid']['config'][0];
}
/* migrate auth settings */
if (!empty($settingsauth['no_auth_hosts']) && strstr($settingsauth['no_auth_hosts'], ",")) {
$settingsauth['no_auth_hosts'] = base64_encode(implode("\n", explode(",", $settingsauth['no_auth_hosts'])));
$config['installedpackages']['squidauth']['config'][0]['no_auth_hosts'] = $settingsauth['no_auth_hosts'];
}
/* migrate cache settings */
if (!empty($settingscache['donotcache']) && strstr($settingscache['donotcache'], ",")) {
$settingscache['donotcache'] = base64_encode(implode("\n", explode(",", $settingscache['donotcache'])));
$config['installedpackages']['squidcache']['config'][0]['donotcache'] = $settingscache['donotcache'];
}
/* unset broken dynamic caching patterns removed since Squid3 package v0.4.3 */
if (!empty($config['installedpackages']['squidcache']['config']['refresh_patterns'])) {
unset($config['installedpackages']['squidcache']['config']['refresh_patterns']);
}
/* migrate nac settings */
if (!empty($settingsnac['allowed_subnets']) && strstr($settingsnac['allowed_subnets'], ",")) {
$settingsnac['allowed_subnets'] = base64_encode(implode("\n", explode(",", $settingsnac['allowed_subnets'])));
$config['installedpackages']['squidnac']['config'][0]['allowed_subnets'] = $settingsnac['allowed_subnets'];
}
if (!empty($settingsnac['banned_hosts']) && strstr($settingsnac['banned_hosts'], ",")) {
$settingsnac['banned_hosts'] = base64_encode(implode("\n", explode(",", $settingsnac['banned_hosts'])));
$config['installedpackages']['squidnac']['config'][0]['banned_hosts'] = $settingsnac['banned_hosts'];
}
if (!empty($settingsnac['banned_macs']) && strstr($settingsnac['banned_macs'], ",")) {
$settingsnac['banned_macs'] = base64_encode(implode("\n", explode(",", $settingsnac['banned_macs'])));
$config['installedpackages']['squidnac']['config'][0]['banned_macs'] = $settingsnac['banned_macs'];
}
if (!empty($settingsnac['unrestricted_hosts']) && strstr($settingsnac['unrestricted_hosts'], ",")) {
$settingsnac['unrestricted_hosts'] = base64_encode(implode("\n", explode(",", $settingsnac['unrestricted_hosts'])));
$config['installedpackages']['squidnac']['config'][0]['unrestricted_hosts'] = $settingsnac['unrestricted_hosts'];
}
if (!empty($settingsnac['unrestricted_macs']) && strstr($settingsnac['unrestricted_macs'], ",")) {
$settingsnac['unrestricted_macs'] = base64_encode(implode("\n", explode(",", $settingsnac['unrestricted_macs'])));
$config['installedpackages']['squidnac']['config'][0]['unrestricted_macs'] = $settingsnac['unrestricted_macs'];
}
if (!empty($settingsnac['whitelist']) && strstr($settingsnac['whitelist'], ",")) {
$settingsnac['whitelist'] = base64_encode(implode("\n", explode(",", $settingsnac['whitelist'])));
$config['installedpackages']['squidnac']['config'][0]['whitelist'] = $settingsnac['whitelist'];
}
if (!empty($settingsnac['blacklist']) && strstr($settingsnac['blacklist'], ",")) {
$settingsnac['blacklist'] = base64_encode(implode("\n", explode(",", $settingsnac['blacklist'])));
$config['installedpackages']['squidnac']['config'][0]['blacklist'] = $settingsnac['blacklist'];
}
if (!empty($settingsnac['block_user_agent']) && strstr($settingsnac['block_user_agent'], ",")) {
$settingsnac['block_user_agent'] = base64_encode(implode("\n", explode(",", $settingsnac['block_user_agent'])));
$config['installedpackages']['squidnac']['config'][0]['block_user_agent'] = $settingsnac['block_user_agent'];
}
if (!empty($settingsnac['block_reply_mime_type']) && strstr($settingsnac['block_reply_mime_type'], ",")) {
$settingsnac['block_reply_mime_type'] = base64_encode(implode("\n", explode(",", $settingsnac['block_reply_mime_type'])));
$config['installedpackages']['squidnac']['config'][0]['block_reply_mime_type'] = $settingsnac['block_reply_mime_type'];
}
/* XXX: broken Captive Portal patch (Bug #5594) */
if (isset($config['installedpackages']['squid']['config'][0]['patch_cp'])) {
if ($config['installedpackages']['squid']['config'][0]['patch_cp'] == "on") {
$cp_msg = "Patch Captive Portal feature was removed - see Bug #5594!";
/* Attempt to restore the backup, remove it after that and unset the config option to avoid running this again in future. */
$cp_file = '/etc/inc/captiveportal.inc';
$backup_file = '/root/' . $pfs_version . '.captiveportal.inc.backup';
if (file_exists($backup_file)) {
copy($backup_file, $cp_file);
$cp_msg .= "Found and restored a previous backup of {$cp_file}. Double-check its contents for sanity!";
unlink($backup_file);
} else {
$cp_msg .= "Failed to find a backup of {$cp_file}! Get a sane copy of the file from pfSense GitHub repository!";
}
file_notice("squid", $cp_msg, "Packages", "");
log_error("[squid] {$cp_msg}");
unset($cp_msg, $cp_file, $backup_file);
}
unset($config['installedpackages']['squid']['config'][0]['patch_cp']);
}
/* migrate reverse proxy settings */
squid_reverse_upgrade_config();
/* unset broken antivirus settings */
squid_antivirus_upgrade_config();
write_config();
}
/*
* Squid input validation
*/
/* Proxy Server: General Settings input validation */
function squid_validate_general($post, &$input_errors) {
global $config;
if (is_array($config['installedpackages']['squid'])) {
$settings = $config['installedpackages']['squid']['config'][0];
} else {
$settings = array();
}
// force users to configure cache
if (!is_array($config['installedpackages']['squidcache']['config'])) {
$input_errors[] = "Please, configure and save 'Local Cache' settings first.";
}
// force users to select at least one proxy or reverse proxy interface when enabling Squid
if ($post['enable_squid'] == "on") {
// if reverse proxy is configured, perhaps the user wants to use the reverse proxy features only
if (!squid_reverse_enabled()) {
if (empty($post['active_interface'])) {
$input_errors[] = "You must select at least one interface under 'Proxy Interface(s)' to enable Squid proxy.";
$input_errors[] = "If you intend to use Squid as reverse proxy ONLY, then visit Services: Squid Proxy Server: General, configure and save the reverse proxy settings first.";
}
} else {
log_error("[squid] Enabled as reverse proxy ONLY. If this is not what you intended, visit Services: Squid Proxy Server: General and configure proxy interfaces.");
}
}
$icp_port = trim($post['icp_port']);
if (!empty($icp_port) && !is_port($icp_port)) {
$input_errors[] = "You must enter a valid port number in the 'ICP port' field.";
}
unset($icp_port);
if (substr($post['log_dir'], -1, 1) == '/') {
$input_errors[] = 'Log location must not end with a / character.';
}
if ($post['log_dir']{0} != '/') {
$input_errors[] = 'Log location must start with a / character.';
}
if (strlen($post['log_dir']) <= 3) {
$input_errors[] = "Configured log location directory is not valid.";
}
$log_rotate = trim($post['log_rotate']);
if (!empty($log_rotate) && (!is_numericint($log_rotate) or ($log_rotate < 1))) {
$input_errors[] = "You must enter a valid number of days in the 'Log rotate' field.";
}
unset($log_rotate);
// check that the proxy port does not clash with WebGUI
$port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128);
$port = $post['proxy_port'] ? $post['proxy_port'] : $port;
$webgui_port = $config['system']['webgui']['port'];
if (($config['system']['webgui']['port'] == "") && ($config['system']['webgui']['protocol'] == "http")) {
$webgui_port = 80;
}
if (($config['system']['webgui']['port'] == "") && ($config['system']['webgui']['protocol'] == "https")) {
$webgui_port = 443;
}
if (($post['transparent_proxy'] != 'on') && ($port == $webgui_port)) {
$input_errors[] = "You can not run Squid on the same port as the pfSense WebGUI";
}
unset($port, $webgui_port);
if ($post['transparent_proxy'] == 'on') {
if (empty($post['transparent_active_interface'])) {
$input_errors[] = "You must select at least one interface under 'Transparent Proxy Interface(s)' when 'Transparent HTTP Proxy' is enabled.";
} else {
// allow transparent proxy only on interfaces where Squid is actually running to keep configuration sane
$a_ifaces = $post['active_interface'] ?: array();
$t_ifaces = $post['transparent_active_interface'];
foreach ($t_ifaces as $t_iface) {
if (!in_array($t_iface, $a_ifaces)) {
$err_iface = convert_friendly_interface_to_friendly_descr($t_iface);
$input_errors[] = "'Transparent Proxy Interface(s)' may only contain interfaces also selected in 'Proxy Interface(s)' above. '{$err_iface}' is not valid.";
unset($err_iface);
}
}
unset($a_ifaces, $t_iface, $t_ifaces);
}
}
if ($post['ssl_proxy'] == 'on') {
if ($post['dca'] == 'none') {
$input_errors[] = "SSL interception cannot be enabled without a CA.";
}
if (empty($post['ssl_active_interface'])) {
$input_errors[] = "You must select at least one interface under 'SSL Intercept Interface(s)' when 'HTTPS/SSL Interception' is enabled.";
} else {
// allow HTTPS/SSL Interception only on interfaces where Squid is actually running to keep configuration sane
$a_ifaces = $post['active_interface'] ?: array();
$s_ifaces = $post['ssl_active_interface'];
foreach ($s_ifaces as $s_iface) {
if (!in_array($s_iface, $a_ifaces)) {
$err_iface = convert_friendly_interface_to_friendly_descr($s_iface);
$input_errors[] = "'SSL Intercept Interface(s)' may only contain interfaces also selected in 'Proxy Interface(s)' above. '{$err_iface}' is not valid.";
unset($err_iface);
}
}
unset($a_ifaces, $s_ifaces, $s_iface);
}
}
foreach (array('defined_ip_proxy_off') as $hosts) {
foreach (explode(";", $post[$hosts]) as $host) {
$host = trim($host);
if (!empty($host) && !is_ipaddr($host) && !is_alias($host) && !is_hostname($host) && !is_subnet($host)) {
$input_errors[] = "'Bypass proxy for these source IPs' entry '$host' is not a valid IP address, hostname, or alias.";
}
}
}
unset($host, $hosts);
foreach (array('defined_ip_proxy_off_dest') as $hosts) {
foreach (explode(";", $post[$hosts]) as $host) {
$host = trim($host);
if (!empty($host) && !is_ipaddr($host) && !is_alias($host) && !is_hostname($host) && !is_subnet($host)) {
$input_errors[] = "'Bypass proxy for these destination IPs' entry '$host' is not a valid IP address, hostname, or alias.";
}
}
}
unset($host, $hosts);
if (!empty($post['dns_nameservers'])) {
$altdns = explode(";", ($post['dns_nameservers']));
foreach ($altdns as $dnssrv) {
if (!is_ipaddr($dnssrv)) {
$input_errors[] = "You must enter a valid IP address in the 'Alternate DNS servers' field.";
break;
}
}
}
unset($altdns, $dnssrv);
}
/* Proxy Server: Remote Proxy Settings input validation */
function squid_validate_upstream($post, &$input_errors) {
if ($post['enabled'] != 'on') {
return;
}
$addr = trim($post['proxyaddr']);
if (empty($addr)) {
$input_errors[] = "The 'Proxy hostname' field is required";
} else {
if (!is_ipaddr($addr) && !is_domain($addr)) {
$input_errors[] = "You must enter a valid IP address or host name in the 'Proxy hostname' field.";
}
}
foreach (array('proxyport' => 'TCP port', 'icpport' => 'ICP port') as $field => $name) {
$port = trim($post[$field]);
if (empty($port)) {
$input_errors[] = "The '$name' field is required.";
} else {
if (!is_port($port)) {
$input_errors[] = "The '$name' field must contain a valid port number (1-65535).";
}
}
}
unset($port);
}
/* Proxy Server: Cache Management input validation */
function squid_validate_cache($post, &$input_errors) {
/* Manually clear hard disk cache */
if ($post['clear_cache'] == 'Clear Disk Cache NOW') {
log_error("[squid] Clear disk cache forced via GUI. Clearing cache now...");
squid_dash_z("clean");
return;
}
$num_fields = array(
'harddisk_cache_size' => 'Hard disk cache size',
'memory_cache_size' => 'Memory cache size',
'maximum_object_size' => 'Maximum object size',
);
foreach ($num_fields as $field => $name) {
$value = trim($post[$field]);
if (!is_numericint($value)) {
$input_errors[] = "You must enter a valid value for '$field'.";
}
}
unset($num_fields);
$value = trim($post['minimum_object_size']);
if (!is_numericint($value)) {
$input_errors[] = "You must enter a valid value for 'Minimum object size'.";
}
unset($value);
if (!empty($post['cache_swap_low'])) {
$value = trim($post['cache_swap_low']);
if (!is_numericint($value) || ($value > 100)) {
$input_errors[] = "You must enter a valid value for 'Low-water-mark'.";
}
unset($value);
}
if (!empty($post['cache_swap_high'])) {
$value = trim($post['cache_swap_high']);
if (!is_numericint($value) || ($value > 100)) {
$input_errors[] = "You must enter a valid value for 'High-water-mark'.";
}
unset($value);
}
if ($post['donotcache'] != "") {
foreach (split("\n", $post['donotcache']) as $host) {
$host = trim($host);
if (!is_ipaddr($host) && !is_domain($host)) {
$input_errors[] = "The host '$host' is not a valid IP or hostname.";
}
}
unset($host);
}
if (substr($post['harddisk_cache_location'], -1, 1) == '/') {
$input_errors[] = 'Log location must not end with a / character.';
}
if ($post['harddisk_cache_location']{0} != '/') {
$input_errors[] = 'Log location must start with a / character.';
}
if (strlen($post['harddisk_cache_location']) <= 3) {
$input_errors[] = "Configured log location directory is not valid.";
}
}
/* Proxy Server: Access Control input validation */
function squid_validate_nac($post, &$input_errors) {
$allowed_subnets = explode("\n", $post['allowed_subnets']);
foreach ($allowed_subnets as $subnet) {
$subnet = trim($subnet);
if (!empty($subnet) && !is_subnet($subnet) && $subnet != "all") {
$input_errors[] = "'Allowed Subnets' must be a valid CIDR range or 'all'. The subnet '$subnet' is not valid.";
}
}
unset($allowed_subnets);
foreach (array('unrestricted_hosts', 'banned_hosts') as $hosts) {
if (preg_match_all("@([0-9.]+)(/[0-9.]+|)@", $_POST[$hosts], $matches)) {
for ($x = 0; $x < count($matches[1]); $x++) {
if ($matches[2][$x] == "") {
if (!is_ipaddr($matches[1][$x])) {
$input_errors[] = "'{$matches[1][$x]}' is not a valid IP address.";
}
} else {
if (!is_subnet($matches[0][$x])) {
$input_errors[] = "The subnet '{$matches[0][$x]}' is not a valid CIDR range.";
}
}
}
}
}
foreach (array('unrestricted_macs', 'banned_macs') as $macs) {
foreach (explode("\n", $post[$macs]) as $mac) {
$mac = trim($mac);
if (!empty($mac) && !is_macaddr($mac)) {
$input_errors[] = "'$mac' is not a valid MAC address.";
}
}
unset($mac);