diff options
Diffstat (limited to 'config')
182 files changed, 16959 insertions, 2677 deletions
diff --git a/config/apache_mod_security-dev/apache_balancer.template b/config/apache_mod_security-dev/apache_balancer.template index 361a5ed4..06422125 100644 --- a/config/apache_mod_security-dev/apache_balancer.template +++ b/config/apache_mod_security-dev/apache_balancer.template @@ -6,7 +6,7 @@ $balancer_config= <<<EOF # then edit /usr/local/pkg/apache_* files. # # # # And don't forget to submit your changes to: # -# https://github.com/bsdperimeter/pfsense-packages # +# https://github.com/pfsense/pfsense-packages # ################################################################################## SetOutputFilter DEFLATE SetInputFilter DEFLATE @@ -37,4 +37,4 @@ Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ EOF; -?>
\ No newline at end of file +?> diff --git a/config/apache_mod_security-dev/apache_mod_security.inc b/config/apache_mod_security-dev/apache_mod_security.inc index cdee4f6b..57f5407b 100644 --- a/config/apache_mod_security-dev/apache_mod_security.inc +++ b/config/apache_mod_security-dev/apache_mod_security.inc @@ -321,7 +321,7 @@ function generate_apache_configuration() { # then edit /usr/local/pkg/apache_* files. # # # # And don't forget to submit your changes to: # -# https://github.com/bsdperimeter/pfsense-packages # +# https://github.com/pfsense/pfsense-packages # ################################################################################## diff --git a/config/autoconfigbackup/parse_config_upload.php b/config/autoconfigbackup/parse_config_upload.php new file mode 100644 index 00000000..ce592966 --- /dev/null +++ b/config/autoconfigbackup/parse_config_upload.php @@ -0,0 +1,8 @@ +<?php + +if(file_exists("/usr/local/pkg/autoconfigbackup.inc")) { + require_once("/usr/local/pkg/autoconfigbackup.inc"); + upload_config(); +} + +?> diff --git a/config/avahi/avahi.xml b/config/avahi/avahi.xml index ef229af1..46f1293b 100644 --- a/config/avahi/avahi.xml +++ b/config/avahi/avahi.xml @@ -84,12 +84,12 @@ <additional_files_needed> <prefix>/root/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/avahi/binaries/avahi.tar.gz</item> + <item>http://files.pfsense.org/packages/avahi/avahi.tar.gz</item> </additional_files_needed> <additional_files_needed> <prefix>/root/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/avahi/binaries/avahi8.tar.gz</item> + <item>http://files.pfsense.org/packages/avahi/avahi8.tar.gz</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> diff --git a/config/bacula-client/bacula-client.inc b/config/bacula-client/bacula-client.inc index 156b3763..94411809 100644 --- a/config/bacula-client/bacula-client.inc +++ b/config/bacula-client/bacula-client.inc @@ -1,113 +1,120 @@ -<?php
-
-/* ========================================================================== */
-/*
- bacula-client.inc
- part of pfSense (http://www.pfSense.com)
- Copyright (C) 2012 Marcio Carlos Braga Antao
- Copyright (C) 2012 Marcello Coutinho
- All rights reserved.
-
- Based on m0n0wall (http://m0n0.ch/wall)
- Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
- 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("util.inc");
-
-function baculaclient_custom_php_install_command(){
- global $g, $config;
- baculaclient_custom_php_write_config();
-}
-
-function baculaclient_custom_php_deinstall_command(){
- global $g, $config;
-
- conf_mount_rw();
-
- // 1. Delete our config file
- unlink_if_exists("/usr/local/etc/bacula-fd.conf");
-
- // 2. Re-run sshd config generation script
- exec("/usr/local/etc/rc.d/bacula-fd.sh stop");
- conf_mount_ro();
-}
-
-function baculaclient_custom_php_write_config(){
- global $g, $config;
- conf_mount_rw();
- //check config_file
- $startup_file="/usr/local/etc/rc.d/bacula-fd";
- if (file_exists($startup_file)){
- $startup_script=file_get_contents($startup_file);
- $startup_script=preg_replace("/NO/","YES",$startup_script);
- file_put_contents("{$startup_file}.sh",$startup_script,LOCK_EX);
- // Ensure bacula-fd has a+rx
- exec("chmod a+rx {$startup_file}.sh");
- }
-
- //check config
- if (is_array($config['installedpackages']['baculaclient']['config'])){
- $baculaclient_conf="";
- foreach ($config['installedpackages']['baculaclient']['config'] as $bc) {
- // create Director
- switch ($bc['type']){
- case "Director":
- $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n";
- Break;
- case "Monitor":
- $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n";
- break;
- case "Local":
- $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n";
- $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n";
- $LocalDirector = $bc['director'];
- }
-
- }
-
- // create Messages
- $baculaclient_conf .= "Messages { \n\t Name = Standard \n\t director = {$LocalDirector}-dir = all, !skipped, !restored\n\t}\n";
- // create FielDaemon
-
- if (is_array($config['installedpackages']['baculaclientfd']['config'])){
- $port = $config['installedpackages']['baculaclientfd']['config'][0]['port'];
- $jobs = $config['installedpackages']['baculaclientfd']['config'][0]['jobs'];
- }
- else{
- $port="9102";
- $jobs="20";
- }
- $baculaclient_conf .= "FileDaemon { \n\t Name = {$LocalDirector}-fd #\n\t FDport = {$port}\n\t WorkingDirectory = /var/db/bacula\n\t Pid Directory = /var/run\n\tMaximum Concurrent Jobs = {$jobs}\n\t}\n";
- file_put_contents("/usr/local/etc/bacula-fd.conf",$baculaclient_conf,LOCK_EX);
- exec("/usr/local/etc/rc.d/bacula-fd.sh restart");
- // Mount Read-only
- conf_mount_ro();
- }
- }
-
+<?php + +/* ========================================================================== */ +/* + bacula-client.inc + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcio Carlos Braga Antao + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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("util.inc"); + + $pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('BACULA_LOCALBASE', '/usr/pbi/bacula-' . php_uname("m")); +else + define('BACULA_LOCALBASE','/usr/local'); + +function baculaclient_custom_php_install_command(){ + global $g, $config; + baculaclient_custom_php_write_config(); +} + +function baculaclient_custom_php_deinstall_command(){ + global $g, $config; + + conf_mount_rw(); + + // 1. Delete our config file + unlink_if_exists(BACULA_LOCALBASE."/etc/bacula-fd.conf"); + + // 2. Re-run sshd config generation script + exec("/usr/local/etc/rc.d/bacula-fd.sh stop"); + conf_mount_ro(); +} + +function baculaclient_custom_php_write_config(){ + global $g, $config; + conf_mount_rw(); + //check config_file + $startup_file="/usr/local/etc/rc.d/bacula-fd"; + if (file_exists($startup_file)){ + $startup_script=file_get_contents($startup_file); + $startup_script=preg_replace("/NO/","YES",$startup_script); + $startup_script=preg_replace("@/usr/local/etc/bacula-fd.conf@",BACULA_LOCALBASE."/etc/bacula-fd.conf",$startup_script); + file_put_contents("{$startup_file}.sh",$startup_script,LOCK_EX); + // Ensure bacula-fd has a+rx + exec("chmod a+rx {$startup_file}.sh"); + } + + //check config + if (is_array($config['installedpackages']['baculaclient']['config'])){ + $baculaclient_conf=""; + foreach ($config['installedpackages']['baculaclient']['config'] as $bc) { + // create Director + switch ($bc['type']){ + case "Director": + $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n"; + Break; + case "Monitor": + $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n"; + break; + case "Local": + $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n"; + $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n"; + $LocalDirector = $bc['director']; + } + + } + + // create Messages + $baculaclient_conf .= "Messages { \n\t Name = Standard \n\t director = {$LocalDirector}-dir = all, !skipped, !restored\n\t}\n"; + // create FielDaemon + + if (is_array($config['installedpackages']['baculaclientfd']['config'])){ + $port = $config['installedpackages']['baculaclientfd']['config'][0]['port']; + $jobs = $config['installedpackages']['baculaclientfd']['config'][0]['jobs']; + } + else{ + $port="9102"; + $jobs="20"; + } + $baculaclient_conf .= "FileDaemon { \n\t Name = {$LocalDirector}-fd #\n\t FDport = {$port}\n\t WorkingDirectory = /var/db/bacula\n\t Pid Directory = /var/run\n\tMaximum Concurrent Jobs = {$jobs}\n\t}\n"; + file_put_contents(BACULA_LOCALBASE."/etc/bacula-fd.conf",$baculaclient_conf,LOCK_EX); + exec("/usr/local/etc/rc.d/bacula-fd.sh restart"); + // Mount Read-only + conf_mount_ro(); + } + } + ?>
\ No newline at end of file diff --git a/config/bacula-client/bacula-client_view_config.php b/config/bacula-client/bacula-client_view_config.php index 7fa64cf4..021e1c15 100644 --- a/config/bacula-client/bacula-client_view_config.php +++ b/config/bacula-client/bacula-client_view_config.php @@ -34,6 +34,12 @@ $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); if(strstr($pfSversion, "1.2")) $one_two = true; + $pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('BACULA_LOCALBASE', '/usr/pbi/bacula-' . php_uname("m")); +else + define('BACULA_LOCALBASE','/usr/local'); + $pgtitle = "Bacula-Client: View Configuration"; include("head.inc"); @@ -68,7 +74,7 @@ include("head.inc"); <td class="tabcont" > <textarea id="varnishlogs" rows="50" cols="87%"> <?php - $config_file = file_get_contents("/usr/local/etc/bacula-fd.conf"); + $config_file = file_get_contents(BACULA_LOCALBASE."/etc/bacula-fd.conf"); echo $config_file; ?> </textarea> diff --git a/config/bandwidthd/bandwidthd.inc b/config/bandwidthd/bandwidthd.inc index 8821ac76..829cdf59 100644 --- a/config/bandwidthd/bandwidthd.inc +++ b/config/bandwidthd/bandwidthd.inc @@ -46,6 +46,8 @@ function bandwidthd_install_deinstall() { exec("rm -f /usr/local/etc/rc.d/bandwidthd*"); exec("rm -rf " . PKG_BANDWIDTHD_BASE . "/htdocs"); exec("rm -f /usr/local/www/bandwidthd"); + // Remove the cron job, if it is there + install_cron_job("/bin/kill -HUP `cat /var/run/bandwidthd.pid`", false); conf_mount_ro(); config_unlock(); } @@ -62,44 +64,47 @@ function bandwidthd_install_config() { config_lock(); /* user defined values */ - $meta_refresh = $config['installedpackages']['bandwidthd']['config'][0]['meta_refresh']; + $bandwidthd_config = $config['installedpackages']['bandwidthd']['config'][0]; + $meta_refresh = $bandwidthd_config['meta_refresh']; if($meta_refresh) $meta_refresh = "meta_refresh $meta_refresh\n"; - $graph = $config['installedpackages']['bandwidthd']['config'][0]['drawgraphs']; + $graph = $bandwidthd_config['drawgraphs']; if($graph) $graph = "graph true\n"; else $graph = "graph false\n"; - $filter_text = $config['installedpackages']['bandwidthd']['config'][0]['filter']; + $filter_text = $bandwidthd_config['filter']; if($filter_text) $filter_text = "filter $filter_text\n"; - $recover_cdf = $config['installedpackages']['bandwidthd']['config'][0]['recovercdf']; + $recover_cdf = $bandwidthd_config['recovercdf']; if($recover_cdf) $recover_cdf = "recover_cdf true\n"; - $output_cdf = $config['installedpackages']['bandwidthd']['config'][0]['outputcdf']; + $output_cdf = $bandwidthd_config['outputcdf']; if($output_cdf) - $output_cdf = "output_cdf true\n"; - $promiscuous = $config['installedpackages']['bandwidthd']['config'][0]['promiscuous']; + $output_cdf_string = "output_cdf true\n"; + else + $output_cdf_string = ""; + $promiscuous = $bandwidthd_config['promiscuous']; if($promiscuous) $promiscuous = "promiscuous true\n"; else $promiscuous = "promiscuous false\n"; - $graph_cutoff = $config['installedpackages']['bandwidthd']['config'][0]['graphcutoff']; + $graph_cutoff = $bandwidthd_config['graphcutoff']; if($graph_cutoff) $graph_cutoff = "graph_cutoff $graph_cutoff\n"; - $skip_intervals = $config['installedpackages']['bandwidthd']['config'][0]['skipintervals']; + $skip_intervals = $bandwidthd_config['skipintervals']; if($skip_intervals) $skip_intervals = "skip_intervals $skip_intervals\n"; - if($config['installedpackages']['bandwidthd']['config'][0]['active_interface']){ - $ifdescrs = array($config['installedpackages']['bandwidthd']['config'][0]['active_interface']); + if($bandwidthd_config['active_interface']){ + $ifdescrs = array($bandwidthd_config['active_interface']); } else { log_error("You should specify an interface for bandwidthd to listen on. Exiting."); } - $subnets_custom = explode(';',str_replace(' ','',$config['installedpackages']['bandwidthd']['config'][0]['subnets_custom'])); + $subnets_custom = explode(';',str_replace(' ','',$bandwidthd_config['subnets_custom'])); /* initialize to "" */ $subnets = ""; @@ -180,7 +185,7 @@ $graph_cutoff $promiscuous #Log data to cdf file htdocs/log.cdf -$output_cdf +$output_cdf_string #Read back the cdf file on startup $recover_cdf @@ -208,26 +213,40 @@ EOF; fwrite($fd, $config_file); fclose($fd); + if ($g['platform'] == 'nanobsd') { + $bandwidthd_nano_dir = "/var/bandwidthd"; + $bandwidthd_htdocs_dir = $bandwidthd_nano_dir . "/htdocs"; + if (!is_dir($bandwidthd_nano_dir)) { + if (file_exists($bandwidthd_nano_dir)) { + unlink($bandwidthd_nano_dir); + } + mkdir($bandwidthd_nano_dir); + } + } else { + $bandwidthd_htdocs_dir = $bandwidthd_base_dir . "/htdocs"; + } + $rc = array(); $rc['file'] = 'bandwidthd.sh'; $rc['stop'] = <<<EOD /usr/bin/killall bandwidthd EOD; - if ($g['platform'] == 'nanobsd') { - // On nanobsd, /var/bandwidthd is created. - // In that is a real /var/bandwidth/htdocs, where the graph data is written - // A soft link to the real bandwidth program is made - /var/bandwidthd/bandwidthd - // A soft link to the etc folder with the conf file is made - /var/bandwidthd/etc - // bandwidthd is started from /var/bandwidthd with the current dir /var/bandwidth - // This way, it: - // looks in ./etc for the conf file - // writes graph files in ./htdocs - // writes cdf log files (if selected in the config) to ./ - // All of this is on the /var filesystem, which is a read-write memory disk on nanobsd - $bandwidthd_nano_dir = "/var/bandwidthd"; - $bandwidthd_htdocs_dir = $bandwidthd_nano_dir . "/htdocs"; - $rc['start'] = <<<EOD + // If this is an old config before the enable checkbox was added, then enable by default + $bandwidthd_enable = (!isset($bandwidthd_config['enable']) || ($bandwidthd_config['enable'])); + if ($bandwidthd_enable) { + if ($g['platform'] == 'nanobsd') { + // On nanobsd, /var/bandwidthd is created. + // In that is a real /var/bandwidth/htdocs, where the graph data is written + // A soft link to the real bandwidth program is made - /var/bandwidthd/bandwidthd + // A soft link to the etc folder with the conf file is made - /var/bandwidthd/etc + // bandwidthd is started from /var/bandwidthd with the current dir /var/bandwidth + // This way, it: + // looks in ./etc for the conf file + // writes graph files in ./htdocs + // writes cdf log files (if selected in the config) to ./ + // All of this is on the /var filesystem, which is a read-write memory disk on nanobsd + $rc['start'] = <<<EOD if [ ! -d "{$bandwidthd_nano_dir}" ] ; then if [ -e "{$bandwidthd_nano_dir}" ] ; then /bin/rm -f {$bandwidthd_nano_dir} @@ -252,22 +271,25 @@ if [ ! -L "{$bandwidthd_nano_dir}/etc" ] ; then fi /bin/ln -s {$bandwidthd_config_dir} {$bandwidthd_nano_dir}/etc fi - +if [ ! -f "{$bandwidthd_htdocs_dir}/legend.gif" ] ; then + /bin/cp {$bandwidthd_base_dir}/htdocs/legend.gif {$bandwidthd_htdocs_dir} +fi +if [ ! -f "{$bandwidthd_htdocs_dir}/logo.gif" ] ; then + /bin/cp {$bandwidthd_base_dir}/htdocs/logo.gif {$bandwidthd_htdocs_dir} +fi cd {$bandwidthd_nano_dir} {$bandwidthd_nano_dir}/bandwidthd cd - EOD; - if (!is_dir($bandwidthd_nano_dir)) { - if (file_exists($bandwidthd_nano_dir)) { - unlink($bandwidthd_nano_dir); - } - mkdir($bandwidthd_nano_dir); - } - } else { - $bandwidthd_htdocs_dir = $bandwidthd_base_dir . "/htdocs"; - $rc['start'] = <<<EOD + } else { + $rc['start'] = <<<EOD /usr/local/bandwidthd/bandwidthd EOD; + } + } else { + // bandwidthd is disabled, so do not put any real start commands in the script. + // This effectively disables it but keeps all the files in place (e.g. saved logs) ready to reload when it is enabled. + $rc['start'] = "return"; } /* write out rc.d start/stop file */ @@ -292,10 +314,22 @@ EOD; if (!file_exists($bandwidthd_index_file)) { exec("echo \"Please start bandwidthd to populate this directory.\" > " . $bandwidthd_index_file); } + + if (($bandwidthd_enable) && ($output_cdf)) { + // Use cron job to rotate logs every day at 00:01 + install_cron_job("/bin/kill -HUP `cat /var/run/bandwidthd.pid`", true, "1", "0"); + } + else + { + // Remove the cron job, if it is there + install_cron_job("/bin/kill -HUP `cat /var/run/bandwidthd.pid`", false); + } conf_mount_ro(); config_unlock(); stop_service("bandwidthd"); - start_service("bandwidthd"); + if ($bandwidthd_enable) { + start_service("bandwidthd"); + } } ?> diff --git a/config/bandwidthd/bandwidthd.xml b/config/bandwidthd/bandwidthd.xml index f82ac69d..f306546a 100644 --- a/config/bandwidthd/bandwidthd.xml +++ b/config/bandwidthd/bandwidthd.xml @@ -7,7 +7,7 @@ /* $Id$ */ /* ========================================================================== */ /* - authng.xml + bandwidthd.xml part of pfSense (http://www.pfSense.com) Copyright (C) 2007 to whom it may belong All rights reserved. @@ -41,10 +41,10 @@ */ /* ========================================================================== */ ]]> - </copyright> - <description>Describe your package here</description> - <requirements>Describe your package requirements here</requirements> - <faq>Currently there are no FAQ items provided.</faq> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> <name>bandwidthd</name> <version>2.0.1.4</version> <title>Bandwidthd</title> @@ -60,7 +60,7 @@ <name>bandwidthd</name> <rcfile>bandwidthd.sh</rcfile> <executable>bandwidthd</executable> - </service> + </service> <tabs> <tab> <text>BandwidthD</text> @@ -80,6 +80,12 @@ </additional_files_needed> <fields> <field> + <fielddescr>Enable bandwidthd</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + <description></description> + </field> + <field> <fielddescr>Interface</fielddescr> <fieldname>active_interface</fieldname> <description>The interface that bandwidthd will bind to.</description> @@ -96,7 +102,7 @@ <field> <fielddescr>Skip intervals</fielddescr> <fieldname>skipintervals</fieldname> - <description>Number of intervals (2.5 minute) to skip between graphing. Default 0.</description> + <description>Number of intervals to skip between graphing. Default 0. Each interval is 200 seconds = 3 min 20 sec.</description> <type>input</type> </field> <field> @@ -108,19 +114,20 @@ <field> <fielddescr>Promiscuous</fielddescr> <fieldname>promiscuous</fieldname> - <description>Put interface in promiscuous mode to score to traffic that may not be routing through the host machine.</description> + <description>Put interface in promiscuous mode to see traffic that may not be routing through the host machine.<br> + Note: If the interface is connected to a switch then the interface will only see the traffic on its port.</description> <type>checkbox</type> </field> <field> <fielddescr>output_cdf</fielddescr> <fieldname>outputcdf</fieldname> - <description>Log data to cdf file htdocs/log.cdf</description> + <description>Log data to cdf files log*.cdf</description> <type>checkbox</type> </field> <field> <fielddescr>recover_cdf</fielddescr> <fieldname>recovercdf</fieldname> - <description>Read back the cdf file on startup</description> + <description>Read back the cdf files on startup</description> <type>checkbox</type> </field> <field> @@ -139,9 +146,24 @@ <field> <fielddescr>Meta Refresh</fielddescr> <fieldname>meta_refresh</fieldname> - <description>Set META REFRESH seconds (default 150, use 0 to disable).</description> + <description>Sets the interval (seconds) at which the browser graph display refreshes (default 150, use 0 to disable).</description> <type>input</type> </field> + <field> + <fielddescr>Graph and Log Info</fielddescr> + <fieldname>graph_log_info</fieldname> + <description>If draw graphs is on, then the daily report and graph html data is regenerated every (skip intervals + 1) * 200 seconds. The data volumes in the report are for the same period as the span of the graph.<br> + If output_cdf is on, then a cron job is added to rotate the log files at 00:01 each day. 6 log files are kept for each log frequency (daily, weekly, monthly, yearly). At the respective rotation intervals, the oldest log is deleted, the others are shuffled back and a new log is created.<br> + <table cellpadding=1 cellspacing=0 style="text-align: left;"> <tbody> + <tr><th> </th><th> Data Interval </th><th> Graph Span </th><th> Log Rotation </th><th> Log File Name </th></tr> + <tr><th> Daily </th><td> 200 seconds </td><td> 2 days </td><td> 1 day </td><td> log.1.[0-5].cdf </td></tr> + <tr><th> Weekly </th><td> 10 minutes </td><td> 7 days </td><td> 7 days </td><td> log.2.[0-5].cdf </td></tr> + <tr><th> Monthly </th><td> 1 hour </td><td> 35 days </td><td> 35 days </td><td> log.3.[0-5].cdf </td></tr> + <tr><th> Yearly </th><td> 12 hours </td><td> 412.5 days </td><td> 412.5 days </td><td> log.4.[0-5].cdf </td></tr> + </tbody> </table> + </description> + <type>info</type> + </field> </fields> <custom_php_resync_config_command> bandwidthd_install_config(); diff --git a/config/checkmk-agent/checkmk.inc b/config/checkmk-agent/checkmk.inc new file mode 100644 index 00000000..056a39eb --- /dev/null +++ b/config/checkmk-agent/checkmk.inc @@ -0,0 +1,302 @@ +<?php +/* ========================================================================== */ +/* + checkmk.inc + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Marcello Coutinho + 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. + */ +/* ========================================================================== */ + +define('ETC_SERVICES','/etc/services'); +define('ETC_INETD','/etc/inetd.conf'); +define('ETC_HOSTS_ALLOW','/etc/hosts.allow'); +define('ETC_RC_CONF','/etc/rc.conf.local'); + +function checkmk_install() { + // Download latest check_mk version from head repo + $checkmk_bin="/usr/local/bin/check_mk_agent"; + mwexec("fetch -o {$checkmk_bin} 'http://git.mathias-kettner.de/git/?p=check_mk.git;a=blob_plain;f=agents/check_mk_agent.freebsd;hb=HEAD'"); + chmod($checkmk_bin,0755); + sync_package_checkmk(); +} + +function checkmk_deinstall() { + // reserved +} + +function checkmk_start() { + global $g, $config; + + // reserved +} + +function checkmk_text_area_decode($text){ + return preg_replace('/\r\n/', "\n",base64_decode($text)); +} +function sync_package_checkmk() { + global $config, $g; + $update_conf=0; + + if (!is_array($config['installedpackages']['checkmk']['config'])) + return; + + $mk_config=$config['installedpackages']['checkmk']['config'][0]; + + $checkmk_bin="/usr/local/bin/check_mk_agent"; + if (!file_exists($checkmk_bin) && $mk_config['checkmkenable']=="on"){ + $error = "Check_mk-agent Binary file not found"; + log_error($error." You can manually download it using this cmd: fetch -o {$checkmk_bin} 'http://git.mathias-kettner.de/git/?p=check_mk.git;a=blob_plain;f=agents/check_mk_agent.freebsd;hb=HEAD'"); + file_notice("Check_mk-agent", $error, "checkmk save config", ""); + return; + } + //mount filesystem writeable + conf_mount_rw(); + + + // check services file + $mk_services= file(ETC_SERVICES); + $port=($mk_config['checkmkport'] ? $mk_config['checkmkport'] : "6556"); + foreach($mk_services as $mk_service){ + if (!preg_match("/check_mk/",$mk_service)) + $mk_service_file.=chop($mk_service)."\n"; + } + if ($mk_config['checkmkenable']=="on") + $mk_service_file.="check_mk {$port}/tcp #check_mk agent\n"; + file_put_contents(ETC_SERVICES,$mk_service_file,LOCK_EX); + + // check inetd file + $mk_inetds= file(ETC_INETD); + foreach($mk_inetds as $mk_inetd){ + if (!preg_match("/check_mk/",$mk_inetd)) + $mk_inetd_file.=chop($mk_inetd)."\n"; + } + if ($mk_config['checkmkenable']=="on") + $mk_inetd_file.="check_mk stream tcp nowait root /usr/local/bin/check_mk_agent check_mk\n"; + file_put_contents(ETC_INETD,$mk_inetd_file,LOCK_EX); + + // check hosts.allow + $mk_hosts= file(ETC_HOSTS_ALLOW); + $inet_daemons_count=0; + foreach($mk_hosts as $mk_host){ + if (!preg_match("/check_mk/",$mk_host)) + $mk_hosts_file.=chop($mk_host)."\n"; + if (preg_match("/^\w+/")) + $inet_daemons_count++; + } + if ($mk_config['checkmkenable']=="on") + foreach (explode(',',$mk_config['checkmkhosts']) as $check_mk_host){ + $mk_hosts_file.="check_mk : {$check_mk_host} : allow\n"; + $inet_daemons_count++; + } + file_put_contents(ETC_HOSTS_ALLOW,$mk_hosts_file,LOCK_EX); + + //check inetd daemon rc_conf option + $mk_rc_confs= file(ETC_RC_CONF); + foreach($mk_rc_confs as $mk_rc_conf){ + if (!preg_match("/inetd_/",$mk_rc_conf)) + $mk_rc_conf_file.=chop($mk_rc_conf)."\n"; + } + if ($mk_config['checkmkenable']=="on"){ + $mk_rc_conf_file.='inetd_enable="YES"'."\n"; + $mk_rc_conf_file.='inetd_flags="-wW"'."\n"; + } + + file_put_contents(ETC_RC_CONF,$mk_rc_conf_file,LOCK_EX); + if ($inet_daemons_count > 0) + mwexec("/etc/rc.d/inetd restart"); + else + mwexec("/etc/rc.d/inetd stop"); + + //Write config if any file from filesystem was loaded + if ($update_conf > 0) + write_config(); + + // mount filesystem readonly + conf_mount_ro(); + + checkmk_sync_on_changes(); +} + +function checkmk_validate_input($post, &$input_errors) { + foreach ($post as $key => $value) { + if (empty($value)) + continue; + if (substr($key, 0, 3) == "port" && !preg_match("/^\d+$/", $value)) + $input_errors[] = "{$value} is no a valid port number"; + if (substr($key, 0, 11) == "description" && !preg_match("@^[a-zA-Z0-9 _/.-]+$@", $value)) + $input_errors[] = "Do not use special characters on description"; + if (substr($key, 0, 8) == "fullfile" && !preg_match("@^[a-zA-Z0-9_/.-]+$@", $value)) + $input_errors[] = "Do not use special characters on filename"; + + } +} +############################################## +/* Uses XMLRPC to synchronize the changes to a remote node */ +function checkmk_sync_on_changes() { + global $config, $g; + if (is_array($config['installedpackages']['checkmksync']['config'])){ + $checkmk_sync=$config['installedpackages']['checkmksync']['config'][0]; + $synconchanges = $checkmk_sync['synconchanges']; + $synctimeout = $checkmk_sync['synctimeout']; + switch ($synconchanges){ + case "manual": + if (is_array($checkmk_sync[row])){ + $rs=$checkmksync[row]; + } + else{ + log_error("[Check_mk-agent] xmlrpc sync is enabled but there is no hosts to push on squid config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + } + else{ + log_error("[Check_mk-agent] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[Check_mk-agent] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($password && $sync_to_ip) + checkmk_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout); + } + log_error("[Check_mk-agent] xmlrpc sync is ending."); + } + } +} +############################################## +/* Do the actual XMLRPC sync */ +function checkmk_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout) { + global $config, $g; + + if(!$username) + return; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['checkmk'] = $config['installedpackages']['checkmk']; + + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("[Check_mk-agent] Beginning checkmk XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after 250 seconds */ + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "[Check_mk-agent] A communications error occurred while attempting checkmk XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "checkmk Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, $synctimeout); + $error = "[Check_mk-agent] An error code was received while attempting checkmk XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "checkmk Settings Sync", ""); + } else { + log_error("[Check_mk-agent] XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell checkmk to reload our settings on the destionation sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/checkmk.inc');\n"; + $execcmd .= "sync_package_checkmk();"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("[Check_mk-agent] XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "[Check_mk-agent] A communications error occurred while attempting checkmk XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "checkmk Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, $synctimeout); + $error = "[Check_mk-agent] An error code was received while attempting checkmk XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "checkmk Settings Sync", ""); + } else { + log_error("[Check_mk-agent] XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } + +} + +?> diff --git a/config/checkmk-agent/checkmk.xml b/config/checkmk-agent/checkmk.xml new file mode 100644 index 00000000..6f458a1d --- /dev/null +++ b/config/checkmk-agent/checkmk.xml @@ -0,0 +1,121 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* ========================================================================== */ +/* + checkmk.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Marcello Coutinho + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>checkmk</name> + <version>0.5</version> + <title>Check_mk Agent</title> + <include_file>/usr/local/pkg/checkmk.inc</include_file> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/checkmk-agent/checkmk.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/checkmk-agent/checkmk_sync.xml</item> + </additional_files_needed> + <menu> + <name>Check_mk Agent</name> + <tooltiptext>checkmk</tooltiptext> + <section>Diagnostics</section> + <url>/pkg_edit.php?xml=checkmk.xml</url> + </menu> + <tabs> + <tab> + <text>Config</text> + <url>/pkg_edit.php?xml=checkmk.xml</url> + <active/> + </tab> + <tab> + <text>XMLRPC Sync</text> + <url>/pkg_edit.php?xml=checkmk_sync.xml</url> + </tab> + </tabs> + + <fields> + <field> + <type>listtopic</type> + <fieldname>temp</fieldname> + <name>Check_mk agent configuration</name> + </field> + <field> + <fielddescr>Enable check_mk Agent</fielddescr> + <fieldname>checkmkenable</fieldname> + <type>checkbox</type> + <size>60</size> + <description><![CDATA[Enable check_mk Agent on this server. This will check all config options to run check_mk binary on your system.<br> + <strong>Reference:</strong><br>https://github.com/sileht/check_mk/tree/master/doc<br><br> + <strong>Latest check_mk version:</strong> fetch -o /usr/local/bin/check_mk_agent 'http://git.mathias-kettner.de/git/?p=check_mk.git;a=blob_plain;f=agents/check_mk_agent.freebsd;hb=HEAD']]></description> + <required/> + </field> + <field> + <fielddescr>Listen Port</fielddescr> + <fieldname>checkmkport</fieldname> + <type>input</type> + <size>10</size> + <description>Enter port to listen on. Leave empty to use Default prot 6556</description> + <required/> + </field> + <field> + <fielddescr>Hosts.allow</fielddescr> + <fieldname>checkmkhosts</fieldname> + <description>Enter hosts(comma separeted) that can communicate with this agent.</description> + <type>input</type> + <size>60</size> + </field> + </fields> + <custom_php_install_command> + checkmk_install(); + </custom_php_install_command> + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_validation_command> + checkmk_validate_input($_POST, &$input_errors); + </custom_php_validation_command> + <custom_delete_php_command> + sync_package_checkmk(); + </custom_delete_php_command> + <custom_php_resync_config_command> + sync_package_checkmk(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/checkmk-agent/checkmk_sync.xml b/config/checkmk-agent/checkmk_sync.xml new file mode 100644 index 00000000..6603991d --- /dev/null +++ b/config/checkmk-agent/checkmk_sync.xml @@ -0,0 +1,129 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* ========================================================================== */ +/* + checkmk_sync.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Marcello Coutinho + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>checkmksync</name> + <version>1.1</version> + <title>Check_mk Agent: Sync</title> + <include_file>/usr/local/pkg/checkmk.inc</include_file> + <tabs> + <tab> + <text>Config</text> + <url>/pkg_edit.php?xml=checkmk.xml</url> + </tab> + <tab> + <text>XMLRPC Sync</text> + <url>/pkg_edit.php?xml=checkmk_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <type>listtopic</type> + <fieldname>temp</fieldname> + <name>Enable checkmk configuration sync</name> + </field> + <field> + <fielddescr>Sync Option</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Automatically sync check_mk configuration changes.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> + </field> + <field> + <fielddescr>Remote Servers</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + <required/> + </rowhelperfield> + <rowhelperfield> + <fielddescr>User Name</fielddescr> + <fieldname>username</fieldname> + <description>user name of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + <required/> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_resync_config_command> + checkmk_sync_on_changes(); + </custom_php_resync_config_command> + <custom_php_command_before_form> + unset($_POST['temp']); + </custom_php_command_before_form> +</packagegui>
\ No newline at end of file diff --git a/config/dansguardian/dansguardian.inc b/config/dansguardian/dansguardian.inc index 8177fe3f..39282409 100755 --- a/config/dansguardian/dansguardian.inc +++ b/config/dansguardian/dansguardian.inc @@ -90,7 +90,7 @@ function check_ca_hashes(){ } } -function sync_package_dansguardian($via_rpc=false,$install_process=false) { +function sync_package_dansguardian($via_rpc="no",$install_process=false) { global $config,$g; # detect boot process @@ -101,8 +101,13 @@ function sync_package_dansguardian($via_rpc=false,$install_process=false) { $boot_process="on"; } - if (is_process_running('dansguardian') && isset($boot_process) && $via_rpc==false) + if (is_process_running('dansguardian') && isset($boot_process) && $via_rpc=="no"){ + log_error("[Dansguardian] - Detected boot process pr:".is_process_running('dansguardian')." bp:".isset($boot_process)." rpc:".$via_rpc); return; + } + else{ + log_error("[Dansguardian] - Save settings package call pr:".is_process_running('dansguardian')." bp:".isset($boot_process)." rpc:".$via_rpc); + } #assign xml arrays if (!is_array($config['installedpackages']['dansguardian'])) @@ -718,6 +723,7 @@ function sync_package_dansguardian($via_rpc=false,$install_process=false) { 'urlacl'=> "Default", 'group_options' => "scancleancache,infectionbypasserrorsonly", 'reportinglevel'=>'3', + 'group_name_source'=>'name', 'mode'=> "1", 'report_level'=>"global"); @@ -921,7 +927,8 @@ EOF; #check blacklist download files if ($install_process == true){ require_once("/usr/local/www/dansguardian.php"); - fetch_blacklist(false); + fetch_blacklist(false,true); + update_output_window("Blacklist check done, continuing package config sync."); } else{ if ($dansguardian_blacklist['cron']=="force_download"){ @@ -956,7 +963,6 @@ EOF; $daemongroup = 'nobody'; } $filtergroups=($count > 1?($count -1):1); - $filterip=""; $filterports=""; foreach (explode(",", $dansguardian['interface']) as $i => $iface) { @@ -974,7 +980,7 @@ EOF; $cron_found=0; if (is_array($config['cron']['item'])) foreach($config['cron']['item'] as $cron) - if (preg_match("@".DANSGUARDIAN_DIR."/(bin.freshclam|www/dansguardian)@",$cron["command"])) + if (preg_match("@(".DANSGUARDIAN_DIR."|/usr/local)/(bin.freshclam|www/dansguardian)@",$cron["command"])) $cron_found++; else $new_cron['item'][]=$cron; @@ -1057,6 +1063,7 @@ EOF; $cron_cmd="/usr/local/bin/php /usr/local/www/dansguardian_ldap.php"; if (is_array($config['installedpackages']['dansguardiangroups']['config'])) foreach ($config['installedpackages']['dansguardiangroups']['config'] as $dansguardian_groups){ + $dans_group_source=($dansguardian_groups['groupnamesource'] !="" ? $dansguardian_groups['groupnamesource'] : "name"); if(preg_match('/(\d+)m/',$dansguardian_groups['freq'],$matches)){ $new_cron['item'][]=array( "minute" => "*/".$matches[1], "hour" => "*", @@ -1064,7 +1071,7 @@ EOF; "month" => "*", "wday" => "*", "who" => "root", - "command"=> $cron_cmd." ".$dansguardian_groups['name']); + "command"=> "{$cron_cmd} $dans_group_source '{$dansguardian_groups[$dans_group_source]}'"); $config['cron']=$new_cron; $cron_found++; } @@ -1075,7 +1082,7 @@ EOF; "month" => "*", "wday" => "*", "who" => "root", - "command"=> $cron_cmd." ".$dansguardian_groups['name']); + "command"=> "{$cron_cmd} $dans_group_source '{$dansguardian_groups[$dans_group_source]}'"); $config['cron']=$new_cron; $cron_found++; } @@ -1084,7 +1091,6 @@ EOF; conf_mount_rw(); write_config(); - #update cron if ($cron_found > 0){ $config['cron']=$new_cron; @@ -1108,19 +1114,15 @@ EOF; #check virus_scanner options $libexec_dir= DANSGUARDIAN_DIR."/libexec/dansguardian/"; - if (preg_match("/clamd/",$dansguardian_config['content_scanners'])){ + if ($install_process==true) + update_output_window("Skipping clamav check during package install."); + if (preg_match("/clamd/",$dansguardian_config['content_scanners']) && $install_process==false){ if (!(file_exists('/var/db/clamav/main.cvd')||file_exists('/var/db/clamav/main.cld'))){ file_notice("Dansguardian - No antivirus database found for clamav, running freshclam in background.",""); log_error('No antivirus database found for clamav, running freshclam in background. Content-scanner may not work until freshclam finishes.'); mwexec_bg(DANSGUARDIAN_DIR.'/bin/freshclam && /usr/local/etc/rc.d/clamav-clamd'); } - - $match=array(); - $match[0]='/NO/'; - $replace=array(); - $replace[0]='YES'; - #clamdscan.conf dansguardian file $cconf=DANSGUARDIAN_DIR . "/etc/dansguardian/contentscanners/clamdscan.conf"; $cconf_file=file_get_contents($cconf); @@ -1128,7 +1130,6 @@ EOF; $cconf_file=preg_replace('/#clamdudsfile/','clamdudsfile',$cconf_file); file_put_contents($cconf, $cconf_file, LOCK_EX); } - #clamd conf file $cconf=DANSGUARDIAN_DIR."/etc/clamd.conf"; $cconf_file=file_get_contents($cconf); @@ -1136,6 +1137,11 @@ EOF; #clamd script file $script='/usr/local/etc/rc.d/clamav-clamd'; $script_file=file($script); + $new_clamav_startup=""; + $cpreg_m[0]="@NO@"; + $cpreg_m[1]="@/usr/local@"; + $cpreg_r[0]="YES"; + $cpreg_r[1]=DANSGUARDIAN_DIR; foreach ($script_file as $script_line){ if(preg_match("/command=/",$script_line)){ $new_clamav_startup.= 'if [ ! -d /var/run/clamav ];then /bin/mkdir /var/run/clamav;fi'."\n"; @@ -1147,12 +1153,12 @@ EOF; $new_clamav_startup.=$script_line; } elseif(!preg_match("/(mkdir|chown|sleep|mailscanner)/",$script_line)) { - $new_clamav_startup.=preg_replace("/NO/","YES",$script_line); - $new_clamav_startup.=preg_replace("@/usr/local@",DANSGUARDIAN_DIR,$script_line); + $new_clamav_startup.=preg_replace($cpreg_m,$cpreg_r,$script_line); } } file_put_contents($script, $new_clamav_startup, LOCK_EX); chmod ($script,0755); + if (file_exists('/var/run/dansguardian.pid') && is_process_running('clamd')){ log_error('Stopping clamav-clamd'); mwexec("$script stop"); @@ -1164,8 +1170,7 @@ EOF; mwexec_bg("$script start"); } } - } - + } #check certificate hashed $script='/usr/local/etc/rc.d/dansguardian.sh'; @@ -1200,23 +1205,58 @@ EOF; #mount read only conf_mount_ro(); + #avoid sync during boot process - if (!isset($boot_process)){ - $synconchanges = $config['installedpackages']['dansguardiansync']['config'][0]['synconchanges']; - if(!$synconchanges && !$syncondbchanges) - return; - log_error("[dansguardian] dansguardian_xmlrpc_sync.php is starting."); - foreach ($config['installedpackages']['dansguardiansync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ + if (!isset($boot_process) || $via_rpc=="yes"){ + /* Uses XMLRPC to synchronize the changes to a remote node */ + if (is_array($config['installedpackages']['dansguardiansync']['config'])){ + $dans_sync=$config['installedpackages']['dansguardiansync']['config'][0]; + $synconchanges = $dans_sync['synconchanges']; + $synctimeout = $dans_sync['synctimeout']; + switch ($synconchanges){ + case "manual": + if (is_array($dans_sync[row])){ + $rs=$dans_sync[row]; + } + else{ + log_error("[Dansguardian] xmlrpc sync is enabled but there is no hosts to push on dansguardian config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + if (! is_ipaddr($system_carp['synchronizetoip'])){ + log_error("[Dansguardian] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + } + else{ + log_error("[Dansguardian] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[Dansguardian] xmlrpc sync is starting."); + foreach($rs as $sh){ $sync_to_ip = $sh['ipaddress']; - $password = $sh['password']; - $sync_type = $sh['sync_type']; + $password = $sh['password']; + $username = ($sh['username']?$sh['username']:"admin"); if($password && $sync_to_ip) - dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type); + dansguardian_do_xmlrpc_sync($sync_to_ip,$username,$password,$sync_type,$synctimeout); } + log_error("[Dansguardian] xmlrpc sync is ending."); } - log_error("[dansguardian] dansguardian_xmlrpc_sync.php is ending."); - } + } + } + } function dansguardian_validate_input($post, &$input_errors) { @@ -1242,7 +1282,7 @@ function dansguardian_validate_input($post, &$input_errors) { } function dansguardian_php_install_command() { - sync_package_dansguardian(false,true); + sync_package_dansguardian("no",true); } function dansguardian_php_deinstall_command() { @@ -1260,15 +1300,21 @@ function dansguardian_php_deinstall_command() { } } -function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { +function dansguardian_do_xmlrpc_sync($sync_to_ip,$username,$password,$sync_type,$synctimeout) { global $config, $g; + if(!$username) + return; + if(!$password) return; if(!$sync_to_ip) return; + if(!$synctimeout) + $synctimeout=30; + $xmlrpc_sync_neighbor = $sync_to_ip; if($config['system']['webgui']['protocol'] != "") { $synchronizetoip = $config['system']['webgui']['protocol']; @@ -1286,28 +1332,26 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { /* xml will hold the sections to sync */ $xml = array(); - $sync_xml=$config['installedpackages']['dansguardiansync']['config'][0]['synconchanges']; - if ($sync_xml){ - log_error("Include dansguardian config"); - $xml['dansguardian'] = $config['installedpackages']['dansguardian']; - $xml['dansguardianantivirusacl'] = $config['installedpackages']['dansguardianantivirusacl']; - $xml['dansguardianconfig'] = $config['installedpackages']['dansguardianconfig']; - $xml['dansguardianblacklist'] = $config['installedpackages']['dansguardianblacklist']; - $xml['dansguardianldap'] = $config['installedpackages']['dansguardianldap']; - $xml['dansguardiancontentacl'] = $config['installedpackages']['dansguardiancontentacl']; - $xml['dansguardianfileacl'] = $config['installedpackages']['dansguardianfileacl']; - $xml['dansguardiangroups'] = $config['installedpackages']['dansguardiangroups']; - $xml['dansguardianheaderacl'] = $config['installedpackages']['dansguardianheaderacl']; - $xml['dansguardianlimits'] = $config['installedpackages']['dansguardianlimits']; - $xml['dansguardianlog'] = $config['installedpackages']['dansguardianlog']; - $xml['dansguardianphraseacl'] = $config['installedpackages']['dansguardianphraseacl']; - $xml['dansguardianpicsacl'] = $config['installedpackages']['dansguardianpicsacl']; - $xml['dansguardiansearchacl'] = $config['installedpackages']['dansguardiansearchacl']; - $xml['dansguardiansiteacl'] = $config['installedpackages']['dansguardiansiteacl']; - $xml['dansguardianurlacl'] = $config['installedpackages']['dansguardianurlacl']; - $xml['dansguardianusers'] = $config['installedpackages']['dansguardianusers']; + log_error("Include dansguardian config"); + $xml['dansguardian'] = $config['installedpackages']['dansguardian']; + $xml['dansguardianantivirusacl'] = $config['installedpackages']['dansguardianantivirusacl']; + $xml['dansguardianconfig'] = $config['installedpackages']['dansguardianconfig']; + $xml['dansguardianblacklist'] = $config['installedpackages']['dansguardianblacklist']; + $xml['dansguardianldap'] = $config['installedpackages']['dansguardianldap']; + $xml['dansguardiancontentacl'] = $config['installedpackages']['dansguardiancontentacl']; + $xml['dansguardianfileacl'] = $config['installedpackages']['dansguardianfileacl']; + $xml['dansguardiangroups'] = $config['installedpackages']['dansguardiangroups']; + $xml['dansguardianheaderacl'] = $config['installedpackages']['dansguardianheaderacl']; + $xml['dansguardianlimits'] = $config['installedpackages']['dansguardianlimits']; + $xml['dansguardianlog'] = $config['installedpackages']['dansguardianlog']; + $xml['dansguardianphraseacl'] = $config['installedpackages']['dansguardianphraseacl']; + $xml['dansguardianpicsacl'] = $config['installedpackages']['dansguardianpicsacl']; + $xml['dansguardiansearchacl'] = $config['installedpackages']['dansguardiansearchacl']; + $xml['dansguardiansiteacl'] = $config['installedpackages']['dansguardiansiteacl']; + $xml['dansguardianurlacl'] = $config['installedpackages']['dansguardianurlacl']; + $xml['dansguardianusers'] = $config['installedpackages']['dansguardianusers']; + $xml['dansguardianips'] = $config['installedpackages']['dansguardianips']; - } if (count($xml) > 0){ /* assemble xmlrpc payload */ $params = array( @@ -1321,18 +1365,18 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { $method = 'pfsense.merge_installedpackages_section_xmlrpc'; $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); + $cli->setCredentials($username, $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 30 seconds */ - $resp = $cli->send($msg, "30"); + /* send our XMLRPC message and timeout after $synctimeout seconds */ + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting dansguardian XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "30"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting dansguardian XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); @@ -1343,7 +1387,7 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { /* tell dansguardian to reload our settings on the destionation sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/dansguardian.inc');\n"; - $execcmd .= "sync_package_dansguardian(true);"; + $execcmd .= "sync_package_dansguardian('yes');"; /* assemble xmlrpc payload */ $params = array( @@ -1354,15 +1398,15 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { log_error("dansguardian XMLRPC reload data {$url}:{$port}."); $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); - $resp = $cli->send($msg, "30"); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting dansguardian XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "30"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting dansguardian XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); @@ -1372,4 +1416,4 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { } } -?> +?>
\ No newline at end of file diff --git a/config/dansguardian/dansguardian.php b/config/dansguardian/dansguardian.php index d4dcf46c..b9c972a1 100644 --- a/config/dansguardian/dansguardian.php +++ b/config/dansguardian/dansguardian.php @@ -39,11 +39,19 @@ require_once("/etc/inc/pkg-utils.inc"); require_once("/etc/inc/globals.inc"); require_once("/usr/local/pkg/dansguardian.inc"); -function fetch_blacklist($log_notice=true) { +function fetch_blacklist($log_notice=true,$install_process=false) { global $config,$g; - $url=$config['installedpackages']['dansguardianblacklist']['config'][0]['url']; - if (is_url($url)) { - conf_mount_rw(); + if (is_array($config['installedpackages']['dansguardianblacklist']) && is_array($config['installedpackages']['dansguardianblacklist']['config'])){ + $url=$config['installedpackages']['dansguardianblacklist']['config'][0]['url']; + $uw="Found a previouns install, checking Blacklist config..."; + } + else{ + $uw="Found a clean install, reading default access lists..."; + } + conf_mount_rw(); + if ($install_process == true) + update_output_window($uw); + if (isset($url) && is_url($url)) { if ($log_notice==true){ print "file download start.."; unlink_if_exists("/usr/local/pkg/blacklist.tgz"); @@ -82,11 +90,13 @@ function fetch_blacklist($log_notice=true) { } } else { - if (!empty($url)) + if ($install_process==true) + read_lists(false,$uw); + elseif (!empty($url)) file_notice("Dansguardian - Blacklist url is invalid.",""); } } -function read_lists($log_notice=true){ +function read_lists($log_notice=true,$uw=""){ global $config,$g; $group_type=array(); $dir=DANSGUARDIAN_DIR . "/etc/dansguardian/lists"; @@ -152,12 +162,14 @@ function read_lists($log_notice=true){ $edit_file=preg_replace('/size.19/','size>5',$edit_file); file_put_contents("/usr/local/pkg/dansguardian_".$edit_xml."_acl.xml",$edit_file,LOCK_EX); } - if($log_notice==true) - file_notice("Dansguardian - Blacklist applied, check site and URL access lists for categories",""); - #foreach($config['installedpackages'] as $key => $values) - # if (preg_match("/dansguardian(phrase|black|white)lists/",$key)) - # print "$key\n"; write_config(); + if($log_notice==true && $uw==""){ + file_notice("Dansguardian - Blacklist applied, check site and URL access lists for categories",""); + } + else{ + $uw.="done\n"; + update_output_window($uw); + } } if ($argv[1]=="update_lists") diff --git a/config/dansguardian/dansguardian_groups.xml b/config/dansguardian/dansguardian_groups.xml index fc9ff8a8..aaa9bcd6 100755 --- a/config/dansguardian/dansguardian_groups.xml +++ b/config/dansguardian/dansguardian_groups.xml @@ -386,10 +386,20 @@ <type>listtopic</type> </field> <field> + <fielddescr>LDAP group name source</fielddescr> + <fieldname>groupnamesource</fieldname> + <description><![CDATA[ This option determines where to look for LDAP group/OU name.]]></description> + <type>select</type> + <options> + <option><name>Dansguardian Group Name(default)</name><value>name</value></option> + <option><name>Dansguardian Group Description</name><value>description</value></option> + </options> + </field> + <field> <fielddescr>LDAP</fielddescr> <fieldname>ldap</fieldname> - <description><![CDATA[Select Active directory servers to extract users from<br> - The group must has the same name in dansguardian and on active directory<br> + <description><![CDATA[Select LDAP servers to extract users from<br> + The group must has the same name( or description) in dansguardian and on active directory<br> <strong>This is not aplicable for default group</strong>]]></description> <type>select_source</type> <size>05</size> @@ -399,6 +409,31 @@ <source_value>dc</source_value> </field> <field> + <fielddescr>LDAP user account status</fielddescr> + <fieldname>useraccountcontrol</fieldname> + <description><![CDATA[Import only users with these account status. Leave empty to do not check account status.]]></description> + <type>select</type> + <options> + <option><name>Normal (code 512)</name><value>512</value></option> + <option><name>Disabled Account (code 514)</name><value>514</value></option> + <option><name>Account is Disabled (code 2)</name><value>2</value></option> + <option><name>Account Locked Out (code 16)</name><value>16</value></option> + <option><name>Entered Bad Password (code 17)</name><value>17</value></option> + <option><name>No Password is Required(code 32)</name><value>32</value></option> + <option><name>Password CANNOT Change(code 64)</name><value>64</value></option> + <option><name>Password has Expired (code 8388608)</name><value>8388608</value></option> + <option><name>Account will Never Expire (code 65536)</name><value>65536</value></option> + <option><name>Enabled and Does NOT expire Paswword (code 66048)</name><value>66048</value></option> + <option><name>Server Trusted Account for Delegation (code 8192)</name><value>8192</value></option> + <option><name>Trusted Account for Delegation (code 524288)</name><value>524288</value></option> + <option><name>Enabled, User Cannot Change Password, Password Never Expires (code 590336)</name><value>590336</value></option> + <option><name>Normal Account, Password will not expire and Currently Disabled (code 66050)</name><value>66050</value></option> + <option><name>Account Enabled, Password does not expire, currently Locked out (code 66064)</name><value>66064</value></option> + </options> + <multiple/> + <size>16</size> + </field> + <field> <fielddescr>Update frequency</fielddescr> <fieldname>freq</fieldname> <description><![CDATA[How often extract users from active directory and verify changes<br> diff --git a/config/dansguardian/dansguardian_ldap.php b/config/dansguardian/dansguardian_ldap.php index 33cbee91..01d4764e 100644 --- a/config/dansguardian/dansguardian_ldap.php +++ b/config/dansguardian/dansguardian_ldap.php @@ -56,6 +56,7 @@ function get_ldap_members($group,$user,$password) { global $ldap_host; global $ldap_dn; $LDAPFieldsToFind = array("member"); + print "{$ldap_host} {$ldap_dn}\n"; $ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP"); // OPTIONS TO AD @@ -64,7 +65,10 @@ function get_ldap_members($group,$user,$password) { ldap_bind($ldap, $user, $password) or die("Could not bind to LDAP"); - $results = ldap_search($ldap,$ldap_dn,"cn=" . $group,$LDAPFieldsToFind); + //check if group is just a name or an ldap string + $group_cn=(preg_match("/cn=/i",$group)? $group : "cn={$group}"); + + $results = ldap_search($ldap,$ldap_dn,$group_cn,$LDAPFieldsToFind); $member_list = ldap_get_entries($ldap, $results); $group_member_details = array(); @@ -77,7 +81,8 @@ function get_ldap_members($group,$user,$password) { $member_search = ldap_search($ldap, $ldap_dn, "(CN=" . $member_cn . ")"); $member_details = ldap_get_entries($ldap, $member_search); $group_member_details[] = array($member_details[0]['samaccountname'][0], - $member_details[0]['displayname'][0]); + $member_details[0]['displayname'][0], + $member_details[0]['useraccountcontrol'][0]); } ldap_close($ldap); array_shift($group_member_details); @@ -96,11 +101,12 @@ $apply_config=0; if (is_array($config['installedpackages']['dansguardiangroups']['config'])) foreach($config['installedpackages']['dansguardiangroups']['config'] as $group) { #ignore default group - if ($id > 0) - if ($argv[1] == "" || $argv[1] == $group['name']){ + if ($id > 0){ + $ldap_group_source=(preg_match("/description/",$argv[1]) ? "description" : "name"); + if ($argv[2] == $group[$ldap_group_source]){ $members=""; $ldap_servers= explode (',',$group['ldap']); - echo "Group : " . $group['name']."\n"; + echo "Group : {$group['name']}({$group['description']})\n"; if (is_array($config['installedpackages']['dansguardianldap']['config'])) foreach ($config['installedpackages']['dansguardianldap']['config'] as $server){ if (in_array($server['dc'],$ldap_servers)){ @@ -113,18 +119,28 @@ if (is_array($config['installedpackages']['dansguardiangroups']['config'])) $ldap_username=$server['username']; #$domainuser=split("cn=",$server['username']); #$ldap_username=preg_replace("/,\./","@",$domainuser[1].preg_replace("/(,|)DC=/i",".",$server['dn'])); - $result = get_ldap_members($group['name'],$ldap_username,$server['password']); - foreach($result as $key => $value) { - if (preg_match ("/\w+/",$value[0])){ + $result = get_ldap_members($group[$ldap_group_source],$ldap_username,$server['password']); + if ($group['useraccountcontrol'] !="") + $valid_account_codes=explode(",",$group['useraccountcontrol']); + foreach($result as $mvalue) { + if (preg_match ("/\w+/",$mvalue[0])){ #var_dump($value); - $name= preg_replace('/[^(\x20-\x7F)]*/','', $value[1]); + $name= preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($mvalue[1]));//preg_replace('/[^(\x20-\x7F)]*/','', $mvalue[1]); $pattern[0]="/USER/"; $pattern[1]="/,/"; $pattern[2]="/NAME/"; - $replace[0]=$value[0]; + $replace[0]=$mvalue[0]; $replace[1]="\n"; $replace[2]="$name"; - $members .= preg_replace($pattern,$replace,$mask)."\n"; + + if (is_array($valid_account_codes)){ + if (in_array($mvalue[2],$valid_account_codes,true)) + $members .= preg_replace($pattern,$replace,$mask)."\n"; + } + else + { + $members .= preg_replace($pattern,$replace,$mask)."\n"; + } } } } @@ -144,8 +160,9 @@ if (is_array($config['installedpackages']['dansguardiangroups']['config'])) $apply_config++; } } - } - $id++; + } + } + $id++; } if ($apply_config > 0){ print "User list from LDAP is different from current group, applying new configuration..."; diff --git a/config/dansguardian/dansguardian_sync.xml b/config/dansguardian/dansguardian_sync.xml index 7f714051..9401253c 100755 --- a/config/dansguardian/dansguardian_sync.xml +++ b/config/dansguardian/dansguardian_sync.xml @@ -104,8 +104,30 @@ <field> <fielddescr>Automatically sync dansguardian configuration changes</fielddescr> <fieldname>synconchanges</fieldname> - <description>pfSense will automatically sync changes to the hosts defined below.</description> - <type>checkbox</type> + <description>Select a sync method for dansguardian.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr>Remote Server</fielddescr> diff --git a/config/dashboard/dashboard.xml b/config/dashboard/dashboard.xml index 7177eed6..c09a2eda 100644 --- a/config/dashboard/dashboard.xml +++ b/config/dashboard/dashboard.xml @@ -57,7 +57,7 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/dashboard/binaries/widgets.tgz</item> + <item>http://files.pfsense.org/packages/widgets.tgz</item> </additional_files_needed> <custom_php_install_command> dashboard_install(); diff --git a/config/dnsblacklist/dnsblacklist.xml b/config/dnsblacklist/dnsblacklist.xml index 1b7c29e5..52c59b35 100644 --- a/config/dnsblacklist/dnsblacklist.xml +++ b/config/dnsblacklist/dnsblacklist.xml @@ -77,7 +77,7 @@ <additional_files_needed> <prefix>/tmp/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.com/packages/config/dnsblacklist/blacklists.tar.gz</item> + <item>http://files.pfsense.org/packages/blacklists.tar.gz</item> </additional_files_needed> <fields> <field> diff --git a/config/filemgr/file_manager.tmp b/config/filemgr/file_manager.tmp index 9699ec22..8c5ee1c5 100644 --- a/config/filemgr/file_manager.tmp +++ b/config/filemgr/file_manager.tmp @@ -477,8 +477,8 @@ if('ok' == 'ok'){ </div> <form id="path" name="path" method="get" action="" class="path"> - <input type="text" name="p" id="location" value="<?php echo $current_folder; ?>" /> - <img src="rbfmimg/go.png" name="go" width="35" height="18" id="go" alt="go" title="go" /> + <input name="p" type="text" id="location" value="<?php echo $current_folder; ?>" /> + <input name="go" type="image" id="go" value="Go" src="rbfmimg/go.png" style="width:35;height:18" /> </form> <div class="url_path"><br />URL path: <a href="/<?php echo $url_path; ?>" target="_blank"><?php echo $url_path; ?></a></div> <div class="container"> <?php echo $container; ?> <?php echo $error; ?> </div> diff --git a/config/freeradius2/freeradius.inc b/config/freeradius2/freeradius.inc index 38093780..b2df3d0b 100644 --- a/config/freeradius2/freeradius.inc +++ b/config/freeradius2/freeradius.inc @@ -4,7 +4,8 @@ /* freeradius.inc part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Marcello Coutinho All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -47,16 +48,24 @@ require_once("services.inc"); // Check pfSense version $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); -switch ($pfs_version) { - case "1.2": - case "2.0": - define('FREERADIUS_BASE', '/usr/local'); - break; - default: - define('FREERADIUS_BASE', '/usr/pbi/freeradius-' . php_uname("m")); +if ($pfs_version > 2.0){ + define('FREERADIUS_BASE', '/usr/pbi/freeradius-' . php_uname("m")); +} +else{ + define('FREERADIUS_BASE', '/usr/local'); } -// End: Check pfSense version +// Check freeradius lib version + $frlib=""; + $libfiles = scandir(FREERADIUS_BASE . "/lib/"); + foreach ($libfiles as $libfile){ + if (preg_match("/freeradius-/",$libfile)) + $frlib=FREERADIUS_BASE . "/lib/{$libfile}"; + } + if ($frlib == ""){ + log_error("freeRADIUS - No freeradius lib found on ".FREERADIUS_BASE."/lib"); + } + function freeradius_deinstall_command() { if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { exec("cd /var/db/pkg && pkg_delete `ls | grep freeradius`"); @@ -68,7 +77,7 @@ function freeradius_deinstall_command() { function freeradius_install_command() { global $config; conf_mount_rw(); - + // put the constant to a variable $varFREERADIUS_BASE = FREERADIUS_BASE; @@ -79,7 +88,7 @@ function freeradius_install_command() { exec("mkdir " . FREERADIUS_BASE . "/etc/raddb/scripts"); if (!file_exists("/var/log/radutmp")) { exec("touch /var/log/radutmp"); } if (!file_exists("/var/log/radwtmp")) { exec("touch /var/log/radwtmp"); } - exec("chown -R root:wheel " . FREERADIUS_BASE . "/etc/raddb && chown -R root:wheel " . FREERADIUS_BASE . "/lib/freeradius-2.1.12 && chown -R root:wheel /var/log/radacct"); + exec("chown -R root:wheel " . FREERADIUS_BASE . "/etc/raddb && chown -R root:wheel {$frlib} && chown -R root:wheel /var/log/radacct"); // creating a backup file of the original policy.conf no matter if user checked this or not if (!file_exists(FREERADIUS_BASE . "/etc/raddb/policy.conf.backup")) { @@ -213,7 +222,7 @@ raddbdir = \${sysconfdir}/raddb radacctdir = \${logdir}/radacct confdir = \${raddbdir} run_dir = \${localstatedir}/run -libdir = \${exec_prefix}/lib/freeradius-2.1.12 +libdir = {$frlib} pidfile = \${run_dir}/radiusd.pid db_dir = \${raddbdir} name = radiusd @@ -948,12 +957,18 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { if(base64_decode($ca_cert['crt'])) { + $crl_cert = lookup_crl($eapconf["ssl_ca_crl"]); + if ($crl_cert != false){ + $crl=base64_decode($crl_cert['text']); + $check_crl="check_crl = yes"; + } + else{ + $check_crl="check_crl = no"; + } file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_cert.pem", - base64_decode($ca_cert['crt'])); + base64_decode($ca_cert['crt']). $crl); $conf['ssl_ca_cert'] = FREERADIUS_BASE . "/etc/raddb/certs/ca_cert.pem"; } - - $svr_cert = lookup_cert($eapconf["ssl_server_cert"]); if ($svr_cert != false) { if(base64_decode($svr_cert['prv'])) { @@ -970,7 +985,7 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { $conf['ssl_server_cert'] = FREERADIUS_BASE . "/etc/raddb/certs/server_cert.pem"; } - + /* Not needed anymore because pfsense can do this by default if ($eapconf['vareapconfenableclientp12'] == 'on') { $svr_cert = lookup_cert($eapconf["ssl_client_cert"]); if ($svr_cert != false) { @@ -990,7 +1005,7 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { exec("openssl pkcs12 -export -in " . FREERADIUS_BASE . "/etc/raddb/certs/client_cert.pem -inkey " . FREERADIUS_BASE . "/etc/raddb/certs/client_key.pem -out " . FREERADIUS_BASE . "/etc/raddb/certs/client_cert.p12 -passout pass\:"); } - + */ $conf['ssl_cert_dir'] = FREERADIUS_BASE . '/etc/raddb/certs'; } @@ -1055,7 +1070,7 @@ else { random_file = \${certdir}/random fragment_size = $vareapconffragmentsize include_length = $vareapconfincludelength - # check_crl = yes + {$check_crl} CA_path = \${cadir} $vareapconfcheckcertissuer $vareapconfcheckcertcn @@ -1120,6 +1135,18 @@ function freeradius_get_ca_certs() { } // Gets started from freeradiuseapconf.xml +function freeradius_get_ca_crl() { + global $config; + $crl_arr = array(); + $crl_arr[] = array('refid' => 'none', 'descr' => 'none'); + + foreach ($config['crl'] as $crl) { + $crl_arr[] = array('refid' => $crl['refid'], 'descr' => $crl['descr']); + } + return $crl_arr; +} + +// Gets started from freeradiuseapconf.xml function freeradius_get_server_certs() { global $config; $cert_arr = array(); @@ -2494,52 +2521,75 @@ conf_mount_ro(); /* Uses XMLRPC to synchronize the changes to a remote node */ function freeradius_sync_on_changes() { global $config, $g; - $varsyncenablexmlrpc = $config['installedpackages']['freeradiussync']['config'][0]['varsyncenablexmlrpc']; - $varsynctimeout = $config['installedpackages']['freeradiussync']['config'][0]['varsynctimeout']; - - // if checkbox is NOT checked do nothing - if(!$varsyncenablexmlrpc) { + if (is_array($config['installedpackages']['freeradiussync'])){ + $synconchanges = $config['installedpackages']['freeradiussync']['config'][0]['varsyncenablexmlrpc']; + $varsynctimeout = $config['installedpackages']['freeradiussync']['config'][0]['varsynctimeout']; + } + else + { return; } - - log_error("FreeRADIUS: Starting XMLRPC process (freeradius_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); - - // if checkbox is checked get IP and password of the destination hosts - foreach ($config['installedpackages']['freeradiussync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - // if checkbox is NOT checked do nothing - if($sh['varsyncdestinenable']) { - $varsyncprotocol = $sh['varsyncprotocol']; - $sync_to_ip = $sh['varsyncipaddress']; - $password = $sh['varsyncpassword']; - $varsyncport = $sh['varsyncport']; - // check if all credentials are complete for this host - if($password && $sync_to_ip && $varsyncport && $varsyncprotocol) { - freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol); + + // if checkbox is NOT checked do nothing + switch ($synconchanges){ + case "manual": + if (is_array($config['installedpackages']['freeradiussync']['config'][0]['row'])){ + $rs=$config['installedpackages']['freeradiussync']['config'][0]['row']; + } + else{ + log_error("[FreeRADIUS]: xmlrpc sync is enabled but there is no hosts to push on FreeRADIUS config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['varsyncdestinenable']="on"; + $rs[0]['varsyncprotocol']=($config['system']['webgui']['protocol']!=""?$config['system']['webgui']['protocol']:"https"); + $rs[0]['varsyncipaddress']=$system_carp['synchronizetoip']; + $rs[0]['varsyncpassword']=$system_carp['password']; + $rs[0]['varsyncport']=($config['system']['webgui']['port']!=""?$config['system']['webgui']['port']:"443"); + if (! is_ipaddr($system_carp['synchronizetoip'])){ + log_error("[FreeRADIUS]: xmlrpc sync is enabled but there is no system backup hosts to push FreeRADIUS config."); + return; + } + } + else{ + log_error("[FreeRADIUS]: xmlrpc sync is enabled but there is no system backup hosts to push FreeRADIUS config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[FreeRADIUS]: xmlrpc sync is starting with timeout {$varsynctimeout} seconds."); + foreach($rs as $sh){ + if($sh['varsyncdestinenable']){ + $varsyncprotocol = $sh['varsyncprotocol']; + $sync_to_ip = $sh['varsyncipaddress']; + $password = $sh['varsyncpassword']; + $varsyncport = $sh['varsyncport']; + if($password && $sync_to_ip) + freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol,$varsynctimeout); + else + log_error("[FreeRADIUS]: XMLRPC Sync with {$sh['varsyncipaddress']} has incomplete credentials. No XMLRPC Sync done!"); } else { - log_error("FreeRADIUS: XMLRPC Sync with {$sh['varsyncipaddress']} has incomplete credentials. No XMLRPC Sync done!"); + log_error("[FreeRADIUS]: XMLRPC Sync with {$sh['varsyncipaddress']} is disabled"); } } - else { - log_error("FreeRADIUS: XMLRPC Sync with {$sh['varsyncipaddress']} is disabled"); + log_error("[FreeRADIUS]: xmlrpc sync is ending."); } - } - } - log_error("FreeRADIUS: Finished XMLRPC process (freeradius_do_xmlrpc_sync)."); } /* Do the actual XMLRPC sync */ -function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol) { +function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol,$varsynctimeout) { global $config, $g; - $varsynctimeout = $config['installedpackages']['freeradiussync']['config'][0]['varsynctimeout']; - - if($varsynctimeout == '' || $varsynctimeout == 0) { + if($varsynctimeout == '' || $varsynctimeout == 0) $varsynctimeout = 150; - } - - // log_error("FreeRADIUS: Starting XMLRPC process (freeradius_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); if(!$password) return; @@ -2573,7 +2623,7 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn /* set a few variables needed for sync code borrowed from filter.inc */ $url = $synchronizetoip; - log_error("FreeRADIUS: Beginning FreeRADIUS XMLRPC sync with {$url}:{$port}."); + log_error("[FreeRADIUS]: Beginning FreeRADIUS XMLRPC sync with {$url}:{$port}."); $method = 'pfsense.merge_installedpackages_section_xmlrpc'; $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); @@ -2584,22 +2634,22 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn $resp = $cli->send($msg, $varsynctimeout); if(!$resp) { $error = "A communications error occurred while FreeRADIUS was attempting XMLRPC sync with {$url}:{$port}."; - log_error("FreeRADIUS: $error"); - file_notice("sync_settings", $error, "freeradius Settings Sync", ""); + log_error("[FreeRADIUS]: $error"); + file_notice("sync_settings", $error, "FreeRADIUS Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); $resp = $cli->send($msg, $varsynctimeout); $error = "An error code was received while FreeRADIUS XMLRPC was attempting to sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); - log_error("FreeRADIUS: $error"); - file_notice("sync_settings", $error, "freeradius Settings Sync", ""); + log_error("[FreeRADIUS]: $error"); + file_notice("sync_settings", $error, "FreeRADIUS Settings Sync", ""); } else { - log_error("FreeRADIUS: XMLRPC has synced data successfully with {$url}:{$port}."); + log_error("[FreeRADIUS]: XMLRPC has synced data successfully with {$url}:{$port}."); } - /* tell freeradius to reload our settings on the destionation sync host. */ + /* tell FreeRADIUS to reload our settings on the destionation sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/freeradius.inc');\n"; - // pfblocker just needed one fuction to reload after XMLRPC. freeRADIUS needs more so we point to a fuction below which contains all fuctions + // pfblocker just needed one fuction to reload after XMLRPC. FreeRADIUS needs more so we point to a fuction below which contains all fuctions $execcmd .= "freeradius_all_after_XMLRPC_resync();"; /* assemble xmlrpc payload */ @@ -2608,7 +2658,7 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn XML_RPC_encode($execcmd) ); - log_error("FreeRADIUS XMLRPC is reloading data on {$url}:{$port}."); + log_error("[FreeRADIUS]: XMLRPC is reloading data on {$url}:{$port}."); $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials('admin', $password); @@ -2616,21 +2666,19 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn if(!$resp) { $error = "A communications error occurred while FreeRADIUS was attempting XMLRPC sync with {$url}:{$port} (exec_php)."; log_error($error); - file_notice("sync_settings", $error, "freeradius Settings Sync", ""); + file_notice("sync_settings", $error, "FreeRADIUS Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); $resp = $cli->send($msg, $varsynctimeout); $error = "An error code was received while FreeRADIUS XMLRPC was attempting to sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); - file_notice("sync_settings", $error, "freeradius Settings Sync", ""); + file_notice("sync_settings", $error, "FreeRADIUS Settings Sync", ""); } else { - log_error("FreeRADIUS: XMLRPC has reloaded data successfully on {$url}:{$port} (exec_php)."); + log_error("[FreeRADIUS]: XMLRPC has reloaded data successfully on {$url}:{$port} (exec_php)."); } } -// ##### The part above is based on the code of pfblocker ##### - // This function restarts all other needed functions after XMLRPC so that the content of .XML + .INC will be written in the files (clients.conf, users) // Adding more functions will increase the to sync function freeradius_all_after_XMLRPC_resync() { diff --git a/config/freeradius2/freeradius.xml b/config/freeradius2/freeradius.xml index fdadab89..c9381c81 100644 --- a/config/freeradius2/freeradius.xml +++ b/config/freeradius2/freeradius.xml @@ -9,7 +9,7 @@ /* freeradius.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -45,7 +45,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>freeradius</name> - <version>2.1.12</version> + <version>2.2.0</version> <title>FreeRADIUS: Users</title> <include_file>/usr/local/pkg/freeradius.inc</include_file> <menu> diff --git a/config/freeradius2/freeradius_view_config.php b/config/freeradius2/freeradius_view_config.php index a29e1a55..a1943653 100644 --- a/config/freeradius2/freeradius_view_config.php +++ b/config/freeradius2/freeradius_view_config.php @@ -2,7 +2,7 @@ /* freeradius_view_config.php part of pfSense (http://www.pfsense.com/) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> based on postfix_view_config.php based on varnish_view_config. diff --git a/config/freeradius2/freeradiusauthorizedmacs.xml b/config/freeradius2/freeradiusauthorizedmacs.xml index 173f8f00..235d0218 100644 --- a/config/freeradius2/freeradiusauthorizedmacs.xml +++ b/config/freeradius2/freeradiusauthorizedmacs.xml @@ -9,7 +9,7 @@ /* freeradiusauthorizedmacs.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) diff --git a/config/freeradius2/freeradiuscerts.xml b/config/freeradius2/freeradiuscerts.xml index 21f18643..6108215b 100644 --- a/config/freeradius2/freeradiuscerts.xml +++ b/config/freeradius2/freeradiuscerts.xml @@ -9,7 +9,7 @@ /* freeradiuscerts.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -290,4 +290,4 @@ <custom_php_resync_config_command> freeradius_allcertcnf_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiusclients.xml b/config/freeradius2/freeradiusclients.xml index 87d8a11f..215a751e 100644 --- a/config/freeradius2/freeradiusclients.xml +++ b/config/freeradius2/freeradiusclients.xml @@ -9,7 +9,7 @@ /* freeradiusclients.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -246,4 +246,4 @@ <custom_php_resync_config_command> freeradius_clients_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiuseapconf.xml b/config/freeradius2/freeradiuseapconf.xml index ac761523..8f8e4dc7 100644 --- a/config/freeradius2/freeradiuseapconf.xml +++ b/config/freeradius2/freeradiuseapconf.xml @@ -9,7 +9,8 @@ /* freeradiuseapconf.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Marcello Coutinho (revocation list code) All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -171,7 +172,7 @@ <b>uncheked</b>: FreeRADIUS Cert-Manager (not recommended) (Default: unchecked)<br> <b>cheked</b>: Firewall Cert-Manager (recommended)]]></description> <type>checkbox</type> - <enablefields>ssl_ca_cert,ssl_server_cert,vareapconfenableclientp12</enablefields> + <enablefields>ssl_ca_cert,ssl_ca_crl,ssl_server_cert</enablefields> </field> <field> <fielddescr>Private Key Password</fielddescr> @@ -191,6 +192,18 @@ <source_value>refid</source_value> </field> <field> + <fielddescr>SSL Revocation List</fielddescr> + <fieldname>ssl_ca_crl</fieldname> + <description><![CDATA[Choose the SSL CA Certficate revocation list here which you created with the firewall's Cert Manager.<br> + <b>HINT:</b> You need to restart freeradius service after adding a certificate to the CRL.<br> + Choose "none" if you do not use any kind of certificates or the freeradius Cert Manager. (Default: none)]]></description> + <type>select_source</type> + <source><![CDATA[freeradius_get_ca_crl()]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + + <field> <fielddescr>SSL Server Certificate</fielddescr> <fieldname>ssl_server_cert</fieldname> <description><![CDATA[Choose the SSL Server Certficate here which you created with the firewall's Cert Manager.<br> @@ -200,6 +213,7 @@ <source_name>descr</source_name> <source_value>refid</source_value> </field> + <!-- Not needed anymore because pfsense itself can do this now> <field> <fielddescr>Create client.p12 for export</fielddescr> <fieldname>vareapconfenableclientp12</fieldname> @@ -217,6 +231,7 @@ <source_name>descr</source_name> <source_value>refid</source_value> </field> + --> <field> <name>EAP-TLS</name> <type>listtopic</type> @@ -470,4 +485,4 @@ <custom_php_resync_config_command> freeradius_eapconf_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiusinterfaces.xml b/config/freeradius2/freeradiusinterfaces.xml index c944ac17..1233f72f 100644 --- a/config/freeradius2/freeradiusinterfaces.xml +++ b/config/freeradius2/freeradiusinterfaces.xml @@ -9,7 +9,7 @@ /* freeradiusinterfaces.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -185,4 +185,4 @@ <custom_php_resync_config_command> freeradius_settings_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiusmodulesldap.xml b/config/freeradius2/freeradiusmodulesldap.xml index 0fa98493..c7b5e79d 100644 --- a/config/freeradius2/freeradiusmodulesldap.xml +++ b/config/freeradius2/freeradiusmodulesldap.xml @@ -9,7 +9,7 @@ /* freeradiusmodulesldap.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -45,7 +45,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>freeradiusmodulesldap</name> - <version>none</version> + <version>2.2.0</version> <title>FreeRADIUS: LDAP</title> <aftersaveredirect>pkg_edit.php?xml=freeradiusmodulesldap.xml&id=0</aftersaveredirect> <include_file>/usr/local/pkg/freeradius.inc</include_file> @@ -705,4 +705,4 @@ <custom_php_resync_config_command> freeradius_modulesldap_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiussettings.xml b/config/freeradius2/freeradiussettings.xml index 4bc98723..1d908ca4 100644 --- a/config/freeradius2/freeradiussettings.xml +++ b/config/freeradius2/freeradiussettings.xml @@ -9,7 +9,7 @@ /* freeradiussettings.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -45,7 +45,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>freeradiussettings</name> - <version>none</version> + <version>2.2.0</version> <title>FreeRADIUS: Settings</title> <aftersaveredirect>pkg_edit.php?xml=freeradiussettings.xml&id=0</aftersaveredirect> <include_file>/usr/local/pkg/freeradius.inc</include_file> @@ -376,4 +376,4 @@ <custom_php_resync_config_command> freeradius_settings_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiussqlconf.xml b/config/freeradius2/freeradiussqlconf.xml index 6851711c..bb72a07a 100644 --- a/config/freeradius2/freeradiussqlconf.xml +++ b/config/freeradius2/freeradiussqlconf.xml @@ -9,7 +9,7 @@ /* freeradiussqlconf.xml part of pfSense (http://www.pfSense.com) - Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) @@ -45,7 +45,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>freeradiussqlconf</name> - <version>none</version> + <version>2.2.0</version> <title>FreeRADIUS: SQL</title> <aftersaveredirect>pkg_edit.php?xml=freeradiussqlconf.xml&id=0</aftersaveredirect> <include_file>/usr/local/pkg/freeradius.inc</include_file> @@ -621,4 +621,4 @@ <custom_php_resync_config_command> freeradius_sqlconf_resync(); </custom_php_resync_config_command> -</packagegui>
\ No newline at end of file +</packagegui> diff --git a/config/freeradius2/freeradiussync.xml b/config/freeradius2/freeradiussync.xml index 5f1acc74..be678e5a 100644 --- a/config/freeradius2/freeradiussync.xml +++ b/config/freeradius2/freeradiussync.xml @@ -9,8 +9,8 @@ /* freeradiussync.xml part of pfSense (http://www.pfSense.com) -Copyright (C) 2011 - 2012 Alexander Wilke <nachtfalkeaw@web.de> -Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> +Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> +Copyright (C) 2013 Marcello Coutinho <marcellocoutinho@gmail.com> based on pfblocker_sync.xml All rights reserved. @@ -47,7 +47,7 @@ POSSIBILITY OF SUCH DAMAGE. <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>freeradiussync</name> - <version>2.1.12</version> + <version>2.2.0</version> <title>FreeRADIUS: XMLRPC Sync</title> <include_file>/usr/local/pkg/freeradius.inc</include_file> <menu> @@ -111,23 +111,29 @@ POSSIBILITY OF SUCH DAMAGE. </tabs> <fields> <field> - <name>freeRADIUS XMLRPC Sync</name> + <name>FreeRADIUS XMLRPC Sync</name> <type>listtopic</type> </field> <field> - <fielddescr>Automatically sync freeRADIUS configuration changes?</fielddescr> + <fielddescr>Enable Sync</fielddescr> <fieldname>varsyncenablexmlrpc</fieldname> <description><![CDATA[All changes will be synced immediately to the IPs listed below if this option is checked.<br> - Only <b>Users</b>, <b>MACs</b> and <b>NAS / Clients</b> will be synced.<br> - <b>Important:</b> Only sync from host A to B, A to C but <b>do not</B> enable XMLRPC sync <b>to</b> A. This will result in a loop!]]></description> - <type>checkbox</type> + <b>Important:</b> While using "Sync to hosts defined below", only sync from host A to B, A to C but <b>do not</B> enable XMLRPC sync <b>to</b> A. This will result in a loop!]]></description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> </field> <field> - <fielddescr>XMLRPC timeout</fielddescr> + <fielddescr>XMLRPC timeout</fielddescr> <fieldname>varsynctimeout</fieldname> <description><![CDATA[Timeout in seconds for the XMLRPC timeout. Default: 150]]></description> <type>input</type> - <default_value>150</default_value> + <default_value>150</default_value> <size>5</size> </field> @@ -166,7 +172,7 @@ POSSIBILITY OF SUCH DAMAGE. <type>input</type> <size>3</size> </rowhelperfield> - <rowhelperfield> + <rowhelperfield> <fielddescr>GUI Admin Password</fielddescr> <fieldname>varsyncpassword</fieldname> <description><![CDATA[Password of the user "admin" on the destination host.]]></description> diff --git a/config/haproxy-devel/haproxy.inc b/config/haproxy-devel/haproxy.inc index 954e933f..66bcf81f 100644 --- a/config/haproxy-devel/haproxy.inc +++ b/config/haproxy-devel/haproxy.inc @@ -599,7 +599,7 @@ function haproxy_writeconf($configfile) { //ssl crt ./server.pem ca-file ./ca.crt verify optional crt-ignore-err all crl-file ./ca_crl.pem $ssl_crt=" crt /var/etc/{$backend['name']}.{$backend['port']}.crt"; $cert = lookup_cert($backend['ssloffloadcert']); - $certcontent = base64_decode($cert['crt']).base64_decode($cert['prv']); + $certcontent = base64_decode($cert['crt'])."\r\n".base64_decode($cert['prv']); file_put_contents("/var/etc/{$backend['name']}.{$backend['port']}.crt", $certcontent); unset($certcontent); }else{ diff --git a/config/lcdproc/lcdproc.xml b/config/lcdproc/lcdproc.xml index bc03b761..32a8f900 100644 --- a/config/lcdproc/lcdproc.xml +++ b/config/lcdproc/lcdproc.xml @@ -38,22 +38,22 @@ <chmod>0755</chmod> </additional_files_needed> <additional_files_needed> - <item>http://www.pfsense.org/packages/config/lcdproc/bin/nexcom.so</item> + <item>http://files.pfsense.org/packages/lcdproc/nexcom.so</item> <prefix>/usr/local/lib/lcdproc/</prefix> <chmod>0755</chmod> </additional_files_needed> <additional_files_needed> - <item>http://www.pfsense.org/packages/config/lcdproc/bin/SureElec.so</item> + <item>http://files.pfsense.org/packages/lcdproc/SureElec.so</item> <prefix>/usr/local/lib/lcdproc/</prefix> <chmod>0755</chmod> </additional_files_needed> <additional_files_needed> - <item>http://www.pfsense.org/packages/config/lcdproc/bin/picolcd.so</item> + <item>http://files.pfsense.org/packages/lcdproc/picolcd.so</item> <prefix>/usr/local/lib/lcdproc/</prefix> <chmod>0755</chmod> </additional_files_needed> <additional_files_needed> - <item>http://www.pfsense.org/packages/config/lcdproc/bin/libusb.so.2</item> + <item>http://files.pfsense.org/packages/lcdproc/libusb.so.2</item> <prefix>/usr/local/lib/lcdproc/</prefix> <chmod>0755</chmod> </additional_files_needed> diff --git a/config/lightsquid/sqstat.php b/config/lightsquid/sqstat.php index a56b604a..7b12b970 100644 --- a/config/lightsquid/sqstat.php +++ b/config/lightsquid/sqstat.php @@ -61,7 +61,7 @@ if ($_REQUEST['getactivity']) $pgtitle = "Proxy Squid: Realtime stat (sqstat)"; require_once("head.inc"); - +$csrf_token= csrf_get_tokens(); ?> <link href="sqstat.css" rel="stylesheet" type="text/css"/> @@ -79,7 +79,7 @@ function el(id) { function getactivity(action) { var url = "<?php echo ($_SERVER["PHP_SELF"]); ?>"; - var pars = "getactivity=yes"; + var pars = "getactivity=yes" + "<? echo '&__csrf_magic='.$csrf_token ?>"; var myAjax = new Ajax.Request( url, { @@ -414,4 +414,4 @@ function sqstat_get_real_interface_address($iface) return array($ip, long2ip(hexdec($netmask))); } -?>
\ No newline at end of file +?> diff --git a/config/mailreport/mail_reports.inc b/config/mailreport/mail_reports.inc index 8ab31301..85b67ddf 100644 --- a/config/mailreport/mail_reports.inc +++ b/config/mailreport/mail_reports.inc @@ -29,6 +29,7 @@ POSSIBILITY OF SUCH DAMAGE. */ +require_once("globals.inc"); require_once("config.inc"); require_once("filter.inc"); require_once("rrd.inc"); @@ -42,6 +43,28 @@ $graph_length = array( "year" => 31622400, "4year" => 126489600); +$logfile_friendly = array( + "dhcpd" => "DHCP", + "filter" => "Firewall (raw)", + "gateways" => "Gateway Events", + "installer" => "Installation", + "ipsec" => "IPsec VPN", + "l2tps" => "L2TP Server (raw)", + "lighttpd" => "Web Server (lighttpd)", + "ntpd" => "NTP", + "openvpn" => "OpenVPN", + "poes" => "PPPoE Server (raw)", + "portalauth" => "Captive Portal Authentication", + "ppp" => "PPP", + "pptps" => "PPTP Server (raw)", + "relayd" => "Load Balancer (relayd)", + "resolver" => "DNS Resolver", + "routing" => "Routing", + "system" => "System", + "vpn" => "PPTP/L2TP/PPPoE Server Login Events", + "wireless" => "Wireless" +); + function get_dates($curperiod, $graph) { global $graph_length; $now = time(); @@ -162,7 +185,7 @@ function set_mail_report_cron_jobs($a_mailreports) { include('phpmailer/class.phpmailer.php'); -function mail_report_send($headertext, $attachments) { +function mail_report_send($headertext, $cmdtext, $logtext, $attachments) { global $config, $g; if (empty($config['notifications']['smtp']['ipaddress'])) @@ -191,7 +214,11 @@ function mail_report_send($headertext, $attachments) { $address = $config['notifications']['smtp']['notifyemailaddress']; $mail->AddAddress($address, "Report Recipient"); $mail->Subject = "{$config['system']['hostname']}.{$config['system']['domain']} Graph Report: {$headertext}"; - $mail->Body .= "This is a periodic graph report from your firewall, {$config['system']['hostname']}.{$config['system']['domain']}.<br/><br/>Current report: {$headertext}\n"; + $mail->Body .= "This is a periodic report from your firewall, {$config['system']['hostname']}.{$config['system']['domain']}.<br /><br />Current report: {$headertext}<br />\n<br />\n"; + if (!empty($cmdtext)) + $mail->Body .= $cmdtext; + if (!empty($logtext)) + $mail->Body .= $logtext; if(is_array($attachments)) { foreach($attachments as $filename) { $shortname = basename($filename); @@ -203,7 +230,7 @@ function mail_report_send($headertext, $attachments) { if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "<strong>Message sent to {$userid}!</strong>\n"; + echo "<strong>Message sent to {$address}!</strong>\n"; } } @@ -1201,4 +1228,32 @@ function timeDiff($time, $opt = array()) { return $str; } +function mail_report_get_log($logfile, $tail, $grepfor) { + global $g, $config; + $logfile = "{$g['varlog_path']}/{$logfile}"; + $logarr = ""; + $grepline = " "; + if(is_array($grepfor)) + foreach($grepfor as $agrep) + $grepline .= " | grep \"$agrep\""; + if($config['system']['disablesyslogclog']) { + exec("cat {$logfile}{$grepline} | /usr/bin/tail -n {$tail}", $logarr); + } else { + if(isset($config['system']['usefifolog'])) { + exec("/usr/sbin/fifolog_reader {$logfile}{$grepline} | /usr/bin/tail -n {$tail}", $logarr); + } else { + exec("/usr/sbin/clog {$logfile}{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail -n {$tail}", $logarr); + } + } + return($logarr); +} + +function get_friendly_log_name($logfile) { + global $logfile_friendly; + $friendly = str_replace(".log", "", $logfile); + if (!empty($logfile_friendly[$friendly])) + $friendly = $logfile_friendly[$friendly]; + return $friendly; +} + ?> diff --git a/config/mailreport/mail_reports_generate.php b/config/mailreport/mail_reports_generate.php index 7ff7b71e..a784c596 100644 --- a/config/mailreport/mail_reports_generate.php +++ b/config/mailreport/mail_reports_generate.php @@ -53,17 +53,42 @@ if (!$config['mailreports']['schedule'][$id]) exit; $thisreport = $config['mailreports']['schedule'][$id]; +$cmds = $thisreport['cmd']['row']; +$logs = $thisreport['log']['row']; $graphs = $thisreport['row']; -// No graphs on the report, bail! -if (!is_array($graphs) || !(count($graphs) > 0)) - exit; +// If there is nothing to do, bail! +if ((!is_array($cmds) || !(count($cmds) > 0)) + && (!is_array($logs) || !(count($logs) > 0)) + && (!is_array($graphs) || !(count($graphs) > 0))) + return; // Print report header +// Print command output +$cmdtext = ""; +foreach ($cmds as $cmd) { + $output = ""; + $cmdtext .= "Command output: {$cmd['descr']} (" . htmlspecialchars($cmd['detail']) . ")<br />\n"; + exec($cmd['detail'], $output); + $cmdtext .= "<pre>\n"; + $cmdtext .= implode("\n", $output); + $cmdtext .= "\n</pre>"; +} + +// Print log output +$logtext = ""; +foreach ($logs as $log) { + $lines = empty($log['lines']) ? 50 : $log['lines']; + $filter = empty($log['detail']) ? null : array($log['detail']); + $logtext .= "Log output: " . get_friendly_log_name($log['logfile']) . " ({$log['logfile']})<br />\n"; + $logtext .= "<pre>\n"; + $logtext .= implode("\n", mail_report_get_log($log['logfile'], $lines, $filter)); + $logtext .= "\n</pre>"; +} + // For each graph, print a header and the graph $attach = array(); -$idx=0; foreach ($graphs as $thisgraph) { $dates = get_dates($thisgraph['period'], $thisgraph['timespan']); $start = $dates['start']; @@ -71,6 +96,6 @@ foreach ($graphs as $thisgraph) { $attach[] = mail_report_generate_graph($thisgraph['graph'], $thisgraph['style'], $thisgraph['timespan'], $start, $end); } -mail_report_send($thisreport['descr'], $attach); +mail_report_send($thisreport['descr'], $cmdtext, $logtext, $attach); ?>
\ No newline at end of file diff --git a/config/mailreport/mailreport.xml b/config/mailreport/mailreport.xml index 613ac42f..d27d3a28 100644 --- a/config/mailreport/mailreport.xml +++ b/config/mailreport/mailreport.xml @@ -37,7 +37,7 @@ ]]> </copyright> <name>mailreport</name> - <version>1.0</version> + <version>2.0.4</version> <title>Status: Mail Reports</title> <additional_files_needed> <prefix>/usr/local/bin/</prefix> @@ -70,11 +70,19 @@ </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/</prefix> + <item>http://www.pfsense.com/packages/config/mailreport/status_mail_report_add_cmd.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <item>http://www.pfsense.com/packages/config/mailreport/status_mail_report_add_log.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> <item>http://www.pfsense.com/packages/config/mailreport/status_mail_report_add_graph.php</item> </additional_files_needed> <menu> - <name>RRD E-Mail Reports</name> - <tooltiptext>Setup periodic e-mail reports with RRD graphs.</tooltiptext> + <name>E-Mail Reports</name> + <tooltiptext>Setup periodic e-mail reports.</tooltiptext> <section>Status</section> <url>/status_mail_report.php</url> </menu> diff --git a/config/mailreport/status_mail_report.php b/config/mailreport/status_mail_report.php index 4dc195bc..b1705fac 100644 --- a/config/mailreport/status_mail_report.php +++ b/config/mailreport/status_mail_report.php @@ -74,11 +74,13 @@ include("head.inc"); <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td><div id="mainarea"> <table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr><td colspan="4">Here you can define a list of reports, containing multiple RRD graphs, to be sent by e-mail. </td></tr> + <tr><td colspan="4">Here you can define a list of reports to be sent by e-mail. </td></tr> <tr><td> </td></tr> <tr> - <td width="45%" class="listhdr"><?=gettext("Description");?></td> - <td width="35%" class="listhdr"><?=gettext("Schedule");?></td> + <td width="35%" class="listhdr"><?=gettext("Description");?></td> + <td width="25%" class="listhdr"><?=gettext("Schedule");?></td> + <td width="10%" class="listhdr"><?=gettext("Cmds");?></td> + <td width="10%" class="listhdr"><?=gettext("Logs");?></td> <td width="10%" class="listhdr"><?=gettext("Graphs");?></td> <td width="10%" class="list"><a href="status_mail_report_edit.php"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a></td> </tr> @@ -86,6 +88,8 @@ include("head.inc"); <tr ondblclick="document.location='status_mail_report_edit.php?id=<?=$i;?>'"> <td class="listlr"><?php echo $mailreport['descr']; ?></td> <td class="listlr"><?php echo $mailreport['schedule_friendly']; ?></td> + <td class="listlr"><?php echo count($mailreport['cmd']['row']); ?></td> + <td class="listlr"><?php echo count($mailreport['log']['row']); ?></td> <td class="listlr"><?php echo count($mailreport['row']); ?></td> <td valign="middle" nowrap class="list"> <a href="status_mail_report_edit.php?id=<?=$i;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0"></a> @@ -95,7 +99,7 @@ include("head.inc"); </tr> <?php $i++; endforeach; ?> <tr> - <td class="list" colspan="3"></td> + <td class="list" colspan="5"></td> <td class="list"><a href="status_mail_report_edit.php"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a></td> </tr> <tr> diff --git a/config/mailreport/status_mail_report_add_cmd.php b/config/mailreport/status_mail_report_add_cmd.php new file mode 100644 index 00000000..7693f7a4 --- /dev/null +++ b/config/mailreport/status_mail_report_add_cmd.php @@ -0,0 +1,146 @@ +<?php +/* $Id$ */ +/* + status_rrd_graph.php + Part of pfSense + Copyright (C) 2011 Jim Pingle <jimp@pfsense.org> + Portions Copyright (C) 2007-2011 Seth Mos <seth.mos@dds.nl> + 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. +*/ +/* + pfSense_MODULE: system +*/ + +##|+PRIV +##|*IDENT=page-status-rrdgraphs +##|*NAME=Status: RRD Graphs page +##|*DESCR=Allow access to the 'Status: RRD Graphs' page. +##|*MATCH=status_rrd_graph.php* +##|-PRIV + +require("guiconfig.inc"); +require_once("mail_reports.inc"); + +$reportid = $_REQUEST['reportid']; +$id = $_REQUEST['id']; + +if (!is_array($config['mailreports']['schedule'])) + $config['mailreports']['schedule'] = array(); + +$a_mailreports = &$config['mailreports']['schedule']; + +if (!isset($reportid) || !isset($a_mailreports[$reportid])) { + header("Location: status_mail_report.php"); + return; +} + +if (!is_array($a_mailreports[$reportid]['cmd']['row'])) { + $a_mailreports[$reportid]['cmd'] = array(); + $a_mailreports[$reportid]['cmd']['row'] = array(); +} +$a_cmds = $a_mailreports[$reportid]['cmd']['row']; + +if (isset($id) && $a_cmds[$id]) { + $pconfig = $a_cmds[$id]; +} else { + $pconfig = array(); +} + +if (isset($id) && !($a_cmds[$id])) { + header("Location: status_mail_report_edit.php?id={$reportid}"); + return; +} + +if ($_POST) { + unset($_POST['__csrf_magic']); + $pconfig = $_POST; + + if (isset($id) && $a_cmds[$id]) + $a_cmds[$id] = $pconfig; + else + $a_cmds[] = $pconfig; + + $a_mailreports[$reportid]['cmd']['row'] = $a_cmds; + + write_config(); + header("Location: status_mail_report_edit.php?id={$reportid}"); + return; +} + + +$pgtitle = array(gettext("Status"),gettext("Add Mail Report Command")); +include("head.inc"); +?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td><div id="mainarea"> + <form action="status_mail_report_add_cmd.php" method="post" name="iform" id="iform"> + <table class="tabcont" width="100%" border="0" cellpadding="1" cellspacing="1"> + <tr> + <td class="listtopic" colspan="2">Command Settings</td> + </tr> + <tr> + <td width="20%" class="listhdr"> + <?=gettext("Name:");?> + </td> + <td width="80%" class="listhdr"> + <input name="descr" type="text" class="formfld unknown" id="descr" size="20" value="<?=htmlspecialchars($pconfig['descr']);?>"> + </td> + </tr> + <tr> + <td class="listhdr"> + <?=gettext("Command:");?> + </td> + <td class="listhdr"> + <input name="detail" type="text" class="formfld unknown" id="detail" size="60" value="<?=htmlspecialchars($pconfig['detail']);?>"> + </td> + </tr> + <tr> + <td> </td> + <td> + <br/>NOTE: Use full paths to commands to ensure they run properly. The command will be run during the report and its stdout output will be included in the report body. Be extremely careful what commands you choose to run, the same warnings apply as those when using Diagnostics > Command. + <br/> + <br/>Do not use this solely as a way to run a command on a schedule, use the Cron package for that purpose instead. + </td> + </tr> + <tr> + <td colspan="2" align="center"> + <input name="Submit" type="submit" class="formbtn" value="<?=gettext("Save");?>"> + <a href="status_mail_report_edit.php?id=<?php echo $reportid;?>"><input name="cancel" type="button" class="formbtn" value="<?=gettext("Cancel");?>"></a> + <input name="reportid" type="hidden" value="<?=htmlspecialchars($reportid);?>"> + <?php if (isset($id) && $a_graphs[$id]): ?> + <input name="id" type="hidden" value="<?=htmlspecialchars($id);?>"> + <?php endif; ?> + </td> + <td></td> + </tr> + </table> + </form> + </div></td></tr> +</table> + +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/mailreport/status_mail_report_add_graph.php b/config/mailreport/status_mail_report_add_graph.php index c0287367..165124f3 100644 --- a/config/mailreport/status_mail_report_add_graph.php +++ b/config/mailreport/status_mail_report_add_graph.php @@ -50,13 +50,8 @@ if(! isset($config['rrd']['enable'])) { header("Location: status_rrd_graph_settings.php"); } -$reportid = $_GET['reportid']; -if (isset($_POST['reportid'])) - $reportid = $_POST['reportid']; - -$id = $_GET['id']; -if (isset($_POST['id'])) - $id = $_POST['id']; +$reportid = $_REQUEST['reportid']; +$id = $_REQUEST['id']; if (!is_array($config['mailreports']['schedule'])) $config['mailreports']['schedule'] = array(); @@ -65,7 +60,7 @@ $a_mailreports = &$config['mailreports']['schedule']; if (!isset($reportid) || !isset($a_mailreports[$reportid])) { header("Location: status_mail_report.php"); - exit; + return; } if (!is_array($a_mailreports[$reportid]['row'])) @@ -80,7 +75,7 @@ if (isset($id) && $a_graphs[$id]) { if (isset($id) && !($a_graphs[$id])) { header("Location: status_mail_report_edit.php?id={$reportid}"); - exit; + return; } @@ -159,7 +154,7 @@ if ($_POST) { write_config(); header("Location: status_mail_report_edit.php?id={$reportid}"); - exit; + return; } diff --git a/config/mailreport/status_mail_report_add_log.php b/config/mailreport/status_mail_report_add_log.php new file mode 100644 index 00000000..75d092b5 --- /dev/null +++ b/config/mailreport/status_mail_report_add_log.php @@ -0,0 +1,162 @@ +<?php +/* $Id$ */ +/* + status_rrd_graph.php + Part of pfSense + Copyright (C) 2011 Jim Pingle <jimp@pfsense.org> + Portions Copyright (C) 2007-2011 Seth Mos <seth.mos@dds.nl> + 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. +*/ +/* + pfSense_MODULE: system +*/ + +##|+PRIV +##|*IDENT=page-status-rrdgraphs +##|*NAME=Status: RRD Graphs page +##|*DESCR=Allow access to the 'Status: RRD Graphs' page. +##|*MATCH=status_rrd_graph.php* +##|-PRIV + +require("guiconfig.inc"); +require_once("mail_reports.inc"); + +$reportid = $_REQUEST['reportid']; +$id = $_REQUEST['id']; + +if (!is_array($config['mailreports']['schedule'])) + $config['mailreports']['schedule'] = array(); + +$a_mailreports = &$config['mailreports']['schedule']; + +if (!isset($reportid) || !isset($a_mailreports[$reportid])) { + header("Location: status_mail_report.php"); + return; +} + +if (!is_array($a_mailreports[$reportid]['log']['row'])) { + $a_mailreports[$reportid]['log'] = array(); + $a_mailreports[$reportid]['log']['row'] = array(); +} +$a_logs = $a_mailreports[$reportid]['log']['row']; + +if (isset($id) && $a_logs[$id]) { + $pconfig = $a_logs[$id]; +} else { + $pconfig = array(); +} + +if (isset($id) && !($a_logs[$id])) { + header("Location: status_mail_report_edit.php?id={$reportid}"); + return; +} + +$logpath = "/var/log/"; +chdir($logpath); +$logfiles = glob("*.log"); + +sort($logfiles); + +if ($_POST) { + unset($_POST['__csrf_magic']); + $pconfig = $_POST; + + if (isset($id) && $a_logs[$id]) + $a_logs[$id] = $pconfig; + else + $a_logs[] = $pconfig; + + $a_mailreports[$reportid]['log']['row'] = $a_logs; + + write_config(); + header("Location: status_mail_report_edit.php?id={$reportid}"); + return; +} + + +$pgtitle = array(gettext("Status"),gettext("Add Mail Report Log")); +include("head.inc"); +?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td><div id="mainarea"> + <form action="status_mail_report_add_log.php" method="post" name="iform" id="iform"> + <table class="tabcont" width="100%" border="0" cellpadding="1" cellspacing="1"> + <tr> + <td class="listtopic" colspan="2">Log Settings</td> + </tr> + <tr> + <td width="20%" class="listhdr"> + <?=gettext("Logs:");?> + </td> + <td width="80%" class="listhdr"> + <select name="logfile" class="formselect" style="z-index: -10;"> + <?php + foreach ($logfiles as $logfile) { + echo "<option value=\"{$logfile}\""; + if ($pconfig['logfile'] == $logfile) { + echo " selected"; + } + echo ">" . htmlspecialchars(get_friendly_log_name($logfile)) . "</option>\n"; + } + ?> + </select> + </td> + </tr> + <tr> + <td width="20%" class="listhdr"> + <?=gettext("# Rows:");?> + </td> + <td width="80%" class="listhdr"> + <input name="lines" type="text" class="formfld unknown" id="lines" size="10" value="<?=htmlspecialchars($pconfig['lines']);?>"> + </td> + </tr> + <tr> + <td class="listhdr"> + <?=gettext("Filter:");?> + </td> + <td class="listhdr"> + <input name="detail" type="text" class="formfld unknown" id="detail" size="60" value="<?=htmlspecialchars($pconfig['detail']);?>"> + </td> + </tr> + <tr> + <td colspan="2" align="center"> + <input name="Submit" type="submit" class="formbtn" value="<?=gettext("Save");?>"> + <a href="status_mail_report_edit.php?id=<?php echo $reportid;?>"><input name="cancel" type="button" class="formbtn" value="<?=gettext("Cancel");?>"></a> + <input name="reportid" type="hidden" value="<?=htmlspecialchars($reportid);?>"> + <?php if (isset($id) && $a_logs[$id]): ?> + <input name="id" type="hidden" value="<?=htmlspecialchars($id);?>"> + <?php endif; ?> + </td> + <td></td> + </tr> + </table> + </form> + </div></td></tr> +</table> + +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/mailreport/status_mail_report_edit.php b/config/mailreport/status_mail_report_edit.php index 3102e958..7ddb4c36 100644 --- a/config/mailreport/status_mail_report_edit.php +++ b/config/mailreport/status_mail_report_edit.php @@ -44,16 +44,13 @@ require_once("mail_reports.inc"); /* if the rrd graphs are not enabled redirect to settings page */ if(! isset($config['rrd']['enable'])) { header("Location: status_rrd_graph_settings.php"); - exit; + return; } -$graphid = $_GET['graphid']; -if (isset($_POST['graphid'])) - $graphid = $_POST['graphid']; - -$id = $_GET['id']; -if (isset($_POST['id'])) - $id = $_POST['id']; +$cmdid = $_REQUEST['cmdid']; +$logid = $_REQUEST['logid']; +$graphid = $_REQUEST['graphid']; +$id = $_REQUEST['id']; if (!is_array($config['mailreports']['schedule'])) $config['mailreports']['schedule'] = array(); @@ -63,19 +60,40 @@ if (isset($id) && $a_mailreports[$id]) { if (!is_array($a_mailreports[$id]['row'])) $a_mailreports[$id]['row'] = array(); $pconfig = $a_mailreports[$id]; + $a_cmds = $a_mailreports[$id]['cmd']['row']; + $a_logs = $a_mailreports[$id]['log']['row']; $a_graphs = $a_mailreports[$id]['row']; -} else { +} + +if (!is_array($pconfig)) $pconfig = array(); +if (!is_array($a_cmds)) + $a_cmds = array(); +if (!is_array($a_logs)) + $a_logs = array(); +if (!is_array($a_graphs)) $a_graphs = array(); -} + if ($_GET['act'] == "del") { - if ($a_graphs[$graphid]) { + if (is_numeric($cmdid) && $a_cmds[$cmdid]) { + unset($a_cmds[$cmdid]); + $a_mailreports[$id]['cmd']['row'] = $a_cmds; + write_config(); + header("Location: status_mail_report_edit.php?id={$id}"); + return; + } elseif (is_numeric($logid) && $a_logs[$logid]) { + unset($a_logs[$logid]); + $a_mailreports[$id]['log']['row'] = $a_logs; + write_config(); + header("Location: status_mail_report_edit.php?id={$id}"); + return; + } elseif (is_numeric($graphid) && $a_graphs[$graphid]) { unset($a_graphs[$graphid]); $a_mailreports[$id]['row'] = $a_graphs; write_config(); header("Location: status_mail_report_edit.php?id={$id}"); - exit; + return; } } @@ -97,7 +115,7 @@ if ($_POST) { if ($_POST['Submit'] == "Send Now") { mwexec_bg("/usr/local/bin/mail_reports_generate.php {$id}"); header("Location: status_mail_report_edit.php?id={$id}"); - exit; + return; } $friendly = ""; @@ -124,7 +142,9 @@ if ($_POST) { unset($pconfig['dayofmonth']); } - // Copy graphs back into the schedule. + // Copy back into the schedule. + $pconfig['cmd']["row"] = $a_cmds; + $pconfig['log']["row"] = $a_logs; $pconfig["row"] = $a_graphs; $pconfig['schedule_friendly'] = $friendly; @@ -139,7 +159,7 @@ if ($_POST) { write_config(); configure_cron(); header("Location: status_mail_report.php"); - exit; + return; } $pgtitle = array(gettext("Status"),gettext("Edit Mail Reports")); @@ -220,6 +240,78 @@ include("head.inc"); <td></td> </tr> <tr> + <td class="listtopic" colspan="4">Report Commands</td> + <td></td> + </tr> + <tr> + <td width="30%" class="listhdr"><?=gettext("Name");?></td> + <td width="60%" colspan="3" class="listhdr"><?=gettext("Command");?></td> + <td width="10%" class="list"> + <?php if (isset($id) && $a_mailreports[$id]): ?> + <a href="status_mail_report_add_cmd.php?reportid=<?php echo $id ;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a> + </td> + <?php else: ?> + </td> + <tr><td colspan="5" align="center"><br/>Save the report first, then items may be added.<br/></td></tr> + <?php endif; ?> + </tr> + <?php $i = 0; foreach ($a_cmds as $cmd): ?> + <tr ondblclick="document.location='status_mail_report_add_cmd.php?reportid=<?php echo $id ;?>&id=<?=$i;?>'"> + <td class="listlr"><?php echo htmlspecialchars($cmd['descr']); ?></td> + <td colspan="3" class="listlr"><?php echo htmlspecialchars($cmd['detail']); ?></td> + <td valign="middle" nowrap class="list"> + <a href="status_mail_report_add_cmd.php?reportid=<?php echo $id ;?>&id=<?=$i;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0"></a> + + <a href="status_mail_report_edit.php?act=del&id=<?php echo $id ;?>&cmdid=<?=$i;?>" onclick="return confirm('<?=gettext("Do you really want to delete this entry?");?>')"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0"></a> + </td> + </tr> + <?php $i++; endforeach; ?> + <tr> + <td class="list" colspan="4"></td> + <td class="list"> + <?php if (isset($id) && $a_mailreports[$id]): ?> + <a href="status_mail_report_add_cmd.php?reportid=<?php echo $id ;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a> + <?php endif; ?> + </td> + </tr> + <tr> + <td class="listtopic" colspan="4">Report Logs</td> + <td></td> + </tr> + <tr> + <td width="30%" class="listhdr"><?=gettext("Log");?></td> + <td width="20%" class="listhdr"><?=gettext("# Rows");?></td> + <td width="40%" colspan="2" class="listhdr"><?=gettext("Filter");?></td> + <td width="10%" class="list"> + <?php if (isset($id) && $a_mailreports[$id]): ?> + <a href="status_mail_report_add_log.php?reportid=<?php echo $id ;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a> + </td> + <?php else: ?> + </td> + <tr><td colspan="5" align="center"><br/>Save the report first, then items may be added.<br/></td></tr> + <?php endif; ?> + </tr> + <?php $i = 0; foreach ($a_logs as $log): ?> + <tr ondblclick="document.location='status_mail_report_add_log.php?reportid=<?php echo $id ;?>&id=<?=$i;?>'"> + <td class="listlr"><?php echo get_friendly_log_name($log['logfile']); ?></td> + <td class="listlr"><?php echo $log['lines']; ?></td> + <td colspan="2" class="listlr"><?php echo $log['detail']; ?></td> + <td valign="middle" nowrap class="list"> + <a href="status_mail_report_add_cmd.php?reportid=<?php echo $id ;?>&id=<?=$i;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0"></a> + + <a href="status_mail_report_edit.php?act=del&id=<?php echo $id ;?>&logid=<?=$i;?>" onclick="return confirm('<?=gettext("Do you really want to delete this entry?");?>')"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0"></a> + </td> + </tr> + <?php $i++; endforeach; ?> + <tr> + <td class="list" colspan="4"></td> + <td class="list"> + <?php if (isset($id) && $a_mailreports[$id]): ?> + <a href="status_mail_report_add_log.php?reportid=<?php echo $id ;?>"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a> + <?php endif; ?> + </td> + </tr> + <tr> <td class="listtopic" colspan="4">Report Graphs</td> <td></td> </tr> @@ -234,7 +326,7 @@ include("head.inc"); </td> <?php else: ?> </td> - <tr><td colspan="5" align="center"><br/>Save the report first, then you may add graphs.<br/></td></tr> + <tr><td colspan="5" align="center"><br/>Save the report first, then items may be added.<br/></td></tr> <?php endif; ?> </tr> <?php $i = 0; foreach ($a_graphs as $graph): @@ -246,7 +338,7 @@ include("head.inc"); } $prettyprint = ucwords(implode(" :: ", $optionc)); ?> - <tr ondblclick="document.location='status_mail_report_edit.php?id=<?=$i;?>'"> + <tr ondblclick="document.location='status_mail_report_add_graph.php?reportid=<?php echo $id ;?>&id=<?=$i;?>'"> <td class="listlr"><?php echo $prettyprint; ?></td> <td class="listlr"><?php echo $graph['style']; ?></td> <td class="listlr"><?php echo $graph['timespan']; ?></td> diff --git a/config/mailscanner/mailscanner.inc b/config/mailscanner/mailscanner.inc index 32cecf4f..1ba0a4ca 100644 --- a/config/mailscanner/mailscanner.inc +++ b/config/mailscanner/mailscanner.inc @@ -2,16 +2,16 @@ /* postfix.inc part of the Postfix package for pfSense - Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho 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, + 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 + 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. @@ -32,6 +32,12 @@ require_once("util.inc"); require("globals.inc"); #require("guiconfig.inc"); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('MAILSCANNER_LOCALBASE', '/usr/pbi/mailscanner-' . php_uname("m")); +else + define('MAILSCANNER_LOCALBASE','/usr/local'); + $uname=posix_uname(); if ($uname['machine']=='amd64') ini_set('memory_limit', '250M'); @@ -40,7 +46,7 @@ function ms_text_area_decode($text){ return preg_replace('/\r\n/', "\n",base64_decode($text)); } -function sync_package_mailscanner() { +function sync_package_mailscanner($via_rpc=false) { global $config; # detect boot process @@ -51,7 +57,7 @@ function sync_package_mailscanner() { $boot_process="on"; } exec('/bin/pgrep -f MailScanner',$pgrep_out); - if (count($pgrep_out) > 0 && isset($boot_process)) + if (count($pgrep_out) > 0 && isset($boot_process) && $via_rpc==false) return; #check default config @@ -254,7 +260,7 @@ function sync_package_mailscanner() { Language Strings = %report-dir%/languages.conf */ #check files - $mailscanner_dir="/usr/local/etc/MailScanner"; + $mailscanner_dir=MAILSCANNER_LOCALBASE ."/etc/MailScanner"; if($attachments['filename_rules'] == ""){ $config['installedpackages']['msattachments']['config'][0]['filename_rules']=base64_encode(file_get_contents($mailscanner_dir.'/archives.filename.rules.conf.sample')); @@ -303,7 +309,7 @@ Language Strings = %report-dir%/languages.conf $load_samples++; } - $report_dir="/usr/local/share/MailScanner/reports/".strtolower($report['language']); + $report_dir=MAILSCANNER_LOCALBASE."/share/MailScanner/reports/".strtolower($report['language']); #CHECK REPORT FILES $report_files= array('deletedbadcontent' => 'deleted.content.message.txt', 'deletedbadfilename' => 'deleted.filename.message.txt', @@ -387,9 +393,9 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf chown ('/var/spool/postfix','postfix'); $mlang=strtolower($report['language']); - $mfiles[]="/usr/local/etc/MailScanner/virus.scanners.conf"; - $mfiles[]="/usr/local/share/MailScanner/reports/{$mlang}/inline.spam.warning.txt"; - $mfiles[]="/usr/local/share/MailScanner/reports/{$mlang}/languages.conf"; + $mfiles[]= MAILSCANNER_LOCALBASE. "/etc/MailScanner/virus.scanners.conf"; + $mfiles[]= MAILSCANNER_LOCALBASE. "/share/MailScanner/reports/{$mlang}/inline.spam.warning.txt"; + $mfiles[]= MAILSCANNER_LOCALBASE. "/share/MailScanner/reports/{$mlang}/languages.conf"; foreach ($mfiles as $mfile) if (! file_exists ($mfile) && file_exists($mfile.".sample")) @@ -512,7 +518,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf file_put_contents($report_dir.'/inline.warning.html',$warning_html,LOCK_EX); #check virus_scanner options - $libexec_dir="/usr/local/libexec/MailScanner/"; + $libexec_dir=MAILSCANNER_LOCALBASE. "/libexec/MailScanner/"; if ($virus_scanning == "yes"){ if ($antivirus['virus_scanner'] =="none"){ unlink_if_exists($libexec_dir.'clamav-autoupdate'); @@ -544,7 +550,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf chmod ($libexec_dir.'clamav-autoupdate',0755); if (!file_exists('/var/db/clamav/main.cvd')){ log_error('No clamav database found, running freshclam in background.'); - mwexec_bg('/usr/local/bin/freshclam'); + mwexec_bg(MAILSCANNER_LOCALBASE. '/bin/freshclam'); } #clamav-wrapper file @@ -558,7 +564,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } #freshclam conf file - $cconf="/usr/local/etc/freshclam.conf"; + $cconf=MAILSCANNER_LOCALBASE. "/etc/freshclam.conf"; if (file_exists($conf)){ $cconf_file=file_get_contents($cconf); if (preg_match('/DatabaseOwner clamav/',$cconf_file)){ @@ -568,7 +574,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } #clamd conf file - $cconf="/usr/local/etc/clamd.conf"; + $cconf=MAILSCANNER_LOCALBASE. "/etc/clamd.conf"; if (file_exists($conf)){ $cconf_file=file_get_contents($cconf); if (preg_match('/User clamav/',$cconf_file)){ @@ -577,7 +583,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } } #clamd script file - $script='/usr/local/etc/rc.d/clamav-clamd'; + $script=MAILSCANNER_LOCALBASE. '/etc/rc.d/clamav-clamd'; if (file_exists($script)){ $script_file=file($script); foreach ($script_file as $script_line){ @@ -618,7 +624,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } #check dcc config file - $script='/usr/local/dcc/dcc_conf'; + $script=MAILSCANNER_LOCALBASE. '/dcc/dcc_conf'; if (file_exists($script)){ $script_file=file_get_contents($script); if (preg_match('/DCCIFD_ENABLE=off/',$script_file)){ @@ -628,7 +634,7 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } #check dcc startup script - $script='/usr/local/etc/rc.d/dccifd'; + $script=MAILSCANNER_LOCALBASE. '/etc/rc.d/dccifd'; if (file_exists($script)){ $script_file=file_get_contents($script); if (preg_match('/NO/',$script_file)){ @@ -655,13 +661,13 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf } } - $script='/usr/local/etc/rc.d/mailscanner'; + $script=MAILSCANNER_LOCALBASE. '/etc/rc.d/mailscanner'; #fix MIME::ToolUtils deprecated function and usecure dependency calls in /usr/local/sbin/mailscanner - $cconf="/usr/local/sbin/mailscanner"; + $cconf=MAILSCANNER_LOCALBASE. "/sbin/mailscanner"; if (file_exists($cconf)){ #check perl's version - exec('find /usr/local/lib/perl5/site_perl -name Df.pm',$find_out); + exec('find '.MAILSCANNER_LOCALBASE. '/lib/perl5/site_perl -name Df.pm',$find_out); $perl_bin="perl"; foreach($find_out as $perl_dir){ if (preg_match ('@usr/local/lib/perl5/site_perl/([.0-9]+)/mach/Filesys/Df.pm@',$perl_dir,$perl_match)) @@ -671,12 +677,12 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf $cconf_file=file_get_contents($cconf); $pattern2[0]='@#!/usr.*bin/perl.*I@'; $pattern2[1]='/\smy .current = config MIME::ToolUtils/'; - $replacement2[0]='#!/usr/local/bin/'.$perl_bin.' -U -I'; + $replacement2[0]='#!'.MAILSCANNER_LOCALBASE. "/bin/{$perl_bin} -U -I"; $replacement2[1]=' #my $current = config MIME::ToolUtils'; if (preg_match('@#!/usr.*bin/perl.*I@',$cconf_file)){ $cconf_file=preg_replace($pattern2,$replacement2,$cconf_file); file_put_contents($cconf, $cconf_file, LOCK_EX); - } + } } if (file_exists($script)){ $script_file=file_get_contents($script); @@ -711,22 +717,56 @@ Country Sub-Domains List = %etc-dir%/country.domains.conf if (isset($boot_process)) return; - $synconchanges = $config['installedpackages']['mailscannersync']['config'][0]['synconchanges']; - if(!$synconchanges && !$syncondbchanges) - return; - - log_error("[MailScanner] mailscanner_xmlrpc_sync.php is starting."); - foreach ($config['installedpackages']['mailscannersync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - $sync_to_ip = $sh['ipaddress']; - $password = $sh['password']; - $sync_type = $sh['sync_type']; - if($password && $sync_to_ip) - mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type); + /* Uses XMLRPC to synchronize the changes to a remote node */ + if (is_array($config['installedpackages']['mailscannersync'])){ + $mailscanner_sync=$config['installedpackages']['mailscannersync']['config'][0]; + $synctimeout = $mailscanner_sync['synctimeout']; + $synconchanges = $mailscanner_sync['synconchanges']; + switch ($synconchanges){ + case "manual": + if (is_array($mailscanner_sync[row])){ + $rs=$mailscanner_sync[row]; + } + else{ + log_error("[Mailscanner] xmlrpc sync is enabled but there is no hosts to push mailscanner config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + $rs[0]['enabless']=true; + if (! is_ipaddr($system_carp['synchronizetoip'])){ + log_error("[Mailscanner] xmlrpc sync is enabled but there is no system backup hosts to push mailscanner config."); + return; + } + } + else{ + log_error("[Mailscanner] xmlrpc sync is enabled but there is no system backup hosts to push mailscanner config."); + return; + } + break; + default: + return; + break; } - } - log_error("[postfix] postfix_xmlrpc_sync.php is ending."); - + if (is_array($rs)){ + log_error("[Mailscanner] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($sh['password'] && $sh['ipaddress'] && $sh['enabless']) + mailscanner_do_xmlrpc_sync($sh['ipaddress'], $username, $sh['password'],$sh['sync_type'],$synctimeout); + } + log_error("[Mailscanner] xmlrpc sync is ending."); + } + } } function mailscanner_validate_input($post, &$input_errors) { @@ -752,23 +792,29 @@ function mailscanner_php_install_command() { function mailscanner_php_deinstall_command() { exec('/bin/pgrep -f MailScanner',$pgrep_out); if (count($pgreg_out) > 0){ - mwexec("/usr/local/etc/rc.d/mailscanner stop"); + mwexec(MAILSCANNER_LOCALBASE. "/etc/rc.d/mailscanner stop"); sleep(1); conf_mount_rw(); - unlink_if_exists("/usr/local/etc/rc.d/mailscanner"); + unlink_if_exists(MAILSCANNER_LOCALBASE. "/etc/rc.d/mailscanner"); conf_mount_ro(); } } -function mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { +function mailscanner_do_xmlrpc_sync($sync_to_ip,$username,$password,$sync_type,$synctimeout) { global $config, $g; + if(!$username) + $username="admin"; + if(!$password) return; if(!$sync_to_ip) return; + if(!$synctimeout) + $synctimeout=120; + $xmlrpc_sync_neighbor = $sync_to_ip; if($config['system']['webgui']['protocol'] != "") { $synchronizetoip = $config['system']['webgui']['protocol']; @@ -809,18 +855,18 @@ function mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { $method = 'pfsense.merge_installedpackages_section_xmlrpc'; $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); + $cli->setCredentials($username, $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 250 seconds */ - $resp = $cli->send($msg, "250"); + /* send our XMLRPC message and timeout after $synctimeout seconds */ + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting mailscanner XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "Mailscanner Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting mailscanner XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "mailscanner Settings Sync", ""); @@ -831,7 +877,7 @@ function mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { /* tell postfix to reload our settings on the destionation sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/mailscanner.inc');\n"; - $execcmd .= "sync_package_mailscanner();"; + $execcmd .= "sync_package_mailscanner(true);"; /* assemble xmlrpc payload */ $params = array( @@ -842,15 +888,15 @@ function mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { log_error("mailscanner XMLRPC reload data {$url}:{$port}."); $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); - $resp = $cli->send($msg, "250"); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting mailscanner XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "mailscanner Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting mailscanner XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "mailscanner Settings Sync", ""); diff --git a/config/mailscanner/mailscanner_sync.xml b/config/mailscanner/mailscanner_sync.xml index da31e853..46f7dbfe 100644 --- a/config/mailscanner/mailscanner_sync.xml +++ b/config/mailscanner/mailscanner_sync.xml @@ -9,7 +9,7 @@ /* postfix_sync.xml part of the Postfix package for pfSense - Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho All rights reserved. */ /* ========================================================================== */ @@ -17,10 +17,10 @@ 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, + 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 + 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. @@ -90,10 +90,32 @@ <type>listtopic</type> </field> <field> - <fielddescr>Automatically sync mailscanner configuration changes</fielddescr> + <fielddescr>Sync method</fielddescr> <fieldname>synconchanges</fieldname> - <description>pfSense will automatically sync changes to the hosts defined below.</description> - <type>checkbox</type> + <description>Automatically sync postfix mailscanner changes.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr>Remote Server</fielddescr> @@ -101,6 +123,11 @@ <type>rowhelper</type> <rowhelper> <rowhelperfield> + <fielddescr>Enable</fielddescr> + <fieldname>enabless</fieldname> + <type>checkbox</type> + </rowhelperfield> + <rowhelperfield> <fielddescr>IP Address</fielddescr> <fieldname>ipaddress</fieldname> <description>IP Address of remote server</description> diff --git a/config/openbgpd/openbgpd.inc b/config/openbgpd/openbgpd.inc index eff2855b..e1619a55 100644 --- a/config/openbgpd/openbgpd.inc +++ b/config/openbgpd/openbgpd.inc @@ -3,7 +3,7 @@ /* $Id$ */ /* openbgpd.inc - Copyright (C) 2007 Scott Ullrich (sullrich@gmail.com) + Copyright (C) 2007 Scott Ullrich (sullrich@gmail.com) part of pfSense All rights reserved. @@ -63,127 +63,127 @@ function openbgpd_install_conf() { // Since we need to embed this in a string, copy to a var. Can't embed constnats. $bgpd_config_base = PKG_BGPD_CONFIG_BASE; - if ($config['installedpackages']['openbgpd']['rawconfig'] && $config['installedpackages']['openbgpd']['rawconfig']['item']) { - // if there is a raw config specified in the config.xml use that instead of the assisted config - $conffile = implode("\n",$config['installedpackages']['openbgpd']['rawconfig']['item']); - //$conffile = $config['installedpackages']['openbgpd']['rawconfig']; - } else { - // generate bgpd.conf based on the assistant - if($config['installedpackages']['openbgpd']['config']) - $openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0]; - if($config['installedpackages']['openbgpd']['config'][0]['row']) - $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; - if($config['installedpackages']['openbgpdgroups']['config']) - $openbgpd_groups = &$config['installedpackages']['openbgpdgroups']['config']; - if($config['installedpackages']['openbgpdneighbors']['config']) - $openbgpd_neighbors = &$config['installedpackages']['openbgpdneighbors']['config']; - - $conffile = "# This file was created by the package manager. Do not edit!\n\n"; - $setkeycf = ""; - - // Setup AS # - if($openbgpd_conf['asnum']) - $conffile .= "AS {$openbgpd_conf['asnum']}\n"; - - if($openbgpd_conf['fibupdate']) - $conffile .= "fib-update {$openbgpd_conf['fibupdate']}\n"; - - // Setup holdtime if defined. Default is 90. - if($openbgpd_conf['holdtime']) - $conffile .= "holdtime {$openbgpd_conf['holdtime']}\n"; - - // Specify listen ip - if($openbgpd_conf['listenip']) - $conffile .= "listen on {$openbgpd_conf['listenip']}\n"; - - // Specify router id - if($openbgpd_conf['routerid']) - $conffile .= "router-id {$openbgpd_conf['routerid']}\n"; - - // Handle advertised networks - if($config['installedpackages']['openbgpd']['config'][0]['row']) - if(is_array($openbgpd_rows)) - foreach($openbgpd_rows as $row) - $conffile .= "network {$row['networks']}\n"; - - // Attach neighbors to their respective group owner - if(is_array($openbgpd_groups)) { - foreach($openbgpd_groups as $group) { - $conffile .= "group \"{$group['name']}\" {\n"; - $conffile .= " remote-as {$group['remoteas']}\n"; - if(is_array($openbgpd_neighbors)) { - foreach($openbgpd_neighbors as $neighbor) { - if($neighbor['groupname'] == $group['name']) { - $conffile .= " neighbor {$neighbor['neighbor']} {\n"; - $conffile .= " descr \"{$neighbor['descr']}\"\n"; - $setkeycf .= "delete {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000;\n"; - if($neighbor['md5sigpass']) { - $setkeycf .= "add {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000 -A tcp-md5 \"{$neighbor['md5sigpass']}\";\n"; - $conffile .= " tcp md5sig password {$neighbor['md5sigpass']}\n"; - } - if($neighbor['md5sigkey']) { - $setkeycf .= "add {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000 -A tcp-md5 0x{$neighbor['md5sigkey']};\n"; - $conffile .= " tcp md5sig key {$neighbor['md5sigkey']}\n"; - } - foreach($neighbor['row'] as $row) { - $conffile .= " {$row['parameters']} {$row['parmvalue']} \n"; - } - $conffile .= "}\n"; - } - } - } - $conffile .= "}\n"; - } - } - - // Handle neighbors that do not have a group assigned to them - if(is_array($openbgpd_neighbors)) { - foreach($openbgpd_neighbors as $neighbor) { - $used_this_item = false; - if($neighbor['groupname'] == "") { - $conffile .= "neighbor {$neighbor['neighbor']} {\n"; - $conffile .= " descr \"{$neighbor['descr']}\"\n"; - $setkeycf .= "delete {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000;\n"; - if ($neighbor['md5sigpass']) { - $setkeycf .= "add {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000 -A tcp-md5 \"{$neighbor['md5sigpass']}\";\n"; - $conffile .= " tcp md5sig password {$neighbor['md5sigpass']}\n"; - } - if ($neighbor['md5sigkey']) { - $setkeycf .= "add {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000 -A tcp-md5 0x{$neighbor['md5sigkey']};\n"; - $conffile .= " tcp md5sig key {$neighbor['md5sigkey']}\n"; - } - $used_this_item = true; - foreach($neighbor['row'] as $row) { - $conffile .= " {$row['parameters']} {$row['parmvalue']} \n"; - } - } - if($used_this_item) - $conffile .= "}\n"; - } - } - - // OpenBGPD filters - $conffile .= "deny from any\n"; - $conffile .= "deny to any\n"; - if(is_array($openbgpd_neighbors)) { - foreach($openbgpd_neighbors as $neighbor) { - $conffile .= "allow from {$neighbor['neighbor']}\n"; - $conffile .= "allow to {$neighbor['neighbor']}\n"; - } - } - } - safe_mkdir($bgpd_config_base); - $fd = fopen("{$bgpd_config_base}/bgpd.conf", "w"); + if ($config['installedpackages']['openbgpd']['rawconfig'] && $config['installedpackages']['openbgpd']['rawconfig']['item']) { + // if there is a raw config specified in the config.xml use that instead of the assisted config + $conffile = implode("\n",$config['installedpackages']['openbgpd']['rawconfig']['item']); + //$conffile = $config['installedpackages']['openbgpd']['rawconfig']; + } else { + // generate bgpd.conf based on the assistant + if($config['installedpackages']['openbgpd']['config']) + $openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0]; + if($config['installedpackages']['openbgpd']['config'][0]['row']) + $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; + if($config['installedpackages']['openbgpdgroups']['config']) + $openbgpd_groups = &$config['installedpackages']['openbgpdgroups']['config']; + if($config['installedpackages']['openbgpdneighbors']['config']) + $openbgpd_neighbors = &$config['installedpackages']['openbgpdneighbors']['config']; + + $conffile = "# This file was created by the package manager. Do not edit!\n\n"; + + // Setup AS # + if($openbgpd_conf['asnum']) + $conffile .= "AS {$openbgpd_conf['asnum']}\n"; + + if($openbgpd_conf['fibupdate']) + $conffile .= "fib-update {$openbgpd_conf['fibupdate']}\n"; + + // Setup holdtime if defined. Default is 90. + if($openbgpd_conf['holdtime']) + $conffile .= "holdtime {$openbgpd_conf['holdtime']}\n"; + + // Specify listen ip + if($openbgpd_conf['listenip']) + $conffile .= "listen on {$openbgpd_conf['listenip']}\n"; + + // Specify router id + if($openbgpd_conf['routerid']) + $conffile .= "router-id {$openbgpd_conf['routerid']}\n"; + + // Handle advertised networks + if($config['installedpackages']['openbgpd']['config'][0]['row']) + if(is_array($openbgpd_rows)) + foreach($openbgpd_rows as $row) + $conffile .= "network {$row['networks']}\n"; + + // Attach neighbors to their respective group owner + if(is_array($openbgpd_groups)) { + foreach($openbgpd_groups as $group) { + $conffile .= "group \"{$group['name']}\" {\n"; + $conffile .= " remote-as {$group['remoteas']}\n"; + if(is_array($openbgpd_neighbors)) { + foreach($openbgpd_neighbors as $neighbor) { + if($neighbor['groupname'] == $group['name']) { + $conffile .= "\tneighbor {$neighbor['neighbor']} {\n"; + $conffile .= "\t\tdescr \"{$neighbor['descr']}\"\n"; + if($neighbor['md5sigpass']) { + $conffile .= "\t\ttcp md5sig password {$neighbor['md5sigpass']}\n"; + } + if($neighbor['md5sigkey']) { + $conffile .= "\t\ttcp md5sig key {$neighbor['md5sigkey']}\n"; + } + $setlocaladdr = true; + if (is_array($neighbor['row'])) { + foreach($neighbor['row'] as $row) { + if ($row['parameters'] == "local-address") + $setlocaladdr = false; + $conffile .= "\t\t{$row['parameters']} {$row['parmvalue']} \n"; + } + } + if ($setlocaladdr == true) + $conffile .= "\t\tlocal-address {$openbgpd_conf['listenip']}\n"; + $conffile .= "}\n"; + } + } + } + $conffile .= "}\n"; + } + } - // Write out the configuration file - fwrite($fd, $conffile); + // Handle neighbors that do not have a group assigned to them + if(is_array($openbgpd_neighbors)) { + foreach($openbgpd_neighbors as $neighbor) { + if($neighbor['groupname'] == "") { + $conffile .= "neighbor {$neighbor['neighbor']} {\n"; + $conffile .= "\tdescr \"{$neighbor['descr']}\"\n"; + if ($neighbor['md5sigpass']) { + $conffile .= "\ttcp md5sig password {$neighbor['md5sigpass']}\n"; + } + if ($neighbor['md5sigkey']) { + $conffile .= "\ttcp md5sig key {$neighbor['md5sigkey']}\n"; + } + $setlocaladdr = true; + if (is_array($neighbor['row'])) { + foreach($neighbor['row'] as $row) { + if ($row['parameters'] == "local-address") + $setlocaladdr = false; + $conffile .= "\t{$row['parameters']} {$row['parmvalue']} \n"; + } + } + if ($setlocaladdr == true) + $conffile .= "\tlocal-address {$openbgpd_conf['listenip']}\n"; + $conffile .= "}\n"; + } + } + } - // Close file handle - fclose($fd); + // OpenBGPD filters + $conffile .= "deny from any\n"; + $conffile .= "deny to any\n"; + if(is_array($openbgpd_neighbors)) { + foreach($openbgpd_neighbors as $neighbor) { + $conffile .= "allow from {$neighbor['neighbor']}\n"; + $conffile .= "allow to {$neighbor['neighbor']}\n"; + } + } + } + safe_mkdir($bgpd_config_base); + // Write out the configuration file + @file_put_contents("{$bgpd_config_base}/bgpd.conf", $conffile); + @chmod("{$bgpd_config_base}/bgpd.conf", 0600); // Create rc.d file $rc_file_stop = <<<EOF -killall -9 bgpd +killall -TERM bgpd EOF; $rc_file_start = <<<EOF @@ -195,12 +195,14 @@ if [ `pw usershow {$pkg_login} 2>&1 | grep -c "pw: no such user"` -gt 0 ]; then fi /bin/mkdir -p {$bgpd_config_base} -chmod u+rw,go-rw {$bgpd_config_base}/bgpd.conf /usr/sbin/chown -R root:wheel {$bgpd_config_base} +/bin/chmod 0600 {$bgpd_config_base}/bgpd.conf NUMBGPD=`ps auxw | grep -c '[b]gpd.*parent'` if [ \${NUMBGPD} -lt 1 ] ; then {$pkg_bin}/bgpd -f {$bgpd_config_base}/bgpd.conf +else + {$pkg_bin}/bgpctl reload fi EOF; write_rcfile(array( @@ -210,17 +212,11 @@ EOF; ) ); - // TCP-MD5 support on freebsd. See tcp(5) for more - $fd = fopen("{$g['tmp_path']}/bgpdsetkey.conf", "w"); - fwrite($fd, $setkeycf ); - fclose($fd); - exec("setkey -f {$g['tmp_path']}/bgpdsetkey.conf"); - // bgpd process running? if so reload, else start. if(is_openbgpd_running() == true) { - exec("bgpctl reload"); + exec("{$pkg_bin}/bgpctl reload"); } else { - exec("bgpd"); + exec("{$pkg_bin}/bgpd -f {$bgpd_config_base}/bgpd.conf"); } conf_mount_ro(); @@ -237,34 +233,19 @@ function openbgpd_get_raw_config() { // serialize the raw openbgpd config file to config.xml function openbgpd_put_raw_config($conffile) { - global $config; - if ($conffile == "") - unset($config['installedpackages']['openbgpd']['rawconfig']); - else { - $config['installedpackages']['openbgpd']['rawconfig'] = array(); - $config['installedpackages']['openbgpd']['rawconfig']['item'] = explode("\n",$_POST['openbgpd_raw']); - //$config['installedpackages']['openbgpd']['rawconfig'] = $conffile; - } + global $config; + if ($conffile == "") + unset($config['installedpackages']['openbgpd']['rawconfig']); + else { + $config['installedpackages']['openbgpd']['rawconfig'] = array(); + $config['installedpackages']['openbgpd']['rawconfig']['item'] = explode("\n",$_POST['openbgpd_raw']); + //$config['installedpackages']['openbgpd']['rawconfig'] = $conffile; + } } function deinstall_openbgpd() { global $config, $g; - if($config['installedpackages']['openbgpd']['config']) - $openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0]; - if($config['installedpackages']['openbgpdneighbors']['config']) - $openbgpd_neighbors = &$config['installedpackages']['openbgpdneighbors']['config']; - $setkeycf = ""; - if(is_array($openbgpd_neighbors)) { - foreach($openbgpd_neighbors as $neighbor) - $setkeycf .= "delete {$openbgpd_conf['listenip']} {$neighbor['neighbor']} tcp 0x1000;\n"; - } - // Clear all SADB entries used. - $fd = fopen("{$g['tmp_path']}/bgpdsetkey.conf", "w"); - fwrite($fd, $setkeycf ); - fclose($fd); - exec("setkey -f {$g['tmp_path']}/bgpdsetkey.conf"); - exec("rm /usr/local/etc/rc.d/bgpd.sh"); exec("rm /usr/local/www/openbgpd_status.php"); exec("killall bgpd"); @@ -369,4 +350,4 @@ function is_openbgpd_running() { return false; } -?>
\ No newline at end of file +?> diff --git a/config/openbgpd/openbgpd_neighbors.xml b/config/openbgpd/openbgpd_neighbors.xml index efa82384..5553c022 100644 --- a/config/openbgpd/openbgpd_neighbors.xml +++ b/config/openbgpd/openbgpd_neighbors.xml @@ -100,13 +100,13 @@ <field> <fielddescr>TCP-MD5 key</fielddescr> <fieldname>md5sigkey</fieldname> - <description>The md5 key to communicate with the peer. Does not work with Cisco BGP routers.</description> + <description>The md5 key to communicate with the peer. Does not work with Cisco BGP routers. If the Local Addr option is not set listening ip will be used.</description> <type>input</type> </field> <field> <fielddescr>TCP-MD5 password</fielddescr> <fieldname>md5sigpass</fieldname> - <description>The md5 password to communicate with the peer. Use this when communicating with a Cisco BGP router.</description> + <description>The md5 password to communicate with the peer. Use this when communicating with a Cisco BGP router. If the Local Addr option is not set listenning ip will be used.</description> <type>input</type> </field> <field> diff --git a/config/openbgpd/openbgpd_status.php b/config/openbgpd/openbgpd_status.php index 3db2781a..6b27b4de 100644 --- a/config/openbgpd/openbgpd_status.php +++ b/config/openbgpd/openbgpd_status.php @@ -60,8 +60,13 @@ function doCmdT($title, $command) { fclose($fd); } else { $fd = popen("{$command} 2>&1", "r"); + $ct = 0; while (($line = fgets($fd)) !== FALSE) { echo htmlspecialchars($line, ENT_NOQUOTES); + if ($ct++ > 1000) { + ob_flush(); + $ct = 0; + } } pclose($fd); } diff --git a/config/openvpn-client-export/openvpn-client-export.xml b/config/openvpn-client-export/openvpn-client-export.xml index 7eeebb0c..e70139a7 100755 --- a/config/openvpn-client-export/openvpn-client-export.xml +++ b/config/openvpn-client-export/openvpn-client-export.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="utf-8" ?> <packagegui> <name>OpenVPN Client Export</name> - <version>1.0.3</version> + <version>1.0.6</version> <title>OpenVPN Client Export</title> <include_file>/usr/local/pkg/openvpn-client-export.inc</include_file> <backup_file></backup_file> diff --git a/config/openvpn-client-export/vpn_openvpn_export.php b/config/openvpn-client-export/vpn_openvpn_export.php index fd2060ad..cfec87f7 100755 --- a/config/openvpn-client-export/vpn_openvpn_export.php +++ b/config/openvpn-client-export/vpn_openvpn_export.php @@ -542,7 +542,7 @@ function usepass_changed() { function useproxy_changed(obj) { if ((obj.id == "useproxy" && obj.checked) || - $(obj.id + 'pass').value != 'none') { + (obj.id == "useproxypass" && (obj.value != 'none'))) { $(obj.id + '_opts').show(); } else { $(obj.id + '_opts').hide(); @@ -781,7 +781,7 @@ function useproxy_changed(obj) { <span class="vexpl"> This will change the generated .ovpn configuration to allow for usage of the management interface. And include the OpenVPNManager program in the "Windows Installers". With this OpenVPN can be used also by non-administrator users. - This is also usefull for Windows7/Vista systems where elevated permissions are needed to add routes to the system. + This is also useful for Windows Vista/7/8 systems where elevated permissions are needed to add routes to the system. </span> </td> </tr> diff --git a/config/openvpn_tapfix_20x/openvpn_tapfix_203.patch b/config/openvpn_tapfix_20x/openvpn_tapfix_203.patch new file mode 100644 index 00000000..897a1199 --- /dev/null +++ b/config/openvpn_tapfix_20x/openvpn_tapfix_203.patch @@ -0,0 +1,290 @@ +diff --git /etc/inc/openvpn.inc.orig /etc/inc/openvpn.inc +index 777b395..701a032 100644 +--- a/etc/inc/openvpn.inc ++++ b/etc/inc/openvpn.inc +@@ -394,19 +394,37 @@ function openvpn_reconfigure($mode, $settings) { + // If the CIDR is less than a /30, OpenVPN will complain if you try to + // use the server directive. It works for a single client without it. + // See ticket #1417 +- if ($cidr < 30) { ++ if (!empty($ip) && !empty($mask) && ($cidr < 30)) { + $conf .= "server {$ip} {$mask}\n"; + $conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n"; + } + case 'p2p_shared_key': +- list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask); +- $conf .= "ifconfig $ip1 $ip2\n"; ++ if (!empty($ip) && !empty($mask)) { ++ list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask); ++ $conf .= "ifconfig $ip1 $ip2\n"; ++ } + break; + case 'server_tls': + case 'server_user': + case 'server_tls_user': +- $conf .= "server {$ip} {$mask}\n"; +- $conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n"; ++ if (!empty($ip) && !empty($mask)) { ++ $conf .= "server {$ip} {$mask}\n"; ++ $conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n"; ++ } else { ++ if ($settings['serverbridge_dhcp']) { ++ if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) { ++ $biface_ip=get_interface_ip($settings['serverbridge_interface']); ++ $biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface'])); ++ if (is_ipaddr($biface_ip) && is_ipaddr($settings['serverbridge_dhcp_start']) && is_ipaddr($settings['serverbridge_dhcp_end'])) { ++ $conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n"; ++ } else { ++ $conf .= "mode server\n"; ++ } ++ } else { ++ $conf .= "mode server\n"; ++ } ++ } ++ } + break; + } + +@@ -452,7 +452,9 @@ function openvpn_reconfigure($mode, $settings) { + case 'server_user': + $conf .= "client-cert-not-required\n"; + case 'server_tls_user': +- $conf .= "username-as-common-name\n"; ++ /* username-as-common-name is not compatible with server-bridge */ ++ if (stristr($conf, "server-bridge") === false) ++ $conf .= "username-as-common-name\n"; + if (!empty($settings['authmode'])) { + $authcfgs = explode(",", $settings['authmode']); + $sed = "\$authmodes=array("; + +diff --git /usr/local/www/vpn_openvpn_server.php.orig /usr/local/www/vpn_openvpn_server.php +index 0ef67a7..bd9f527 100644 +--- a/usr/local/www/vpn_openvpn_server.php ++++ b/usr/local/www/vpn_openvpn_server.php +@@ -147,6 +147,11 @@ if($_GET['act']=="edit"){ + $pconfig['dynamic_ip'] = $a_server[$id]['dynamic_ip']; + $pconfig['pool_enable'] = $a_server[$id]['pool_enable']; + ++ $pconfig['serverbridge_dhcp'] = $a_server[$id]['serverbridge_dhcp']; ++ $pconfig['serverbridge_interface'] = $a_server[$id]['serverbridge_interface']; ++ $pconfig['serverbridge_dhcp_start'] = $a_server[$id]['serverbridge_dhcp_start']; ++ $pconfig['serverbridge_dhcp_end'] = $a_server[$id]['serverbridge_dhcp_end']; ++ + $pconfig['dns_domain'] = $a_server[$id]['dns_domain']; + if ($pconfig['dns_domain']) + $pconfig['dns_domain_enable'] = true; +@@ -188,7 +193,6 @@ if($_GET['act']=="edit"){ + $pconfig['duplicate_cn'] = isset($a_server[$id]['duplicate_cn']); + } + } +- + if ($_POST) { + + unset($input_errors); +@@ -284,9 +288,22 @@ if ($_POST) { + $reqdfieldsn = array(gettext('Shared key')); + } + +- $reqdfields[] = 'tunnel_network'; +- $reqdfieldsn[] = gettext('Tunnel network'); +- ++ if ($pconfig['dev_mode'] != "tap") { ++ $reqdfields[] = 'tunnel_network'; ++ $reqdfieldsn[] = gettext('Tunnel network'); ++ } else { ++ if ($pconfig['serverbridge_dhcp'] && $pconfig['tunnel_network']) ++ $input_errors[] = gettext("Using a tunnel network and server bridge settings together is not allowed."); ++ if (($pconfig['serverbridge_dhcp_start'] && !$pconfig['serverbridge_dhcp_end']) ++ || (!$pconfig['serverbridge_dhcp_start'] && $pconfig['serverbridge_dhcp_end'])) ++ $input_errors[] = gettext("Server Bridge DHCP Start and End must both be empty, or defined."); ++ if (($pconfig['serverbridge_dhcp_start'] && !is_ipaddr($pconfig['serverbridge_dhcp_start']))) ++ $input_errors[] = gettext("Server Bridge DHCP Start must be an IPv4 address."); ++ if (($pconfig['serverbridge_dhcp_end'] && !is_ipaddr($pconfig['serverbridge_dhcp_end']))) ++ $input_errors[] = gettext("Server Bridge DHCP End must be an IPv4 address."); ++ if (ip2ulong($pconfig['serverbridge_dhcp_start']) > ip2ulong($pconfig['serverbridge_dhcp_end'])) ++ $input_errors[] = gettext("The Server Bridge DHCP range is invalid (start higher than end)."); ++ } + do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); + + if (!$input_errors) { +@@ -341,6 +358,11 @@ if ($_POST) { + $server['dynamic_ip'] = $pconfig['dynamic_ip']; + $server['pool_enable'] = $pconfig['pool_enable']; + ++ $server['serverbridge_dhcp'] = $pconfig['serverbridge_dhcp']; ++ $server['serverbridge_interface'] = $pconfig['serverbridge_interface']; ++ $server['serverbridge_dhcp_start'] = $pconfig['serverbridge_dhcp_start']; ++ $server['serverbridge_dhcp_end'] = $pconfig['serverbridge_dhcp_end']; ++ + if ($pconfig['dns_domain_enable']) + $server['dns_domain'] = $pconfig['dns_domain']; + +@@ -559,6 +581,56 @@ function netbios_change() { + } + } + ++function tuntap_change() { ++ ++ mindex = document.iform.mode.selectedIndex; ++ mvalue = document.iform.mode.options[mindex].value; ++ ++ switch(mvalue) { ++ case "p2p_tls": ++ case "p2p_shared_key": ++ p2p = true; ++ break; ++ default: ++ p2p = false; ++ break; ++ } ++ ++ index = document.iform.dev_mode.selectedIndex; ++ value = document.iform.dev_mode.options[index].value; ++ switch(value) { ++ case "tun": ++ document.getElementById("ipv4_tunnel_network").className="vncellreq"; ++ document.getElementById("serverbridge_dhcp").style.display="none"; ++ document.getElementById("serverbridge_interface").style.display="none"; ++ document.getElementById("serverbridge_dhcp_start").style.display="none"; ++ document.getElementById("serverbridge_dhcp_end").style.display="none"; ++ break; ++ case "tap": ++ document.getElementById("ipv4_tunnel_network").className="vncell"; ++ if (!p2p) { ++ document.getElementById("serverbridge_dhcp").style.display=""; ++ document.getElementById("serverbridge_interface").style.display=""; ++ document.getElementById("serverbridge_dhcp_start").style.display=""; ++ document.getElementById("serverbridge_dhcp_end").style.display=""; ++ if (document.iform.serverbridge_dhcp.checked) { ++ document.iform.serverbridge_interface.disabled = false; ++ document.iform.serverbridge_dhcp_start.disabled = false; ++ document.iform.serverbridge_dhcp_end.disabled = false; ++ } else { ++ document.iform.serverbridge_interface.disabled = true; ++ document.iform.serverbridge_dhcp_start.disabled = true; ++ document.iform.serverbridge_dhcp_end.disabled = true; ++ } ++ } else { ++ document.iform.serverbridge_dhcp.disabled = true; ++ document.iform.serverbridge_interface.disabled = true; ++ document.iform.serverbridge_dhcp_start.disabled = true; ++ document.iform.serverbridge_dhcp_end.disabled = true; ++ } ++ break; ++ } ++} + //--> + </script> + <?php +@@ -619,7 +691,7 @@ if ($savemsg) + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Server Mode");?></td> + <td width="78%" class="vtable"> +- <select name='mode' id='mode' class="formselect" onchange='mode_change()'> ++ <select name='mode' id='mode' class="formselect" onchange='mode_change(); tuntap_change()'> + <?php + foreach ($openvpn_server_modes as $name => $desc): + $selected = ""; +@@ -666,7 +738,7 @@ if ($savemsg) + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Device Mode"); ?></td> + <td width="78%" class="vtable"> +- <select name="dev_mode" class="formselect"> ++ <select name="dev_mode" class="formselect" onchange='tuntap_change()'> + <?php + foreach ($openvpn_dev_mode as $device): + $selected = ""; +@@ -976,7 +1048,7 @@ if ($savemsg) + <td colspan="2" valign="top" class="listtopic"><?=gettext("Tunnel Settings"); ?></td> + </tr> + <tr> +- <td width="22%" valign="top" class="vncellreq"><?=gettext("Tunnel Network"); ?></td> ++ <td width="22%" valign="top" class="vncellreq" id="ipv4_tunnel_network"><?=gettext("Tunnel Network"); ?></td> + <td width="78%" class="vtable"> + <input name="tunnel_network" type="text" class="formfld unknown" size="20" value="<?=htmlspecialchars($pconfig['tunnel_network']);?>"> + <br> +@@ -989,6 +1061,76 @@ if ($savemsg) + "to connecting clients. (see Address Pool)"); ?> + </td> + </tr> ++ <tr id="serverbridge_dhcp"> ++ <td width="22%" valign="top" class="vncell"><?=gettext("Bridge DHCP"); ?></td> ++ <td width="78%" class="vtable"> ++ <table border="0" cellpadding="2" cellspacing="0"> ++ <tr> ++ <td> ++ <?php set_checked($pconfig['serverbridge_dhcp'],$chk); ?> ++ <input name="serverbridge_dhcp" type="checkbox" value="yes" <?=$chk;?> onchange='tuntap_change()' /> ++ </td> ++ <td> ++ <span class="vexpl"> ++ <?=gettext("Allow clients on the bridge to obtain DHCP."); ?><br> ++ </span> ++ </td> ++ </tr> ++ </table> ++ </td> ++ </tr> ++ <tr id="serverbridge_interface"> ++ <td width="22%" valign="top" class="vncell"><?=gettext("Bridge Interface"); ?></td> ++ <td width="78%" class="vtable"> ++ <select name="serverbridge_interface" class="formselect"> ++ <?php ++ $serverbridge_interface['none'] = "none"; ++ $serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr()); ++ $carplist = get_configured_carp_interface_list(); ++ foreach ($carplist as $cif => $carpip) ++ $serverbridge_interface[$cif.'|'.$carpip] = $carpip." (".get_vip_descr($carpip).")"; ++ $aliaslist = get_configured_ip_aliases_list(); ++ foreach ($aliaslist as $aliasip => $aliasif) ++ $serverbridge_interface[$aliasif.'|'.$aliasip] = $aliasip." (".get_vip_descr($aliasip).")"; ++ foreach ($serverbridge_interface as $iface => $ifacename): ++ $selected = ""; ++ if ($iface == $pconfig['serverbridge_interface']) ++ $selected = "selected"; ++ ?> ++ <option value="<?=$iface;?>" <?=$selected;?>> ++ <?=htmlspecialchars($ifacename);?> ++ </option> ++ <?php endforeach; ?> ++ </select> <br> ++ <?=gettext("The interface to which this tap instance will be, " . ++ "bridged. This is not done automatically. You must assign this " . ++ "interface and create the bridge separately. " . ++ "This setting controls which existing IP address and subnet " . ++ "mask are used by OpenVPN for the bridge. Setting this to " . ++ "'none' will cause the Server Bridge DHCP settings below to be ignored."); ?> ++ </td> ++ </tr> ++ <tr id="serverbridge_dhcp_start"> ++ <td width="22%" valign="top" class="vncell"><?=gettext("Server Bridge DHCP Start"); ?></td> ++ <td width="78%" class="vtable"> ++ <input name="serverbridge_dhcp_start" type="text" class="formfld unknown" size="20" value="<?=htmlspecialchars($pconfig['serverbridge_dhcp_start']);?>"> ++ <br> ++ <?=gettext("When using tap mode as multi-point server, " . ++ "you may optionally supply a DHCP range to use on the " . ++ "interface to which this tap instance is bridged. " . ++ "If these settings are left blank, DHCP will be passed " . ++ "through to the LAN, and the interface setting above " . ++ "will be ignored."); ?> ++ </td> ++ </tr> ++ <tr id="serverbridge_dhcp_end"> ++ <td width="22%" valign="top" class="vncell"><?=gettext("Server Bridge DHCP End"); ?></td> ++ <td width="78%" class="vtable"> ++ <input name="serverbridge_dhcp_end" type="text" class="formfld unknown" size="20" value="<?=htmlspecialchars($pconfig['serverbridge_dhcp_end']);?>"> ++ <br> ++ <?=gettext(""); ?> ++ </td> ++ </tr> + <tr id="gwredir_opts"> + <td width="22%" valign="top" class="vncell"><?=gettext("Redirect Gateway"); ?></td> + <td width="78%" class="vtable"> +@@ -1486,6 +1628,7 @@ dns_server_change(); + wins_server_change(); + ntp_server_change(); + netbios_change(); ++tuntap_change(); + //--> + </script> + </body> diff --git a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.inc b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.inc index 197a5e25..8f574212 100644 --- a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.inc +++ b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.inc @@ -2,15 +2,22 @@ function openvpn_tapfix_20x_install() { global $g, $config; - + $pfs_version = substr(trim(file_get_contents("/etc/version")),0,5); + switch ($pfs_version) { + case "2.0.3": + $patch_file = "openvpn_tapfix_203.patch"; + break; + default: + $patch_file = "openvpn_tapfix_20x.patch"; + } // Test to make sure the patch is not already applied. - $out = `patch -fslC --reverse -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/openvpn_tapfix_20x.patch |& grep -ci reject`; + $out = `patch -fslC --reverse -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/{$patch_file} |& grep -ci reject`; if ($out == 0) { // If the patch has not already been applied, test to see if it will apply cleanly. - $out = `patch -fsNlC -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/openvpn_tapfix_20x.patch |& grep -ci reject`; + $out = `patch -fsNlC -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/{$patch_file} |& grep -ci reject`; if ($out == 0) { // The patch should apply cleanly, let 'er rip. - mwexec("patch -fsNl -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/openvpn_tapfix_20x.patch "); + mwexec("patch -fsNl -p1 -b .before_openvpn_tapfix_20x -d / -i /usr/local/pkg/{$patch_file} "); } } } diff --git a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.patch b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.patch index 35925ea8..ed4232bb 100644 --- a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.patch +++ b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.patch @@ -281,7 +281,7 @@ index 0ef67a7..bd9f527 100644 + </td> + </tr> + <tr id="serverbridge_dhcp_end"> -+ <td width="22%" valign="top" class="vncell"><?=gettext("Server Bridge DHCP Start"); ?></td> ++ <td width="22%" valign="top" class="vncell"><?=gettext("Server Bridge DHCP End"); ?></td> + <td width="78%" class="vtable"> + <input name="serverbridge_dhcp_end" type="text" class="formfld unknown" size="20" value="<?=htmlspecialchars($pconfig['serverbridge_dhcp_end']);?>"> + <br> diff --git a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.xml b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.xml index 17a59947..a9754610 100644 --- a/config/openvpn_tapfix_20x/openvpn_tapfix_20x.xml +++ b/config/openvpn_tapfix_20x/openvpn_tapfix_20x.xml @@ -46,7 +46,7 @@ <requirements>pfSense 2.0.x</requirements> <faq>None</faq> <name>OpenVPN tap Bridging Fix</name> - <version>0.1</version> + <version>0.4</version> <title>OpenVPN tap Bridging Fix</title> <include_file>/usr/local/pkg/openvpn_tapfix_20x.inc</include_file> <additional_files_needed> @@ -59,6 +59,11 @@ <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/openvpn_tapfix_20x/openvpn_tapfix_20x.patch</item> </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/openvpn_tapfix_20x/openvpn_tapfix_203.patch</item> + </additional_files_needed> <custom_php_install_command> openvpn_tapfix_20x_install(); </custom_php_install_command> diff --git a/config/pf-blocker/pfblocker.inc b/config/pf-blocker/pfblocker.inc index 58b93bb5..c40d742e 100755 --- a/config/pf-blocker/pfblocker.inc +++ b/config/pf-blocker/pfblocker.inc @@ -52,29 +52,6 @@ function cb_get_real_interface_address($iface) { return array($ip, long2ip(hexdec($netmask))); } -function pfblocker_Range2CIDR($ip_min, $ip_max) { - #function called without any args - if ($ip_min == "" || $ip_max == "") - return ""; - #function called with same ip in min and max - if ($ip_min == $ip_max) - return $ip_min. "/32"; - #convert ip to decimal numbers - $ip_min_long=ip2long($ip_min); - $ip_max_long=ip2long($ip_max); - #check long results - if ($ip_min_long == -1 || $ip_max_long == -1) - return ""; - #identify bits mask - $bits=(32 -strlen(decbin($ip_max_long - $ip_min_long))); - if ($bits < 0) - return ""; - #identify first ip on range network - $network=long2ip( $ip_min_long & ((1<<32)-(1<<(32-$bits))-1) ); - #print decbin($ip_min_long)."\n".$network."\n"; - return $network . "/". $bits; -} - function sync_package_pfblocker($cron="") { global $g,$config; @@ -290,10 +267,12 @@ function sync_package_pfblocker($cron="") { foreach ($url_list as $line){ # Network range 192.168.0.0-192.168.0.254 if (preg_match("/(\d+\.\d+\.\d+\.\d+)-(\d+\.\d+\.\d+\.\d+)/",$line,$matches)){ - $cidr= pfblocker_Range2CIDR($matches[1],$matches[2]); - if ($cidr != ""){ - ${$alias}.= $cidr."\n"; - $new_file.= $cidr."\n"; + $a_cidr = ip_range_to_subnet_array($matches[1],$matches[2]); + if (is_array($a_cidr)) { + foreach ($a_cidr as $cidr) { + ${$alias}.= $cidr."\n"; + $new_file.= $cidr."\n"; + } } } # CIDR format 192.168.0.0/16 diff --git a/config/phpsysinfo/phpsysinfo.xml b/config/phpsysinfo/phpsysinfo.xml index 3cbe4a5b..116643a4 100644 --- a/config/phpsysinfo/phpsysinfo.xml +++ b/config/phpsysinfo/phpsysinfo.xml @@ -75,7 +75,7 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/phpsysinfo/bin/phpsysinfo-2.5.4.tar.gz</item> + <item>http://files.pfsense.org/packages/phpsysinfo-2.5.4.tar.gz</item> </additional_files_needed> <fields> <field> diff --git a/config/postfix/postfix.inc b/config/postfix/postfix.inc index e64f8cca..4378a1f9 100644..100755 --- a/config/postfix/postfix.inc +++ b/config/postfix/postfix.inc @@ -3,14 +3,14 @@ postfix.inc part of the Postfix package for pfSense Copyright (C) 2010 Erik Fonnesbeck - Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho 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, + 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 @@ -34,6 +34,13 @@ require_once("functions.inc"); require_once("pkg-utils.inc"); require_once("globals.inc"); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('POSTFIX_LOCALBASE', '/usr/pbi/postfix-' . php_uname("m")); +else + define('POSTFIX_LOCALBASE','/usr/local'); + + $uname=posix_uname(); if ($uname['machine']=='amd64') ini_set('memory_limit', '250M'); @@ -57,7 +64,7 @@ function sync_relay_recipients($via_cron="cron"){ if ($config['installedpackages']['postfixrecipients']['config']) { $relay_recipients=""; $relay_ldap_recipients=""; - $ad_export="/usr/local/etc/postfix/adexport.pl"; + $ad_export= "/usr/local/bin/adexport.pl"; $postfix_enabled=$config['installedpackages']['postfix']['config'][0]['enable_postfix']; if (is_array($config['installedpackages']['postfixrecipients']['config'])) { $relay_ldap_recipients=""; @@ -73,7 +80,7 @@ function sync_relay_recipients($via_cron="cron"){ #validate cront job if ($via_cron == "gui"){ #running via pfsense gui, not time for ldap fetch. - $ldap_recipients='/usr/local/etc/postfix/relay_ldap_recipients.txt'; + $ldap_recipients= POSTFIX_LOCALBASE. '/etc/postfix/relay_ldap_recipients.txt'; if (!file_exists($ldap_recipients)) system('/usr/bin/touch '. $ldap_recipients); $relay_ldap_recipients=file_get_contents($ldap_recipients); @@ -83,7 +90,7 @@ function sync_relay_recipients($via_cron="cron"){ $ldap_temp=array(); foreach ($postfix_recipients_config['row'] as $postfix_ldap) { print "extracting from ".$postfix_ldap['dc']."..."; - $filename="/usr/local/etc/postfix/relay_ldap_recipients.".$postfix_ldap['dc'].".txt"; + $filename=POSTFIX_LOCALBASE."/etc/postfix/relay_ldap_recipients.".$postfix_ldap['dc'].".txt"; exec($ad_export." ".$postfix_ldap['dc']." ".$postfix_ldap['cn']." ".$postfix_ldap['username']." ".$postfix_ldap['password'],$ldap_fetch,$status); if ($status == 0){ #write backup conf for ldap server @@ -115,20 +122,20 @@ function sync_relay_recipients($via_cron="cron"){ $relay_ldap_recipients.=($recipient != ""?preg_replace("/\s+/","",$recipient)." OK\n":""); #save ldap relay recipients - file_put_contents("/usr/local/etc/postfix/relay_ldap_recipients.txt",$relay_ldap_recipients, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/relay_ldap_recipients.txt",$relay_ldap_recipients, LOCK_EX); } } } #save all relay recipients, remove duplicates and reload postfix - $recipients_file="/usr/local/etc/postfix/relay_recipients"; + $recipients_file=POSTFIX_LOCALBASE."/etc/postfix/relay_recipients"; file_put_contents($recipients_file.".unsort",$relay_ldap_recipients."\n".$relay_recipients, LOCK_EX); exec('/usr/bin/sort -u '.$recipients_file.'.unsort > '.$recipients_file); unlink_if_exists($recipients_file.'.unsort'); - exec("/usr/local/sbin/postmap /usr/local/etc/postfix/relay_recipients"); + exec(POSTFIX_LOCALBASE."/sbin/postmap ".POSTFIX_LOCALBASE."/etc/postfix/relay_recipients"); mwexec("/usr/local/sbin/postfix reload"); } if($relay_recipients !="" || $relay_ldap_recipients!="") - return("relay_recipient_maps = hash:/usr/local/etc/postfix/relay_recipients\n"); + return("relay_recipient_maps = hash:".POSTFIX_LOCALBASE."/etc/postfix/relay_recipients\n"); } function check_cron(){ @@ -137,7 +144,7 @@ function check_cron(){ $new_cron=array(); $cron_cmd_sqlite = ""; $cron_postfix_sqlite=""; - $cron_cmd="/usr/local/bin/php -q /usr/local/www/postfix_recipients.php"; + $cron_cmd= "/usr/local/bin/php -q /usr/local/www/postfix_recipients.php"; $postfix_enabled=$config['installedpackages']['postfix']['config'][0]['enable_postfix']; #check ldap update if (is_array($config['installedpackages']['postfixrecipients']['config'])) @@ -271,9 +278,10 @@ function check_cron(){ } -function sync_package_postfix() { +function sync_package_postfix($via_rpc="no") { global $config; + log_error("sync_package_postfix called with via_rpc={$via_rpc}"); # detect boot process if (is_array($_POST)){ if (preg_match("/\w+/",$_POST['__csrf_magic'])) @@ -282,7 +290,7 @@ function sync_package_postfix() { $boot_process="on"; } - if(is_process_running("master") && isset($boot_process)) + if(is_process_running("master") && isset($boot_process) && $via_rpc=="no") return; #check patch in /etc/inc/config. @@ -353,17 +361,23 @@ function sync_package_postfix() { $copyright=<<<ABOUT #Part of the Postfix package for pfSense #Copyright (C) 2010 Erik Fonnesbeck -#Copyright (C) 2011 Marcello Coutinho +#Copyright (C) 2011-2013 Marcello Coutinho #All rights reserved. #DO NOT EDIT THIS FILE ABOUT; +$pf_dir=POSTFIX_LOCALBASE; $postfix_main=<<<EOF #main.cf\ {$copyright} -mynetworks = /usr/local/etc/postfix/mynetwork_table +mynetworks = {$pf_dir}/etc/postfix/mynetwork_table mynetworks_style = host +access_map_reject_code= 554 +access_map_defer_code = 451 +unverified_recipient_reject_code = 550 +unknown_client_reject_code = 550 +unknown_hostname_reject_code = 550 EOF; #Header Maps @@ -373,22 +387,26 @@ EOF; } #Header Maps if ($config['installedpackages']['postfixacl']['config'][0]['header_maps']){ - $postfix_main .= "header_checks = pcre:/usr/local/etc/postfix/header_check\n"; + $postfix_main .= "header_checks = pcre:".POSTFIX_LOCALBASE."/etc/postfix/header_check\n"; $postfix_main .= "header_size_limit = 1024000\n"; $header_check = px_text_area_decode($config['installedpackages']['postfixacl']['config'][0]['header_maps']); } + #Helo Maps + if ($config['installedpackages']['postfixacl']['config'][0]['helo_maps']){ + $helo_check = px_text_area_decode($config['installedpackages']['postfixacl']['config'][0]['helo_maps']); + } #Sender access if ($config['installedpackages']['postfixacl']['config'][0]['sender_access']){ $sender_access = px_text_area_decode($config['installedpackages']['postfixacl']['config'][0]['sender_access']); } #MIME Maps if ($config['installedpackages']['postfixacl']['config'][0]['mime_maps']){ - $postfix_main .= "mime_header_checks = pcre:/usr/local/etc/postfix/mime_check\n"; + $postfix_main .= "mime_header_checks = pcre:".POSTFIX_LOCALBASE."/etc/postfix/mime_check\n"; $mime_check = px_text_area_decode($config['installedpackages']['postfixacl']['config'][0]['mime_maps']); } #Body Maps if ($config['installedpackages']['postfixacl']['config'][0]['body_maps']){ - $postfix_main .= "body_checks = pcre:/usr/local/etc/postfix/body_check\n"; + $postfix_main .= "body_checks = pcre:".POSTFIX_LOCALBASE."/etc/postfix/body_check\n"; $body_check = px_text_area_decode($config['installedpackages']['postfixacl']['config'][0]['body_maps']); } #Client CIDR @@ -406,7 +424,7 @@ EOF; } $postfix_main .= px_text_area_decode($postfix_config['maincf'])."\n". "relay_domains ={$relay_domains}\n" . - "transport_maps = hash:/usr/local/etc/postfix/transport\n" . + "transport_maps = hash:".POSTFIX_LOCALBASE."/etc/postfix/transport\n" . "local_recipient_maps =\n" . $all_relay_recipients. "mydestination =\n" . @@ -444,7 +462,16 @@ EOF; break; } } - $reject_unknown_helo_hostname=($antispam['reject_unknown_helo_hostname']?"reject_unknown_helo_hostname":""); + if ($antispam['reject_unknown_helo_hostname']){ + $reject_unknown_helo_hostname = <<<EOF +smtpd_helo_restrictions = check_helo_access pcre:{$pf_dir}/etc/postfix/helo_check, + reject_unknown_helo_hostname, + reject_invalid_helo_hostname, + reject_non_fqdn_helo_hostname, + permit + +EOF; + } if ($antispam['header_check'] == "strong") { $postfix_main .= <<<EOF @@ -456,7 +483,7 @@ smtpd_delay_reject = yes # Don't talk to mail systems that don't know their own hostname. smtpd_helo_required = yes -smtpd_helo_restrictions ={$reject_unknown_helo_hostname} +{$reject_unknown_helo_hostname} smtpd_sender_restrictions = reject_non_fqdn_sender, reject_unknown_sender_domain, @@ -467,8 +494,8 @@ smtpd_sender_restrictions = reject_non_fqdn_sender, # Allow connections from specified local clients and strong check everybody else. smtpd_client_restrictions = permit_mynetworks, reject_unauth_destination, - check_client_access pcre:/usr/local/etc/postfix/cal_pcre, - check_client_access cidr:/usr/local/etc/postfix/cal_cidr, + check_client_access pcre:{$pf_dir}/etc/postfix/cal_pcre, + check_client_access cidr:{$pf_dir}/etc/postfix/cal_cidr, reject_unknown_client_hostname, reject_unauth_pipelining, reject_multi_recipient_bounce, @@ -477,14 +504,14 @@ smtpd_client_restrictions = permit_mynetworks, smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, reject_unauth_pipelining, - check_client_access pcre:/usr/local/etc/postfix/cal_pcre, - check_client_access cidr:/usr/local/etc/postfix/cal_cidr, - check_sender_access hash:/usr/local/etc/postfix/sender_access, - reject_invalid_helo_hostname, + check_client_access pcre:{$pf_dir}/etc/postfix/cal_pcre, + check_client_access cidr:{$pf_dir}/etc/postfix/cal_cidr, + check_sender_access hash:{$pf_dir}/etc/postfix/sender_access, reject_non_fqdn_helo_hostname, reject_unknown_recipient_domain, reject_non_fqdn_recipient, reject_multi_recipient_bounce, + reject_unverified_recipient, SPFSPFSPFRBLRBLRBL EOF; @@ -497,7 +524,7 @@ smtpd_delay_reject = yes # Don't talk to mail systems that don't know their own hostname. smtpd_helo_required = yes -smtpd_helo_restrictions = {$reject_unknown_helo_hostname} +{$reject_unknown_helo_hostname} smtpd_sender_restrictions = reject_unknown_sender_domain, RBLRBLRBL @@ -505,18 +532,18 @@ smtpd_sender_restrictions = reject_unknown_sender_domain, # Allow connections from specified local clients and rbl check everybody else if rbl check are set. smtpd_client_restrictions = permit_mynetworks, reject_unauth_destination, - check_sender_access hash:/usr/local/etc/postfix/sender_access, - check_client_access pcre:/usr/local/etc/postfix/cal_pcre, - check_client_access cidr:/usr/local/etc/postfix/cal_cidr + check_sender_access hash:{$pf_dir}/etc/postfix/sender_access, + check_client_access pcre:{$pf_dir}/etc/postfix/cal_pcre, + check_client_access cidr:{$pf_dir}/etc/postfix/cal_cidr RBLRBLRBL # Whitelisting: local clients may specify any destination domain. #, smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, - check_sender_access hash:/usr/local/etc/postfix/sender_access, - check_client_access pcre:/usr/local/etc/postfix/cal_pcre, - check_client_access cidr:/usr/local/etc/postfix/cal_cidr, + check_sender_access hash:{$pf_dir}/etc/postfix/sender_access, + check_client_access pcre:{$pf_dir}/etc/postfix/cal_pcre, + check_client_access cidr:{$pf_dir}/etc/postfix/cal_cidr, SPFSPFSPFRBLRBLRBL EOF; @@ -578,7 +605,7 @@ switch ($antispam['zombie_blocker']) $postfix_main.="postscreen_greet_action = ".$antispam['zombie_blocker']."\n"; } - $postfix_main.="postscreen_access_list = permit_mynetworks,\n\t\t\tcidr:/usr/local/etc/postfix/cal_cidr\n"; + $postfix_main.="postscreen_access_list = permit_mynetworks,\n\t\t\tcidr:".POSTFIX_LOCALBASE."/etc/postfix/cal_cidr\n"; $postfix_main.="postscreen_dnsbl_action= ".$antispam['zombie_blocker']."\n"; $postfix_main.="postscreen_blacklist_action= ".$antispam['zombie_blocker']."\n"; @@ -670,20 +697,21 @@ MASTEREOF2; conf_mount_rw(); log_error("Writing out configuration"); - file_put_contents("/usr/local/etc/postfix/main.cf", $postfix_main, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/master.cf", $postfix_master, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/transport", $transport, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/sender_access", $sender_access, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/cal_cidr", $cal_cidr, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/cal_pcre", $cal_pcre, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/header_check", $header_check, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/mime_check", $mime_check, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/body_check", $body_check, LOCK_EX); - file_put_contents("/usr/local/etc/postfix/mynetwork_table", $mynetworks, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/main.cf", $postfix_main, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/master.cf", $postfix_master, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/transport", $transport, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/sender_access", $sender_access, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/cal_cidr", $cal_cidr, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/cal_pcre", $cal_pcre, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/header_check", $header_check, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/helo_check", $helo_check, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/mime_check", $mime_check, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/body_check", $body_check, LOCK_EX); + file_put_contents(POSTFIX_LOCALBASE."/etc/postfix/mynetwork_table", $mynetworks, LOCK_EX); $FILES=array("transport","sender_access"); foreach ($FILES as $file) { - mwexec("/usr/local/sbin/postmap /usr/local/etc/postfix/".$file); + mwexec(POSTFIX_LOCALBASE."/sbin/postmap ".POSTFIX_LOCALBASE."/etc/postfix/".$file); } #check postix dirs @@ -704,12 +732,13 @@ MASTEREOF2; postfix_start(); #Do not sync during boot - if(!isset($boot_process)) + if(!isset($boot_process) || $via_rpc=="yes") postfix_sync_on_changes(); } function postfix_start(){ global $config; + $pf_dir=POSTFIX_LOCALBASE; $start=<<<EOF sysctl kern.ipc.nmbclusters=65536 @@ -717,20 +746,18 @@ function postfix_start(){ sysctl kern.maxfiles=131072 sysctl kern.maxfilesperproc=104856 sysctl kern.threads.max_threads_per_proc=4096 - /usr/local/sbin/postfix start + {$pf_dir}/sbin/postfix start EOF; - $stop = "/usr/local/sbin/postfix stop\n"; + $stop = POSTFIX_LOCALBASE."/sbin/postfix stop\n"; log_error("Writing rc_file"); write_rcfile(array("file" => "postfix.sh", "start" => $start, "stop" => $stop)); - conf_mount_ro(); - sleep(1); - if ($config['installedpackages']['postfix']['config'][0]['enable_postfix']){ + if (is_array($config['installedpackages']['postfix']) && $config['installedpackages']['postfix']['config'][0]['enable_postfix']){ log_error("Reloading/starting postfix"); system('/bin/chmod +x /usr/local/etc/rc.d/postfix.sh'); - mwexec_bg("/usr/local/sbin/postfix reload || /usr/local/etc/rc.d/postfix.sh start"); + mwexec_bg(POSTFIX_LOCALBASE."/sbin/postfix reload || /usr/local/etc/rc.d/postfix.sh start"); log_error("Postfix setup completed"); } else{ @@ -738,6 +765,8 @@ EOF; mwexec("/usr/local/etc/rc.d/postfix.sh stop"); system('/bin/chmod -x /usr/local/etc/rc.d/postfix.sh'); } + + conf_mount_ro(); } function postfix_validate_input($post, &$input_errors) { @@ -773,7 +802,8 @@ function postfix_php_install_command() { function postfix_php_deinstall_command() { global $config; #disable service - $config['installedpackages']['postfix']['config'][0]['enable_postfix']=""; + if (is_array($config['installedpackages']['postfix'])) + $config['installedpackages']['postfix']['config'][0]['enable_postfix']=""; write_config(); sync_package_postfix(); conf_mount_rw(); @@ -783,33 +813,75 @@ function postfix_php_deinstall_command() { /* Uses XMLRPC to synchronize the changes to a remote node */ function postfix_sync_on_changes() { - global $config, $g; - $synconchanges = $config['installedpackages']['postfixsync']['config'][0]['synconchanges']; - $syncondbchanges= $config['installedpackages']['postfixsync']['config'][0]['rsync']; - if(!$synconchanges && !$syncondbchanges) - return; - log_error("[postfix] postfix_xmlrpc_sync.php is starting."); - foreach ($config['installedpackages']['postfixsync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - $sync_to_ip = $sh['ipaddress']; - $password = $sh['password']; - $sync_type = $sh['sync_type']; - if($password && $sync_to_ip) - postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type); + global $config, $g; + if (is_array($config['installedpackages']['postfixsync']['config'])){ + $postfix_sync=$config['installedpackages']['postfixsync']['config'][0]; + $synctimeout = $postfix_sync['synctimeout']; + $synconchanges = $postfix_sync['synconchanges']; + switch ($synconchanges){ + case "manual": + if (is_array($postfix_sync[row])){ + $rs=$postfix_sync[row]; + } + else{ + log_error("[postfix] xmlrpc sync is enabled but there is no hosts to push postfix config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + $rs[0]['enabless']=true; + $rs[0]['sync_type']="xmlrpc"; + if (! is_ipaddr($system_carp['synchronizetoip'])){ + log_error("[postfix] xmlrpc sync is enabled but there is no system backup hosts to push postfix config."); + return; + } + } + else{ + log_error("[postfix] xmlrpc sync is enabled but there is no system backup hosts to push postfix config."); + return; + } + break; + default: + return; + break; } - } - log_error("[postfix] postfix_xmlrpc_sync.php is ending."); + if (is_array($rs)){ + log_error("[postfix] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($sh['password'] && $sh['ipaddress'] && $sh['enabless']) + postfix_do_xmlrpc_sync($sh['ipaddress'], $username, $sh['password'],$sh['sync_type'],$synctimeout); + } + log_error("[postfix] xmlrpc sync is ending."); + } + } } + /* Do the actual XMLRPC sync */ -function postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { +function postfix_do_xmlrpc_sync($sync_to_ip,$username,$password,$sync_type,$synctimeout) { global $config, $g; + if(!$username) + $username="admin"; + if(!$password) return; if(!$sync_to_ip) return; + + if(!$synctimeout) + $synctimeout=120; $xmlrpc_sync_neighbor = $sync_to_ip; if($config['system']['webgui']['protocol'] != "") { @@ -851,18 +923,18 @@ function postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { $method = 'pfsense.merge_installedpackages_section_xmlrpc'; $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); + $cli->setCredentials($username, $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 250 seconds */ - $resp = $cli->send($msg, "250"); + /* send our XMLRPC message and timeout after $sync_timeout seconds */ + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting postfix XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "Postfix Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting postfix XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "Postfix Settings Sync", ""); @@ -873,7 +945,7 @@ function postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { /* tell postfix to reload our settings on the destionation sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/postfix.inc');\n"; - $execcmd .= "sync_package_postfix();"; + $execcmd .= "sync_package_postfix('yes');"; /* assemble xmlrpc payload */ $params = array( @@ -884,15 +956,15 @@ function postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { log_error("postfix XMLRPC reload data {$url}:{$port}."); $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); - $cli->setCredentials('admin', $password); - $resp = $cli->send($msg, "250"); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting postfix XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "postfix Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting postfix XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "postfix Settings Sync", ""); diff --git a/config/postfix/postfix.php b/config/postfix/postfix.php index ff42918c..a11af2dd 100644 --- a/config/postfix/postfix.php +++ b/config/postfix/postfix.php @@ -2,14 +2,14 @@ /* postfix.php part of pfSense (http://www.pfsense.com/) - Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> + Copyright (C) 2011-2013 Marcello Coutinho <marcellocoutinho@gmail.com> based on varnish_view_config. 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, + 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 diff --git a/config/postfix/postfix.xml b/config/postfix/postfix.xml index 51ddf601..25f7a81d 100644 --- a/config/postfix/postfix.xml +++ b/config/postfix/postfix.xml @@ -10,7 +10,7 @@ postfix.xml part of the Postfix package for pfSense Copyright (C) 2010 Erik Fonnesbeck - Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho All rights reserved. */ @@ -19,7 +19,7 @@ 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, + 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 @@ -142,7 +142,7 @@ </additional_files_needed> <additional_files_needed> <item>http://www.pfsense.org/packages/config/postfix/adexport.pl</item> - <prefix>/usr/local/etc/postfix/</prefix> + <prefix>/usr/local/bin/</prefix> <chmod>0755</chmod> </additional_files_needed> <tabs> diff --git a/config/postfix/postfix_acl.xml b/config/postfix/postfix_acl.xml index efc72721..4eeda7a4 100644 --- a/config/postfix/postfix_acl.xml +++ b/config/postfix/postfix_acl.xml @@ -5,11 +5,11 @@ <copyright> <![CDATA[ /* $Id$ */ -/* ========================================================================== */ +/* ========================================================================== */post /* postfix.xml part of the Postfix package for pfSense - Copyright (C) 2010 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho All rights reserved. */ /* ========================================================================== */ @@ -17,10 +17,10 @@ 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, + 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 + 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. @@ -115,6 +115,20 @@ <encoding>base64</encoding> </field> <field> + <fielddescr>Helo</fielddescr> + <fieldname>helo_maps</fieldname> + <description><![CDATA[<strong>PCRE filters</strong><a href=http://www.postfix.org/pcre_table.5.html> that are applied to initial message helo info. Hint:<br> + /^tmpstr.*/ REJECT<br> + /^myserver.local/ REJECT external server with local domain info<br> + /^trusted_network.local/ DUNNO trusted remote misconfigured server<br> + See http://www.postfix.org/postconf.5.html#smtpd_helo_restrictions for more help]]> + </description> + <type>textarea</type> + <cols>83</cols> + <rows>15</rows> + <encoding>base64</encoding> + </field> + <field> <fielddescr>Sender</fielddescr> <fieldname>sender_access</fieldname> <description><![CDATA[<strong>HASH filters</strong> that implements whitelisting and blacklisting of full or partial email addresses and domains as specified in the MAIL FROM field :<br> diff --git a/config/postfix/postfix_queue.php b/config/postfix/postfix_queue.php index 914ad88e..76bed31f 100755 --- a/config/postfix/postfix_queue.php +++ b/config/postfix/postfix_queue.php @@ -2,14 +2,14 @@ /* postfix_view_config.php part of pfSense (http://www.pfsense.com/) - Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> + Copyright (C) 2011-2013 Marcello Coutinho <marcellocoutinho@gmail.com> based on varnish_view_config. 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, + 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 @@ -33,11 +33,17 @@ require("guiconfig.inc"); $uname=posix_uname(); if ($uname['machine']=='amd64') ini_set('memory_limit', '250M'); - + +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('POSTFIX_LOCALBASE', '/usr/pbi/postfix-' . php_uname("m")); +else + define('POSTFIX_LOCALBASE','/usr/local'); + function get_cmd(){ if ($_REQUEST['cmd'] =='mailq'){ #exec("/usr/local/bin/mailq" . escapeshellarg('^'.$m.$j." ".$hour.".*".$grep)." /var/log/maillog", $lists); - exec("/usr/local/bin/mailq", $mailq); + exec(POSTFIX_LOCALBASE."/bin/mailq", $mailq); print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">'; print '<tr><td colspan="6" valign="top" class="listtopic">'.gettext($_REQUEST['cmd']." Results").'</td></tr>'; print '<tr><td class="listlr"><strong>SID</strong></td>'; @@ -67,9 +73,9 @@ function get_cmd(){ } if ($_REQUEST['cmd'] =='qshape'){ if ($_REQUEST['qshape']!="") - exec("/usr/local/bin/qshape -".preg_replace("/\W/","",$_REQUEST['type'])." ". preg_replace("/\W/","",$_REQUEST['qshape']), $qshape); + exec(POSTFIX_LOCALBASE."/bin/qshape -".preg_replace("/\W/","",$_REQUEST['type'])." ". preg_replace("/\W/","",$_REQUEST['qshape']), $qshape); else - exec("/usr/local/bin/qshape", $qshape); + exec(POSTFIX_LOCALBASE."/bin/qshape", $qshape); print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">'; print '<tr><td colspan="12" valign="top" class="listtopic">'.gettext($_REQUEST['cmd']." Results").'</td></tr>'; $td='<td valign="top" class="listlr">'; diff --git a/config/postfix/postfix_search.php b/config/postfix/postfix_search.php index 2b831f72..a1cf6b3f 100755 --- a/config/postfix/postfix_search.php +++ b/config/postfix/postfix_search.php @@ -2,14 +2,14 @@ /* postfix_search.php part of pfSense (http://www.pfsense.com/) - Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> + Copyright (C) 2011-2013 Marcello Coutinho <marcellocoutinho@gmail.com> based on varnish_view_config. 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, + 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 diff --git a/config/postfix/postfix_sync.xml b/config/postfix/postfix_sync.xml index 08a62d87..88617fbf 100644 --- a/config/postfix/postfix_sync.xml +++ b/config/postfix/postfix_sync.xml @@ -9,7 +9,7 @@ /* postfix_sync.xml part of the Postfix package for pfSense - Copyright (C) 2010 Marcello Coutinho + Copyright (C) 2011-2013 Marcello Coutinho All rights reserved. */ /* ========================================================================== */ @@ -20,7 +20,7 @@ 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 + 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. @@ -100,23 +100,46 @@ <type>listtopic</type> </field> <field> - <fielddescr>Automatically sync Postfix configuration changes</fielddescr> + <fielddescr>Sync method</fielddescr> <fieldname>synconchanges</fieldname> - <description><![CDATA[pfSense will automatically sync changes to the hosts defined below.<br><br> - Remote server options are:<br> - <strong>XMLRPC Sync</strong> - Forward postfix settings to other pfsense boxes. Remote password required<br> - <strong>Share Database To</strong> - Allow other pfsense boxes to fetch maillog data via xml. Remote password NOT required.<br> - <strong>Fetch Database From</strong> - Merge logs from other pfsense boxes to this local database. Remote password required.<br> - <strong>Disabled</strong> - Ignore this host while sync.<br><br> - While sharing databases, you must setup 'Share Database To' in one box and 'Fetch Database From' on other box.]]></description> - <type>checkbox</type> + <description>Automatically sync postfix configuration changes.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr><![CDATA[Remote Server]]></fielddescr> <fieldname>none</fieldname> <type>rowhelper</type> + <dontdisplayname/> + <usecolspan2/> <rowhelper> <rowhelperfield> + <fielddescr>Enable</fielddescr> + <fieldname>enabless</fieldname> + <type>checkbox</type> + </rowhelperfield> + <rowhelperfield> <fielddescr>Sync Type </fielddescr> <fieldname>sync_type</fieldname> <type>select</type> @@ -126,18 +149,22 @@ <option><name>Fetch Database From</name><value>fetch</value></option> <option><name>Disabled</name><value>disabled</value></option> </options> - <description><![CDATA[<strong>Default: Strong</strong><br> - Enable sender, client, recipients and rfc verification.<br>]]></description> </rowhelperfield> - <rowhelperfield> - <fielddescr>IP Address</fielddescr> + <fielddescr>Remote Server IP</fielddescr> <fieldname>ipaddress</fieldname> <description>IP Address of remote server</description> <type>input</type> <size>10</size> </rowhelperfield> <rowhelperfield> + <fielddescr>Username</fielddescr> + <fieldname>username</fieldname> + <description>Username for remote server.</description> + <type>input</type> + <size>10</size> + </rowhelperfield> + <rowhelperfield> <fielddescr>Password</fielddescr> <fieldname>password</fieldname> <description>Password for remote server.</description> @@ -148,9 +175,15 @@ <fielddescr>Description</fielddescr> <fieldname>description</fieldname> <type>input</type> - <size>25</size> + <size>27</size> </rowhelperfield> </rowhelper> + <description><![CDATA[<br>Sync types Description:<br><br> + <strong>XMLRPC Sync</strong> - Forward postfix settings to other pfsense boxes. Remote password required<br> + <strong>Share Database To</strong> - Allow other pfsense boxes to fetch maillog data via xml. Remote password NOT required.<br> + <strong>Fetch Database From</strong> - Merge logs from other pfsense boxes to this local database. Remote password required.<br> + <strong>Disabled</strong> - Ignore this host while sync.<br><br> + While sharing databases works only when you select 'Sync to host(s) defined below' on sync method and you must setup 'Share Database To' in source box and 'Fetch Database From' on destination box.]]></description> </field> </fields> <custom_php_install_command> diff --git a/config/postfix/postfix_view_config.php b/config/postfix/postfix_view_config.php index 2c0b973e..5e1f6271 100644 --- a/config/postfix/postfix_view_config.php +++ b/config/postfix/postfix_view_config.php @@ -2,14 +2,14 @@ /* postfix_view_config.php part of pfSense (http://www.pfsense.com/) - Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> + Copyright (C) 2011-2013 Marcello Coutinho <marcellocoutinho@gmail.com> based on varnish_view_config. 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, + 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 @@ -29,15 +29,21 @@ */ require("guiconfig.inc"); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('POSTFIX_LOCALBASE', '/usr/pbi/postfix-' . php_uname("m")); +else + define('POSTFIX_LOCALBASE','/usr/local'); + function get_file($file){ - $files['main']="/usr/local/etc/postfix/main.cf"; - $files['master']="/usr/local/etc/postfix/master.cf"; - $files['recipients']="/usr/local/etc/postfix/relay_recipients"; - $files['header']="/usr/local/etc/postfix/header_check"; - $files['mime']="/usr/local/etc/postfix/mime_check"; - $files['body']="/usr/local/etc/postfix/body_check"; - $files['cidr']="/usr/local/etc/postfix/cal_cidr"; - $files['pcre']="/usr/local/etc/postfix/cal_pcre"; + $files['main']=POSTFIX_LOCALBASE."/etc/postfix/main.cf"; + $files['master']=POSTFIX_LOCALBASE."/etc/postfix/master.cf"; + $files['recipients']=POSTFIX_LOCALBASE."/etc/postfix/relay_recipients"; + $files['header']=POSTFIX_LOCALBASE."/etc/postfix/header_check"; + $files['mime']=POSTFIX_LOCALBASE."/etc/postfix/mime_check"; + $files['body']=POSTFIX_LOCALBASE."/etc/postfix/body_check"; + $files['cidr']=POSTFIX_LOCALBASE."/etc/postfix/cal_cidr"; + $files['pcre']=POSTFIX_LOCALBASE."/etc/postfix/cal_pcre"; if ($files[$file]!="" && file_exists($files[$file])){ print '<textarea rows="50" cols="100%">'; diff --git a/config/quagga_ospfd/quagga_ospfd.inc b/config/quagga_ospfd/quagga_ospfd.inc index 598d3c00..46037bd9 100644 --- a/config/quagga_ospfd/quagga_ospfd.inc +++ b/config/quagga_ospfd/quagga_ospfd.inc @@ -290,7 +290,24 @@ EOF; exec("chmod u+rw,go-rw {$quagga_config_base}/zebra.conf"); // Kick off newly created rc.d script - exec("/usr/local/etc/rc.d/quagga.sh restart"); + if (is_ipaddr($ospfd_conf['carpstatusip'])) { + $status = quagga_get_carp_status_by_ip($ospfd_conf['carpstatusip']); + switch (strtoupper($status)) { + // Stop the service if the VIP is in BACKUP or INIT state. + case "BACKUP": + case "INIT": + exec("/usr/local/etc/rc.d/quagga.sh stop"); + break; + // Start the service if the VIP is MASTER state. + case "MASTER": + // Assume it's up if the status can't be determined. + default: + exec("/usr/local/etc/rc.d/quagga.sh restart"); + break; + } + } else { + exec("/usr/local/etc/rc.d/quagga.sh restart"); + } // Back to RO mount for NanoBSD and friends conf_mount_ro(); @@ -345,4 +362,18 @@ function quagga_ospfd_put_raw_config($conffile) { } } +function quagga_get_carp_status_by_ip($ipaddr) { + $iface = find_carp_interface($ipaddr); + if ($iface) { + $status = get_carp_interface_status($iface); + // If there is no status for that interface, return null. + if (!$status) + $status = null; + } else { + // If there is no VIP by that IP, return null. + $status = null; + } + return $status; +} + ?> diff --git a/config/quagga_ospfd/quagga_ospfd.xml b/config/quagga_ospfd/quagga_ospfd.xml index 3348dff3..c48d0f47 100644 --- a/config/quagga_ospfd/quagga_ospfd.xml +++ b/config/quagga_ospfd/quagga_ospfd.xml @@ -1,6 +1,6 @@ <packagegui> <name>quagga_ospfd</name> - <version>0.5.2</version> + <version>0.5.3</version> <title>Services: Quagga OSPFd</title> <include_file>/usr/local/pkg/quagga_ospfd.inc</include_file> <aftersaveredirect>pkg_edit.php?xml=quagga_ospfd.xml&id=0</aftersaveredirect> @@ -176,6 +176,13 @@ </rowhelperfield> </rowhelper> </field> + <field> + <fielddescr>CARP Status IP</fielddescr> + <fieldname>carpstatusip</fieldname> + <description>IP address used to determine the CARP status. When the VIP is in BACKUP status, quagga will not be started. <br/>NOTE: Requires changes to /etc/rc.carpmaster to start quagga and /etc/rc.carpbackup to stop quagga or it will not be fully effective.</description> + <type>input</type> + <size>25</size> + </field> </fields> <custom_php_resync_config_command> quagga_ospfd_install_conf(); diff --git a/config/sarg/sarg.inc b/config/sarg/sarg.inc index 5d0a91a5..32cca7ed 100644 --- a/config/sarg/sarg.inc +++ b/config/sarg/sarg.inc @@ -434,31 +434,63 @@ function sarg_validate_input($post, &$input_errors) { } } - /* Uses XMLRPC to synchronize the changes to a remote node */ function sarg_sync_on_changes() { global $config, $g; - - log_error("[sarg] sarg_xmlrpc_sync.php is starting."); - $synconchanges = $config['installedpackages']['sargsync']['config'][0]['synconchanges']; - if(!$synconchanges) - return; - foreach ($config['installedpackages']['sargsync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - $sync_to_ip = $sh['ipaddress']; - $password = $sh['password']; - if($sh['username']) - $username = $sh['username']; - else - $username = 'admin'; - if($password && $sync_to_ip) - sarg_do_xmlrpc_sync($sync_to_ip, $username, $password); + if (is_array($config['installedpackages']['sargsync']['config'])){ + $sarg_sync=$config['installedpackages']['sargsync']['config'][0]; + $synconchanges = $sarg_sync['synconchanges']; + $synctimeout = $sarg_sync['synctimeout']; + switch ($synconchanges){ + case "manual": + if (is_array($sarg_sync[row])){ + $rs=$sarg_sync[row]; + } + else{ + log_error("[sarg] xmlrpc sync is enabled but there is no hosts to push on sarg config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + if ($system_carp['synchronizetoip'] =="" || $system_carp['username']==""){ + log_error("[sarg] xmlrpc sync is enabled but there is no system backup hosts to push sarg config."); + return; + } + + } + else{ + log_error("[sarg] xmlrpc sync is enabled but there is no system backup hosts to push sarg config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[sarg] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($password && $sync_to_ip) + sarg_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout); + } + log_error("[sarg] xmlrpc sync is ending."); } - } - log_error("[sarg] sarg_xmlrpc_sync.php is ending."); + } } + /* Do the actual XMLRPC sync */ -function sarg_do_xmlrpc_sync($sync_to_ip, $username, $password) { +function sarg_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout) { global $config, $g; if(!$username) @@ -469,7 +501,10 @@ function sarg_do_xmlrpc_sync($sync_to_ip, $username, $password) { if(!$sync_to_ip) return; - + + if(!$synctimeout) + $synctimeout="150"; + $xmlrpc_sync_neighbor = $sync_to_ip; if($config['system']['webgui']['protocol'] != "") { $synchronizetoip = $config['system']['webgui']['protocol']; @@ -504,15 +539,15 @@ function sarg_do_xmlrpc_sync($sync_to_ip, $username, $password) { $cli->setCredentials($username, $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 250 seconds */ - $resp = $cli->send($msg, "250"); + /* send our XMLRPC message and timeout after $synctimeout seconds */ + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting sarg XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "sarg Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting sarg XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "sarg Settings Sync", ""); @@ -534,14 +569,14 @@ function sarg_do_xmlrpc_sync($sync_to_ip, $username, $password) { $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting sarg XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "sarg Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting sarg XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "sarg Settings Sync", ""); diff --git a/config/sarg/sarg_sync.xml b/config/sarg/sarg_sync.xml index 6c81b3f8..6cff7b6d 100755 --- a/config/sarg/sarg_sync.xml +++ b/config/sarg/sarg_sync.xml @@ -84,8 +84,30 @@ <field> <fielddescr>Automatically sync sarg configuration changes</fielddescr> <fieldname>synconchanges</fieldname> - <description>pfSense will automatically sync changes to the hosts defined below.</description> - <type>checkbox</type> + <description>Select a sync method for sarg.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr>Remote Server</fielddescr> diff --git a/config/snort/snort.inc b/config/snort/snort.inc index c36fc873..fe390a41 100755 --- a/config/snort/snort.inc +++ b/config/snort/snort.inc @@ -33,21 +33,55 @@ require_once("pfsense-utils.inc"); require_once("config.inc"); require_once("functions.inc"); +require_once("service-utils.inc"); +require_once("pkg-utils.inc"); // Needed on 2.0 because of filter_get_vpns_list() require_once("filter.inc"); +// Explicitly declare these as global so they work through function call includes +global $snort_rules_file, $snort_version, $emerging_threats_version, $snort_rules_upd_log; +global $all_rules, $flowbit_rules_file, $snort_enforcing_rules_file, $rebuild_rules, $is_postinstall; +global $snort_community_rules_filename, $snort_community_rules_url, $emergingthreats_filename; + /* package version */ -$snort_version = "2.9.2.3"; -$pfSense_snort_version = "2.5.4"; +$snort_version = "2.9.4.1"; +$pfSense_snort_version = "2.5.8"; $snort_package_version = "Snort {$snort_version} pkg v. {$pfSense_snort_version}"; -$snort_rules_file = "snortrules-snapshot-2923.tar.gz"; -$emerging_threats_version = "2.9.3"; + +// Define SNORTDIR and SNORTLIBDIR constants according to FreeBSD version (PBI support or no PBI) +if (floatval(php_uname("r")) >= 8.3) { + exec("/usr/local/sbin/pbi_info | grep 'snort-{$snort_version}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray); + $snort_pbidir = "{$pbidirarray[0]}"; + /* In case this is an initial Snort install and pbi_info() above returned null, set a sane default value */ + if (empty($snort_pbidir)) + $snort_pbidir = "/usr/pbi/snort-" . php_uname("m"); + define("SNORTDIR", "{$snort_pbidir}/etc/snort"); + define("SNORTLIBDIR", "{$snort_pbidir}/lib/snort"); +} +else { + define("SNORTDIR", "/usr/local/etc/snort"); + define("SNORTLIBDIR", "/usr/local/lib/snort"); +} + +define("SNORTLOGDIR", "/var/log/snort"); + +/* Important file definitions */ +$snort_rules_file = "snortrules-snapshot-2941.tar.gz"; +$emerging_threats_version = "2.9.0"; +$emergingthreats_filename = "emerging.rules.tar.gz"; +$snort_community_rules_url = "https://s3.amazonaws.com/snort-org/www/rules/community/"; +$snort_community_rules_filename = "community-rules.tar.gz"; $flowbit_rules_file = "flowbit-required.rules"; $snort_enforcing_rules_file = "snort.rules"; +$snort_rules_upd_log = SNORTLOGDIR; +$snort_rules_upd_log .= "/snort_rules_update.log"; -define("SNORTDIR", "/usr/local/etc/snort"); -define("SNORTLOGDIR", "/var/log/snort"); +/* Rebuild Rules Flag -- if "on", rebuild enforcing rules and flowbit-rules files */ +$rebuild_rules = "off"; + +/* Post-install Flag -- normally "false" except during post-install of package */ +$is_postinstall = false; if (!is_array($config['installedpackages']['snortglobal'])) $config['installedpackages']['snortglobal'] = array(); @@ -99,6 +133,53 @@ function snort_generate_id() { return $snort_uuid; } +function snort_load_suppress_sigs($snortcfg) { + + global $config; + + /**********************************************************/ + /* This function loads the GEN_ID and SIG_ID for all the */ + /* suppressed alert entries from the Suppression List of */ + /* the passed Snort interface. The results are returned */ + /* in an array with GEN_ID and SIG_ID as the keys. */ + /**********************************************************/ + + $suppress = array(); + + if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + return; + if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + return; + $a_suppress = $config['installedpackages']['snortglobal']['suppress']['item']; + + foreach ($a_suppress as $a_id => $alist) { + if ($alist['name'] == $snortcfg['suppresslistname']) { + if (!empty($alist['suppresspassthru'])) { + $tmplist = str_replace("\r", "", base64_decode($alist['suppresspassthru'])); + $tmp = explode("\n", $tmplist); + foreach ($tmp as $line) { + // Skip any blank lines + if (trim($line, " \n") == "") + continue; + // Skip any comment lines + if (preg_match('/^\s*#/', $line)) + continue; + if (preg_match('/gen_id\b\s*(\d+),\s*sig_id\b\s*(\d+)/i', $line, $matches)) { + $genid = $matches[1]; + $sigid = $matches[2]; + if (!empty($genid) && !empty($sigid)) + $suppress[$genid][$sigid] = "suppress"; + } + } + unset($tmp); + } + break; + } + } + unset($alist); + return $suppress; +} + /* func builds custom white lists */ function snort_find_list($find_name, $type = 'whitelist') { global $config; @@ -117,117 +198,129 @@ function snort_find_list($find_name, $type = 'whitelist') { return array(); } -/* func builds custom whitelests */ +/* func builds custom whitelists and the HOME_NET variable */ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { global $config, $g; - - /* Add loopback to whitelist (ftphelper) */ - $home_net = "127.0.0.1 "; + global $aliastable, $filterdns; + $home_net = array(); if ($listname == 'default' || empty($listname)) { - $wanip = 'yes'; $wangw = 'yes'; $wandns = 'yes'; $vips = 'yes'; $vpns = 'yes'; + $localnet = 'yes'; $wanip = 'yes'; $wangw = 'yes'; $wandns = 'yes'; $vips = 'yes'; $vpns = 'yes'; } else { $list = snort_find_list($listname); if (empty($list)) return $list; + $localnet = $list['localnets']; $wanip = $list['wanips']; $wangw = $list['wangateips']; $wandns = $list['wandnsips']; $vips = $list['vips']; $vpns = $list['vpnips']; if (!empty($list['address']) && is_alias($list['address'])) { - $home_net .= trim(filter_expand_alias($list['address'])); - $home_net .= " "; + $home_net = explode(" ", trim(filter_expand_alias($list['address']))); } } - /* Always put snort running interface in the list */ + /* Always add loopback to HOME_NET and whitelist (ftphelper) */ + if (!in_array("127.0.0.1", $home_net)) + $home_net[] = "127.0.0.1"; + + /********************************************************************/ + /* Always put the interface running Snort in HOME_NET and whitelist */ + /* unless it's the WAN. WAN options are handled further down. */ + /********************************************************************/ $snortip = get_interface_ip($snortcfg['interface']); - if (is_ipaddr($snortip)) - $home_net .= "{$snortip} "; + if (is_ipaddr($snortip)) { + if ($snortcfg['interface'] <> "wan") { + $sn = get_interface_subnet($snortcfg['interface']); + $ip = gen_subnet($snortip, $sn) . "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + } + if (function_exists('get_interface_ipv6')) { $snortip = get_interface_ipv6($snortcfg['interface']); if (is_ipaddrv6($snortip)) { - if ($whitelist === false) { + if ($snortcfg['interface'] <> "wan") { $sn = get_interface_subnetv6($snortcfg['interface']); - $home_net .= "{$snortip}/{$sn} "; - } else - $home_net .= "{$snortip} "; + $ip = gen_subnetv6($snortip, $sn). "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } } } - - /* iterate through interface list and write out whitelist items - * and also compile a home_net list for snort. - */ - if ($wanip == 'yes') { - /* build an interface array list */ + + if ($localnet == 'yes') { + /*************************************************************************/ + /* Iterate through the interface list and write out whitelist items and */ + /* also compile a HOME_NET list of all the local interfaces for snort. */ + /* Skip the WAN interface as we do not typically want that whole subnet */ + /* whitelisted (just the interface IP itself). */ + /*************************************************************************/ if (function_exists('get_configured_interface_list')) $int_array = get_configured_interface_list(); else { $int_array = array('wan', 'lan'); - for ($j = 1; isset ($config['interfaces']['opt' . $j]); $j++) + for ($j = 1; isset ($config['interfaces']['opt' . $j]); $j++) { if(isset($config['interfaces']['opt' . $j]['enable'])) $int_array[] = "opt{$j}"; + } } - foreach ($int_array as $int) { - /* calculate interface subnet information */ - if (function_exists('get_interface_ip')) { - if (!interface_has_gateway($int)) + if ($int == "wan") + continue; + $subnet = get_interface_ip($int); + if (is_ipaddr($subnet)) { + $sn = get_interface_subnet($int); + $ip = gen_subnet($subnet, $sn) . "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + if (function_exists("get_interface_ipv6")) { + if ($int == "wan") continue; - $subnet = get_interface_ip($int); - if (is_ipaddr($subnet)) { - if ($whitelist === false) { - $sn = get_interface_subnet($int); - $home_net .= "{$subnet}/{$sn} "; - } else - $home_net .= "{$subnet} "; - } - if (function_exists("get_interface_ipv6")) { - if (!interface_has_gatewayv6($int)) - continue;; - $subnet = get_interface_ipv6($int); - if (is_ipaddrv6($subnet)) { - if ($whitelist === false) { - $sn = get_interface_subnetv6($int); - $home_net .= "{$subnet}/{$sn} "; - } else - $home_net .= "{$subnet} "; - } - } - } else { - $ifcfg = $config['interfaces'][$int]; - switch ($ifcfg['ipaddr']) { - case "pppoe": - case "pptp": - case "l2tp": - $subnet = find_interface_ip("ng0"); - if (is_ipaddr($subnet)) - $home_net .= "{$subnet} "; - break; - case "dhcp": - $subnet = find_interface_ip(snort_get_real_interface($int)); - if (is_ipaddr($subnet)) - $home_net .= "{$subnet} "; - break; - default: - if (is_ipaddr($ifcfg['ipaddr'])) { - $home_net .= "{$ifcfg['ipaddr']} "; - } - break; + $subnet = get_interface_ipv6($int); + if (is_ipaddrv6($subnet)) { + $sn = get_interface_subnetv6($int); + $ip = gen_subnetv6($subnet, $sn). "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; } } } } + /* Grab the default gateway if set */ + $default_gw = exec("/sbin/route -n get default |grep 'gateway:' | /usr/bin/awk '{ print $2 }'"); + + if ($wanip == 'yes') { + $ip = get_interface_ip("wan"); + if (is_ipaddr($ip)) { + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + if (function_exists("get_interface_ipv6")) { + $ip = get_interface_ipv6("wan"); + if (is_ipaddrv6($ip)) { + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + } + } + if ($wangw == 'yes') { + if (is_ipaddr($default_gw) && !in_array($default_gw, $home_net)) + $home_net[] = $default_gw; + + /* Get any other interface gateway and put in $HOME_NET if not there already */ $gw = get_interface_gateway($snortcfg['interface']); - if (is_ipaddr($gw)) - $home_net .= "{$gw} "; + if (is_ipaddr($gw) && !in_array($gw, $home_net)) + $home_net[] = $gw; if (function_exists("get_interface_gatewayv6")) { $gw = get_interface_gatewayv6($snortcfg['interface']); - if (is_ipaddrv6($gw)) - $home_net .= "{$gw} "; + if (is_ipaddrv6($gw) && !in_array($gw, $home_net)) + $home_net[] = $gw; } } @@ -235,8 +328,8 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { /* Add DNS server for WAN interface to whitelist */ $dns_servers = get_dns_servers(); foreach ($dns_servers as $dns) { - if ($dns) - $home_net .= "{$dns} "; + if ($dns && !in_array($dns, $home_net)) + $home_net[] = $dns; } } @@ -245,10 +338,8 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { if (is_array($config['virtualip']) && is_array($config['virtualip']['vip'])) { foreach($config['virtualip']['vip'] as $vip) { if ($vip['subnet'] && $vip['mode'] != 'proxyarp') { - if ($whitelist === false) - $home_net .= "{$vip['subnet']}/{$vip['subnet_bits']} "; - else - $home_net .= "{$vip['subnet']} "; + if (!in_array("{$vip['subnet']}/{$vip['subnet_bits']}", $home_net)) + $home_net[] = "{$vip['subnet']}/{$vip['subnet_bits']}"; } } } @@ -256,27 +347,31 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { /* grab a list of vpns and whitelist if user desires added by nestorfish 954 */ if ($vpns == 'yes') { - if ($config['version'] <= 6) // chk what pfsense version were on - $vpns_list = get_vpns_list(); - else - $vpns_list = filter_get_vpns_list(); - - if (!empty($vpns_list)) - $home_net .= "{$vpns_list} "; + $vpns_list = filter_get_vpns_list(); + if (!empty($vpns_list)) { + /* Convert the returned space-delimited string to an array */ + /* and then add each VPN address to our HOME_NET array. */ + $vpns = explode(" ", $vpns_list); + foreach ($vpns as $vpn) + $home_net[] = trim($vpn); + unset($vpns, $vpns_list); + } } - $home_net = trim($home_net); - $validator = explode(" ", $home_net); $valresult = array(); - foreach ($validator as $vald) { + foreach ($home_net as $vald) { if (empty($vald)) continue; $vald = trim($vald); if (empty($valresult[$vald])) $valresult[$vald] = $vald; } - unset($home_net, $validator); + /* Release memory no longer required */ + unset($home_net); + + /* Sort the list and return it */ + natsort($valresult); return $valresult; } @@ -295,8 +390,8 @@ function snort_barnyard_stop($snortcfg, $if_real) { $snort_uuid = $snortcfg['uuid']; if (file_exists("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) { + log_error("[Snort] Barnyard2 STOP for {$snortcfg['descr']}({$if_real})..."); killbypid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); - @unlink("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); } } @@ -305,13 +400,11 @@ function snort_stop($snortcfg, $if_real) { $snort_uuid = $snortcfg['uuid']; if (file_exists("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { + log_error("[Snort] Snort STOP for {$snortcfg['descr']}({$if_real})..."); killbypid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); - exec("/bin/rm {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); } snort_barnyard_stop($snortcfg, $if_real); - - log_error("Interface Rule STOP for {$snortcfg['descr']}({$if_real})..."); } function snort_barnyard_start($snortcfg, $if_real) { @@ -321,9 +414,10 @@ function snort_barnyard_start($snortcfg, $if_real) { $snort_uuid = $snortcfg['uuid']; /* define snortbarnyardlog_chk */ - if ($snortcfg['barnyard_enable'] == 'on' && !empty($snortcfg['barnyard_mysql'])) + if ($snortcfg['barnyard_enable'] == 'on' && !empty($snortcfg['barnyard_mysql'])) { + log_error("[Snort] Barnyard2 START for {$snortcfg['descr']}({$if_real})..."); exec("/usr/local/bin/barnyard2 -r {$snort_uuid} -f \"snort_{$snort_uuid}_{$if_real}.u2\" --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q"); - + } } function snort_start($snortcfg, $if_real) { @@ -332,14 +426,37 @@ function snort_start($snortcfg, $if_real) { $snortdir = SNORTDIR; $snort_uuid = $snortcfg['uuid']; - if ($snortcfg['enable'] == 'on') + if ($snortcfg['enable'] == 'on') { + log_error("[Snort] Snort START for {$snortcfg['descr']}({$if_real})..."); exec("/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}"); + } else return; snort_barnyard_start($snortcfg, $if_real); +} + +/**************************************************************/ +/* This function sends a SIGHUP to the Snort instance on the */ +/* passed interface to cause Snort to reload and parse the */ +/* running configuration without stopping packet processing. */ +/* It also executes the reload as a background process and */ +/* returns control immediately to the caller. */ +/**************************************************************/ +function snort_reload_config($snortcfg, $if_real) { + global $config, $g; + + $snortdir = SNORTDIR; + $snort_uuid = $snortcfg['uuid']; - log_error("Interface Rule START for {$snortcfg['descr']}({$if_real})..."); + /******************************************************/ + /* Only send the SIGHUP if Snort is running and we */ + /* can find a valid PID for the process. */ + /******************************************************/ + if (file_exists("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { + log_error("[Snort] Snort RELOAD CONFIG for {$snortcfg['descr']}({$if_real})..."); + exec("/bin/pkill -SIGHUP -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid 2>&1 &"); + } } function snort_get_friendly_interface($interface) { @@ -394,8 +511,7 @@ function snort_get_real_interface($interface) { this code block is for deleteing logs while keeping the newest file, snort is linked to these files while running, do not take the easy way out by touch and rm, snort will lose sync and not log. - - */ +*/ function snort_post_delete_logs($snort_uuid = 0) { global $config, $g; @@ -427,9 +543,15 @@ function snort_post_delete_logs($snort_uuid = 0) { } function snort_postinstall() { - global $config, $g; + global $config, $g, $snort_rules_file, $emerging_threats_version; + global $snort_version, $rebuild_rules, $is_postinstall; $snortdir = SNORTDIR; + $snortlibdir = SNORTLIBDIR; + $rcdir = RCFILEPREFIX; + + /* Set flag for post-install in progress */ + $is_postinstall = true; /* cleanup default files */ @rename("{$snortdir}/snort.conf-sample", "{$snortdir}/snort.conf"); @@ -440,25 +562,52 @@ function snort_postinstall() { @rename("{$snortdir}/generators-sample", "{$snortdir}/generators"); @rename("{$snortdir}/reference.config-sample", "{$snortdir}/reference.config"); @rename("{$snortdir}/gen-msg.map-sample", "{$snortdir}/gen-msg.map"); - @unlink("{$snortdir}/sid"); - @unlink("/usr/local/etc/rc.d/snort"); - @unlink("/usr/local/etc/rc.d/barnyard2"); - /* remove example files */ - if (file_exists('/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so.0')) - exec('rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example*'); + /* fix up the preprocessor rules filenames from a PBI package install */ + $preproc_rules = array("decoder.rules", "preprocessor.rules", "sensitive-data.rules"); + foreach ($preproc_rules as $file) { + if (file_exists("{$snortdir}/preproc_rules/{$file}-sample")) + @rename("{$snortdir}/preproc_rules/{$file}-sample", "{$snortdir}/preproc_rules/{$file}"); + } + + /* Remove any previously installed scripts since we rebuild them */ + @unlink("{$snortdir}/sid"); + @unlink("{$rcdir}/snort.sh"); + @unlink("{$rcdir}/barnyard2"); - if (file_exists('/usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example.so')) - exec('/bin/rm /usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example*'); + /* remove example library files */ + $files = glob("{$snortlibdir}/dynamicrules/*_example*"); + foreach ($files as $f) + @unlink($f); + $files = glob("{$snortlibdir}/dynamicpreprocessor/*_example*"); + foreach ($files as $f) + @unlink($f); /* remake saved settings */ if ($config['installedpackages']['snortglobal']['forcekeepsettings'] == 'on') { + log_error(gettext("[Snort] Saved settings detected... rebuilding installation with saved settings...")); update_status(gettext("Saved settings detected...")); - update_output_window(gettext("Please wait... rebuilding files...")); + update_output_window(gettext("Please wait... rebuilding installation with saved settings...")); + log_error(gettext("[Snort] Downloading and updating configured rule types...")); @include_once("/usr/local/pkg/snort/snort_check_for_rule_updates.php"); + update_status(gettext("Generating snort.conf configuration file from saved settings...")); + $rebuild_rules = "on"; sync_snort_package_config(); - update_output_window(gettext("Finnished Rebuilding files...")); + $rebuild_rules = "off"; + update_output_window(gettext("Finished rebuilding files...")); + log_error(gettext("[Snort] Finished rebuilding installation from saved settings...")); + + /* Only try to start Snort if not in reboot */ + if (!$g['booting']) { + update_status(gettext("Starting Snort using rebuilt configuration...")); + log_error(gettext("[Snort] Starting Snort using rebuilt configuration...")); + start_service("snort"); + } } + + /* Done with post-install, so clear flag */ + $is_postinstall = false; + log_error(gettext("[Snort] Package post-installation tasks completed...")); } function snort_Getdirsize($node) { @@ -592,17 +741,20 @@ function snort_rm_blocked_install_cron($should_install) { } switch($should_install) { case true: - if(!$is_installed) { - $cron_item = array(); - $cron_item['minute'] = "$snort_rm_blocked_min"; - $cron_item['hour'] = "$snort_rm_blocked_hr"; - $cron_item['mday'] = "$snort_rm_blocked_mday"; - $cron_item['month'] = "$snort_rm_blocked_month"; - $cron_item['wday'] = "$snort_rm_blocked_wday"; - $cron_item['who'] = "root"; - $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t $snort_rm_blocked_expire snort2c"; + $cron_item = array(); + $cron_item['minute'] = "$snort_rm_blocked_min"; + $cron_item['hour'] = "$snort_rm_blocked_hr"; + $cron_item['mday'] = "$snort_rm_blocked_mday"; + $cron_item['month'] = "$snort_rm_blocked_month"; + $cron_item['wday'] = "$snort_rm_blocked_wday"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t $snort_rm_blocked_expire snort2c"; + + /* Add cron job if not already installed, else just update the existing one */ + if (!$is_installed) $config['cron']['item'][] = $cron_item; - } + elseif ($is_installed) + $config['cron']['item'][$x] = $cron_item; break; case false: if ($is_installed == true) @@ -672,17 +824,20 @@ function snort_rules_up_install_cron($should_install) { } switch($should_install) { case true: - if(!$is_installed) { - $cron_item = array(); - $cron_item['minute'] = "$snort_rules_up_min"; - $cron_item['hour'] = "$snort_rules_up_hr"; - $cron_item['mday'] = "$snort_rules_up_mday"; - $cron_item['month'] = "$snort_rules_up_month"; - $cron_item['wday'] = "$snort_rules_up_wday"; - $cron_item['who'] = "root"; - $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_for_rule_updates.php >> /tmp/snort_update.log"; + $cron_item = array(); + $cron_item['minute'] = "$snort_rules_up_min"; + $cron_item['hour'] = "$snort_rules_up_hr"; + $cron_item['mday'] = "$snort_rules_up_mday"; + $cron_item['month'] = "$snort_rules_up_month"; + $cron_item['wday'] = "$snort_rules_up_wday"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_for_rule_updates.php"; + + /* Add cron job if not already installed, else just update the existing one */ + if (!$is_installed) $config['cron']['item'][] = $cron_item; - } + elseif ($is_installed) + $config['cron']['item'][$x] = $cron_item; break; case false: if($is_installed == true) @@ -693,13 +848,16 @@ function snort_rules_up_install_cron($should_install) { /* Only run when all ifaces needed to sync. Expects filesystem rw */ function sync_snort_package_config() { - global $config, $g; + global $config, $g, $flowbit_rules_file, $snort_enforcing_rules_file; + global $snort_version, $rebuild_rules, $is_postinstall; + + $snortdir = SNORTDIR; conf_mount_rw(); - /* do not start config build if rules is empty */ - if (!is_array($config['installedpackages']['snortglobal']) && !is_array($config['installedpackages']['snortglobal']['rule'])) { - exec('/bin/rm /usr/local/etc/rc.d/snort.sh'); + /* do not start config build if rules is empty or there are no Snort settings */ + if (!is_array($config['installedpackages']['snortglobal']) || !is_array($config['installedpackages']['snortglobal']['rule'])) { + exec("/bin/rm /usr/local/etc/rc.d/snort.sh"); conf_mount_ro(); return; } @@ -708,10 +866,10 @@ function sync_snort_package_config() { foreach ($snortconf as $value) { $if_real = snort_get_real_interface($value['interface']); - /* create snort configuration file */ + /* create a snort.conf file for interface */ snort_generate_conf($value); - /* create barnyard2 configuration file */ + /* create barnyard2.conf file for interface */ if ($value['barnyard_enable'] == 'on') snort_create_barnyard2_conf($value, $if_real); } @@ -730,7 +888,11 @@ function sync_snort_package_config() { snort_rules_up_install_cron($snortglob['autorulesupdate7'] != "never_up" ? true : false); configure_cron(); - + + /* Do not attempt package sync if reinstalling package or booting */ + if (!$is_postinstall && !$g['booting']) + snort_sync_on_changes(); + conf_mount_ro(); } @@ -748,7 +910,7 @@ function snort_build_sid_msg_map($rules_path, $sid_file) { /* First check if we were passed a directory, a single file */ /* or an array of filenames to read. Set our $rule_files */ /* variable accordingly. If we can't figure it out, return */ - /* an empty rules map array. */ + /* and don't write a sid_msg_map file. */ if (is_string($rules_path)) { if (is_dir($rules_path)) $rule_files = glob($rules_path . "*.rules"); @@ -858,11 +1020,19 @@ function snort_merge_reference_configs($cfg_in, $cfg_out) { /* Sort the new reference map. */ uksort($outMap,'strnatcasecmp'); + /**********************************************************/ + /* Do NOT write an empty references.config file, just */ + /* exit instead. */ + /**********************************************************/ + if (empty($outMap)) + return false; + /* Format and write it to the supplied output file. */ $format = "config reference: %-12s %s\n"; foreach ($outMap as $key=>$value) $outMap[$key] = sprintf($format, $key, $value); @file_put_contents($cfg_out, array_values($outMap)); + return true; } function snort_merge_classification_configs($cfg_in, $cfg_out) { @@ -895,11 +1065,19 @@ function snort_merge_classification_configs($cfg_in, $cfg_out) { /* Sort the new classification map. */ uksort($outMap,'strnatcasecmp'); + /**********************************************************/ + /* Do NOT write an empty classification.config file, just */ + /* exit instead. */ + /**********************************************************/ + if (empty($outMap)) + return false; + /* Format and write it to the supplied output file. */ $format = "config classification: %s,%s\n"; foreach ($outMap as $key=>$value) $outMap[$key] = sprintf($format, $key, $value); @file_put_contents($cfg_out, array_values($outMap)); + return true; } function snort_load_rules_map($rules_path) { @@ -1013,8 +1191,13 @@ function snort_load_rules_map($rules_path) { } $gid = snort_get_gid($rule); + if (!is_array($map_ref[$gid])) + $map_ref[$gid] = array(); + if (!is_array($map_ref[$gid][$sid])) + $map_ref[$gid][$sid] = array(); $map_ref[$gid][$sid]['rule'] = $rule; $map_ref[$gid][$sid]['category'] = basename($file, ".rules"); + if (preg_match('/^\s*\#+/', $rule)) $map_ref[$gid][$sid]['disabled'] = 1; else @@ -1077,16 +1260,31 @@ function snort_get_flowbits($rule) { /*************************************************************/ /* This will pull out "flowbits:" options from the rule text */ - /* and return them in an array. */ + /* and return them in an array (minus the "flowbits:" part). */ /*************************************************************/ $flowbits = array(); - if (preg_match_all('/flowbits\b:\s*(set|setx|unset|toggle|isset|isnotset)\s*,([^;]+)/i', $rule, $matches)) { + + /* Grab any "flowbits:set, setx, unset, isset or toggle" options first. */ + /* Examine flowbits targets for logical operators to capture all targets */ + if (preg_match_all('/flowbits\b\s*:\s*(set|setx|unset|toggle|isset|isnotset)\s*,([^;]+)/i', $rule, $matches)) { $i = -1; while (++$i < count($matches[1])) { - $flowbits[] = trim($matches[1][$i]) ."," . trim($matches[2][$i]); + $action = trim($matches[1][$i]); + $target = preg_split('/[&|]/', $matches[2][$i]); + foreach ($target as $t) + $flowbits[] = "{$action}," . trim($t); } } + + /* Include the "flowbits:noalert or reset" options, if present. */ + if (preg_match_all('/flowbits\b\s*:\s*(noalert|reset)\b/i', $rule, $matches)) { + $i = -1; + while (++$i < count($matches[1])) { + $flowbits[] = trim($matches[1][$i]); + } + } + return $flowbits; } @@ -1114,11 +1312,16 @@ function snort_get_checked_flowbits(&$rules_map) { foreach ($rulem2['flowbits'] as $flowbit) { if (empty($flowbit)) continue; - $action = substr($flowbit, 0, strpos($flowbit, ",")); - if (preg_match('/is(not)?set/i', $action)) { - $tmp = substr($flowbit, strpos($flowbit, ",") +1 ); - if (!empty($tmp) && !in_array($tmp, $checked_flowbits)) - $checked_flowbits[] = $tmp; + /* If no comma in flowbits option, then skip it. */ + $pos = strpos($flowbit, ","); + if ($pos === false) + continue; + $action = substr(strtolower($flowbit), 0, $pos); + if ($action == "isset" || $action == "isnotset") { + $target = preg_split('/[&|]/', substr($flowbit, $pos + 1)); + foreach ($target as $t) + if (!empty($t) && !isset($checked_flowbits[$t])) + $checked_flowbits[$t] = $action; } } } @@ -1150,11 +1353,16 @@ function snort_get_set_flowbits(&$rules_map) { foreach ($rulem2['flowbits'] as $flowbit) { if (empty($flowbit)) continue; - $action = substr($flowbit, 0, strpos($flowbit, ",")); - if (preg_match('/^set/i', $action)) { - $tmp = substr($flowbit, strpos($flowbit, ",") +1 ); - if (!empty($tmp) && !in_array($tmp, $set_flowbits)) - $set_flowbits[] = $tmp; + /* If no comma in flowbits option, then skip it. */ + $pos = strpos($flowbit, ","); + if ($pos === false) + continue; + $action = substr(strtolower($flowbit), 0, $pos); + if ($action == "set" || $action == "toggle" || $action == "setx") { + $target = preg_split('/[&|]/', substr($flowbit, $pos + 1)); + foreach ($target as $t) + if (!empty($t) && !isset($set_flowbits[$t])) + $set_flowbits[$t] = $action; } } } @@ -1188,7 +1396,7 @@ function snort_find_flowbit_required_rules(&$all_rules, &$unchecked_flowbits) { $action = substr($flowbit, 0, strpos($flowbit, ",")); if (!strcasecmp(substr($action, 0, 3), "set")) { $tmp = substr($flowbit, strpos($flowbit, ",") +1 ); - if (!empty($tmp) && in_array($tmp, $unchecked_flowbits)) { + if (!empty($tmp) && isset($unchecked_flowbits[$tmp])) { if (!is_array($required_flowbits_rules[$k1])) $required_flowbits_rules[$k1] = array(); if (!is_array($required_flowbits_rules[$k1][$k2])) @@ -1212,7 +1420,7 @@ function snort_find_flowbit_required_rules(&$all_rules, &$unchecked_flowbits) { return $required_flowbits_rules; } -function snort_resolve_flowbits($rule_path) { +function snort_resolve_flowbits(&$active_rules) { /******************************************************/ /* This function auto-resolves flowbit requirements */ @@ -1222,31 +1430,32 @@ function snort_resolve_flowbits($rule_path) { /* enabled. For any that are not enabled, they are */ /* copied to an array, enabled, and returned. */ /* */ - /* $rule_path --> rules files of the interface */ - /* to resolve flowbit dependencies */ - /* for. This can be either of the */ - /* following: */ - /* - directory of *.rules files */ - /* - array of *.rules filenames */ - /* - a single *.rules filename */ + /* $active_rules --> Rules Map array containing */ + /* the current rules for the */ + /* interface to resolve flowbit */ + /* dependencies for. */ + /* */ + /* NOTE: this function assumes the global variable */ + /* $all_rules is populated with all the rules */ + /* currently downloaded. */ /******************************************************/ + global $all_rules; $snortdir = SNORTDIR; - /* First, load up all the enabled rules. */ - $rules_map = snort_load_rules_map($rule_path); - - /* Next, find all the "checked" and "set" flowbits. */ - $checked_flowbits = snort_get_checked_flowbits($rules_map); - $set_flowbits = snort_get_set_flowbits($rules_map); + /* Check $all_rules array to be sure it is filled. */ + if (empty($all_rules)) { + log_error(gettext("[Snort] WARNING: Flowbit resolution not done - no rules in {$snortdir}/rules/ ...")); + return array(); + } - /* We're done with the first rules array, so cleanup */ - /* to conserve memory. */ - unset($rules_map); + /* First, find all the "checked" and "set" flowbits. */ + $checked_flowbits = snort_get_checked_flowbits($active_rules); + $set_flowbits = snort_get_set_flowbits($active_rules); /* Next find any "checked" flowbits without matching */ /* "set" flowbit rules in the enabled rule set. */ - $delta_flowbits = array_diff($checked_flowbits, $set_flowbits); + $delta_flowbits = array_diff_key($checked_flowbits, $set_flowbits); /* Cleanup and release the memory we no longer need. */ unset($checked_flowbits); @@ -1254,11 +1463,9 @@ function snort_resolve_flowbits($rule_path) { /* Now find all the needed "set flowbit" rules from */ /* the master list of all rules. */ - $all_rules_map = snort_load_rules_map("{$snortdir}/rules/"); - $required_rules = snort_find_flowbit_required_rules($all_rules_map, $delta_flowbits); + $required_rules = snort_find_flowbit_required_rules($all_rules, $delta_flowbits); /* Cleanup and release memory we no longer need. */ - unset($all_rules_map); unset($delta_flowbits); return $required_rules; @@ -1272,11 +1479,13 @@ function snort_write_flowbit_rules_file($flowbit_rules, $rule_file) { /* given. */ /************************************************/ + global $flowbit_rules_file; + /* See if we were passed a directory or full */ /* filename to write the rules to, and adjust */ /* the destination argument accordingly. */ if (is_dir($rule_file)) - $rule_file = rtrim($rule_file, '/').'/flowbit-required.rules'; + $rule_file = rtrim($rule_file, '/')."/{$flowbit_rules_file}"; if (empty($flowbit_rules)) { @file_put_contents($rule_file, ""); @@ -1302,7 +1511,7 @@ function snort_write_flowbit_rules_file($flowbit_rules, $rule_file) { } } -function snort_load_vrt_policy($policy) { +function snort_load_vrt_policy($policy, $load_rules_map=true) { /************************************************/ /* This function returns an array of all rules */ @@ -1312,21 +1521,29 @@ function snort_load_vrt_policy($policy) { /* 1. connectivity */ /* 2. balanced */ /* 3. security */ + /* */ + /* $load_rules --> load a local copy of all */ + /* the rules if true. If */ + /* false, assume the global */ + /* $all_rules array is valid. */ /************************************************/ + global $all_rules; $snortdir = SNORTDIR; $vrt_policy_rules = array(); /* Create regular expression for searching. */ $policy_pcre = "/policy\\s" . $policy . "/i"; - /* First, load up all the rules we have. */ - $all_rules_map = snort_load_rules_map("{$snortdir}/rules/"); + /* Refresh the map of all the rules if flag */ + /* is set. */ + if ($load_rules_map == true) + $all_rules = snort_load_rules_map("{$snortdir}/rules/"); /* Now walk the rules list and find all those */ /* that are defined as active for the chosen */ /* security policy. */ - foreach ($all_rules_map as $k1 => $arulem) { + foreach ($all_rules as $k1 => $arulem) { foreach ($arulem as $k2 => $arulem2) { if (preg_match($policy_pcre, $arulem2['rule'])) { if (!preg_match('/flowbits\s*:\s*noalert/i', $arulem2['rule'])) { @@ -1347,7 +1564,12 @@ function snort_load_vrt_policy($policy) { } /* Release memory we no longer need. */ - unset($all_rules_map, $arulem, $arulem2); + unset($arulem, $arulem2); + + /* If we loaded the ALL_RULES map, */ + /* then release the memory. */ + if ($load_rules_map == true) + unset($all_rules); /* Return all the rules that match the policy. */ return $vrt_policy_rules; @@ -1363,7 +1585,7 @@ function snort_write_enforcing_rules_file($rule_map, $rule_path) { global $snort_enforcing_rules_file; - $rule_file = "/snort.rules"; + $rule_file = "/{$snort_enforcing_rules_file}"; /* See if we were passed a directory or full */ /* filename to write the rules to, and adjust */ @@ -1389,6 +1611,9 @@ function snort_write_enforcing_rules_file($rule_map, $rule_path) { @fwrite($fp, "# to the rules in this file.\n\n"); foreach ($rule_map as $rulem) { foreach ($rulem as $rulem2) { + /* No reason to write disabled rules to enforcing file, so skip them. */ + if ($rulem2['disabled'] == 1) + continue; @fwrite($fp, $rulem2['rule']); } } @@ -1402,9 +1627,17 @@ function snort_load_sid_mods($sids, $value) { /* This function parses the string of */ /* SID values in $sids and returns an */ /* array with the SID as the key and */ - /* passed $value as the value. The SID */ - /* values in $sids are assumed to be */ - /* delimited by "||". */ + /* value. The SID values in $sids are */ + /* assumed to be delimited by "||". */ + /* */ + /* $sids ==> string of SID values from */ + /* saved config file. */ + /* */ + /* $value ==> type of mod (enable or */ + /* disable). Not currently */ + /* utilized, but maintained */ + /* so as not to break legacy */ + /* code elsewhere. */ /*****************************************/ $result = array(); @@ -1413,7 +1646,7 @@ function snort_load_sid_mods($sids, $value) { $tmp = explode("||", $sids); foreach ($tmp as $v) { if (preg_match('/\s\d+/', $v, $match)) - $result[trim($match[0])] = $value; + $result[trim($match[0])] = trim($match[0]); } unset($tmp); @@ -1458,14 +1691,13 @@ function snort_modify_sids(&$rule_map, $snortcfg) { if (!empty($disablesid)) { foreach ($rule_map as $k1 => $rulem) { foreach ($rulem as $k2 => $v) { - if (in_array($k2, $disablesid) && $v['disabled'] == 0) { + if (in_array($k2, $disablesid) && $v['disabled'] == 0) { $rule_map[$k1][$k2]['rule'] = "# " . $v['rule']; $rule_map[$k1][$k2]['disabled'] = 1; } } } } - unset($enablesid, $disablesid); } @@ -1475,6 +1707,7 @@ function snort_create_rc() { global $config, $g; $snortdir = SNORTDIR; + $rcdir = RCFILEPREFIX; if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; @@ -1493,23 +1726,59 @@ function snort_create_rc() { $start_barnyard = <<<EOE if [ ! -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then - /bin/pgrep -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' > {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid - fi - /bin/pgrep -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid - if [ $? = 0 ]; then - /bin/pkill -HUP -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid -a + pid=`/bin/pgrep -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' > {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid` else - /usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q + pid=`/bin/pgrep -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid` + fi + if [ ! -z \$pid ]; then + /usr/bin/logger -p daemon.info -i -t SnortStartup "Barnyard2 STOP for {$value['descr']}({$snort_uuid}_{$if_real})..." + /bin/pkill $pid -a + time=0 timeout=30 + while kill -0 \$pid 2>/dev/null; do + sleep 1 + time=\$((time+1)) + if [ \$time -gt \$timeout ]; then + break + fi + done + if [ -f /var/run/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /bin/rm /var/run/barnyard2_{$if_real}{$snort_uuid}.pid + fi fi + /usr/bin/logger -p daemon.info -i -t SnortStartup "Barnyard2 START for {$value['descr']}({$snort_uuid}_{$if_real})..." + /usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q EOE; $stop_barnyard2 = <<<EOE if [ -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /usr/bin/logger -p daemon.info -i -t SnortStartup "Barnyard2 STOP for {$value['descr']}({$snort_uuid}_{$if_real})..." + pid=`/bin/pgrep -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid` /bin/pkill -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid -a - /bin/rm /var/run/barnyard2_{$if_real}{$snort_uuid}.pid + time=0 timeout=30 + while kill -0 \$pid 2>/dev/null; do + sleep 1 + time=\$((time+1)) + if [ \$time -gt \$timeout ]; then + break + fi + done + if [ -f /var/run/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /bin/rm /var/run/barnyard2_{$if_real}{$snort_uuid}.pid + fi else - /bin/pkill -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' + pid=`/bin/pgrep -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q'` + if [ ! -z \$pid ]; then + /bin/pkill -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' + time=0 timeout=30 + while kill -0 \$pid 2>/dev/null; do + sleep 1 + time=\$((time+1)) + if [ \$time -gt \$timeout ]; then + break + fi + done + fi fi EOE; @@ -1521,19 +1790,18 @@ EOE; $start_snort_iface_start[] = <<<EOE ###### For Each Iface -#### Only try to restart if snort is running on Iface + # Start snort and barnyard2 if [ ! -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then - /bin/pgrep -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}' > {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid + pid=`/bin/pgrep -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}'` + else + pid=`/bin/pgrep -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid` fi - /bin/pgrep -nF {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid - if [ $? = 0 ]; then - /bin/pkill -HUP -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid -a - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort SOFT START For {$value['descr']}({$snort_uuid}_{$if_real})..." + if [ ! -z \$pid ]; then + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort SOFT RESTART for {$value['descr']}({$snort_uuid}_{$if_real})..." + /bin/pkill -HUP \$pid else - # Start snort and barnyard2 - /bin/rm {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort START for {$value['descr']}({$snort_uuid}_{$if_real})..." /usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real} - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort START For {$value['descr']}({$snort_uuid}_{$if_real})..." fi sleep 2 @@ -1543,12 +1811,35 @@ EOE; $start_snort_iface_stop[] = <<<EOE - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort STOP For {$value['descr']}({$snort_uuid}_{$if_real})..." if [ -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then + pid=`/bin/pgrep -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid` + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort STOP for {$value['descr']}({$snort_uuid}_{$if_real})..." /bin/pkill -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid -a - /bin/rm /var/run/snort_{$if_real}{$snort_uuid}.pid - else - /bin/pkill -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}' + time=0 timeout=30 + while kill -0 \$pid 2>/dev/null; do + sleep 1 + time=\$((time+1)) + if [ \$time -gt \$timeout ]; then + break + fi + done + if [ -f /var/run/snort_{$if_real}{$snort_uuid}.pid ]; then + /bin/rm /var/run/snort_{$if_real}{$snort_uuid}.pid + fi + else + pid=`/bin/pgrep -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}'` + if [ ! -z \$pid ]; then + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort STOP for {$value['descr']}({$snort_uuid}_{$if_real})..." + /bin/pkill -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}' + time=0 timeout=30 + while kill -0 \$pid 2>/dev/null; do + sleep 1 + time=\$((time+1)) + if [ \$time -gt \$timeout ]; then + break + fi + done + fi fi sleep 2 @@ -1584,6 +1875,7 @@ case $1 in rc_stop ;; restart) + rc_stop rc_start ;; esac @@ -1591,11 +1883,11 @@ esac EOD; /* write out snort.sh */ - if (!@file_put_contents("/usr/local/etc/rc.d/snort.sh", $snort_sh_text)) { - log_error("Could not open /usr/local/etc/rc.d/snort.sh for writing."); + if (!@file_put_contents("{$rcdir}/snort.sh", $snort_sh_text)) { + log_error("Could not open {$rcdir}/snort.sh for writing."); return; } - @chmod("/usr/local/etc/rc.d/snort.sh", 0755); + @chmod("{$rcdir}/snort.sh", 0755); } /* open barnyard2.conf for writing */ @@ -1642,13 +1934,16 @@ function snort_generate_barnyard2_conf($snortcfg, $if_real) { config reference_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/reference.config config classification_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/classification.config config gen_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/gen-msg.map -config sid_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/sid-msg.map +config sid_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/sid-msg.map config hostname: $snortbarnyardlog_hostname_info_chk config interface: {$if_real} config decode_data_link config waldo_file: /var/log/snort/snort_{$if_real}{$snort_uuid}/barnyard2/{$snort_uuid}_{$if_real}.waldo +# Show year in timestamps +config show_year + ## START user pass through ## {$snortbarnyardlog_config_pass_thru} @@ -1671,23 +1966,38 @@ EOD; } function snort_deinstall() { - global $config, $g; + + global $config, $g, $snort_rules_upd_log; $snortdir = SNORTDIR; + $snortlibdir = SNORTLIBDIR; $snortlogdir = SNORTLOGDIR; + $rcdir = RCFILEPREFIX; - /* decrease bpf buffers back to 4096, from 20480 */ + log_error(gettext("[Snort] Snort package uninstall in progress...")); + + /* Make sure all active Snort processes are terminated */ + /* Log a message only if a running process is detected */ + if (is_service_running("snort")) + log_error(gettext("[Snort] Snort STOP for all interfaces...")); mwexec('/usr/bin/killall snort', true); sleep(2); mwexec('/usr/bin/killall -9 snort', true); sleep(2); + + /* Make sure all active Barnyard2 processes are terminated */ + /* Log a message only if a running process is detected */ + if (is_service_running("barnyard2")) + log_error(gettext("[Snort] Barnyard2 STOP for all interfaces...")); mwexec('/usr/bin/killall barnyard2', true); sleep(2); mwexec('/usr/bin/killall -9 barnyard2', true); sleep(2); + + /* Remove the snort user and group */ mwexec('/usr/sbin/pw userdel snort; /usr/sbin/pw groupdel snort', true); - /* Remove snort cron entries Ugly code needs smoothness*/ + /* Remove snort cron entries Ugly code needs smoothness */ if (!function_exists('snort_deinstall_cron')) { function snort_deinstall_cron($crontask) { global $config, $g; @@ -1709,52 +2019,105 @@ function snort_deinstall() { } } - mwexec("/bin/rm {$snortdir}/*.md5; /bin/rm -r {$snortdir}/snort_*"); + /* Remove all the Snort cron jobs. */ snort_deinstall_cron("snort2c"); snort_deinstall_cron("snort_check_for_rule_updates.php"); snort_deinstall_cron("snort_check_cron_misc.inc"); configure_cron(); + /**********************************************************/ + /* Test for existence of library backup tarballs in /tmp. */ + /* If these are present, then a package "delete" */ + /* operation is in progress and we need to wipe out the */ + /* configuration files. Otherwise we leave the binary- */ + /* side configuration intact since only a GUI files */ + /* deinstall and reinstall operation is in progress. */ + /* */ + /* XXX: hopefully a better method presents itself in */ + /* future versions of pfSense. */ + /**********************************************************/ + if (file_exists("/tmp/pkg_libs.tgz") || file_exists("/tmp/pkg_bins.tgz")) { + log_error(gettext("[Snort] Package deletion requested... removing all files...")); + mwexec("/bin/rm -rf {$snortdir}"); + mwexec("/bin/rm -rf {$snortlibdir}/dynamicrules"); + mwexec("/bin/rm -f {$rcdir}/snort.sh"); + mwexec("/bin/rm -rf /usr/local/pkg/snort"); + mwexec("/bin/rm -rf /usr/local/www/snort"); + mwexec("/bin/rm -rf /usr/local/etc/snort"); + } + /* Keep this as a last step */ - if ($config['installedpackages']['snortglobal']['forcekeepsettings'] != 'on') + if ($config['installedpackages']['snortglobal']['forcekeepsettings'] != 'on') { + log_error(gettext("Not saving settings... all Snort configuration info and logs deleted...")); unset($config['installedpackages']['snortglobal']); + unset($config['installedpackages']['snortsync']); + @unlink("{$snort_rules_upd_log}"); + mwexec("/bin/rm -rf {$snortlogdir}"); + log_error(gettext("[Snort] The package has been removed from this system...")); + } } function snort_prepare_rule_files($snortcfg, $snortcfgdir) { - global $snort_enforcing_rules_file, $flowbit_rules_file; + + global $snort_enforcing_rules_file, $flowbit_rules_file, $rebuild_rules, $all_rules; $snortdir = SNORTDIR; + $no_rules_defined = true; + + /* If there is no reason to rebuild the rules, exit to save time. */ + if ($rebuild_rules == "off") + return; + /* Log a message for rules rebuild in progress */ + log_error(gettext("[Snort] Updating rules configuration for: " . snort_get_friendly_interface($snortcfg['interface']) . " ...")); + + /* Only rebuild rules if some are selected or an IPS Policy is enabled */ if (!empty($snortcfg['rulesets']) || $snortcfg['ips_policy_enable'] == 'on') { $enabled_rules = array(); $enabled_files = array(); + $no_rules_defined = false; + + /* Load up all the rules into a Rules Map array. */ + $all_rules = snort_load_rules_map("{$snortdir}/rules/"); - /* Create an array with the full path filenames of the enabled */ - /* rule category files if we have any. */ + /* Create an array with the filenames of the enabled */ + /* rule category files if we have any. */ if (!empty($snortcfg['rulesets'])) { - foreach (explode("||", $snortcfg['rulesets']) as $file) { - if (file_exists("{$snortdir}/rules/{$file}")) - $enabled_files[] = "{$snortdir}/rules/{$file}"; + foreach (explode("||", $snortcfg['rulesets']) as $file){ + $category = basename($file, ".rules"); + if (!is_array($enabled_files[$category])) + $enabled_files[$category] = array(); + $enabled_files[$category] = $file; } - /* Load our rules map in preparation for writing the enforcing rules file. */ - $enabled_rules = snort_load_rules_map($enabled_files); - } + /****************************************************/ + /* Walk the ALL_RULES map array and copy the rules */ + /* matching our selected file categories to the */ + /* ENABLED_RULES map array. */ + /****************************************************/ + foreach ($all_rules as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + if (isset($enabled_files[$v['category']])) { + if (!is_array($enabled_rules[$k1])) + $enabled_rules[$k1] = array(); + if (!is_array($enabled_rules[$k1][$k2])) + $enabled_rules[$k1][$k2] = array(); + $enabled_rules[$k1][$k2]['rule'] = $v['rule']; + $enabled_rules[$k1][$k2]['category'] = $v['category']; + $enabled_rules[$k1][$k2]['disabled'] = $v['disabled']; + $enabled_rules[$k1][$k2]['flowbits'] = $v['flowbits']; + } + } + } - /* Remove any existing rules files (except custom rules) prior to building a new set. */ - foreach (glob("{$snortcfgdir}/rules/*.rules") as $file) { - $tmpfile = basename($file); - if (in_array("{$snortdir}/rules/{$tmpfile}", $enabled_files)) - continue; - if ($tmpfile != "custom.rules" && $tmpfile != $flowbit_rules_file && - $tmpfile != $snort_enforcing_rules_file) - @unlink($file); + /* Release memory we no longer need. */ + unset($enabled_files, $rulem, $v); } /* Check if a pre-defined Snort VRT policy is selected. If so, */ /* add all the VRT policy rules to our enforcing rule set. */ if (!empty($snortcfg['ips_policy'])) { - $policy_rules = snort_load_vrt_policy($snortcfg['ips_policy']); + $policy_rules = snort_load_vrt_policy($snortcfg['ips_policy'], false); foreach ($policy_rules as $k1 => $policy) { foreach ($policy as $k2 => $p) { if (!is_array($enabled_rules[$k1])) @@ -1767,46 +2130,63 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { $enabled_rules[$k1][$k2]['flowbits'] = $p['flowbits']; } } - unset($policy_rules); + unset($policy_rules, $policy, $p); } /* Process any enablesid or disablesid modifications for the selected rules. */ snort_modify_sids($enabled_rules, $snortcfg); - /* Check for and disable any rules dependent upon disabled preprocessors. */ - log_error('Checking for and disabling any rules dependent upon disabled preprocessors for ' . snort_get_friendly_interface($snortcfg['interface']) . '...'); - snort_filter_preproc_rules($snortcfg, $enabled_rules); + /* Check for and disable any rules dependent upon disabled preprocessors if */ + /* this option is enabled for the interface. */ + if ($snortcfg['preproc_auto_rule_disable'] == "on") { + log_error('[Snort] Checking for rules dependent on disabled preprocessors for: ' . snort_get_friendly_interface($snortcfg['interface']) . '...'); + snort_filter_preproc_rules($snortcfg, $enabled_rules); + } /* Write the enforcing rules file to the Snort interface's "rules" directory. */ snort_write_enforcing_rules_file($enabled_rules, "{$snortcfgdir}/rules/{$snort_enforcing_rules_file}"); - unset($enabled_rules); /* If auto-flowbit resolution is enabled, generate the dependent flowbits rules file. */ if ($snortcfg['autoflowbitrules'] == 'on') { - log_error('Resolving and auto-enabling flowbit required rules for ' . snort_get_friendly_interface($snortcfg['interface']) . '...'); - $enabled_files[] = "{$snortcfgdir}/rules/{$snort_enforcing_rules_file}"; - snort_write_flowbit_rules_file(snort_resolve_flowbits($enabled_files), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); + log_error('[Snort] Enabling any flowbit-required rules for: ' . snort_get_friendly_interface($snortcfg['interface']) . '...'); + $fbits = snort_resolve_flowbits($enabled_rules); + + /* Check for and disable any flowbit-required rules dependent upon */ + /* disabled preprocessors if this option is enabled for the interface. */ + if ($snortcfg['preproc_auto_rule_disable'] == "on") { + log_error('[Snort] Checking flowbit rules dependent on disabled preprocessors for: ' . snort_get_friendly_interface($snortcfg['interface']) . '...'); + snort_filter_preproc_rules($snortcfg, $fbits, true); + } + snort_write_flowbit_rules_file($fbits, "{$snortcfgdir}/rules/{$flowbit_rules_file}"); + unset($fbits); } else /* Just put an empty file to always have the file present */ snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); - unset($enabled_files); + unset($enabled_rules, $all_rules); } else { snort_write_enforcing_rules_file(array(), "{$snortcfgdir}/rules/{$snort_enforcing_rules_file}"); snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); } - if (!empty($snortcfg['customrules'])) + if (!empty($snortcfg['customrules'])) { @file_put_contents("{$snortcfgdir}/rules/custom.rules", base64_decode($snortcfg['customrules'])); + $no_rules_defined = false; + } else @file_put_contents("{$snortcfgdir}/rules/custom.rules", ""); + /* Log a warning if the interface has no rules defined or enabled */ + if ($no_rules_defined) + log_error(gettext("[Snort] Warning - no text rules selected for: " . snort_get_friendly_interface($snortcfg['interface']) . " ...")); + /* Build a new sid-msg.map file from the enabled */ /* rules and copy it to the interface directory. */ + log_error(gettext("[Snort] Building new sig-msg.map file for " . snort_get_friendly_interface($snortcfg['interface']) . "...")); snort_build_sid_msg_map("{$snortcfgdir}/rules/", "{$snortcfgdir}/sid-msg.map"); } -function snort_filter_preproc_rules($snortcfg, &$active_rules) { +function snort_filter_preproc_rules($snortcfg, &$active_rules, $persist_log = false) { /**************************************************/ /* This function checks the $active_rules array */ @@ -1819,11 +2199,22 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules) { /* the interface */ /* $active_rules -> rules_map array of enabled */ /* rules for the interface */ + /* */ + /* NOTE: This feature must be enabled in the GUI */ + /* by the user. Use of this feature can */ + /* severely degrade Snort's ability to */ + /* detect threats by disabling potentially */ + /* crucial detection rules. */ /**************************************************/ global $config; - if (empty($active_rules)) + $snortlogdir = SNORTLOGDIR; + $disabled_count = 0; + $log_msg = array(); + + /* Check if no rules or if this option is disabled */ + if (empty($active_rules) || $snortcfg['preproc_auto_rule_disable'] <> 'on') return; /*************************************************** @@ -1833,8 +2224,20 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules) { * IMPORTANT -- Keep this part of the code current * * with changes to preprocessor rule options in * * Snort VRT rules. * + * * + * * + * Format of array is: * + * "rule_option" => "dependent_preprocessor" * + * * + * Last Update: 04/05/2013 * + * * + * Added: http_inspect content modifiers and * + * various "service" metadata values. * + * * ***************************************************/ $rule_opts_preprocs = array("ssl_version:" => "ssl_preproc","ssl_state:" => "ssl_preproc", + "service ssl" => "ssl_preproc", "service ftp" => "ftp_preprocessor", + "service telnet" => "ftp_preprocessor", "service dns" => "dns_preprocessor", "dce_iface:" => "dce_rpc_2", "dce_opnum:" => "dce_rpc_2", "dce_stub_data;" => "dce_rpc_2", "sd_pattern:" => "sensitive_data", "sip_method:" => "sip_preproc", "sip_stat_code:" => "sip_preproc", @@ -1843,7 +2246,16 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules) { "gtp_version:" => "gtp_preproc", "modbus_func:" => "modbus_preproc", "modbus_unit:" => "modbus_preproc", "modbus_data;" => "modbus_preproc", "dnp3_func:" => "dnp3_preproc", "dnp3_obj:" => "dnp3_preproc", - "dnp3_ind:" => "dnp3_preproc", "dnp3_data;" => "dnp3_preproc"); + "dnp3_ind:" => "dnp3_preproc", "dnp3_data;" => "dnp3_preproc", + "http_client_body;" => "http_inspect", "http_cookie;" => "http_inspect", + "http_raw_cookie;" => "http_inspect", "http_header;" => "http_inspect", + "http_raw_header;" => "http_inspect", "http_method;" => "http_inspect", + "http_uri;" => "http_inspect", "http_raw_uri;" => "http_inspect", + "http_stat_code;" => "http_inspect", "http_stat_msg;" => "http_inspect", + "uricontent:" => "http_inspect", "urilen:" => "http_inspect", + "http_encode;" => "http_inspect", "service http" => "http_inspect", + "service imap" => "imap_preproc", "service pop2" => "pop_preproc", + "service pop3" => "pop_preproc", "service smtp" => "smtp_preprocessor"); /*************************************************** * Iterate the enabled rules, and check for rule * @@ -1855,31 +2267,102 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules) { ***************************************************/ foreach ($active_rules as $k1 => $rulem) { foreach ($rulem as $k2 => $v) { - if ($v['disabled'] == 0) + + /* If rule is already disabled, skip it. */ + if ($v['disabled'] == 1) continue; + foreach ($rule_opts_preprocs as $opt => $preproc) { - $pcre = "/\s*\b" . $opt . "/i"; + $pcre = "/\s*\b" . preg_quote($opt) . "/i"; if (($snortcfg[$preproc] != 'on') && preg_match($pcre, $v['rule'])) { $active_rules[$k1][$k2]['rule'] = "# " . $v['rule']; $active_rules[$k1][$k2]['disabled'] = 1; + $disabled_count++; + + /* Accumulate auto-disabled rules for logging */ + $tmp = $active_rules[$k1][$k2]['category'] . ","; + $tmp .= "{$k1}:{$k2},{$preproc},{$opt}"; + $log_msg[] = $tmp; break; } } } } + + /* Release memory we no longer need. */ + unset($rulem, $v, $preproc); + + /***************************************************************/ + /* If we are persisting the log from the last pass, then open */ + /* the log file in append mode. Otherwise open in overwrite */ + /* to clear the log in case we have zero disabled rules. */ + /* */ + /* Typically "persist log" mode is used on the second pass */ + /* when flowbit-required rules are being assessed after the */ + /* primary enforcing rules have been evaluated. */ + /***************************************************************/ + $iface = snort_get_friendly_interface($snortcfg['interface']); + $file = "{$snortlogdir}/{$iface}_disabled_preproc_rules.log"; + if ($persist_log) + $fp = fopen($file, 'a'); + else + $fp = fopen($file, 'w'); + + /***************************************************/ + /* Log a warning if we auto-disabled any rules */ + /* just so the user is aware protection is less */ + /* than optimal with the preprocessors disabled. */ + /***************************************************/ + if ($disabled_count > 0) { + log_error(gettext("[Snort] Warning: auto-disabled {$disabled_count} rules due to disabled preprocessor dependencies.")); + natcasesort($log_msg); + if ($fp) { + /* Only write the header when not persisting the log */ + if (!$persist_log) { + @fwrite($fp, "#\n# Run Time: " . date("Y-m-d H:i:s") . "\n#\n"); + @fwrite($fp, "#\n# These rules were auto-disabled because they contain options or operators\n"); + @fwrite($fp, "# dependent on preprocessors that are currently NOT ENABLED on the Preprocessors\n"); + @fwrite($fp, "# tab. Without these dependent preprocessors enabled, Snort would fail to start\n"); + @fwrite($fp, "# if the rules listed below were enabled. Therefore the listed rules have been\n"); + @fwrite($fp, "# automatically disabled. This behavior is controlled by the Auto-Rule Disable\n"); + @fwrite($fp, "# feature on the Preprocessors tab.\n#\n"); + @fwrite($fp, "# WARNING: Using the auto-disable rule feature is not recommended because it can\n"); + @fwrite($fp, "# significantly reduce the threat detection capabilities of Snort!\n#"); + @fwrite($fp, "\n# In the list below, the PREPROCESSOR column is the disabled preprocessor that\n"); + @fwrite($fp, "# triggered the auto-disable of the rule represented by GID:SID. The RULE OPTION\n"); + @fwrite($fp, "# column shows the specific rule option or content modifier contained within\n"); + @fwrite($fp, "# the rule text that requires the preprocessor be enabled in order to execute.\n#"); + @fwrite($fp, "\n# RULE CATEGORY GID:SID PREPROCESSOR RULE OPTION\n"); + } + foreach ($log_msg as $m) { + $tmp = explode(",", $m); + @fwrite($fp, sprintf("%-30s %-10s %-20s %s", $tmp[0], $tmp[1], $tmp[2], $tmp[3]) . "\n"); + } + } + log_error(gettext("[Snort] See '{$file}' for list of auto-disabled rules.")); + unset($log_msg); + } + if ($fp) + fclose($fp); } function snort_generate_conf($snortcfg) { - global $config, $g; + + global $config, $g, $flowbit_rules_file, $snort_enforcing_rules_file, $rebuild_rules; $snortdir = SNORTDIR; + $snortlibdir = SNORTLIBDIR; $snortlogdir = SNORTLOGDIR; - $flowbit_rules_file = "flowbit-required.rules"; - $snort_enforcing_rules_file = "snort.rules"; if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; + /* See if we should protect and not modify the preprocessor rules files */ + if (!empty($snortcfg['protect_preproc_rules'])) + $protect_preproc_rules = $snortcfg['protect_preproc_rules']; + else + $protect_preproc_rules = "off"; + $if_real = snort_get_real_interface($snortcfg['interface']); $snort_uuid = $snortcfg['uuid']; $snortcfgdir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}"; @@ -1902,8 +2385,8 @@ function snort_generate_conf($snortcfg) { "{$snortlogdir}/snort_{$if_real}{$snort_uuid}", "{$snortlogdir}/snort_{$if_real}{$snort_uuid}/barnyard2", "{$snortcfgdir}/preproc_rules", - "dynamicrules" => "/usr/local/lib/snort/dynamicrules", - "dynamicengine" => "/usr/local/lib/snort/dynamicengine", + "dynamicrules" => "{$snortlibdir}/dynamicrules", + "dynamicengine" => "{$snortlibdir}/dynamicengine", "dynamicpreprocessor" => "{$snortcfgdir}/dynamicpreprocessor" ); foreach ($snort_dirs as $dir) { @@ -1911,13 +2394,24 @@ function snort_generate_conf($snortcfg) { safe_mkdir($dir); } + /********************************************************************/ + /* For fail-safe on an initial startup following installation, and */ + /* before a rules update has occurred, copy the default config */ + /* files to the interface directory. If files already exist in */ + /* the interface directory, or they are newer, that means a rule */ + /* update has been done and we should leave the customized files */ + /* put in place by the rules update process. */ + /********************************************************************/ $snort_files = array("gen-msg.map", "classification.config", "reference.config", "sid-msg.map", "unicode.map", "threshold.conf", "preproc_rules/preprocessor.rules", "preproc_rules/decoder.rules", "preproc_rules/sensitive-data.rules" ); foreach ($snort_files as $file) { - if (file_exists("{$snortdir}/{$file}")) - @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); + if (file_exists("{$snortdir}/{$file}")) { + $ftime = filemtime("{$snortdir}/{$file}"); + if (!file_exists("{$snortcfgdir}/{$file}") || ($ftime > filemtime("{$snortcfgdir}/{$file}"))) + @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); + } } /* define alertsystemlog */ @@ -1936,8 +2430,7 @@ function snort_generate_conf($snortcfg) { $pfkill = ""; if ($snortcfg['blockoffenderskill'] == "on") $pfkill = "kill"; - /* No subnets to default addresses */ - $spoink_wlist = snort_build_list($snortcfg, $snortcfg['whitelistname'], true); + $spoink_wlist = snort_build_list($snortcfg, $snortcfg['whitelistname']); /* write whitelist */ @file_put_contents("{$snortcfgdir}/{$snortcfg['whitelistname']}", implode("\n", $spoink_wlist)); $spoink_type = "output alert_pf: {$snortcfgdir}/{$snortcfg['whitelistname']},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; @@ -1968,7 +2461,7 @@ function snort_generate_conf($snortcfg) { "telnet_ports" => "23","snmp_ports" => "161", "ftp_ports" => "21", "ssh_ports" => $ssh_port, "pop2_ports" => "109", "pop3_ports" => "110", "imap_ports" => "143", "sip_proxy_ports" => "5060:5090,16384:32768", - "sip_ports" => "5060, 5061", "auth_ports" => "113", "finger_ports" => "79", + "sip_ports" => "5060,5061", "auth_ports" => "113", "finger_ports" => "79", "irc_ports" => "6665,6666,6667,6668,6669,7000", "smb_ports" => "139,445", "nntp_ports" => "119", "rlogin_ports" => "513", "rsh_ports" => "514", "ssl_ports" => "443,465,563,636,989,990,992,993,994,995", @@ -1985,7 +2478,7 @@ function snort_generate_conf($snortcfg) { foreach ($snort_ports as $alias => $avalue) { if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) $snort_ports[$alias] = filter_expand_alias($snortcfg["def_{$alias}"]); - $snort_ports[$alias] = str_replace(" ", ",", trim($snort_ports[$alias])); + $snort_ports[$alias] = preg_replace('/\s+/', ',', trim($snort_ports[$alias])); $portvardef .= "portvar " . strtoupper($alias) . " [" . $snort_ports[$alias] . "]\n"; } @@ -1999,41 +2492,53 @@ preprocessor perfmonitor: time 300 file {$snortlogdir}/snort_{$if_real}{$snort_u EOD; - $def_server_flow_depth_type = '300'; - if ((!empty($snortcfg['server_flow_depth'])) || ($snortcfg['server_flow_depth'] == '0')) - $def_server_flow_depth_type = $snortcfg['server_flow_depth']; + /* Pull in the user-configurable HTTP_INSPECT global preprocessor options */ + $http_inspect_memcap = "150994944"; + if (!empty($snortcfg['http_inspect_memcap'])) + $http_inspect_memcap = $snortcfg['http_inspect_memcap']; + /* Pull in the user-configurable HTTP_INSPECT server preprocessor options */ + $server_flow_depth = '300'; + if ((!empty($snortcfg['server_flow_depth'])) || ($snortcfg['server_flow_depth'] == '0')) + $server_flow_depth = $snortcfg['server_flow_depth']; $http_server_profile = "all"; if (!empty($snortcfg['http_server_profile'])) $http_server_profile = $snortcfg['http_server_profile']; - - $def_client_flow_depth_type = '300'; + $client_flow_depth = '300'; if ((!empty($snortcfg['client_flow_depth'])) || ($snortcfg['client_flow_depth'] == '0')) - $def_client_flow_depth_type = $snortcfg['client_flow_depth']; - - if ($snortcfg['noalert_http_inspect'] == 'on') - $noalert_http_inspect = "no_alerts "; + $client_flow_depth = $snortcfg['client_flow_depth']; + if ($snortcfg['noalert_http_inspect'] == 'on' || empty($snortcfg['noalert_http_inspect'])) + $noalert_http_inspect = "no_alerts"; else $noalert_http_inspect = ""; + $http_inspect_server_opts = "enable_cookie \\\n\textended_response_inspection \\\n\tnormalize_javascript \\\n"; + $http_inspect_server_opts .= "\tinspect_gzip \\\n\tnormalize_utf \\\n\tunlimited_decompress \\\n"; + $http_inspect_server_opts .= "\tnormalize_headers \\\n\tnormalize_cookies"; + if ($snortcfg['http_inspect_enable_xff'] == "on") + $http_inspect_server_opts .= " \\\n\tenable_xff"; + + /* If Stream5 is enabled, then we can enable the "log_uri" and "log_hostname" options */ + if ($snortcfg['stream5_reassembly'] == "on") { + if ($snortcfg['http_inspect_log_uri'] == "on") + $http_inspect_server_opts .= " \\\n\tlog_uri"; + if ($snortcfg['http_inspect_log_hostname'] == "on") + $http_inspect_server_opts .= " \\\n\tlog_hostname"; + } $http_ports = str_replace(",", " ", $snort_ports['http_ports']); + /* def http_inspect */ $http_inspect = <<<EOD -# HTTP Inspect # -preprocessor http_inspect: global iis_unicode_map unicode.map 1252 compress_depth 65535 decompress_depth 65535 +# HTTP Inspect # +preprocessor http_inspect: global iis_unicode_map unicode.map 1252 compress_depth 65535 decompress_depth 65535 memcap {$http_inspect_memcap} -preprocessor http_inspect_server: server default profile {$http_server_profile} {$noalert_http_inspect}\ - ports { {$http_ports} } \ +preprocessor http_inspect_server: server default profile {$http_server_profile} {$noalert_http_inspect} \ + ports { {$http_ports} } \ http_methods { GET POST PUT SEARCH MKCOL COPY MOVE LOCK UNLOCK NOTIFY POLL BCOPY BDELETE BMOVE LINK UNLINK OPTIONS HEAD DELETE TRACE TRACK CONNECT SOURCE SUBSCRIBE UNSUBSCRIBE PROPFIND PROPPATCH BPROPFIND BPROPPATCH RPC_CONNECT PROXY_SUCCESS BITS_POST CCM_POST SMS_POST RPC_IN_DATA RPC_OUT_DATA RPC_ECHO_DATA } \ - server_flow_depth {$def_server_flow_depth_type} \ - client_flow_depth {$def_client_flow_depth_type} \ - enable_cookie \ - extended_response_inspection \ - inspect_gzip \ - normalize_utf \ - unlimited_decompress \ - normalize_javascript - + server_flow_depth {$server_flow_depth} \ + client_flow_depth {$client_flow_depth} \ + {$http_inspect_server_opts} + EOD; /* def ftp_preprocessor */ @@ -2136,28 +2641,35 @@ PIPELINING CHUNKING DATA DSN RSET QUIT ONEX QUEU STARTTLS TICK TIME TURNME VERB log_filename \ qp_decode_depth 0 \ b64_decode_depth 0 \ - bitenc_decode_depth 0 + bitenc_decode_depth 0 \ + uu_decode_depth 0 EOD; /* def sf_portscan */ + $sf_pscan_protocol = "all"; + if (!empty($snortcfg['pscan_protocol'])) + $sf_pscan_protocol = $snortcfg['pscan_protocol']; + $sf_pscan_type = "all"; + if (!empty($snortcfg['pscan_type'])) + $sf_pscan_type = $snortcfg['pscan_type']; + $sf_pscan_memcap = "10000000"; + if (!empty($snortcfg['pscan_memcap'])) + $sf_pscan_memcap = $snortcfg['pscan_memcap']; + $sf_pscan_sense_level = "medium"; if (!empty($snortcfg['pscan_sense_level'])) $sf_pscan_sense_level = $snortcfg['pscan_sense_level']; - else - $sf_pscan_sense_level = "medium"; - + $sf_pscan_ignore_scanners = "\$HOME_NET"; if (!empty($snortcfg['pscan_ignore_scanners']) && is_alias($snortcfg['pscan_ignore_scanners'])) { $sf_pscan_ignore_scanners = filter_expand_alias($snortcfg['pscan_ignore_scanners']); $sf_pscan_ignore_scanners = preg_replace('/\s+/', ',', trim($sf_pscan_ignore_scanners)); } - else - $sf_pscan_ignore_scanners = "\$HOME_NET"; $sf_portscan = <<<EOD # sf Portscan # -preprocessor sfportscan: scan_type { all } \ - proto { all } \ - memcap { 10000000 } \ +preprocessor sfportscan: scan_type { {$sf_pscan_type} } \ + proto { {$sf_pscan_protocol} } \ + memcap { {$sf_pscan_memcap} } \ sense_level { {$sf_pscan_sense_level} } \ ignore_scanners { {$sf_pscan_ignore_scanners} } @@ -2243,18 +2755,16 @@ EOD; $sensitive_data = "preprocessor sensitive_data:\n"; - /* stream5 queued settings */ - $def_max_queued_bytes_type = ''; - if ((!empty($snortcfg['max_queued_bytes'])) || ($snortcfg['max_queued_bytes'] == '0')) - $def_max_queued_bytes_type = ", max_queued_bytes {$snortcfg['max_queued_bytes']}"; - - $def_max_queued_segs_type = ''; - if ((!empty($snortcfg['max_queued_segs'])) || ($snortcfg['max_queued_segs'] == '0')) - $def_max_queued_segs_type = ", max_queued_segs {$snortcfg['max_queued_segs']}"; - - $def_stream5_mem_cap = ''; - if (!empty($snortcfg['stream5_mem_cap'])) - $def_stream5_mem_cap = ", memcap {$snortcfg['stream5_mem_cap']}"; + /**************************************************************/ + /* Default the HTTP_INSPECT preprocessor to "on" if not set. */ + /* The preprocessor is required by hundreds of Snort rules, */ + /* and without it Snort may not start and/or the number of */ + /* rules required to be disabled reduces Snort's capability. */ + /* Alerts from the HTTP_INSPECT preprocessor default to "off" */ + /* unless a specific value has been set by the user. */ + /**************************************************************/ + if (empty($snortcfg['http_inspect'])) + $snortcfg['http_inspect'] = 'on'; /* define servers and ports snortdefservers */ $snort_servers = array ( @@ -2287,15 +2797,23 @@ EOD; "perform_stat", "http_inspect", "other_preprocs", "ftp_preprocessor", "smtp_preprocessor", "ssl_preproc", "sip_preproc", "gtp_preproc", "sf_portscan", "dce_rpc_2", "dns_preprocessor", "sensitive_data", "pop_preproc", "imap_preproc", "dnp3_preproc", "modbus_preproc" ); + $default_disabled_preprocs = array( + "sf_portscan", "gtp_preproc", "sensitive_data", "dnp3_preproc", "modbus_preproc" + ); $snort_preprocessors = ""; foreach ($snort_preproc as $preproc) { - if ($snortcfg[$preproc] == 'on') { - /* NOTE: The $$ is not a bug. Its a advanced feature of php */ + if ($snortcfg[$preproc] == 'on' || empty($snortcfg[$preproc]) ) { + + /* If preprocessor is not explicitly "on" or "off", then default to "off" if in our default disabled list */ + if (empty($snortcfg[$preproc]) && in_array($preproc, $default_disabled_preprocs)) + continue; + + /* NOTE: The $$ is not a bug. It is an advanced feature of php */ if (!empty($snort_preproc_libs[$preproc])) { $preproclib = "libsf_" . $snort_preproc_libs[$preproc]; if (!file_exists($snort_dirs['dynamicpreprocessor'] . "{$preproclib}.so")) { - if (file_exists("/usr/local/lib/snort/dynamicpreprocessor/{$preproclib}.so")) { - @copy("/usr/local/lib/snort/dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); + if (file_exists("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so")) { + @copy("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); $snort_preprocessors .= $$preproc; $snort_preprocessors .= "\n"; } else @@ -2317,28 +2835,32 @@ EOD; if (file_exists("{$snortcfgdir}/classification.config")) $snort_misc_include_rules .= "include {$snortcfgdir}/classification.config\n"; if (is_dir("{$snortcfgdir}/preproc_rules")) { - if ($snortcfg['sensitive_data'] == 'on') { + if ($snortcfg['sensitive_data'] == 'on' && $protect_preproc_rules == "off") { $sedcmd = '/^#alert.*classtype:sdf/s/^#//'; if (file_exists("{$snortcfgdir}/preproc_rules/sensitive-data.rules")) $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/sensitive-data.rules\n"; } else $sedcmd = '/^alert.*classtype:sdf/s/^/#/'; if (file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") && - file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules")) { + file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules") && $protect_preproc_rules == "off") { @file_put_contents("{$g['tmp_path']}/sedcmd", $sedcmd); mwexec("/usr/bin/sed -I '' -f {$g['tmp_path']}/sedcmd {$snortcfgdir}/preproc_rules/preprocessor.rules"); mwexec("/usr/bin/sed -I '' -f {$g['tmp_path']}/sedcmd {$snortcfgdir}/preproc_rules/decoder.rules"); @unlink("{$g['tmp_path']}/sedcmd"); - $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/decoder.rules\n"; $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/preprocessor.rules\n"; - } else { + } else if (file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") && + file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules") && $protect_preproc_rules == "on") { + $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/decoder.rules\n"; + $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/preprocessor.rules\n"; + } + else { $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; - log_error("Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); + log_error("[Snort] Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); } } else { $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; - log_error("Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); + log_error("[Snort] Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); } /* generate rule sections to load */ @@ -2346,12 +2868,84 @@ EOD; $selected_rules_sections = "include \$RULE_PATH/{$snort_enforcing_rules_file}\n"; $selected_rules_sections .= "include \$RULE_PATH/{$flowbit_rules_file}\n"; $selected_rules_sections .= "include \$RULE_PATH/custom.rules\n"; + + /* Create the actual rules files and save in the interface directory */ snort_prepare_rule_files($snortcfg, $snortcfgdir); $cksumcheck = "all"; if ($snortcfg['cksumcheck'] == 'on') $cksumcheck = "none"; + /* Pull in user-configurable options for Frag3 preprocessor settings */ + $frag3_disabled = ""; + if ($snortcfg['frag3_detection'] == "off") + $frag3_disabled = ", disabled"; + $frag3_memcap = "memcap 4194304"; + if (!empty($snortcfg['frag3_memcap']) || $snortcfg['frag3_memcap'] == "0") + $frag3_memcap = "memcap {$snortcfg['frag3_memcap']}"; + $frag3_max_frags = "max_frags 8192"; + if (!empty($snortcfg['frag3_max_frags'])) + $frag3_max_frags = "max_frags {$snortcfg['frag3_max_frags']}"; + $frag3_overlap_limit = "overlap_limit 0"; + if (!empty($snortcfg['frag3_overlap_limit'])) + $frag3_overlap_limit = "overlap_limit {$snortcfg['frag3_overlap_limit']}"; + $frag3_min_frag_len = "min_fragment_length 0"; + if (!empty($snortcfg['frag3_min_frag_len'])) + $frag3_min_frag_len = "min_fragment_length {$snortcfg['frag3_min_frag_len']}"; + $frag3_timeout = "timeout 60"; + if (!empty($snortcfg['frag3_timeout'])) + $frag3_timeout = "timeout {$snortcfg['frag3_timeout']}"; + $frag3_policy = "policy bsd"; + if (!empty($snortcfg['frag3_policy'])) + $frag3_policy = "policy {$snortcfg['frag3_policy']}"; + + /* Pull in user-configurable options for Stream5 preprocessor settings */ + $stream5_reassembly = ""; + if ($snortcfg['stream5_reassembly'] == "off") + $stream5_reassembly = "disabled,"; + $stream5_track_tcp = "yes"; + if ($snortcfg['stream5_track_tcp'] =="off") + $stream5_track_tcp = "no"; + $stream5_track_udp = "yes"; + if ($snortcfg['stream5_track_udp'] =="off") + $stream5_track_udp = "no"; + $stream5_track_icmp = "no"; + if ($snortcfg['stream5_track_icmp'] =="on") + $stream5_track_icmp = "yes"; + $stream5_require_3whs = ""; + if ($snortcfg['stream5_require_3whs'] == "on") + $stream5_require_3whs = ", require_3whs 0"; + $stream5_no_reassemble_async = ""; + if ($snortcfg['stream5_no_reassemble_async'] == "on") + $stream5_no_reassemble_async = ", dont_reassemble_async"; + $stream5_dont_store_lg_pkts = ""; + if ($snortcfg['stream5_dont_store_lg_pkts'] == "on") + $stream5_dont_store_lg_pkts = ", dont_store_large_packets"; + $stream5_max_queued_bytes_type = ""; + if ((!empty($snortcfg['max_queued_bytes'])) || ($snortcfg['max_queued_bytes'] == '0')) + $stream5_max_queued_bytes_type = ", max_queued_bytes {$snortcfg['max_queued_bytes']}"; + $stream5_max_queued_segs_type = ""; + if ((!empty($snortcfg['max_queued_segs'])) || ($snortcfg['max_queued_segs'] == '0')) + $stream5_max_queued_segs_type = ", max_queued_segs {$snortcfg['max_queued_segs']}"; + $stream5_mem_cap = ""; + if (!empty($snortcfg['stream5_mem_cap'])) + $stream5_mem_cap = ", memcap {$snortcfg['stream5_mem_cap']}"; + $stream5_overlap_limit = "overlap_limit 0"; + if (!empty($snortcfg['stream5_overlap_limit'])) + $stream5_overlap_limit = "overlap_limit {$snortcfg['stream5_overlap_limit']}"; + $stream5_policy = "policy bsd"; + if (!empty($snortcfg['stream5_policy'])) + $stream5_policy = "policy {$snortcfg['stream5_policy']}"; + $stream5_tcp_timeout = "timeout 30"; + if (!empty($snortcfg['stream5_tcp_timeout'])) + $stream5_tcp_timeout = "timeout {$snortcfg['stream5_tcp_timeout']}"; + $stream5_udp_timeout = "timeout 30"; + if (!empty($snortcfg['stream5_udp_timeout'])) + $stream5_udp_timeout = "timeout {$snortcfg['stream5_udp_timeout']}"; + $stream5_icmp_timeout = "timeout 30"; + if (!empty($snortcfg['stream5_icmp_timeout'])) + $stream5_icmp_timeout = "timeout {$snortcfg['stream5_icmp_timeout']}"; + /* build snort configuration file */ $snort_conf_text = <<<EOD @@ -2393,6 +2987,9 @@ config pcre_match_limit_recursion: 1500 config detection: search-method {$snort_performance} search-optimize max-pattern-len 20 max_queue_events 5 config event_queue: max_queue 8 log 5 order_events content_length +# Configure to show year in timestamps +config show_year + # Configure protocol aware flushing # # For more information see README.stream5 # config paf_max: 16000 @@ -2410,12 +3007,13 @@ preprocessor normalize_ip6 preprocessor normalize_icmp6 # Flow and stream # -preprocessor frag3_global: max_frags 65536 -preprocessor frag3_engine: policy bsd detect_anomalies overlap_limit 10 min_fragment_length 100 timeout 180 +preprocessor frag3_global: {$frag3_memcap}, {$frag3_max_frags}{$frag3_disabled} +preprocessor frag3_engine: {$frag3_policy} detect_anomalies {$frag3_timeout} {$frag3_overlap_limit} {$frag3_min_frag_len} -preprocessor stream5_global: track_tcp yes, track_udp yes, track_icmp no, max_tcp 262144, max_udp 131072, max_active_responses 2, min_response_seconds 5{$def_stream5_mem_cap} -preprocessor stream5_tcp: policy BSD, overlap_limit 10, timeout 180, ports both all{$def_max_queued_bytes_type}{$def_max_queued_segs_type} -preprocessor stream5_udp: timeout 180 +preprocessor stream5_global:{$stream5_reassembly} track_tcp {$stream5_track_tcp}, track_udp {$stream5_track_udp}, track_icmp {$stream5_track_icmp}, max_tcp 262144, max_udp 131072, max_active_responses 2, min_response_seconds 5{$stream5_mem_cap} +preprocessor stream5_tcp: {$stream5_policy}, {$stream5_overlap_limit}, {$stream5_tcp_timeout}, ports both all{$stream5_max_queued_bytes_type}{$stream5_max_queued_segs_type}{$stream5_require_3whs}{$stream5_no_reassemble_async}$stream5_dont_store_lg_pkts +preprocessor stream5_udp: {$stream5_udp_timeout} +preprocessor stream5_icmp: {$stream5_icmp_timeout} {$snort_preprocessors} @@ -2450,4 +3048,193 @@ EOD; unset($home_net, $external_net, $vardef, $portvardef); } +/* Uses XMLRPC to synchronize the changes to a remote node */ +function snort_sync_on_changes() { + global $config, $g, $is_postinstall; + + /* Do not attempt a package sync while booting up or installing package */ + if ($g['booting'] || $is_postinstall) + return; + + if (is_array($config['installedpackages']['snortsync']['config'])){ + $snort_sync=$config['installedpackages']['snortsync']['config'][0]; + $synconchanges = $snort_sync['varsynconchanges']; + $synctimeout = $snort_sync['varsynctimeout']; + $syncdownloadrules = $snort_sync['vardownloadrules']; + switch ($synconchanges){ + case "manual": + if (is_array($snort_sync[row])){ + $rs=$snort_sync[row]; + } + else{ + log_error("[snort] xmlrpc sync is enabled but there are no hosts configured as replication targets."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['varsyncipaddress']=$system_carp['synchronizetoip']; + $rs[0]['varsyncusername']=$system_carp['username']; + $rs[0]['varsyncpassword']=$system_carp['password']; + $rs[0]['varsyncsnortstart']="no"; + if ($system_carp['synchronizetoip'] ==""){ + log_error("[snort] xmlrpc sync is enabled but there are no system backup hosts configured as replication targets."); + return; + } + } + else{ + log_error("[snort] xmlrpc sync is enabled but there are no system backup hosts configured as replication targets."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[snort] Snort pkg xmlrpc sync is starting."); + foreach($rs as $sh){ + if ($sh['varsyncsnortstart']) + $syncstartsnort = $sh['varsyncsnortstart']; + else + $syncstartsnort = "OFF"; + $sync_to_ip = $sh['varsyncipaddress']; + $password = $sh['varsyncpassword']; + if($sh['varsyncusername']) + $username = $sh['varsyncusername']; + else + $username = 'admin'; + if($password && $sync_to_ip) + snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $password, $synctimeout, $syncstartsnort); + } + log_error("[snort] Snort pkg xmlrpc sync completed."); + } + } +} + +/* Do the actual XMLRPC sync */ +function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $password, $synctimeout, $syncstartsnort) { + global $config, $g, $is_postinstall; + + /* Do not attempt a package sync while booting up or installing package */ + if ($g['booting'] || $is_postinstall) + return; + + if(!$username || !$password || !$sync_to_ip) { + log_error("[snort] A required XMLRPC sync parameter (user, host IP or password) is empty ... aborting pkg sync"); + return; + } + + /* Test key variables and set defaults if empty */ + if(!$synctimeout) + $synctimeout=150; + + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['snortglobal'] = $config['installedpackages']['snortglobal']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("[snort] Beginning Snort pkg configuration XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + + /* send our XMLRPC message and timeout after defined sync timeout value*/ + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "A communications error occurred while attempting snort XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "snort Settings Sync", ""); + } elseif($resp->faultCode()) { + $error = "An error code was received while attempting snort XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "snort Settings Sync", ""); + } else { + log_error("[snort] Snort pkg configuration XMLRPC sync successfully completed with {$url}:{$port}."); + } + + $downloadrulescmd = ""; + if ($syncdownloadrules == "yes") { + $downloadrulescmd = "log_error(gettext(\"[snort] XMLRPC pkg sync: Update of downloaded rule sets requested...\"));\n"; + $downloadrulescmd .= "include_once(\"/usr/local/pkg/snort/snort_check_for_rule_updates.php\");\n"; + } + $snortstart = ""; + if ($syncstartsnort == "ON") { + $snortstart = "log_error(gettext(\"[snort] XMLRPC pkg sync: Checking Snort status...\"));\n"; + $snortstart .= "if (!is_process_running(\"snort\")) {\n"; + $snortstart .= "log_error(gettext(\"[snort] XMLRPC pkg sync: Snort not running. Sending a start command...\"));\n"; + $snortstart .= "exec(\"/usr/local/etc/rc.d/snort.sh start 2>&1 &\");\n}\n"; + $snortstart .= "else {log_error(gettext(\"[snort] XMLRPC pkg sync: Snort is running...\"));\n}\n"; + } + + /* Build a series of commands for the secondary host to execute that will load the new settings. */ + $execcmd = <<<EOD + require_once("/usr/local/pkg/snort/snort.inc"); + require_once("service-utils.inc"); + global \$g, \$rebuild_rules, \$snort_gui_include, \$is_postinstall, \$pkg_interface; + \$orig_pkg_interface = \$pkg_interface; + \$is_postinstall = true; + \$snort_gui_include = false; + \$pkg_interface = "console"; + {$downloadrulescmd} + \$is_postinstall = false; + log_error(gettext("[snort] XMLRPC pkg sync: Generating snort.conf file using Master Host's settings...")); + \$rebuild_rules = "on"; + sync_snort_package_config(); + \$rebuild_rules = "off"; + {$snortstart} + log_error(gettext("[snort] XMLRPC pkg sync process on this host is complete...")); + \$pkg_interface = \$orig_pkg_interface; + return true; + +EOD; + + /* assemble xmlrpc payload */ + $method = 'pfsense.exec_php'; + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("[snort] Snort XMLRPC sending reload configuration cmd to {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "A communications error occurred while attempting snort XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "snort Settings Sync", ""); + } elseif($resp->faultCode()) { + $error = "An error code was received while attempting snort XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "snort Settings Sync", ""); + } else { + log_error("[snort] Snort pkg XMLRPC reload configuration success with {$url}:{$port} (pfsense.exec_php)."); + } +} + ?> diff --git a/config/snort/snort.xml b/config/snort/snort.xml index b18e66e1..1066b75c 100755 --- a/config/snort/snort.xml +++ b/config/snort/snort.xml @@ -46,8 +46,8 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>Snort</name> - <version>2.9.2.3</version> - <title>Services:2.9.2.3 pkg v. 2.5.3</title> + <version>2.9.4.1</version> + <title>Services:2.9.4.1 pkg v. 2.5.8</title> <include_file>/usr/local/pkg/snort/snort.inc</include_file> <menu> <name>Snort</name> @@ -74,6 +74,11 @@ <item>http://www.pfsense.com/packages/config/snort/snort_check_cron_misc.inc</item> </additional_files_needed> <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/snort_sync.xml</item> + </additional_files_needed> + <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/snort/snort_alerts.php</item> @@ -163,6 +168,21 @@ <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/snort/snort_interfaces_suppress_edit.php</item> </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/snort_log_view.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/snort_list_view.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/snort_rules_flowbits.php</item> + </additional_files_needed> <fields> </fields> <custom_add_php_command> @@ -177,3 +197,4 @@ snort_deinstall(); </custom_php_deinstall_command> </packagegui> + diff --git a/config/snort/snort_alerts.php b/config/snort/snort_alerts.php index e6ebefeb..607fba54 100755 --- a/config/snort/snort_alerts.php +++ b/config/snort/snort_alerts.php @@ -38,6 +38,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); $snortalertlogt = $config['installedpackages']['snortglobal']['snortalertlogtype']; +$supplist = array(); if ($_GET['instance']) $instanceid = $_GET['instance']; @@ -80,8 +81,10 @@ if ($_POST['todelete'] || $_GET['todelete']) { $ip = $_POST['todelete']; else if($_GET['todelete']) $ip = $_GET['todelete']; - if (is_ipaddr($ip)) + if (is_ipaddr($ip)) { exec("/sbin/pfctl -t snort2c -T delete {$ip}"); + $savemsg = "Host IP address {$ip} has been removed from the Blocked Table."; + } } if ($_GET['act'] == "addsuppress" && is_numeric($_GET['sidid']) && is_numeric($_GET['gen_id'])) { @@ -99,7 +102,7 @@ if ($_GET['act'] == "addsuppress" && is_numeric($_GET['sidid']) && is_numeric($_ $s_list = array(); $s_list['name'] = $a_instance[$instanceid]['interface'] . "suppress"; $s_list['uuid'] = uniqid(); - $s_list['descr'] = "Auto generted list for suppress"; + $s_list['descr'] = "Auto-generated list for suppress"; $s_list['suppresspassthru'] = base64_encode($suppress); $a_suppress[] = $s_list; $a_instance[$instanceid]['suppresslistname'] = $s_list['name']; @@ -115,6 +118,7 @@ if ($_GET['act'] == "addsuppress" && is_numeric($_GET['sidid']) && is_numeric($_ } } } + $savemsg = "An entry for 'suppress gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']}' has been added to the Suppress List."; write_config(); sync_snort_package_config(); } @@ -157,6 +161,9 @@ if ($_POST['download']) { exit; } +/* Load up an array with the current Suppression List GID,SID values */ +$supplist = snort_load_suppress_sigs($a_instance[$instanceid]); + $pgtitle = "Services: Snort: Snort Alerts"; include_once("head.inc"); @@ -177,6 +184,9 @@ if ($pconfig['arefresh'] == 'on') if ($input_errors) { print_input_errors($input_errors); // TODO: add checks } + if ($savemsg) { + print_info_box($savemsg); + } ?> <form action="/snort/snort_alerts.php" method="post" id="formalert"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> @@ -190,20 +200,20 @@ if ($pconfig['arefresh'] == 'on') $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array); ?> </td></tr> <tr> - <td> - <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> <tr> - <td width="22%" class="listtopic"><?php printf(gettext('Last %s Alert Entries.'),$anentries); ?></td> - <td width="78%" class="listtopic"><?php echo gettext('Latest Alert Entries Are Listed First.'); ?></td> + <td colspan="2" class="listtopic"><?php echo gettext("Alert Log View Settings"); ?></td> </tr> <tr> <td width="22%" class="vncell"><?php echo gettext('Instance to inspect'); ?></td> <td width="78%" class="vtable"> - <br/> <select name="instance" id="instance" class="formselect" onChange="document.getElementById('formalert').submit()"> + <select name="instance" id="instance" class="formselect" onChange="document.getElementById('formalert').submit()"> <?php foreach ($a_instance as $id => $instance) { $selected = ""; @@ -212,14 +222,14 @@ if ($pconfig['arefresh'] == 'on') echo "<option value='{$id}' {$selected}> (" . snort_get_friendly_interface($instance['interface']) . "){$instance['descr']}</option>\n"; } ?> - </select><br/> <?php echo gettext('Choose which instance alerts you want to inspect.'); ?> + </select> <?php echo gettext('Choose which instance alerts you want to inspect.'); ?> </td> <tr> <td width="22%" class="vncell"><?php echo gettext('Save or Remove Logs'); ?></td> <td width="78%" class="vtable"> - <input name="download" type="submit" class="formbtn" value="Download"> <?php echo gettext('All ' . - 'log files will be saved.'); ?> <a href="/snort/snort_alerts.php?action=clear&instance=<?=$instanceid;?>"> - <input name="delete" type="button" class="formbtn" value="Clear" + <input name="download" type="submit" class="formbtns" value="Download"> <?php echo gettext('All ' . + 'log files will be saved.'); ?> <a href="/snort/snort_alerts.php?action=clear&instance=<?=$instanceid;?>"> + <input name="delete" type="submit" class="formbtns" value="Clear" onclick="return confirm('Do you really want to remove all instance logs?')"></a> <span class="red"><strong><?php echo gettext('Warning:'); ?></strong></span> <?php echo ' ' . gettext('all log files will be deleted.'); ?> </td> @@ -227,32 +237,45 @@ if ($pconfig['arefresh'] == 'on') <tr> <td width="22%" class="vncell"><?php echo gettext('Auto Refresh and Log View'); ?></td> <td width="78%" class="vtable"> - <input name="save" type="submit" class="formbtn" value="Save"> + <input name="save" type="submit" class="formbtns" value="Save"> <?php echo gettext('Refresh'); ?> <input name="arefresh" type="checkbox" value="on" <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['arefresh']=="on") echo "checked"; ?>> - <?php printf(gettext('%sDefault%s is %sON%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> + <?php printf(gettext('%sDefault%s is %sON%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> <input name="alertnumber" type="text" class="formfld" id="alertnumber" size="5" value="<?=htmlspecialchars($anentries);?>"> - <?php printf(gettext('Enter the number of log entries to view. %sDefault%s is %s250%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> + <?php printf(gettext('Enter number of log entries to view. %sDefault%s is %s250%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> </td> </tr> <tr> - <td colspan="2" ><br/><br/></td> + <td colspan="2" class="listtopic"><?php printf(gettext("Last %s Alert Entries"), $anentries); ?> + <?php echo gettext("(Most recent entries are listed first)"); ?></td> </tr> <tr> - <td width="100%" colspan="2" class='vtable'> - <table id="myTable" width="100%" class="sortable" border="1" cellpadding="0" cellspacing="0"> - <thead> - <th class='listhdr' width='10%' axis="date"><?php echo gettext("Date"); ?></th> - <th class='listhdrr' width='5%' axis="number"><?php echo gettext("PRI"); ?></th> - <th class='listhdrr' width='3%' axis="string"><?php echo gettext("PROTO"); ?></th> - <th class='listhdrr' width='7%' axis="string"><?php echo gettext("CLASS"); ?></th> - <th class='listhdrr' width='15%' axis="string"><?php echo gettext("SRC"); ?></th> - <th class='listhdrr' width='5%' axis="string"><?php echo gettext("SRCPORT"); ?></th> - <th class='listhdrr' width='15%' axis="string"><?php echo gettext("DST"); ?></th> - <th class='listhdrr' width='5%' axis="string"><?php echo gettext("DSTPORT"); ?></th> - <th class='listhdrr' width='5%' axis="string"><?php echo gettext("SID"); ?></th> - <th class='listhdrr' width='20%' axis="string"><?php echo gettext("DESCRIPTION"); ?></th> - </thead> + <td width="100%" colspan="2"> + <table id="myTable" style="table-layout: fixed;" width="100%" class="sortable" border="1" cellpadding="0" cellspacing="0"> + <colgroup> + <col width="9%" align="center" axis="date"> + <col width="45" align="center" axis="number"> + <col width="65" align="center" axis="string"> + <col width="10%" axis="string"> + <col width="13%" align="center" axis="string"> + <col width="8%" align="center" axis="string"> + <col width="13%" align="center" axis="string"> + <col width="8%" align="center" axis="string"> + <col width="9%" align="center" axis="number"> + <col axis="string"> + </colgroup> + <thead> + <th class="listhdrr" axis="date"><?php echo gettext("DATE"); ?></th> + <th class="listhdrr" axis="number"><?php echo gettext("PRI"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("PROTO"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("CLASS"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("SRC"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("SPORT"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("DST"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("DPORT"); ?></th> + <th class="listhdrr" axis="number"><?php echo gettext("SID"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("DESCRIPTION"); ?></th> + </thead> <tbody> <?php @@ -269,8 +292,10 @@ if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { if(count($fields) < 11) continue; + /* Time */ + $alert_time = substr($fields[0], strpos($fields[0], '-')+1, -8); /* Date */ - $alert_date = substr($fields[0], 0, -8); + $alert_date = substr($fields[0], 0, strpos($fields[0], '-')); /* Description */ $alert_descr = $fields[4]; $alert_descr_url = urlencode($fields[4]); @@ -281,40 +306,43 @@ if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { /* IP SRC */ $alert_ip_src = $fields[6]; if (isset($tmpblocked[$fields[6]])) { - $alert_ip_src .= "<a href='?instance={$id}&todelete=" . trim(urlencode($fields[6])) . "'> - <img title=\"" . gettext("Remove from blocked ips") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a>"; + $alert_ip_src .= "<br/><a href='?instance={$id}&todelete=" . trim(urlencode($fields[6])) . "'> + <img title=\"" . gettext("Remove host from Blocked Table") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Remove from Blocked Hosts\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"/></a>"; } /* IP SRC Port */ $alert_src_p = $fields[7]; /* IP Destination */ $alert_ip_dst = $fields[8]; if (isset($tmpblocked[$fields[8]])) { - $alert_ip_dst .= "<a href='?instance={$id}&todelete=" . trim(urlencode($fields[8])) . "'> - <img title=\"" . gettext("Remove from blocked ips") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a>"; + $alert_ip_dst .= "<br/><a href='?instance={$id}&todelete=" . trim(urlencode($fields[8])) . "'> + <img title=\"" . gettext("Remove host from Blocked Table") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Remove from Blocked Hosts\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"/></a>"; } /* IP DST Port */ $alert_dst_p = $fields[9]; /* SID */ - $alert_sid_str = "{$fields[1]}:{$fields[2]}:{$fields[3]}"; + $alert_sid_str = "{$fields[1]}:{$fields[2]}"; + if (!isset($supplist[$fields[1]][$fields[2]])) { + $sidsupplink = "<a href='?instance={$instanceid}&act=addsuppress&sidid={$fields[2]}&gen_id={$fields[1]}&descr={$alert_descr_url}'>"; + $sidsupplink .= "<img src='../themes/{$g['theme']}/images/icons/icon_plus.gif' width='10' height='10' border='0' "; + $sidsupplink .= "title='" . gettext("Add this gen_id:sig_id to Suppress List") . "'></a>"; + } + else { + $sidsupplink = "<img src='../themes/{$g['theme']}/images/icons/icon_plus_d.gif' width='10' height='10' border='0' "; + $sidsupplink .= "title='" . gettext("This gen_id:sig_id already in Suppress List") . "'/>"; + } $alert_class = $fields[11]; echo "<tr> - <td class='listr' width='10%'>{$alert_date}</td> - <td class='listr' width='5%' >{$alert_priority}</td> - <td class='listr' width='3%'>{$alert_proto}</td> - <td class='listr' width='7%' >{$alert_class}</td> - <td class='listr' width='15%'>{$alert_ip_src}</td> - <td class='listr' width='5%'>{$alert_src_p}</td> - <td class='listr' width='15%'>{$alert_ip_dst}</td> - <td class='listr' width='5%'>{$alert_dst_p}</td> - <td class='listr' width='5%' > - {$alert_sid_str} - <a href='?instance={$instanceid}&act=addsuppress&sidid={$fields[2]}&gen_id={$fields[1]}&descr={$alert_descr_url}'> - <img src='../themes/{$g['theme']}/images/icons/icon_plus.gif' - width='10' height='10' border='0' - title='" . gettext("click to add to suppress list") . "'></a> - </td> - <td class='listr' width='20%'>{$alert_descr}</td> + <td class='listr' align='center'>{$alert_date}<br/>{$alert_time}</td> + <td class='listr' align='center'>{$alert_priority}</td> + <td class='listr' align='center'>{$alert_proto}</td> + <td class='listr' style=\"word-wrap:break-word;\">{$alert_class}</td> + <td class='listr' align='center'>{$alert_ip_src}</td> + <td class='listr' align='center'>{$alert_src_p}</td> + <td class='listr' align='center'>{$alert_ip_dst}</td> + <td class='listr' align='center'>{$alert_dst_p}</td> + <td class='listr' align='center'>{$alert_sid_str}<br/>{$sidsupplink}</td> + <td class='listr' style=\"word-wrap:break-word;\">{$alert_descr}</td> </tr>\n"; $counter++; @@ -329,6 +357,7 @@ if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { </td> </tr> </table> +</div> </td></tr> </table> </form> diff --git a/config/snort/snort_barnyard.php b/config/snort/snort_barnyard.php index ccbe3c26..a7f04e39 100644 --- a/config/snort/snort_barnyard.php +++ b/config/snort/snort_barnyard.php @@ -32,7 +32,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $rebuild_rules; $id = $_GET['id']; if (isset($_POST['id'])) @@ -87,6 +87,9 @@ if ($_POST) { } write_config(); + + /* No need to rebuild rules if just toggling Barnyard2 on or off */ + $rebuild_rules = "off"; sync_snort_package_config(); /* after click go to this page */ @@ -147,20 +150,32 @@ function enable_change(enable_change) { <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td>'; + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface "); $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Barnyard2 " . "Settings"); ?></td> @@ -173,10 +188,10 @@ function enable_change(enable_change) { <?php echo gettext("This will enable barnyard2 for this interface. You will also have to set the database credentials."); ?></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Mysql Settings"); ?></td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("MySQL Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Log to a Mysql Database"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log to a MySQL Database"); ?></td> <td width="78%" class="vtable"><input name="barnyard_mysql" type="text" class="formfld" id="barnyard_mysql" size="100" value="<?=htmlspecialchars($pconfig['barnyard_mysql']);?>"> <br> @@ -207,10 +222,12 @@ function enable_change(enable_change) { <td width="22%" valign="top"> </td> <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> - <?php echo gettext("Please save your settings befor you click start."); ?> </td> + <?php echo gettext("Please save your settings before you click start."); ?> </td> </tr> </table> - + </div> + </td> + </tr> </table> </form> <script language="JavaScript"> diff --git a/config/snort/snort_blocked.php b/config/snort/snort_blocked.php index def5dd22..5fb7e608 100644 --- a/config/snort/snort_blocked.php +++ b/config/snort/snort_blocked.php @@ -134,62 +134,70 @@ if ($pconfig['brefresh'] == 'on') <?php if ($savemsg) print_info_box($savemsg); ?> <form action="/snort/snort_blocked.php" method="post"> -<table width="99%" border="0" cellpadding="0" cellspacing="0"> -<tr><td> -<?php - $tab_array = array(); - $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); - $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); - $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); - $tab_array[4] = array(gettext("Blocked"), true, "/snort/snort_blocked.php"); - $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); - $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - display_top_tabs($tab_array); -?> -</td></tr> - <tr> - <td> - <table id="maintable" class="tabcont" width="100%" border="0" - cellpadding="0" cellspacing="0"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td> + <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), true, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + ?> + </td> +</tr> +<tr> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td width="22%" colspan="0" class="listtopic"><?php printf(gettext("Last %s " . - "Blocked."), $bnentries); ?></td> - <td width="78%" class="listtopic"><?php echo gettext("This page lists hosts that have " . - "been blocked by Snort."); ?> <?=$blocked_msg_txt;?></td> + <td colspan="2" class="listtopic"><?php echo gettext("Blocked Hosts Log View Settings"); ?></td> </tr> <tr> <td width="22%" class="vncell"><?php echo gettext("Save or Remove Hosts"); ?></td> <td width="78%" class="vtable"> - <input name="download" type="submit" class="formbtn" value="Download"> <?php echo gettext("All " . - "blocked hosts will be saved."); ?> <input name="remove" type="submit" - class="formbtn" value="Clear"> <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> - <?php echo gettext("all hosts will be removed."); ?></form> + <input name="download" type="submit" class="formbtns" value="Download"> <?php echo gettext("All " . + "blocked hosts will be saved."); ?> <input name="remove" type="submit" + class="formbtns" value="Clear"> <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> + <?php echo gettext("all hosts will be removed."); ?> </td> </tr> <tr> <td width="22%" class="vncell"><?php echo gettext("Auto Refresh and Log View"); ?></td> <td width="78%" class="vtable"> - <input name="save" type="submit" class="formbtn" value="Save"> <?php echo gettext("Refresh"); ?> <input + <input name="save" type="submit" class="formbtns" value="Save"> <?php echo gettext("Refresh"); ?> <input name="brefresh" type="checkbox" value="on" <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=="on" || $config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=='') echo "checked"; ?>> - <?php printf(gettext("%sDefault%s is %sON%s."), '<strong>', '</strong>', '<strong>', '</strong>'); ?> <input + <?php printf(gettext("%sDefault%s is %sON%s."), '<strong>', '</strong>', '<strong>', '</strong>'); ?> <input name="blertnumber" type="text" class="formfld" id="blertnumber" size="5" value="<?=htmlspecialchars($bnentries);?>"> <?php printf(gettext("Enter the " . "number of blocked entries to view. %sDefault%s is %s500%s."), '<strong>', '</strong>', '<strong>', '</strong>'); ?> </td> </tr> - <tr> - <td colspan="2"> - <table id="sortabletable1" class="sortable" width="100%" border="0" - cellpadding="0" cellspacing="0"> - <tr id="frheader"> - <td width="5%" class="listhdrr">#</td> - <td width="15%" class="listhdrr"><?php echo gettext("IP"); ?></td> - <td width="70%" class="listhdrr"><?php echo gettext("Alert Description"); ?></td> - <td width="5%" class="listhdrr"><?php echo gettext("Remove"); ?></td> - </tr> - <?php + <tr> + <td colspan="2" class="listtopic"><?php printf(gettext("Last %s Hosts Blocked by Snort"), $bnentries); ?></td> + </tr> + <tr> + <td colspan="2"> + <table id="sortabletable1" style="table-layout: fixed;" class="sortable" width="100%" border="0" cellpadding="2" cellspacing="0"> + <colgroup> + <col width="5%" align="center" axis="number"> + <col width="15%" align="center" axis="string"> + <col width="70%" align="left" axis="string"> + <col width="10%" align="center"> + </colgroup> + <thead> + <th class="listhdrr" axis="number">#</th> + <th class="listhdrr" axis="string"><?php echo gettext("IP"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("Alert Description"); ?></th> + <th class="listhdrr"><?php echo gettext("Remove"); ?></th> + </thead> + <tbody> + <?php /* set the arrays */ $blocked_ips_array = array(); if (is_array($blocked_ips)) { @@ -232,37 +240,49 @@ if ($pconfig['brefresh'] == 'on') $src_ip_list[$blocked_ip] = array("N\A\n"); } - /* buil final list, preg_match, buld html */ + /* build final list, preg_match, build html */ $counter = 0; foreach($src_ip_list as $blocked_ip => $blocked_msg) { - $blocked_desc = "<br/>" . implode("<br/>", $blocked_msg); + $blocked_desc = implode("<br/>", $blocked_msg); if($counter > $bnentries) break; else $counter++; /* use one echo to do the magic*/ - echo "<tr> - <td width='5%' > {$counter}</td> - <td width='15%' > {$blocked_ip}</td> - <td width='70%' > {$blocked_desc}</td> - <td width='5%' align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($blocked_ip)) . "'> - <img title=\"" . gettext("Delete") . "\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> - </tr>\n"; - + echo "<tr> + <td align=\"center\" valign=\"middle\" class=\"listr\">{$counter}</td> + <td valign=\"middle\" class=\"listr\">{$blocked_ip}</td> + <td valign=\"middle\" class=\"listr\">{$blocked_desc}</td> + <td align=\"center\" valign=\"middle\" class=\"listr\"><a href='snort_blocked.php?todelete=" . trim(urlencode($blocked_ip)) . "'> + <img title=\"" . gettext("Delete host from Blocked Table") . "\" border=\"0\" name='todelete' id='todelete' alt=\"Delete host from Blocked Table\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> + </tr>\n"; } - echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\">{$counter} items listed.</td></tr>"; - } else - echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\"><br><strong>There are currently no items being blocked by snort.</strong></td></tr>"; - + } ?> - </table> - </td> - </tr> -</table> - </td> - </tr> + </tbody> + </table> + </td> + </tr> + <tr> + <td colspan="2" class="vexpl" align="center"> + <?php if (!empty($blocked_ips_array)) { + if ($counter > 1) + echo "{$counter}" . gettext(" host IP addresses are currently being blocked."); + else + echo "{$counter}" . gettext(" host IP address is currently being blocked."); + } + else { + echo gettext("There are currently no hosts being blocked by Snort."); + } + ?> + </td> + </tr> + </table> + </div> + </td> +</tr> </table> </form> <?php diff --git a/config/snort/snort_check_for_rule_updates.php b/config/snort/snort_check_for_rule_updates.php index af5d378c..3e3dd658 100755 --- a/config/snort/snort_check_for_rule_updates.php +++ b/config/snort/snort_check_for_rule_updates.php @@ -31,71 +31,175 @@ require_once("functions.inc"); require_once("service-utils.inc"); -require_once("/usr/local/pkg/snort/snort.inc"); +require_once "/usr/local/pkg/snort/snort.inc"; -global $snort_gui_include; +global $snort_gui_include, $vrt_enabled, $et_enabled, $rebuild_rules, $snort_rules_upd_log; +global $protect_preproc_rules, $is_postinstall, $snort_community_rules_filename; +global $snort_community_rules_url, $snort_rules_file, $emergingthreats_filename, $g, $pkg_interface; $snortdir = SNORTDIR; +$snortlibdir = SNORTLIBDIR; +$snortlogdir = SNORTLOGDIR; -if (!isset($snort_gui_include)) +if ($snort_gui_include) + $pkg_interface = ""; +else $pkg_interface = "console"; -$tmpfname = "{$snortdir}/tmp/snort_rules_up"; -$snort_filename_md5 = "{$snort_rules_file}.md5"; -$snort_filename = "{$snort_rules_file}"; -$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; -$emergingthreats_filename = "emerging.rules.tar.gz"; - /* define checks */ $oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; +$snortcommunityrules = $config['installedpackages']['snortglobal']['snortcommunityrules']; $vrt_enabled = $config['installedpackages']['snortglobal']['snortdownload']; $et_enabled = $config['installedpackages']['snortglobal']['emergingthreats']; -/* Start of code */ -conf_mount_rw(); +/* Directory where we download rule tarballs */ +$tmpfname = "{$snortdir}/tmp/snort_rules_up"; -if (!is_dir($tmpfname)) - exec("/bin/mkdir -p {$tmpfname}"); +/* Snort VRT rules files and URL */ +$snort_filename_md5 = "{$snort_rules_file}.md5"; +$snort_filename = "{$snort_rules_file}"; +//$snort_rule_url = "http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/"; +/* Use current Sourcefire VRT download URL and abandon the old CGI one */ +$snort_rule_url = "https://www.snort.org/reg-rules/"; + +/* Emerging Threats rules MD5 file */ +$emergingthreats_filename_md5 = "{$emergingthreats_filename}.md5"; + +/* Snort GPLv2 Community Rules MD5 file */ +$snort_community_rules_filename_md5 = "{$snort_community_rules_filename}.md5"; + +/* Custom function for rules file download via URL */ +function snort_download_file_url($url, $file_out) { + + /************************************************/ + /* This function downloads the file specified */ + /* by $url using the CURL library functions and */ + /* saves the content to the file specified by */ + /* $file. */ + /* */ + /************************************************/ + + global $g, $config, $pkg_interface, $last_curl_error; + + /* Array of message strings for HTTP Response Codes */ + $http_resp_msg = array( 200 => "OK", 202 => "Accepted", 204 => "No Content", 205 => "Reset Content", + 206 => "Partial Content", 301 => "Moved Permanently", 302 => "Found", + 305 => "Use Proxy", 307 => "Temporary Redirect", 400 => "Bad Request", + 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", + 404 => "Not Found", 405 => "Method Not Allowed", 407 => "Proxy Authentication Required", + 408 => "Request Timeout", 410 => "Gone", 500 => "Internal Server Error", + 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", + 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported" ); + + $last_curl_error = ""; + + /* If not in console mode, use the built-in progress-bar function */ + if ($pkg_interface <> "console") + return download_file_with_progress_bar($url, $file_out); + + /* Otherwise, use our custom function with no output */ + /* (Note: required to suppress errors from XMLRPC) */ + $fp = fopen($file_out, "wb"); + if ($fp) { + $ch = curl_init($url); + if (!$ch) + return false; + curl_setopt($ch, CURLOPT_FILE, $fp); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Win64; x64; Trident/6.0)"); + /* Don't verify SSL peers since we don't have the certificates to do so. */ + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($ch, CURLOPT_TIMEOUT, 0); + $counter = 0; + $rc = true; + /* Try up to 4 times to download the file before giving up */ + while ($counter < 4) { + $counter++; + $rc = curl_exec($ch); + if ($rc === true) + break; + sleep(15); + } + if ($rc === false) + $last_curl_error = curl_error($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (isset($http_resp_msg[$http_code])) + $last_curl_error = $http_resp_msg[$http_code]; + curl_close($ch); + fclose($fp); + /* If we had to try more than once, log it */ + if ($counter > 1) + log_error(gettext("File '" . basename($file_out) . "' download attempts: {$counter} ...")); + return ($http_code == 200) ? true : $http_code; + } + else { + $last_curl_error = gettext("Failed to create file " . $file_out); + log_error(gettext("[Snort] Failed to create file {$file_out} ...")); + return false; + } +} -/* Set user agent to Mozilla */ -ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); -ini_set("memory_limit","150M"); +/* Start of code */ +conf_mount_rw(); /* remove old $tmpfname files */ if (is_dir("{$tmpfname}")) exec("/bin/rm -r {$tmpfname}"); -/* Make sure snortdir exits */ +/* Make sure required snortdirs exsist */ exec("/bin/mkdir -p {$snortdir}/rules"); exec("/bin/mkdir -p {$snortdir}/signatures"); +exec("/bin/mkdir -p {$snortdir}/preproc_rules"); exec("/bin/mkdir -p {$tmpfname}"); -exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules"); +exec("/bin/mkdir -p {$snortlibdir}/dynamicrules"); +exec("/bin/mkdir -p {$snortlogdir}"); + +/* See if we need to automatically clear the Update Log based on 1024K size limit */ +if (file_exists($snort_rules_upd_log)) { + if (1048576 < filesize($snort_rules_upd_log)) + exec("/bin/rm -r {$snort_rules_upd_log}"); +} + +/* Log start time for this rules update */ +error_log(gettext("Starting rules update... Time: " . date("Y-m-d H:i:s") . "\n"), 3, $snort_rules_upd_log); +$last_curl_error = ""; /* download md5 sig from snort.org */ if ($snortdownload == 'on') { - update_status(gettext("Downloading snort.org md5 file...")); - $max_tries = 4; - while ($max_tries > 0) { - $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); - if (false === $image) { - $max_tries--; - if ($max_tries > 0) - sleep(30); - continue; - } else - break; - } - log_error("Snort MD5 Attempts: " . (4 - $max_tries + 1)); - @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); - if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) { - update_status(gettext("Please wait... You may only check for New Rules every 15 minutes...")); - log_error(gettext("Please wait... You may only check for New Rules every 15 minutes...")); - update_output_window(gettext("Rules are released every month from snort.org. You may download the Rules at any time.")); + if ($pkg_interface <> "console") + update_status(gettext("Downloading Snort VRT md5 file...")); + error_log(gettext("\tDownloading Snort VRT md5 file...\n"), 3, $snort_rules_upd_log); + $rc = snort_download_file_url("{$snort_rule_url}{$snort_filename_md5}/{$oinkid}/", "{$tmpfname}/{$snort_filename_md5}"); + if ($rc === true) { + if ($pkg_interface <> "console") + update_status(gettext("Done downloading snort.org md5.")); + error_log("\tChecking Snort VRT md5 file...\n", 3, $snort_rules_upd_log); + } + else { + error_log(gettext("\tSnort VRT md5 download failed.\n"), 3, $snort_rules_upd_log); + if ($rc == 403) { + $snort_err_msg = gettext("Too many attempts or Oinkcode not authorized for this Snort version.\n"); + $snort_err_msg .= gettext("\tFree Registered User accounts may download Snort VRT Rules once every 15 minutes.\n"); + $snort_err_msg .= gettext("\tPaid Subscriber accounts have no download limits.\n"); + } + else + $snort_err_msg = gettext("Server returned error code '{$rc}'."); + if ($pkg_interface <> "console") { + update_status(gettext("Snort VRT md5 error ... Server returned error code {$rc} ...")); + update_output_window(gettext("Snort VRT rules will not be updated.\n{$snort_err_msg}")); + } + log_error(gettext("[Snort] Snort VRT md5 download failed...")); + log_error(gettext("[Snort] Server returned error code '{$rc}'...")); + error_log(gettext("\t{$snort_err_msg}\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tServer error message was '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tSnort VRT rules will not be updated.\n"), 3, $snort_rules_upd_log); $snortdownload = 'off'; - } else - update_status(gettext("Done downloading snort.org md5")); + } } /* Check if were up to date snort.org */ @@ -104,8 +208,10 @@ if ($snortdownload == 'on') { $md5_check_new = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); $md5_check_old = file_get_contents("{$snortdir}/{$snort_filename_md5}"); if ($md5_check_new == $md5_check_old) { - update_status(gettext("Snort rules are up to date...")); - log_error("Snort rules are up to date..."); + if ($pkg_interface <> "console") + update_status(gettext("Snort VRT rules are up to date...")); + log_error(gettext("[Snort] Snort VRT rules are up to date...")); + error_log(gettext("\tSnort VRT rules are up to date.\n"), 3, $snort_rules_upd_log); $snortdownload = 'off'; } } @@ -113,84 +219,246 @@ if ($snortdownload == 'on') { /* download snortrules file */ if ($snortdownload == 'on') { - update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); - log_error(gettext("There is a new set of Snort.org rules posted. Downloading...")); - $max_tries = 4; - while ($max_tries > 0) { - download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); - if (300000 > filesize("{$tmpfname}/$snort_filename")){ - $max_tries--; - if ($max_tries > 0) - sleep(30); - continue; - } else - break; - } - update_status(gettext("Done downloading rules file.")); - log_error("Snort Rules Attempts: " . (4 - $max_tries + 1)); - if (300000 > filesize("{$tmpfname}/$snort_filename")){ - update_output_window(gettext("Snort rules file download failed...")); - log_error(gettext("Snort rules file download failed...")); - log_error("Failed Rules Filesize: " . filesize("{$tmpfname}/$snort_filename")); + if ($pkg_interface <> "console") + update_status(gettext("There is a new set of Snort VRT rules posted. Downloading...")); + log_error(gettext("[Snort] There is a new set of Snort VRT rules posted. Downloading...")); + error_log(gettext("\tThere is a new set of Snort VRT rules posted. Downloading...\n"), 3, $snort_rules_upd_log); + $rc = snort_download_file_url("{$snort_rule_url}{$snort_filename}/{$oinkid}/", "{$tmpfname}/{$snort_filename}"); + if ($rc === true) { + if ($pkg_interface <> "console") + update_status(gettext("Done downloading Snort VRT rules file.")); + error_log(gettext("\tDone downloading rules file.\n"),3, $snort_rules_upd_log); + if (trim(file_get_contents("{$tmpfname}/{$snort_filename_md5}")) != trim(md5_file("{$tmpfname}/{$snort_filename}"))){ + if ($pkg_interface <> "console") + update_output_window(gettext("Snort VRT rules file MD5 checksum failed...")); + log_error(gettext("[Snort] Snort VRT rules file download failed. Bad MD5 checksum...")); + log_error(gettext("[Snort] Failed File MD5: " . md5_file("{$tmpfname}/{$snort_filename}"))); + log_error(gettext("[Snort] Expected File MD5: " . file_get_contents("{$tmpfname}/{$snort_filename_md5}"))); + error_log(gettext("\tSnort VRT rules file download failed. Bad MD5 checksum.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tDownloaded Snort VRT file MD5: " . md5_file("{$tmpfname}/{$snort_filename}") . "\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tExpected Snort VRT file MD5: " . file_get_contents("{$tmpfname}/{$snort_filename_md5}") . "\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tSnort VRT rules file download failed. Snort VRT rules will not be updated.\n"), 3, $snort_rules_upd_log); + $snortdownload = 'off'; + } + } + else { + if ($pkg_interface <> "console") + update_output_window(gettext("Snort VRT rules file download failed...")); + log_error(gettext("[Snort] Snort VRT rules file download failed... server returned error '{$rc}'...")); + error_log(gettext("\tSnort VRT rules file download failed. Server returned error {$rc}.\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tThe error text was '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tSnort VRT rules will not be updated.\n"), 3, $snort_rules_upd_log); $snortdownload = 'off'; } } +/* download md5 sig from Snort GPLv2 Community Rules */ +if ($snortcommunityrules == 'on') { + if ($pkg_interface <> "console") + update_status(gettext("Downloading Snort GPLv2 Community Rules md5 file...")); + error_log(gettext("\tDownloading Snort GPLv2 Community Rules md5 file...\n"), 3, $snort_rules_upd_log); + $rc = snort_download_file_url("{$snort_community_rules_url}{$snort_community_rules_filename_md5}", "{$tmpfname}/{$snort_community_rules_filename_md5}"); + if ($rc === true) { + if ($pkg_interface <> "console") + update_status(gettext("Done downloading Snort GPLv2 Community Rules md5")); + error_log(gettext("\tChecking Snort GPLv2 Community Rules md5.\n"), 3, $snort_rules_upd_log); + if (file_exists("{$snortdir}/{$snort_community_rules_filename_md5}") && $snortcommunityrules == "on") { + /* Check if were up to date Snort GPLv2 Community Rules */ + $snort_comm_md5_check_new = file_get_contents("{$tmpfname}/{$snort_community_rules_filename_md5}"); + $snort_comm_md5_check_old = file_get_contents("{$snortdir}/{$snort_community_rules_filename_md5}"); + if ($snort_comm_md5_check_new == $snort_comm_md5_check_old) { + if ($pkg_interface <> "console") + update_status(gettext("Snort GPLv2 Community Rules are up to date...")); + log_error(gettext("[Snort] Snort GPLv2 Community Rules are up to date...")); + error_log(gettext("\tSnort GPLv2 Community Rules are up to date.\n"), 3, $snort_rules_upd_log); + $snortcommunityrules = 'off'; + } + } + } + else { + if ($pkg_interface <> "console") + update_output_window(gettext("Snort GPLv2 Community Rules md5 file download failed. Community Rules will not be updated.")); + log_error(gettext("[Snort] Snort GPLv2 Community Rules md5 file download failed. Server returned error code '{$rc}'.")); + error_log(gettext("\tSnort GPLv2 Community Rules md5 file download failed. Server returned error code '{$rc}'.\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tThe error text is '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tSnort GPLv2 Community Rules will not be updated.\n"), 3, $snort_rules_upd_log); + $snortcommunityrules = 'off'; + } +} + +/* download Snort GPLv2 Community rules file */ +if ($snortcommunityrules == "on") { + if ($pkg_interface <> "console") + update_status(gettext("There is a new set of Snort GPLv2 Community Rules posted. Downloading...")); + log_error(gettext("[Snort] There is a new set of Snort GPLv2 Community Rules posted. Downloading...")); + error_log(gettext("\tThere is a new set of Snort GPLv2 Community Rules posted. Downloading...\n"), 3, $snort_rules_upd_log); + $rc = snort_download_file_url("{$snort_community_rules_url}{$snort_community_rules_filename}", "{$tmpfname}/{$snort_community_rules_filename}"); + + /* Test for a valid rules file download. Turn off Snort Community update if download failed. */ + if ($rc === true) { + if (trim(file_get_contents("{$tmpfname}/{$snort_community_rules_filename_md5}")) != trim(md5_file("{$tmpfname}/{$snort_community_rules_filename}"))){ + if ($pkg_interface <> "console") + update_output_window(gettext("Snort GPLv2 Community Rules file MD5 checksum failed...")); + log_error(gettext("[Snort] Snort GPLv2 Community Rules file download failed. Bad MD5 checksum...")); + log_error(gettext("[Snort] Failed File MD5: " . md5_file("{$tmpfname}/{$snort_community_rules_filename}"))); + log_error(gettext("[Snort] Expected File MD5: " . file_get_contents("{$tmpfname}/{$snort_community_rules_filename_md5}"))); + error_log(gettext("\tSnort GPLv2 Community Rules file download failed. Community Rules will not be updated.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tDownloaded Snort GPLv2 file MD5: " . md5_file("{$tmpfname}/{$snort_community_rules_filename}") . "\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tExpected Snort GPLv2 file MD5: " . file_get_contents("{$tmpfname}/{$snort_community_rules_filename_md5}") . "\n"), 3, $snort_rules_upd_log); + $snortcommunityrules = 'off'; + } + else { + if ($pkg_interface <> "console") + update_status(gettext('Done downloading Snort GPLv2 Community Rules file.')); + log_error("[Snort] Snort GPLv2 Community Rules file update downloaded successfully"); + error_log(gettext("\tDone downloading Snort GPLv2 Community Rules file.\n"), 3, $snort_rules_upd_log); + } + } + else { + if ($pkg_interface <> "console") { + update_status(gettext("The server returned error code {$rc} ... skipping GPLv2 Community Rules...")); + update_output_window(gettext("Snort GPLv2 Community Rules file download failed...")); + } + log_error(gettext("[Snort] Snort GPLv2 Community Rules file download failed. Server returned error '{$rc}'...")); + error_log(gettext("\tSnort GPLv2 Community Rules download failed. Server returned error '{$rc}'...\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tThe error text is '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + $snortcommunityrules = 'off'; + } +} + +/* Untar Snort GPLv2 Community rules to tmp */ +if ($snortcommunityrules == 'on') { + safe_mkdir("{$snortdir}/tmp/community"); + if (file_exists("{$tmpfname}/{$snort_community_rules_filename}")) { + if ($pkg_interface <> "console") { + update_status(gettext("Extracting Snort GPLv2 Community Rules...")); + update_output_window(gettext("Installing Snort GPLv2 Community Rules...")); + } + error_log(gettext("\tExtracting and installing Snort GPLv2 Community Rules...\n"), 3, $snort_rules_upd_log); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_community_rules_filename} -C {$snortdir}/tmp/community/"); + + $files = glob("{$snortdir}/tmp/community/community-rules/*.rules"); + foreach ($files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/rules/GPLv2_{$newfile}"); + } + /* base etc files for Snort GPLv2 Community rules */ + foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { + if (file_exists("{$snortdir}/tmp/community/community-rules/{$file}")) + @copy("{$snortdir}/tmp/community/community-rules/{$file}", "{$snortdir}/tmp/GPLv2_{$file}"); + } + /* Copy snort community md5 sig to snort dir */ + if (file_exists("{$tmpfname}/{$snort_community_rules_filename_md5}")) { + if ($pkg_interface <> "console") + update_status(gettext("Copying md5 signature to snort directory...")); + @copy("{$tmpfname}/{$snort_community_rules_filename_md5}", "{$snortdir}/{$snort_community_rules_filename_md5}"); + } + if ($pkg_interface <> "console") { + update_status(gettext("Extraction of Snort GPLv2 Community Rules completed...")); + update_output_window(gettext("Installation of Snort GPLv2 Community Rules file completed...")); + } + error_log(gettext("\tInstallation of Snort GPLv2 Community Rules completed.\n"), 3, $snort_rules_upd_log); + exec("rm -r {$snortdir}/tmp/community"); + } +} + /* download md5 sig from emergingthreats.net */ if ($emergingthreats == 'on') { - update_status(gettext("Downloading emergingthreats md5 file...")); - + if ($pkg_interface <> "console") + update_status(gettext("Downloading EmergingThreats md5 file...")); + error_log(gettext("\tDownloading EmergingThreats md5 file...\n"), 3, $snort_rules_upd_log); /* If using Sourcefire VRT rules with ET, then we should use the open-nogpl ET rules. */ if ($vrt_enabled == "on") - $image = @file_get_contents("http://rules.emergingthreats.net/open-nogpl/snort-{$emerging_threats_version}/emerging.rules.tar.gz.md5"); + $rc = snort_download_file_url("http://rules.emergingthreats.net/open-nogpl/snort-{$emerging_threats_version}/{$emergingthreats_filename_md5}", "{$tmpfname}/{$emergingthreats_filename_md5}"); else - $image = @file_get_contents("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/emerging.rules.tar.gz.md5"); - - /* XXX: error checking */ - @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); - update_status(gettext("Done downloading emergingthreats md5")); - - if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) { - /* Check if were up to date emergingthreats.net */ - $emerg_md5_check_new = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); - $emerg_md5_check_old = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); - if ($emerg_md5_check_new == $emerg_md5_check_old) { - update_status(gettext("Emerging threat rules are up to date...")); - log_error(gettext("Emerging threat rules are up to date...")); - $emergingthreats = 'off'; + $rc = snort_download_file_url("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/{$emergingthreats_filename_md5}", "{$tmpfname}/{$emergingthreats_filename_md5}"); + if ($rc === true) { + if ($pkg_interface <> "console") + update_status(gettext("Done downloading EmergingThreats md5")); + error_log(gettext("\tChecking EmergingThreats md5.\n"), 3, $snort_rules_upd_log); + if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}") && $emergingthreats == "on") { + /* Check if were up to date emergingthreats.net */ + $emerg_md5_check_new = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_old = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); + if ($emerg_md5_check_new == $emerg_md5_check_old) { + if ($pkg_interface <> "console") + update_status(gettext("Emerging Threats rules are up to date...")); + log_error(gettext("[Snort] Emerging Threat rules are up to date...")); + error_log(gettext("\tEmerging Threats rules are up to date.\n"), 3, $snort_rules_upd_log); + $emergingthreats = 'off'; + } } } + else { + if ($pkg_interface <> "console") + update_output_window(gettext("EmergingThreats md5 file download failed. EmergingThreats rules will not be updated.")); + log_error(gettext("[Snort] EmergingThreats md5 file download failed. Server returned error code '{$rc}'.")); + error_log(gettext("\tEmergingThreats md5 file download failed. Server returned error code '{$rc}'.\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tThe error text is '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tEmergingThreats rules will not be updated.\n"), 3, $snort_rules_upd_log); + $emergingthreats = 'off'; + } } /* download emergingthreats rules file */ if ($emergingthreats == "on") { - update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); - log_error(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); + if ($pkg_interface <> "console") + update_status(gettext("There is a new set of EmergingThreats rules posted. Downloading...")); + log_error(gettext("[Snort] There is a new set of EmergingThreats rules posted. Downloading...")); + error_log(gettext("\tThere is a new set of EmergingThreats rules posted. Downloading...\n"), 3, $snort_rules_upd_log); /* If using Sourcefire VRT rules with ET, then we should use the open-nogpl ET rules. */ if ($vrt_enabled == "on") - download_file_with_progress_bar("http://rules.emergingthreats.net/open-nogpl/snort-{$emerging_threats_version}/emerging.rules.tar.gz", "{$tmpfname}/{$emergingthreats_filename}"); + $rc = snort_download_file_url("http://rules.emergingthreats.net/open-nogpl/snort-{$emerging_threats_version}/emerging.rules.tar.gz", "{$tmpfname}/{$emergingthreats_filename}"); else - download_file_with_progress_bar("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/emerging.rules.tar.gz", "{$tmpfname}/{$emergingthreats_filename}"); - - update_status(gettext('Done downloading Emergingthreats rules file.')); - log_error("Emergingthreats rules file update downloaded succsesfully"); + $rc = snort_download_file_url("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/emerging.rules.tar.gz", "{$tmpfname}/{$emergingthreats_filename}"); + + /* Test for a valid rules file download. Turn off ET update if download failed. */ + if ($rc === true) { + if (trim(file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}")) != trim(md5_file("{$tmpfname}/{$emergingthreats_filename}"))){ + if ($pkg_interface <> "console") + update_output_window(gettext("EmergingThreats rules file MD5 checksum failed...")); + log_error(gettext("[Snort] EmergingThreats rules file download failed. Bad MD5 checksum...")); + log_error(gettext("[Snort] Failed File MD5: " . md5_file("{$tmpfname}/{$emergingthreats_filename}"))); + log_error(gettext("[Snort] Expected File MD5: " . file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"))); + error_log(gettext("\tEmergingThreats rules file download failed. EmergingThreats rules will not be updated.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tDownloaded ET file MD5: " . md5_file("{$tmpfname}/{$emergingthreats_filename}") . "\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tExpected ET file MD5: " . file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}") . "\n"), 3, $snort_rules_upd_log); + $emergingthreats = 'off'; + } + else { + if ($pkg_interface <> "console") + update_status(gettext('Done downloading EmergingThreats rules file.')); + log_error("[Snort] EmergingThreats rules file update downloaded successfully"); + error_log(gettext("\tDone downloading EmergingThreats rules file.\n"), 3, $snort_rules_upd_log); + } + } + else { + if ($pkg_interface <> "console") { + update_status(gettext("The server returned error code {$rc} ... skipping EmergingThreats update...")); + update_output_window(gettext("EmergingThreats rules file download failed...")); + } + log_error(gettext("[Snort] EmergingThreats rules file download failed. Server returned error '{$rc}'...")); + error_log(gettext("\tEmergingThreats rules file download failed. Server returned error '{$rc}'...\n"), 3, $snort_rules_upd_log); + if ($pkg_interface == "console") + error_log(gettext("\tThe error text is '{$last_curl_error}'\n"), 3, $snort_rules_upd_log); + $emergingthreats = 'off'; + } } -/* Normalize rulesets */ -$sedcmd = "s/^#alert/# alert/g\n"; -$sedcmd .= "s/^##alert/# alert/g\n"; -$sedcmd .= "s/^#[ \\t#]*alert/# alert/g\n"; -$sedcmd .= "s/^##\\talert/# alert/g\n"; -$sedcmd .= "s/^\\talert/alert/g\n"; -$sedcmd .= "s/^[ \\t]*alert/alert/g\n"; -@file_put_contents("{$snortdir}/tmp/sedcmd", $sedcmd); - /* Untar emergingthreats rules to tmp */ if ($emergingthreats == 'on') { safe_mkdir("{$snortdir}/tmp/emerging"); if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) { - update_status(gettext("Extracting EmergingThreats.org rules...")); + if ($pkg_interface <> "console") { + update_status(gettext("Extracting EmergingThreats.org rules...")); + update_output_window(gettext("Installing EmergingThreats rules...")); + } + error_log(gettext("\tExtracting and installing EmergingThreats.org rules...\n"), 3, $snort_rules_upd_log); exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir}/tmp/emerging rules/"); $files = glob("{$snortdir}/tmp/emerging/rules/*.rules"); @@ -199,7 +467,7 @@ if ($emergingthreats == 'on') { @copy($file, "{$snortdir}/rules/{$newfile}"); } /* IP lists for Emerging Threats rules */ - $files = glob("{$snortdir}/tmp/emerging/rules/*.txt"); + $files = glob("{$snortdir}/tmp/emerging/rules/*ips.txt"); foreach ($files as $file) { $newfile = basename($file); @copy($file, "{$snortdir}/rules/{$newfile}"); @@ -207,31 +475,39 @@ if ($emergingthreats == 'on') { /* base etc files for Emerging Threats rules */ foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { if (file_exists("{$snortdir}/tmp/emerging/rules/{$file}")) - @copy("{$snortdir}/tmp/emerging/rules/{$file}", "{$snortdir}/ET_{$file}"); + @copy("{$snortdir}/tmp/emerging/rules/{$file}", "{$snortdir}/tmp/ET_{$file}"); } -// /* make sure default rules are in the right format */ -// exec("/usr/bin/sed -I '' -f {$snortdir}/tmp/sedcmd {$snortdir}/rules/emerging*.rules"); - /* Copy emergingthreats md5 sig to snort dir */ - if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) { - update_status(gettext("Copying md5 sig to snort directory...")); - @copy("{$tmpfname}/$emergingthreats_filename_md5", "{$snortdir}/$emergingthreats_filename_md5"); + if (file_exists("{$tmpfname}/{$emergingthreats_filename_md5}")) { + if ($pkg_interface <> "console") + update_status(gettext("Copying md5 signature to snort directory...")); + @copy("{$tmpfname}/{$emergingthreats_filename_md5}", "{$snortdir}/{$emergingthreats_filename_md5}"); } - update_status(gettext("Extraction of EmergingThreats.org rules completed...")); + if ($pkg_interface <> "console") { + update_status(gettext("Extraction of EmergingThreats.org rules completed...")); + update_output_window(gettext("Installation of EmergingThreats rules completed...")); + } + error_log(gettext("\tInstallation of EmergingThreats.org rules completed.\n"), 3, $snort_rules_upd_log); + exec("rm -r {$snortdir}/tmp/emerging"); } } /* Untar snort rules file individually to help people with low system specs */ if ($snortdownload == 'on') { if (file_exists("{$tmpfname}/{$snort_filename}")) { - if ($pfsense_stable == 'yes') - $freebsd_version_so = 'FreeBSD-7-2'; - else - $freebsd_version_so = 'FreeBSD-8-1'; - - update_status(gettext("Extracting Snort VRT rules...")); - /* extract snort.org rules and add prefix to all snort.org files*/ + /* Currently, only FreeBSD-8-1 and FreeBSD-9-0 precompiled SO rules exist from Snort.org */ + /* Default to FreeBSD 8.1, and then test for FreeBSD 9.x */ + $freebsd_version_so = 'FreeBSD-8-1'; + if (substr(php_uname("r"), 0, 1) == '9') + $freebsd_version_so = 'FreeBSD-9-0'; + + if ($pkg_interface <> "console") { + update_status(gettext("Extracting Snort VRT rules...")); + update_output_window(gettext("Installing Sourcefire VRT rules...")); + } + error_log(gettext("\tExtracting and installing Snort VRT rules...\n"), 3, $snort_rules_upd_log); + /* extract snort.org rules and add prefix to all snort.org files */ safe_mkdir("{$snortdir}/tmp/snortrules"); exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp/snortrules rules/"); $files = glob("{$snortdir}/tmp/snortrules/rules/*.rules"); @@ -246,154 +522,216 @@ if ($snortdownload == 'on') { @copy($file, "{$snortdir}/rules/{$newfile}"); } exec("rm -r {$snortdir}/tmp/snortrules"); - /* extract so rules */ - update_status(gettext("Extracting Snort VRT Shared Objects rules...")); - exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); + if ($pkg_interface <> "console") { + update_status(gettext("Extracting Snort VRT Shared Objects rules...")); + update_output_window(gettext("Installing precompiled Shared Objects rules for {$freebsd_version_so}...")); + } + exec("/bin/mkdir -p {$snortlibdir}/dynamicrules/"); + error_log(gettext("\tUsing Snort VRT precompiled SO rules for {$freebsd_version_so} ...\n"), 3, $snort_rules_upd_log); $snort_arch = php_uname("m"); $nosorules = false; if ($snort_arch == 'i386'){ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/$freebsd_version_so/i386/{$snort_version}/"); - exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/$freebsd_version_so/i386/{$snort_version}/* /usr/local/lib/snort/dynamicrules/"); - } else if ($snort_arch == 'amd64') { - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/$freebsd_version_so/x86-64/{$snort_version}/"); - exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/$freebsd_version_so/x86-64/{$snort_version}/* /usr/local/lib/snort/dynamicrules/"); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/{$freebsd_version_so}/i386/{$snort_version}/"); + exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/{$freebsd_version_so}/i386/{$snort_version}/* {$snortlibdir}/dynamicrules/"); + } elseif ($snort_arch == 'amd64') { + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/{$freebsd_version_so}/x86-64/{$snort_version}/"); + exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/{$freebsd_version_so}/x86-64/{$snort_version}/* {$snortlibdir}/dynamicrules/"); } else $nosorules = true; exec("rm -r {$snortdir}/tmp/so_rules"); - if ($nosorules == false) { - /* extract so rules none bin and rename */ - update_status(gettext("Copying Snort VRT Shared Objects rules...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/"); + /* extract so stub rules, rename and copy to the rules folder. */ + if ($pkg_interface <> "console") + update_status(gettext("Copying Snort VRT Shared Objects rules...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp --exclude precompiled/ --exclude src/ so_rules/"); $files = glob("{$snortdir}/tmp/so_rules/*.rules"); foreach ($files as $file) { $newfile = basename($file, ".rules"); @copy($file, "{$snortdir}/rules/snort_{$newfile}.so.rules"); } exec("rm -r {$snortdir}/tmp/so_rules"); - - /* extract base etc files */ - update_status(gettext("Extracting Snort VRT base config files...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp etc/"); - foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { - if (file_exists("{$snortdir}/tmp/etc/{$file}")) - @copy("{$snortdir}/tmp/etc/{$file}", "{$snortdir}/VRT_{$file}"); - } - exec("rm -r {$snortdir}/tmp/etc"); - - /* Untar snort signatures */ - $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; - if ($premium_url_chk == 'on') { + } + /* extract base etc files */ + if ($pkg_interface <> "console") { + update_status(gettext("Extracting Snort VRT config and map files...")); + update_output_window(gettext("Copying config and map files...")); + } + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp etc/"); + foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { + if (file_exists("{$snortdir}/tmp/etc/{$file}")) + @copy("{$snortdir}/tmp/etc/{$file}", "{$snortdir}/tmp/VRT_{$file}"); + } + exec("rm -r {$snortdir}/tmp/etc"); + /* Untar snort signatures */ + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') { + if ($pkg_interface <> "console") update_status(gettext("Extracting Snort VRT Signatures...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); + if ($pkg_interface <> "console") update_status(gettext("Done extracting Signatures.")); - if (is_dir("{$snortdir}/doc/signatures")) { + if (is_dir("{$snortdir}/doc/signatures")) { + if ($pkg_interface <> "console") update_status(gettext("Copying Snort VRT signatures...")); - exec("/bin/cp -r {$snortdir}/doc/signatures {$snortdir}/signatures"); + exec("/bin/cp -r {$snortdir}/doc/signatures {$snortdir}/signatures"); + if ($pkg_interface <> "console") update_status(gettext("Done copying signatures.")); - } - } - - foreach (glob("/usr/local/lib/snort/dynamicrules/*example*") as $file) - @unlink($file); - - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} preproc_rules/"); - -// /* make sure default rules are in the right format */ -// exec("/usr/bin/sed -I '' -f {$snortdir}/tmp/sedcmd {$snortdir}/rules/snort_*.rules"); - - if (file_exists("{$tmpfname}/{$snort_filename_md5}")) { - update_status(gettext("Copying md5 sig to snort directory...")); - @copy("{$tmpfname}/$snort_filename_md5", "{$snortdir}/$snort_filename_md5"); } } - update_status(gettext("Extraction of Snort VRT rules completed...")); + /* Extract the Snort preprocessor rules */ + if ($pkg_interface <> "console") + update_output_window(gettext("Extracting preprocessor rules files...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp preproc_rules/"); + + if (file_exists("{$tmpfname}/{$snort_filename_md5}")) { + if ($pkg_interface <> "console") + update_status(gettext("Copying md5 signature to snort directory...")); + @copy("{$tmpfname}/{$snort_filename_md5}", "{$snortdir}/{$snort_filename_md5}"); + } + if ($pkg_interface <> "console") { + update_status(gettext("Extraction of Snort VRT rules completed...")); + update_output_window(gettext("Installation of Sourcefire VRT rules completed...")); + } + error_log(gettext("\tInstallation of Snort VRT rules completed.\n"), 3, $snort_rules_upd_log); } } -/* remove old $tmpfname files */ -if (is_dir("{$snortdir}/tmp")) { - update_status(gettext("Cleaning up after rules extraction...")); - exec("/bin/rm -r {$snortdir}/tmp"); -} - function snort_apply_customizations($snortcfg, $if_real) { + global $vrt_enabled; $snortdir = SNORTDIR; + + /* Update the Preprocessor rules for the master configuration and for the interface if Snort VRT rules are in use. */ + if ($vrt_enabled == 'on') { + exec("/bin/mkdir -p {$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/preproc_rules"); + $preproc_files = glob("{$snortdir}/tmp/preproc_rules/*.rules"); + foreach ($preproc_files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/preproc_rules/{$newfile}"); + /* Check if customized preprocessor rule protection is enabled for interface before overwriting them. */ + if ($snortcfg['protect_preproc_rules'] <> 'on') + @copy($file, "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/preproc_rules/{$newfile}"); + } + } + else { + exec("/bin/mkdir -p {$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/preproc_rules"); + } + snort_prepare_rule_files($snortcfg, "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}"); - /* Copy the master *.config and other *.map files to the interface's directory */ + /* Copy the master config and map files to the interface directory */ @copy("{$snortdir}/classification.config", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/classification.config"); @copy("{$snortdir}/gen-msg.map", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/gen-msg.map"); @copy("{$snortdir}/reference.config", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/reference.config"); @copy("{$snortdir}/unicode.map", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/unicode.map"); } -if ($snortdownload == 'on' || $emergingthreats == 'on') { +if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules == 'on') { - update_status(gettext('Copying new config and map files...')); + if ($pkg_interface <> "console") + update_status(gettext('Copying new config and map files...')); + error_log(gettext("\tCopying new config and map files...\n"), 3, $snort_rules_upd_log); - /* Determine which base etc file set to use for the master copy. */ - /* If the Snort VRT rules are not enabled, then use Emerging Threats. */ + /* Determine which config and map file set to use for the master copy. */ + /* If the Snort VRT rules are not enabled, then use Emerging Threats. */ if (($vrt_enabled == 'off') && ($et_enabled == 'on')) { - foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { - if (file_exists("{$snortdir}/ET_{$file}")) - @rename("{$snortdir}/ET_{$file}", "{$snortdir}/{$file}"); - } + $cfgs = glob("{$snortdir}/tmp/*reference.config"); + $cfgs[] = "{$snortdir}/reference.config"; + snort_merge_reference_configs($cfgs, "{$snortdir}/reference.config"); + $cfgs = glob("{$snortdir}/tmp/*classification.config"); + $cfgs[] = "{$snortdir}/classification.config"; + snort_merge_classification_configs($cfgs, "{$snortdir}/classification.config"); } elseif (($vrt_enabled == 'on') && ($et_enabled == 'off')) { foreach (array("classification.config", "reference.config", "gen-msg.map", "unicode.map") as $file) { - if (file_exists("{$snortdir}/VRT_{$file}")) - @rename("{$snortdir}/VRT_{$file}", "{$snortdir}/{$file}"); + if (file_exists("{$snortdir}/tmp/VRT_{$file}")) + @copy("{$snortdir}/tmp/VRT_{$file}", "{$snortdir}/{$file}"); } } - else { - /* Both VRT and ET rules are enabled, so build combined */ - /* reference.config and classification.config files. */ - $cfgs = glob("{$snortdir}/*reference.config"); - snort_merge_reference_configs($cfgs, "{$snortdir}/reference.config"); - $cfgs = glob("{$snortdir}/*classification.config"); - snort_merge_classification_configs($cfgs, "{$snortdir}/classification.config"); + elseif (($vrt_enabled == 'on') && ($et_enabled == 'on')) { + /* Both VRT and ET rules are enabled, so build combined */ + /* reference.config and classification.config files. */ + $cfgs = glob("{$snortdir}/tmp/*reference.config"); + $cfgs[] = "{$snortdir}/reference.config"; + snort_merge_reference_configs($cfgs, "{$snortdir}/reference.config"); + $cfgs = glob("{$snortdir}/tmp/*classification.config"); + $cfgs[] = "{$snortdir}/classification.config"; + snort_merge_classification_configs($cfgs, "{$snortdir}/classification.config"); + /* Use the unicode.map and gen-msg.map files from VRT rules. */ + if (file_exists("{$snortdir}/tmp/VRT_unicode.map")) + @copy("{$snortdir}/tmp/VRT_unicode.map", "{$snortdir}/unicode.map"); + if (file_exists("{$snortdir}/tmp/VRT_gen-msg.map")) + @copy("{$snortdir}/tmp/VRT_gen-msg.map", "{$snortdir}/gen-msg.map"); } - /* Clean-up our temp versions of the config and map files. */ - update_status(gettext('Cleaning up temp files...')); - $cfgs = glob("{$snortdir}/??*_*.config"); - foreach ($cfgs as $file) { - if (file_exists($file)) - @unlink($file); - } - $cfgs = glob("{$snortdir}/??*_*.map"); - foreach ($cfgs as $file) { - if (file_exists($file)) - @unlink($file); - } - - /* Start the proccess for each configured interface */ + /* Start the rules rebuild proccess for each configured interface */ if (is_array($config['installedpackages']['snortglobal']['rule'])) { - foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { - /* Create configuration for each active Snort interface */ + /* Set the flag to force rule rebuilds since we downloaded new rules, */ + /* except when in post-install mode. Post-install does its own rebuild. */ + if ($is_postinstall) + $rebuild_rules = 'off'; + else + $rebuild_rules = 'on'; + + /* Create configuration for each active Snort interface */ + foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { $if_real = snort_get_real_interface($value['interface']); $tmp = "Updating rules configuration for: " . snort_get_friendly_interface($value['interface']) . " ..."; - update_status(gettext($tmp)); - log_error($tmp); + if ($pkg_interface <> "console"){ + update_status(gettext($tmp)); + update_output_window(gettext("Please wait while Snort interface files are being updated...")); + } snort_apply_customizations($value, $if_real); + + /* Log a message in Update Log if protecting customized preprocessor rules. */ + $tmp = "\t" . $tmp . "\n"; + if ($value['protect_preproc_rules'] == 'on') { + $tmp .= gettext("\tPreprocessor text rules flagged as protected and not updated for "); + $tmp .= snort_get_friendly_interface($value['interface']) . "...\n"; + } + error_log($tmp, 3, $snort_rules_upd_log); + } + } + else { + if ($pkg_interface <> "console") { + update_output_window(gettext("Warning: No interfaces configured for Snort were found...")); + update_output_window(gettext("No interfaces currently have Snort configured and enabled on them...")); + } + error_log(gettext("\tWarning: No interfaces configured for Snort were found...\n"), 3, $snort_rules_upd_log); + } + + /* Clear the rebuild rules flag. */ + $rebuild_rules = 'off'; + + /* remove old $tmpfname files */ + if (is_dir("{$snortdir}/tmp")) { + if ($pkg_interface <> "console") + update_status(gettext("Cleaning up after rules extraction...")); + exec("/bin/rm -r {$snortdir}/tmp"); + } + + /* Restart snort if already running and we are not rebooting to pick up the new rules. */ + if (is_process_running("snort") && !$g['booting']) { + if ($pkg_interface <> "console") { + update_status(gettext('Restarting Snort to activate the new set of rules...')); + update_output_window(gettext("Please wait ... restarting Snort will take some time...")); } + error_log(gettext("\tRestarting Snort to activate the new set of rules...\n"), 3, $snort_rules_upd_log); + restart_service("snort"); + if ($pkg_interface <> "console") + update_output_window(gettext("Snort has restarted with your new set of rules...")); + log_error(gettext("[Snort] Snort has restarted with your new set of rules...")); + error_log(gettext("\tSnort has restarted with your new set of rules.\n"), 3, $snort_rules_upd_log); } - update_status(gettext('Restarting Snort to activate the new set of rules...')); - exec("/bin/sh /usr/local/etc/rc.d/snort.sh restart"); - sleep(20); - if (!is_process_running("snort")) - exec("/bin/sh /usr/local/etc/rc.d/snort.sh start"); - update_output_window(gettext("Snort has restarted with your new set of rules...")); - log_error("Snort has restarted with your new set of rules..."); } -update_status(gettext("The Rules update has finished...")); -log_error("The Rules update has finished..."); +if ($pkg_interface <> "console") + update_status(gettext("The Rules update has finished...")); +log_error(gettext("[Snort] The Rules update has finished.")); +error_log(gettext("The Rules update has finished. Time: " . date("Y-m-d H:i:s"). "\n\n"), 3, $snort_rules_upd_log); conf_mount_ro(); ?> diff --git a/config/snort/snort_define_servers.php b/config/snort/snort_define_servers.php index 4085b325..8c19325b 100755 --- a/config/snort/snort_define_servers.php +++ b/config/snort/snort_define_servers.php @@ -33,7 +33,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $rebuild_rules; $id = $_GET['id']; if (isset($_POST['id'])) @@ -126,7 +126,9 @@ if ($_POST) { write_config(); - sync_snort_package_config(); + /* Update the snort conf file for this interface. */ + $rebuild_rules = "off"; + snort_generate_conf($a_nat[$id]); /* after click go to this page */ header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); @@ -164,20 +166,32 @@ if ($savemsg) <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td class="tabnavtbl">'; + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface "); $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), true, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext(" Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), true, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Define Servers"); ?></td> </tr> @@ -230,6 +244,7 @@ if ($savemsg) </td> </tr> </table> +</div> </td></tr> </table> </form> diff --git a/config/snort/snort_download_rules.php b/config/snort/snort_download_rules.php index bbbf689c..e35eb983 100755 --- a/config/snort/snort_download_rules.php +++ b/config/snort/snort_download_rules.php @@ -34,6 +34,8 @@ require_once("functions.inc"); require_once("service-utils.inc"); require_once("/usr/local/pkg/snort/snort.inc"); +global $g; + $pgtitle = "Services: Snort: Update Rules"; include("head.inc"); ?> @@ -44,34 +46,43 @@ include("head.inc"); <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <form action="/snort/snort_download_updates.php" method="GET"> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr> - <td> - <div id="mainarea"> - <table class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td ><!-- progress bar --> - <table id="progholder" width='320' style='border-collapse: collapse; border: 1px solid #000000;' cellpadding='2' cellspacing='2'> + +<table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td align="center"><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td> - <img border='0' src='../themes/<?= $g['theme']; ?>/images/misc/progress_bar.gif' - width='280' height='23' name='progressbar' id='progressbar' alt='' /> + <td class="tabcont" align="center"> + <table width="420" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td style="background:url('../themes/<?= $g['theme']; ?>/images/misc/bar_left.gif')" height="15" width="5"></td> + <td style="background:url('../themes/<?= $g['theme']; ?>/images/misc/bar_gray.gif')" height="15" width="410"> + <table id="progholder" width='410' cellpadding='0' cellspacing='0'> + <tr> + <td align="left"><img border='0' src='../themes/<?= $g['theme']; ?>/images/misc/bar_blue.gif' + width='0' height='15' name='progressbar' id='progressbar' alt='' /></td + </tr> + </table></td> + <td style="background:url('../themes/<?= $g['theme']; ?>/images/misc/bar_right.gif')" height="15" width="5"></td> + </tr> + </table> </td> </tr> - </table> - <br /> - <textarea cols="60" rows="2" name="status" id="status" wrap="hard"> - <?=gettext("Initializing...");?> - </textarea> - <textarea cols="60" rows="2" name="output" id="output" wrap="hard"> - </textarea> - </td> - </tr> + <tr> + <td class="tabcont" align="center"> + <!-- status box --> + <textarea cols="85" rows="1" name="status" id="status" wrap="soft"><?=gettext("Initializing..."); ?>.</textarea> + <!-- command output box --> + <textarea cols="85" rows="12" name="output" id="output" wrap="soft"></textarea> + </td> + </tr> + <tr> + <td class="tabcont" align="center" valign="middle"><input type="submit" name="return" id="return" Value="Return"></td> + </tr> </table> - </div> - </td> -</tr> - <tr><td><input type="submit" name="return" id="return" Value="Return"></td></tr> + </div> + </td> + </tr> </table> </form> <?php include("fend.inc");?> diff --git a/config/snort/snort_download_updates.php b/config/snort/snort_download_updates.php index 0c879e44..a397a7b0 100755 --- a/config/snort/snort_download_updates.php +++ b/config/snort/snort_download_updates.php @@ -36,16 +36,18 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $snort_rules_upd_log, $snort_rules_file, $emergingthreats_filename; $snortdir = SNORTDIR; -$snort_upd_log = "/tmp/snort_update.log"; + +$log = $snort_rules_upd_log; /* load only javascript that is needed */ $snort_load_jquery = 'yes'; $snort_load_jquery_colorbox = 'yes'; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; +$snortcommunityrules = $config['installedpackages']['snortglobal']['snortcommunityrules']; /* quick md5s chk */ $snort_org_sig_chk_local = 'N/A'; @@ -53,13 +55,28 @@ if (file_exists("{$snortdir}/{$snort_rules_file}.md5")) $snort_org_sig_chk_local = file_get_contents("{$snortdir}/{$snort_rules_file}.md5"); $emergingt_net_sig_chk_local = 'N/A'; -if (file_exists("{$snortdir}/emerging.rules.tar.gz.md5")) - $emergingt_net_sig_chk_local = file_get_contents("{$snortdir}/emerging.rules.tar.gz.md5"); +if (file_exists("{$snortdir}/{$emergingthreats_filename}.md5")) + $emergingt_net_sig_chk_local = file_get_contents("{$snortdir}/{$emergingthreats_filename}.md5"); + +$snort_community_sig_chk_local = 'N/A'; +if (file_exists("{$snortdir}/{$snort_community_rules_filename}.md5")) + $snort_community_sig_chk_local = file_get_contents("{$snortdir}/{$snort_community_rules_filename}.md5"); + +/* Check for postback to see if we should clear the update log file. */ +if (isset($_POST['clear'])) { + if (file_exists("{$snort_rules_upd_log}")) + mwexec("/bin/rm -f {$snort_rules_upd_log}"); +} + +if (isset($_POST['update'])) { + header("Location: /snort/snort_download_rules.php"); + exit; +} /* check for logfile */ -$update_logfile_chk = 'no'; -if (file_exists("{$snort_upd_log}")) - $update_logfile_chk = 'yes'; +$snort_rules_upd_logfile_chk = 'no'; +if (file_exists("{$snort_rules_upd_log}")) + $snort_rules_upd_logfile_chk = 'yes'; $pgtitle = "Services: Snort: Updates"; include_once("head.inc"); @@ -71,19 +88,25 @@ include_once("head.inc"); <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <script language="javascript" type="text/javascript"> -function popup(url) +function wopen(url, name, w, h) { - params = 'width='+screen.width; - params += ', height='+screen.height; - params += ', top=0, left=0' - params += ', fullscreen=yes'; - - newwin=window.open(url,'windowname4', params); - if (window.focus) {newwin.focus()} - return false; +// Fudge factors for window decoration space. +// In my tests these work well on all platforms & browsers. +w += 32; +h += 96; + var win = window.open(url, + name, + 'width=' + w + ', height=' + h + ', ' + + 'location=no, menubar=no, ' + + 'status=no, toolbar=no, scrollbars=yes, resizable=yes'); + win.resizeTo(w, h); + win.focus(); } + </script> +<form action="snort_download_updates.php" method="post" name="iform" id="iform"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -95,14 +118,14 @@ function popup(url) $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array); ?> </td></tr> <tr> <td> - <div id="mainarea3"> - <table id="maintable4" class="tabcont" width="100%" border="0" - cellpadding="0" cellspacing="0"> + <div id="mainarea"> + <table id="maintable4" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr align="center"> <td> <br/> @@ -112,14 +135,15 @@ function popup(url) <td id="download_rules_td" style="background-color: #eeeeee"> <div height="32" width="725px" style="background-color: #eeeeee"> - <font color="#777777" size="1.5px"> + <font color="#777777" size="2.5px"> <p style="text-align: left; margin-left: 225px;"> - <b><?php echo gettext("INSTALLED SIGNATURE RULESET"); ?></b></font><br> - <br> - <font color="#FF850A" size="1px"><b>SNORT.ORG >>></b></font> + <b><?php echo gettext("INSTALLED RULESET SIGNATURES"); ?></b></font><br/> + <font color="#FF850A" size="1px"><b>SNORT.ORG --></b></font> <font size="1px" color="#000000"> <? echo $snort_org_sig_chk_local; ?></font><br> - <font color="#FF850A" size="1px"><b>EMERGINGTHREATS.NET >>></b></font> + <font color="#FF850A" size="1px"><b>EMERGINGTHREATS.NET --></b></font> <font size="1px" color="#000000"> <? echo $emergingt_net_sig_chk_local; ?></font><br> + <font color="#FF850A" size="1px"><b>SNORT GPLv2 COMMUNITY RULES --></b></font> + <font size="1px" color="#000000"> <? echo $snort_community_sig_chk_local; ?></font><br> </p> </div> </td> @@ -133,22 +157,23 @@ function popup(url) <div height="32" width="725px" style='background-color: #eeeeee'> <p style="text-align: left; margin-left: 225px;"> - <font color='#777777' size='1.5px'><b><?php echo gettext("UPDATE YOUR RULES"); ?></b></font><br> + <font color='#777777' size='2.5px'><b><?php echo gettext("UPDATE YOUR RULESET"); ?></b></font><br> <br/> <?php if ($snortdownload != 'on' && $emergingthreats != 'on') { echo ' - <button disabled="disabled"><span class="download">' . gettext("Update Rules") . ' </span></button><br/> + <button disabled="disabled"><span class="download">' . gettext("Update Rules") . '</span></button><br/> <p style="text-align:left; margin-left:150px;"> - <font color="#fc3608" size="2px"><b>' . gettext("WARNING:") . '</b></font><font size="1px" color="#000000"> ' . gettext('No rule types have been selected for download. "Global Settings Tab"') . '</font><br>'; + <font color="#fc3608" size="2px"><b>' . gettext("WARNING:") . '</b></font><font size="1px" color="#000000"> ' . gettext('No rule types have been selected for download. ') . + gettext('Visit the ') . '<a href="snort_interfaces_global.php">Global Settings Tab</a>' . gettext(' to select rule types.') . '</font><br>'; echo '</p>' . "\n"; } else { echo ' - <a href="/snort/snort_download_rules.php"><button ><span class="download">' . gettext("Update Rules") . ' </span></button></a><br/>' . "\n"; + <input type="submit" value="' . gettext("Update Rules") . '" name="update" id="Submit" class="formbtn" /><br/>' . "\n"; } @@ -166,19 +191,19 @@ function popup(url) <div height="32" width="725px" style='background-color: #eeeeee'> <p style="text-align: left; margin-left: 225px;"> - <font color='#777777' size='1.5px'><b><?php echo gettext("VIEW UPDATE LOG"); ?></b></font><br> + <font color='#777777' size='2.5px'><b><?php echo gettext("VIEW UPDATE LOG"); ?></b></font><br> <br> - <?php - if ($update_logfile_chk == 'yes') { + if ($snort_rules_upd_logfile_chk == 'yes') { echo " - <button href='/snort/snort_rules_edit.php?openruleset={$snort_upd_log}'><span class='pwhitetxt'>" . gettext("Update Log") . " </span></button>\n"; + <button class=\"formbtn\" onclick=\"wopen('snort_log_view.php?logfile={$log}', 'LogViewer', 800, 600)\"><span class='pwhitetxt'>" . gettext("View Log") . "</span></button>"; + echo " <input type=\"submit\" value=\"Clear Log\" name=\"clear\" id=\"Submit\" class=\"formbtn\" />\n"; }else{ echo " - <button disabled='disabled' href='/snort/snort_rules_edit.php?openruleset={$snort_upd_log}'><span class='pwhitetxt'>" . gettext("Update Log") . " </span></button>\n"; + <button disabled='disabled'><span class='pwhitetxt'>" . gettext("View Log") . "</span></button> " . gettext("Log is empty.") . "\n"; } - + echo '<br><br>' . gettext("The log file is limited to 1024K in size and automatically clears when the limit is exceeded."); ?> <br/> </p> @@ -194,8 +219,8 @@ function popup(url) <tr> <td id="download_rules_td" style='background-color: #eeeeee'> <div height="32" width="725px" style='background-color: #eeeeee'> - <font color='#FF850A' size='1px'><b><?php echo gettext("NOTE:"); ?></b></font><font size='1px' - color='#000000'> <?php echo gettext("Snort.org and Emergingthreats.net " . + <font size='1px'><span class="red"><b><?php echo gettext("NOTE:"); ?></b></span></font><font size='1px' + color='#000000'> <?php echo gettext("Snort.org and EmergingThreats.net " . "will go down from time to time. Please be patient."); ?> </font> </div> @@ -207,16 +232,12 @@ function popup(url) </tr> </table> </div> - - - - - <br> </td> </tr> </table> <!-- end of final table --></div> + </form> <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_interfaces.php b/config/snort/snort_interfaces.php index e8e690a8..ad492df2 100755 --- a/config/snort/snort_interfaces.php +++ b/config/snort/snort_interfaces.php @@ -32,7 +32,7 @@ $nocsrf = true; require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $rebuild_rules; $snortdir = SNORTDIR; @@ -57,14 +57,30 @@ if (isset($_POST['del_x'])) { exec("/bin/rm -r /var/log/snort/snort_{$if_real}{$snort_uuid}"); exec("/bin/rm -r {$snortdir}/snort_{$snort_uuid}_{$if_real}"); + // If interface had auto-generated Suppress List, then + // delete that along with the interface + $autolist = "{$a_nat[$rulei]['interface']}" . "suppress"; + $a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; + foreach ($a_suppress as $k => $i) { + if ($i['name'] == $autolist) { + unset($config['installedpackages']['snortglobal']['suppress']['item'][$k]); + break; + } + } + + // Finally delete the interface's config entry entirely unset($a_nat[$rulei]); } conf_mount_ro(); + /* If all the Snort interfaces are removed, then unset the config array. */ + if (empty($a_nat)) + unset($a_nat); + write_config(); sleep(2); - /* if there are no ifaces do not create snort.sh */ + /* if there are no ifaces remaining do not create snort.sh */ if (!empty($config['installedpackages']['snortglobal']['rule'])) snort_create_rc(); else { @@ -93,11 +109,11 @@ if ($_GET['act'] == 'bartoggle' && is_numeric($id)) { $if_friendly = snort_get_friendly_interface($snortcfg['interface']); if (snort_is_running($snortcfg['uuid'], $if_real, 'barnyard2') == 'no') { - log_error("Toggle(barnyard starting) for {$if_friendly}({$snortcfg['descr']}}..."); + log_error("Toggle (barnyard starting) for {$if_friendly}({$snortcfg['descr']})..."); sync_snort_package_config(); snort_barnyard_start($snortcfg, $if_real); } else { - log_error("Toggle(barnyard stopping) for {$if_friendly}({$snortcfg['descr']}}..."); + log_error("Toggle (barnyard stopping) for {$if_friendly}({$snortcfg['descr']})..."); snort_barnyard_stop($snortcfg, $if_real); } @@ -113,7 +129,7 @@ if ($_GET['act'] == 'toggle' && is_numeric($id)) { $if_friendly = snort_get_friendly_interface($snortcfg['interface']); if (snort_is_running($snortcfg['uuid'], $if_real) == 'yes') { - log_error("Toggle(snort stopping) for {$if_friendly}({$snortcfg['descr']})..."); + log_error("Toggle (snort stopping) for {$if_friendly}({$snortcfg['descr']})..."); snort_stop($snortcfg, $if_real); header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); @@ -122,8 +138,12 @@ if ($_GET['act'] == 'toggle' && is_numeric($id)) { header( 'Cache-Control: post-check=0, pre-check=0', false ); header( 'Pragma: no-cache' ); } else { - log_error("Toggle(snort starting) for {$if_friendly}({$snortcfg['descr']})..."); + log_error("Toggle (snort starting) for {$if_friendly}({$snortcfg['descr']})..."); + + /* set flag to rebuild interface rules before starting Snort */ + $rebuild_rules = "on"; sync_snort_package_config(); + $rebuild_rules = "off"; snort_start($snortcfg, $if_real); header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); @@ -174,26 +194,28 @@ if ($pfsense_stable == 'yes') ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td> -<?php - $tab_array = array(); - $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); - $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); - $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); - $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); - $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); - $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); - $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - display_top_tabs($tab_array); -?> -</td></tr> <tr> <td> - <div id="mainarea2"> - <table class="tabcont" width="100%" border="0" cellpadding="0" - cellspacing="0"> + <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + ?> + </td> +</tr> +<tr> + <td> + <div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr id="frheader"> - <td width="5%" class="list"> </td> + <td width="3%" class="list"> </td> <td width="10%" class="listhdrr"><?php echo gettext("If"); ?></td> <td width="13%" class="listhdrr"><?php echo gettext("Snort"); ?></td> <td width="10%" class="listhdrr"><?php echo gettext("Performance"); ?></td> @@ -201,44 +223,86 @@ if ($pfsense_stable == 'yes') <td width="12%" class="listhdrr"><?php echo gettext("Barnyard2"); ?></td> <td width="30%" class="listhdr"><?php echo gettext("Description"); ?></td> <td width="3%" class="list"> - <table border="0" cellspacing="0" cellpadding="1"> + <table border="0" cellspacing="0" cellpadding="0"> <tr> - <td width="17"></td> - <td><a href="snort_interfaces_edit.php?id=<?php echo $id_gen;?>"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0" title="<?php echo gettext('add interface');?>"></a></td> + <td></td> + <td align="center" valign="middle"><a href="snort_interfaces_edit.php?id=<?php echo $id_gen;?>"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="<?php echo gettext('Add Snort interface mapping');?>"></a></td> </tr> </table> </td> </tr> -<?php $nnats = $i = 0; foreach ($a_nat as $natent): ?> -<tr valign="top" id="fr<?=$nnats;?>"> -<?php + <?php $nnats = $i = 0; -/* convert fake interfaces to real and check if iface is up */ -/* There has to be a smarter way to do this */ - $if_real = snort_get_real_interface($natent['interface']); - $snort_uuid = $natent['uuid']; - if (snort_is_running($snort_uuid, $if_real) == 'no') - $iconfn = 'pass'; - else - $iconfn = 'block'; - if (snort_is_running($snort_uuid, $if_real, 'barnyard2') == 'no') - $biconfn = 'pass'; - else - $biconfn = 'block'; + // Turn on buffering to speed up rendering + ini_set('output_buffering','true'); - ?> - <td class="listt"> - <input type="checkbox" id="frc<?=$nnats;?>" name="rule[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$nnats;?>')" style="margin: 0; padding: 0;"></td> - <td class="listr" + // Start buffering to fix display lag issues in IE9 and IE10 + ob_start(null, 0); + + /* If no interfaces are defined, then turn off the "no rules" warning */ + $no_rules_footnote = false; + if ($id_gen == 0) + $no_rules = false; + else + $no_rules = true; + + foreach ($a_nat as $natent): ?> + <tr valign="top" id="fr<?=$nnats;?>"> + <?php + + /* convert fake interfaces to real and check if iface is up */ + /* There has to be a smarter way to do this */ + $if_real = snort_get_real_interface($natent['interface']); + $natend_friendly= snort_get_friendly_interface($natent['interface']); + $snort_uuid = $natent['uuid']; + if (snort_is_running($snort_uuid, $if_real) == 'no'){ + $iconfn = 'block'; + $iconfn_msg1 = 'Snort is not running on '; + $iconfn_msg2 = '. Click to start.'; + } + else{ + $iconfn = 'pass'; + $iconfn_msg1 = 'Snort is running on '; + $iconfn_msg2 = '. Click to stop.'; + } + if (snort_is_running($snort_uuid, $if_real, 'barnyard2') == 'no'){ + $biconfn = 'block'; + $biconfn_msg1 = 'Barnyard2 is not running on '; + $biconfn_msg2 = '. Click to start.'; + } + else{ + $biconfn = 'pass'; + $biconfn_msg1 = 'Barnyard2 is running on '; + $biconfn_msg2 = '. Click to stop.'; + } + + /* See if interface has any rules defined and set boolean flag */ + $no_rules = true; + if (isset($natent['customrules']) && !empty($natent['customrules'])) + $no_rules = false; + if (isset($natent['rulesets']) && !empty($natent['rulesets'])) + $no_rules = false; + if (isset($natent['ips_policy']) && !empty($natent['ips_policy'])) + $no_rules = false; + /* Do not display the "no rules" warning if interface disabled */ + if ($natent['enable'] == "off") + $no_rules = false; + if ($no_rules) + $no_rules_footnote = true; + ?> + <td class="listt"> + <input type="checkbox" id="frc<?=$nnats;?>" name="rule[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$nnats;?>')" style="margin: 0; padding: 0;"> + </td> + <td class="listr" id="frd<?=$nnats;?>" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> <?php - echo snort_get_friendly_interface($natent['interface']); + echo $natend_friendly; ?> - </td> - <td class="listr" + </td> + <td class="listr" id="frd<?=$nnats;?>" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> <?php @@ -248,12 +312,13 @@ if ($pfsense_stable == 'yes') echo "<a href='?act=toggle&id={$i}'> <img src='../themes/{$g['theme']}/images/icons/icon_{$iconfn}.gif' width='13' height='13' border='0' - title='" . gettext('click to toggle start/stop snort') . "'></a>"; + title='" . gettext($iconfn_msg1.$natend_friendly.$iconfn_msg2) . "'></a>"; + echo ($no_rules) ? " <img src=\"../themes/{$g['theme']}/images/icons/icon_frmfld_imp.png\" width=\"15\" height=\"15\" border=\"0\">" : ""; } else echo strtoupper("disabled"); ?> - </td> - <td class="listr" + </td> + <td class="listr" id="frd<?=$nnats;?>" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> <?php @@ -263,8 +328,9 @@ if ($pfsense_stable == 'yes') }else{ $check_performance = "lowmem"; } - ?> <?=strtoupper($check_performance);?></td> - <td class="listr" + ?> <?=strtoupper($check_performance);?> + </td> + <td class="listr" id="frd<?=$nnats;?>" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> <?php @@ -275,8 +341,9 @@ if ($pfsense_stable == 'yes') } else { $check_blockoffenders = disabled; } - ?> <?=strtoupper($check_blockoffenders);?></td> - <td class="listr" + ?> <?=strtoupper($check_blockoffenders);?> + </td> + <td class="listr" id="frd<?=$nnats;?>" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> <?php @@ -286,94 +353,140 @@ if ($pfsense_stable == 'yes') echo "<a href='?act=bartoggle&id={$i}'> <img src='../themes/{$g['theme']}/images/icons/icon_{$biconfn}.gif' width='13' height='13' border='0' - title='" . gettext('click to toggle start/stop barnyard') . "'></a>"; + title='" . gettext($biconfn_msg1.$natend_friendly.$biconfn_msg2) . "'></a>"; } else echo strtoupper("disabled"); ?> - </td> - <td class="listbg" + </td> + <td class="listbg" ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <font color="#ffffff"> <?=htmlspecialchars($natent['descr']);?> - </td> - <td valign="middle" class="list" nowrap> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="<?php echo gettext('edit interface'); ?>"></a></td> - </tr> - </table> - - </tr> - <?php $i++; $nnats++; endforeach; ?> - <tr> - <td class="list" colspan="8"></td> - <td class="list" valign="middle" nowrap> - <table border="0" cellspacing="0" cellpadding="1"> + <font color="#ffffff"> <?=htmlspecialchars($natent['descr']);?> + </td> + <td valign="middle" class="list" nowrap> + <table border="0" cellspacing="0" cellpadding="0"> + <tr> + <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="<?php echo gettext('Edit Snort interface mapping'); ?>"></a> + </td> + </tr> + </table> + </td> + </tr> + <?php $i++; $nnats++; endforeach; ob_end_flush(); ?> + <tr> + <td class="list"></td> + <td class="list" colspan="6"> + <?php if ($no_rules_footnote): ?><br><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_frmfld_imp.png" width="15" height="15" border="0"> + <span class="red">   <?php echo gettext("WARNING: Marked interface currently has no rules defined for Snort"); ?></span> + <?php else: ?> + <?php endif; ?> + </td> + <td class="list" valign="middle" nowrap> + <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><?php if ($nnats == 0): ?><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" - width="17" height="17" title="<?php echo gettext("delete selected interface"); ?>" border="0"><?php else: ?><input - name="del" type="image" - src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" title="<?php echo gettext("delete selected interface"); ?>" - onclick="return confirm('Do you really want to delete the selected Snort mapping?')"><?php endif; ?></td> + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" + width="17" height="17" " border="0"> + <?php else: ?> + <input name="del" type="image" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" title="<?php echo gettext("Delete selected Snort interface mapping(s)"); ?>" + onclick="return intf_del()"> + <?php endif; ?></td> </tr> </table> - </td> - </tr> - </table> - </div> - </td> - </tr> -</table> - -<br> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - <div id="mainarea4"> - <table class="tabcont" width="100%" border="0" cellpadding="0" - cellspacing="0"> - <tr id="frheader"> - <td width="100%"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> - <?php echo gettext('This is the <strong>Snort Menu</strong> where you can see an over ' . - 'view of all your interface settings. <br> ' . - 'Please edit the <strong>Global Settings</strong> tab before adding ' . - 'an interface.'); ?> <br> - <br> - <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> <br> - <strong><?php echo gettext("New settings will not take effect until interface restart."); ?></strong> - <br> - <br> - <strong>Click</strong> on the <img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0" title="<?php echo gettext("Add Icon"); ?>"> icon to add a - interface.<strong> Click</strong> - on the <img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" - width="13" height="13" border="0" title="<?php echo gettext("Start Icon"); ?>"> icon to <strong>start</strong> - snort and barnyard2. <br> - <strong>Click</strong> on the <img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="<?php echo gettext("Edit Icon"); ?>"> icon to edit a - interface and settings.<strong> Click</strong> - on the <img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" - width="13" height="13" border="0" title="<?php echo gettext("Stop Icon"); ?>"> icon to <strong>stop</strong> - snort and barnyard2. <br> - <strong> Click</strong> on the <img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" border="0" title="<?php echo gettext("Delete Icon"); ?>"> icon to - delete a interface and settings.</td> - </tr> - </table> - </div> - - </tr> + </td> + </tr> + <tr> + <td colspan="8"> </td> + </tr> + <tr> + <td> </td> + <td colspan="6"> + <table class="tabcont" width="100%" border="0" cellpadding="1" cellspacing="0"> + <tr> + <td colspan="3" class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> + <?php echo gettext("This is the ") . "<strong>" . gettext("Snort Menu ") . + "</strong>" . gettext("where you can see an overview of all your interface settings."); + if (empty($a_nat)) { + echo gettext("Please visit the ") . "<strong>" . gettext("Global Settings") . + "</strong>" . gettext(" tab before adding an interface."); + }?> + </td> + </tr> + <tr> + <td colspan="3" class="vexpl"><br> + </td> + </tr> + <tr> + <td colspan="3" class="vexpl"><span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span><br> + <strong><?php echo gettext("New settings will not take effect until interface restart."); ?></strong> + </td> + </tr> + <tr> + <td colspan="3" class="vexpl"><br> + </td> + </tr> + <tr> + <td class="vexpl"><strong>Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="<?php echo gettext("Add Icon"); ?>"> icon to add + an interface. + </td> + <td width="3%" class="vexpl"> + </td> + <td class="vexpl"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" + width="13" height="13" border="0" title="<?php echo gettext("Running"); ?>"> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" + width="13" height="13" border="0" title="<?php echo gettext("Not Running"); ?>"> icons will show current + snort and barnyard2 status. + </td> + </tr> + <tr> + <td class="vexpl"><strong>Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="<?php echo gettext("Edit Icon"); ?>"> icon to edit + an interface and settings. + <td width="3%"> + </td> + <td class="vexpl"><strong>Click</strong> on the status icons to <strong>toggle</strong> snort and barnyard2 status. + </td> + </tr> + <tr> + <td colspan="3" class="vexpl"><strong> Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="<?php echo gettext("Delete Icon"); ?>"> icon to + delete an interface and settings. + </td> + </tr> + </table> + </td> + <td> </td> + </tr> + </table> + </div> </td> +</tr> </table> </form> + +<script type="text/javascript"> + +function intf_del() { + var isSelected = false; + var inputs = document.iform.elements; + for (var i = 0; i < inputs.length; i++) { + if (inputs[i].type == "checkbox") { + if (inputs[i].checked) + isSelected = true; + } + } + if (isSelected) + return confirm('Do you really want to delete the selected Snort mapping?'); + else + alert("There is no Snort mapping selected for deletion. Click the checkbox beside the Snort mapping(s) you wish to delete."); +} + +</script> + <?php include("fend.inc"); ?> diff --git a/config/snort/snort_interfaces_edit.php b/config/snort/snort_interfaces_edit.php index d0fabbf4..08d7d2ba 100755 --- a/config/snort/snort_interfaces_edit.php +++ b/config/snort/snort_interfaces_edit.php @@ -31,7 +31,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $rebuild_rules; if (!is_array($config['installedpackages']['snortglobal'])) $config['installedpackages']['snortglobal'] = array(); @@ -50,12 +50,28 @@ if (is_null($id)) { } $pconfig = array(); -if (empty($snortglob['rule'][$id]['uuid'])) +if (empty($snortglob['rule'][$id]['uuid'])) { + /* Adding new interface, so flag rules to build. */ $pconfig['uuid'] = snort_generate_id(); -else + $rebuild_rules = "on"; +} +else { $pconfig['uuid'] = $a_rule[$id]['uuid']; + $pconfig['descr'] = $a_rule[$id]['descr']; + $rebuild_rules = "off"; +} $snort_uuid = $pconfig['uuid']; +// Get the physical configured interfaces on the firewall +if (function_exists('get_configured_interface_with_descr')) + $interfaces = get_configured_interface_with_descr(); +else { + $interfaces = array('wan' => 'WAN', 'lan' => 'LAN'); + for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) + $interfaces['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; +} + +// See if interface is already configured, and use its values if (isset($id) && $a_rule[$id]) { /* old options */ $pconfig = $a_rule[$id]; @@ -63,28 +79,32 @@ if (isset($id) && $a_rule[$id]) { $pconfig['configpassthru'] = base64_decode($pconfig['configpassthru']); if (empty($pconfig['uuid'])) $pconfig['uuid'] = $snort_uuid; - if (!$pconfig['interface']) - $pconfig['interface'] = "wan"; +} +// Must be a new interface, so try to pick next available physical interface to use +elseif (isset($id) && !isset($a_rule[$id])) { + $ifaces = get_configured_interface_list(); + $ifrules = array(); + foreach($a_rule as $r) + $ifrules[] = $r['interface']; + foreach ($ifaces as $i) { + if (!in_array($i, $ifrules)) { + $pconfig['interface'] = $i; + break; + } + } + if (count($ifrules) == count($ifaces)) { + $input_errors[] = "No more available interfaces to configure for Snort!"; + $interfaces = array(); + $pconfig = array(); + } } if (isset($_GET['dup'])) unset($id); if ($_POST["Submit"]) { - if ($_POST['descr'] == '' && $pconfig['descr'] == '') { - $input_errors[] = "Please enter a description for your reference."; - } - if (!$_POST['interface']) $input_errors[] = "Interface is mandatory"; -/* - foreach ($a_rule as $natent) { - if (isset($id) && ($a_rule[$id]) && ($a_rule[$id] === $natent)) - continue; - if ($natent['interface'] == $_POST['interface']) - $input_errors[] = "This interface is already configured for another instance"; - } -*/ /* if no errors write to conf */ if (!$input_errors) { @@ -92,7 +112,19 @@ if ($_POST["Submit"]) { $natent['interface'] = $_POST['interface']; $natent['enable'] = $_POST['enable'] ? 'on' : 'off'; $natent['uuid'] = $pconfig['uuid']; - if ($_POST['descr']) $natent['descr'] = $_POST['descr']; else unset($natent['descr']); + + /* See if the HOME_NET, EXTERNAL_NET, WHITELIST or SUPPRESS LIST values were changed */ + $snort_reload = false; + if ($_POST['homelistname'] && ($_POST['homelistname'] <> $natent['homelistname'])) + $snort_reload = true; + if ($_POST['externallistname'] && ($_POST['externallistname'] <> $natent['externallistname'])) + $snort_reload = true; + if ($_POST['suppresslistname'] && ($_POST['suppresslistname'] <> $natent['suppresslistname'])) + $snort_reload = true; + if ($_POST['whitelistname'] && ($_POST['whitelistname'] <> $natent['whitelistname'])) + $snort_reload = true; + + if ($_POST['descr']) $natent['descr'] = $_POST['descr']; else $natent['descr'] = strtoupper($natent['interface']); if ($_POST['performance']) $natent['performance'] = $_POST['performance']; else unset($natent['performance']); /* if post = on use on off or rewrite the conf */ if ($_POST['blockoffenders7'] == "on") $natent['blockoffenders7'] = 'on'; else $natent['blockoffenders7'] = 'off'; @@ -118,11 +150,28 @@ if ($_POST["Submit"]) { } else $a_rule[] = $natent; + /* If Snort is disabled on this interface, stop any running instance */ if ($natent['enable'] != 'on') snort_stop($natent, $if_real); + + /* Save configuration changes */ write_config(); + + /* Most changes don't require a rules rebuild, so default to "off" */ + $rebuild_rules = "off"; + + /* Update snort.conf and snort.sh files for this interface */ sync_snort_package_config(); + /*******************************************************/ + /* Signal Snort to reload configuration if we changed */ + /* HOME_NET, the Whitelist, EXTERNAL_NET or Suppress */ + /* list values. The function only signals a running */ + /* Snort instance to safely reload these parameters. */ + /*******************************************************/ + if ($snort_reload == true) + snort_reload_config($natent, $if_real); + header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); header( 'Cache-Control: no-store, no-cache, must-revalidate' ); @@ -143,29 +192,6 @@ include_once("head.inc"); <?php include("fbegin.inc"); ?> -<script language="JavaScript"> -<!-- - -function enable_blockoffenders() { - var endis = !(document.iform.blockoffenders7.checked); - document.iform.blockoffenderskill.disabled=endis; - document.iform.blockoffendersip.disabled=endis; -} - -function enable_change(enable_change) { - endis = !(document.iform.enable.checked || enable_change); - // make sure a default answer is called if this is invoked. - endis2 = (document.iform.enable); - document.iform.performance.disabled = endis; - document.iform.blockoffenders7.disabled = endis; - document.iform.alertsystemlog.disabled = endis; - document.iform.externallistname.disabled = endis; - document.iform.homelistname.disabled = endis; - document.iform.suppresslistname.disabled = endis; - document.iform.configpassthru.disabled = endis; -} -//--> -</script> <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <?php @@ -181,21 +207,33 @@ function enable_change(enable_change) { <form action="snort_interfaces_edit.php<?php echo "?id=$id";?>" method="post" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td class="tabnavtbl"> +<tr><td> <?php - $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), true, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); - display_top_tabs($tab_array); + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td class="tabnavtbl">'; + $tab_array = array(); + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface "); + $tab_array[] = array($menu_iface . gettext("Settings"), true, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); ?> </td></tr> -<tr><td class="tabcont"> -<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr><td><div id="mainarea"> +<table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Settings"); ?></td> </tr> @@ -215,32 +253,22 @@ function enable_change(enable_change) { <tr> <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Interface"); ?></td> <td width="78%" class="vtable"> - <select name="interface" class="formselect"> + <select name="interface" class="formselect" tabindex="0"> <?php - if (function_exists('get_configured_interface_with_descr')) - $interfaces = get_configured_interface_with_descr(); - else { - $interfaces = array('wan' => 'WAN', 'lan' => 'LAN'); - for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { - $interfaces['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; - } - } foreach ($interfaces as $iface => $ifacename): ?> <option value="<?=$iface;?>" - <?php if ($iface == $pconfig['interface']) echo "selected"; ?>><?=htmlspecialchars($ifacename);?> + <?php if ($iface == $pconfig['interface']) echo " selected"; ?>><?=htmlspecialchars($ifacename);?> </option> - <?php endforeach; ?> - </select><br> - <span class="vexpl"><?php echo gettext("Choose which interface this rule applies to."); ?><br/> + <?php endforeach; ?> + </select> + <span class="vexpl"><?php echo gettext("Choose which interface this Snort instance applies to."); ?><br/> <span class="red"><?php echo gettext("Hint:"); ?> </span><?php echo gettext("in most cases, you'll want to use WAN here."); ?></span><br/></td> </tr> <tr> <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Description"); ?></td> <td width="78%" class="vtable"><input name="descr" type="text" - class="formfld" id="descr" size="40" - value="<?=htmlspecialchars($pconfig['descr']);?>"> <br/> - <span class="vexpl"><?php echo gettext("You may enter a description here for your " . - "reference (not parsed)."); ?></span><br/></td> + class="formfld" id="descr" size="40" value="<?=htmlspecialchars($pconfig['descr']); ?>"> <br/> + <span class="vexpl"><?php echo gettext("Enter a meaningful description here for your reference."); ?></span><br/></td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Alert Settings"); ?></td> @@ -251,7 +279,7 @@ function enable_change(enable_change) { <td width="78%" class="vtable"><input name="alertsystemlog" type="checkbox" value="on" <?php if ($pconfig['alertsystemlog'] == "on") echo "checked"; ?> - onClick="enable_change(false)"><br> + onClick="enable_change(false)"> <?php echo gettext("Snort will send Alerts to the firewall's system logs."); ?></td> </tr> <tr> @@ -259,7 +287,7 @@ function enable_change(enable_change) { <td width="78%" class="vtable"> <input name="blockoffenders7" id="blockoffenders7" type="checkbox" value="on" <?php if ($pconfig['blockoffenders7'] == "on") echo "checked"; ?> - onClick="enable_blockoffenders()"><br> + onClick="enable_blockoffenders()"> <?php echo gettext("Checking this option will automatically block hosts that generate a " . "Snort alert."); ?></td> </tr> @@ -267,11 +295,11 @@ function enable_change(enable_change) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Kill states"); ?></td> <td width="78%" class="vtable"> <input name="blockoffenderskill" id="blockoffenderskill" type="checkbox" value="on" <?php if ($pconfig['blockoffenderskill'] == "on") echo "checked"; ?>> - <br/><?php echo gettext("Checking this option will kill firewall states for the blocked ip"); ?> + <?php echo gettext("Checking this option will kill firewall states for the blocked IP"); ?> </td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Which ip to block"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Which IP to block"); ?></td> <td width="78%" class="vtable"> <select name="blockoffendersip" class="formselect" id="blockoffendersip"> <?php @@ -283,8 +311,8 @@ function enable_change(enable_change) { echo htmlspecialchars($btype) . '</option>'; } ?> - </select> - <br/><?php echo gettext("Which ip extracted from the packet you want to block"); ?> + </select> + <?php echo gettext("Select which IP extracted from the packet you wish to block"); ?> </td> </tr> <tr> @@ -303,7 +331,8 @@ function enable_change(enable_change) { <?php if ($iface2 == $pconfig['performance']) echo "selected"; ?>> <?=htmlspecialchars($ifacename2);?></option> <?php endforeach; ?> - </select><br> + </select> + <?php echo gettext("Choose a search performance setting"); ?><br/> <span class="vexpl"><?php echo gettext("LOWMEM and AC-BNFA are recommended for low end " . "systems, AC-SPLIT: low memory, high performance, short-hand for search-method ac split-any-any, AC: high memory, " . "best performance, -NQ: the -nq option specifies that matches should not be queued and evaluated as they are found," . @@ -315,86 +344,99 @@ function enable_change(enable_change) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Checksum Check Disable"); ?></td> <td width="78%" class="vtable"> <input name="cksumcheck" id="cksumcheck" type="checkbox" value="on" <?php if ($pconfig['cksumcheck'] == "on") echo "checked"; ?>> - <br><?php echo gettext("If ticked, checksum checking on Snort will be disabled to improve performance."); ?> - <br><?php echo gettext("Most of this is already done at the firewall/filter level."); ?> + <?php echo gettext("Disable checksum checking within Snort to improve performance."); ?> + <br><span class="red"><?php echo gettext("Hint: ") . "</span>" . + gettext("Most of this is already done at the firewall/filter level, so it is usually safe to check this box."); ?> </td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Choose the networks " . - "snort should inspect and whitelist."); ?></td> + "Snort should inspect and whitelist."); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Home net"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Home Net"); ?></td> <td width="78%" class="vtable"> + <select name="homelistname" class="formselect" id="homelistname"> - <?php - echo "<option value='default' >default</option>"; - /* find whitelist names and filter by type */ - if (is_array($snortglob['whitelist']['item'])) { - foreach ($snortglob['whitelist']['item'] as $value) { - $ilistname = $value['name']; - if ($ilistname == $pconfig['homelistname']) - echo "<option value='$ilistname' selected>"; - else - echo "<option value='$ilistname'>"; - echo htmlspecialchars($ilistname) . '</option>'; + <?php + echo "<option value='default' >default</option>"; + /* find whitelist names and filter by type */ + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['homelistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; + } } - } - ?> - </select><br/> - <span class="vexpl"><?php echo gettext("Choose the home net you will like this rule to " . - "use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default home " . - "net adds only local networks."); ?><br> - <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Most users add a list of " . - "friendly ips that the firewall cant see."); ?><br/></td> + ?> + </select> + <input type="button" class="formbtns" value="View List" + onclick="viewList('<?=$id;?>','homelistname')" id="btnHomeNet" + title="<?php echo gettext("Click to view currently selected Home Net contents"); ?>"/> + <br/> + <span class="vexpl"><?php echo gettext("Choose the Home Net you want this interface to use."); ?></span> + <br/></br> + <span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default Home " . + "Net adds only local networks, WAN IPs, Gateways, VPNs and VIPs."); ?><br/> + <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Create an Alias to hold a list of " . + "friendly IPs that the firewall cannot see or to customize the default Home Net."); ?><br/> + </td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("External net"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("External Net"); ?></td> <td width="78%" class="vtable"> <select name="externallistname" class="formselect" id="externallistname"> - <?php - echo "<option value='default' >default</option>"; - /* find whitelist names and filter by type */ - if (is_array($snortglob['whitelist']['item'])) { - foreach ($snortglob['whitelist']['item'] as $value) { - $ilistname = $value['name']; - if ($ilistname == $pconfig['externallistname']) - echo "<option value='$ilistname' selected>"; - else - echo "<option value='$ilistname'>"; - echo htmlspecialchars($ilistname) . '</option>'; + <?php + echo "<option value='default' >default</option>"; + /* find whitelist names and filter by type */ + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['externallistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; + } } - } - ?> - </select><br/> - <span class="vexpl"><?php echo gettext("Choose the external net you will like this rule " . - "to use."); ?> </span> <br/><span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default " . - "external net, networks that are not home net."); ?><br/> - <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Most users should leave this " . - "setting at default."); ?><br/></td> + ?> + </select> + <span class="vexpl"><?php echo gettext("Choose the External Net you want this interface " . + "to use."); ?></span> <br/><br/> + <span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default " . + "External Net is networks that are not Home Net."); ?><br/> + <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Most users should leave this " . + "setting at default. Create an Alias for custom External Net settings."); ?><br/> + </td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Whitelist"); ?></td> <td width="78%" class="vtable"> <select name="whitelistname" class="formselect" id="whitelistname"> - <?php - /* find whitelist names and filter by type, make sure to track by uuid */ - echo "<option value='default' >default</option>\n"; - if (is_array($snortglob['whitelist']['item'])) { - foreach ($snortglob['whitelist']['item'] as $value) { - if ($value['name'] == $pconfig['whitelistname']) - echo "<option value='{$value['name']}' selected>"; - else - echo "<option value='{$value['name']}'>"; - echo htmlspecialchars($value['name']) . '</option>'; + <?php + /* find whitelist names and filter by type, make sure to track by uuid */ + echo "<option value='default' >default</option>\n"; + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + if ($value['name'] == $pconfig['whitelistname']) + echo "<option value='{$value['name']}' selected>"; + else + echo "<option value='{$value['name']}'>"; + echo htmlspecialchars($value['name']) . '</option>'; + } } - } - ?> - </select><br> - <span class="vexpl"><?php echo gettext("Choose the whitelist you will like this rule to " . - "use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("Default " . - "whitelist adds only local networks."); ?><br/> - <span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("This option will only be used when block offenders is on."); ?> + ?> + </select> + <input type="button" class="formbtns" value="View List" onclick="viewList('<?=$id;?>','whitelistname')" + id="btnWhitelist" title="<?php echo gettext("Click to view currently selected Whitelist contents"); ?>"/> + <br/> + <span class="vexpl"><?php echo gettext("Choose the whitelist you want this interface to " . + "use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Default " . + "whitelist adds local networks, WAN IPs, Gateways, VPNs and VIPs. Create an Alias to customize."); ?><br/> + <span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("This option will only be used when block offenders is on."); ?> </td> </tr> <tr> @@ -419,10 +461,14 @@ function enable_change(enable_change) { } } ?> - </select><br> + </select> + <input type="button" class="formbtns" value="View List" onclick="viewList('<?=$id;?>','suppresslistname', 'suppress')" + id="btnSuppressList" title="<?php echo gettext("Click to view currently selected Suppression List contents"); ?>"/> + <br/> <span class="vexpl"><?php echo gettext("Choose the suppression or filtering file you " . - "will like this interface to use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("Default " . - "option disables suppression and filtering."); ?></td> + "want this interface to use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note: ") . "</span>" . + gettext("Default option disables suppression and filtering."); ?> + </td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Arguments here will " . @@ -432,29 +478,83 @@ function enable_change(enable_change) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Advanced configuration pass through"); ?></td> <td width="78%" class="vtable"> <textarea wrap="off" name="configpassthru" cols="65" rows="12" id="configpassthru"><?=htmlspecialchars($pconfig['configpassthru']);?></textarea> - </td> </tr> <tr> <td width="22%" valign="top"></td> - <td width="78%"><input name="Submit" type="submit" class="formbtn" value="Save"> - <input name="id" type="hidden" value="<?=$id;?>"> + <td width="78%"><input name="Submit" type="submit" class="formbtn" value="Save" title="<?php echo + gettext("Click to save settings and exit"); ?>"/> + <input name="id" type="hidden" value="<?=$id;?>"/> </td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span><br/> - <?php echo gettext("Please save your settings before you click start."); ?> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note: ") . "</strong></span>" . + gettext("Please save your settings before you attempt to start Snort."); ?> </td> </tr> </table> +</div> </td></tr> </table> </form> <script language="JavaScript"> <!-- -enable_change(false); -enable_blockoffenders(); +function enable_blockoffenders() { + var endis = !(document.iform.blockoffenders7.checked); + document.iform.blockoffenderskill.disabled=endis; + document.iform.blockoffendersip.disabled=endis; + document.iform.whitelistname.disabled=endis; + document.iform.btnWhitelist.disabled=endis; +} + +function enable_change(enable_change) { + endis = !(document.iform.enable.checked || enable_change); + // make sure a default answer is called if this is invoked. + endis2 = (document.iform.enable); + document.iform.performance.disabled = endis; + document.iform.blockoffenders7.disabled = endis; + document.iform.blockoffendersip.disabled=endis; + document.iform.blockoffenderskill.disabled=endis; + document.iform.alertsystemlog.disabled = endis; + document.iform.externallistname.disabled = endis; + document.iform.cksumcheck.disabled = endis; + document.iform.homelistname.disabled = endis; + document.iform.whitelistname.disabled=endis; + document.iform.suppresslistname.disabled = endis; + document.iform.configpassthru.disabled = endis; + document.iform.btnHomeNet.disabled=endis; + document.iform.btnWhitelist.disabled=endis; + document.iform.btnSuppressList.disabled=endis; +} + +function wopen(url, name, w, h) { + // Fudge factors for window decoration space. + // In my tests these work well on all platforms & browsers. + w += 32; + h += 96; + var win = window.open(url, + name, + 'width=' + w + ', height=' + h + ', ' + + 'location=no, menubar=no, ' + + 'status=no, toolbar=no, scrollbars=yes, resizable=yes'); + win.resizeTo(w, h); + win.focus(); +} + +function getSelectedValue(elemID) { + var ctrl = document.getElementById(elemID); + return ctrl.options[ctrl.selectedIndex].value; +} + +function viewList(id, elemID, elemType) { + if (typeof elemType == "undefined") { + elemType = "whitelist"; + } + var url = "snort_list_view.php?id=" + id + "&wlist="; + url = url + getSelectedValue(elemID) + "&type=" + elemType; + wopen(url, 'WhitelistViewer', 640, 480); +} //--> </script> <?php include("fend.inc"); ?> diff --git a/config/snort/snort_interfaces_global.php b/config/snort/snort_interfaces_global.php index 9dde8aaf..0b9c5f2d 100644 --- a/config/snort/snort_interfaces_global.php +++ b/config/snort/snort_interfaces_global.php @@ -50,6 +50,10 @@ $pconfig['snortloglimit'] = $config['installedpackages']['snortglobal']['snortlo $pconfig['snortloglimitsize'] = $config['installedpackages']['snortglobal']['snortloglimitsize']; $pconfig['autorulesupdate7'] = $config['installedpackages']['snortglobal']['autorulesupdate7']; $pconfig['forcekeepsettings'] = $config['installedpackages']['snortglobal']['forcekeepsettings']; +$pconfig['snortcommunityrules'] = $config['installedpackages']['snortglobal']['snortcommunityrules']; + +if (empty($pconfig['snortloglimit'])) + $pconfig['snortloglimit'] = 'on'; /* if no errors move foward */ if (!$input_errors) { @@ -58,7 +62,9 @@ if (!$input_errors) { $config['installedpackages']['snortglobal']['snortdownload'] = $_POST['snortdownload']; $config['installedpackages']['snortglobal']['oinkmastercode'] = $_POST['oinkmastercode']; + $config['installedpackages']['snortglobal']['snortcommunityrules'] = $_POST['snortcommunityrules'] ? 'on' : 'off'; $config['installedpackages']['snortglobal']['emergingthreats'] = $_POST['emergingthreats'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['rm_blocked'] = $_POST['rm_blocked']; if ($_POST['snortloglimitsize']) { $config['installedpackages']['snortglobal']['snortloglimit'] = $_POST['snortloglimit']; @@ -110,9 +116,23 @@ if ($input_errors) ?> +<script language="JavaScript"> +<!-- +function enable_snort_vrt(btn) { + if (btn == 'off') { + document.iform.oinkmastercode.disabled = "true"; + } + if (btn == 'on') { + document.iform.oinkmastercode.disabled = ""; + } +} +//--> +</script> + + <form action="snort_interfaces_global.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td class="tabnavtbl"> +<tr><td> <?php $tab_array = array(); $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); @@ -122,65 +142,81 @@ if ($input_errors) $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array); ?> </td></tr> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <td> + <div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Please Choose The " . "Type Of Rules You Wish To Download"); ?></td> </tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Install Snort.org rules"); ?></td> + <td width="22%" valign="top" class="vncell"><?php printf(gettext("Install %sSnort VRT%s rules"), '<strong>' , '</strong>'); ?></td> <td width="78%" class="vtable"> - <table cellpadding="0" cellspacing="0"> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tr> - <td colspan="2"><input name="snortdownload" type="radio" - id="snortdownload" value="off" -<?php if($pconfig['snortdownload']=='off' || $pconfig['snortdownload']=='') echo 'checked'; ?>> - <?php printf(gettext("Do %sNOT%s Install"), '<strong>', '</strong>'); ?></td> + <td><input name="snortdownload" type="radio" id="snortdownload" value="off" onclick="enable_snort_vrt('off')" + <?php if($pconfig['snortdownload']=='off' || $pconfig['snortdownload']=='') echo 'checked'; ?> > </td> + <td><span class="vexpl"><?php printf(gettext("Do %sNOT%s Install"), '<strong>', '</strong>'); ?></span></td> </tr> <tr> - <td colspan="2"><input name="snortdownload" type="radio" - id="snortdownload" value="on" - <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>> <?php echo gettext("Install " . - "Basic Rules or Premium rules"); ?> <br> - <a - href="https://www.snort.org/signup" target="_blank"><?php echo gettext("Sign Up for a " . - "Basic Rule Account"); ?></a><br> - <a - href="http://www.snort.org/vrt/buy-a-subscription" - target="_blank"><?php echo gettext("Sign Up for Sourcefire VRT Certified Premium " . - "Rules. This Is Highly Recommended"); ?></a></td> - </tr> + <td><input name="snortdownload" type="radio" id="snortdownload" value="on" onclick="enable_snort_vrt('on')" + <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>></td> + <td><span class="vexpl"><?php echo gettext("Install Basic Rules or Premium rules"); ?></span></td> <tr> <td> </td> + <td><a href="https://www.snort.org/signup" target="_blank"><?php echo gettext("Sign Up for a Basic Rule Account"); ?> </a><br> + <a href="http://www.snort.org/vrt/buy-a-subscription" target="_blank"> + <?php echo gettext("Sign Up for Sourcefire VRT Certified Premium Rules. This Is Highly Recommended"); ?></a></td> </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td colspan="2" valign="top" class="optsect_t2"><?php echo gettext("Oinkmaster code"); ?></td> + <td colspan="2"> </td> </tr> + </table> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tr> - <td class="vncell" valign="top"><?php echo gettext("Code"); ?></td> - <td class="vtable"><input name="oinkmastercode" type="text" + <td colspan="2" valign="top"><b><span class="vexpl"><?php echo gettext("Oinkmaster Configuration"); ?></span></b></td> + </tr> + <tr> + <td valign="top"><span class="vexpl"><strong><?php echo gettext("Code"); ?><strong></span</td> + <td><input name="oinkmastercode" type="text" class="formfld" id="oinkmastercode" size="52" - value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>"><br> - <?php echo gettext("Obtain a snort.org Oinkmaster code and paste here."); ?></td> - + value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>" + <?php if($pconfig['snortdownload']<>'on') echo 'disabled'; ?>><br> + <?php echo gettext("Obtain a snort.org Oinkmaster code and paste it here."); ?></td> + </tr> </table> - </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php printf(gettext("Install %sEmergingthreats%s " . + <td width="22%" valign="top" class="vncell"><?php printf(gettext("Install %sSnort Community%s " . + "rules"), '<strong>' , '</strong>'); ?></td> + <td width="78%" class="vtable"> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <tr> + <td valign="top" width="8%"><input name="snortcommunityrules" type="checkbox" value="yes" + <?php if ($config['installedpackages']['snortglobal']['snortcommunityrules']=="on") echo "checked"; ?> ></td> + <td><span class="vexpl"><?php echo gettext("The Snort Community Ruleset is a GPLv2 VRT certified ruleset that is distributed free of charge " . + "without any VRT License restrictions. This ruleset is updated daily and is a subset of the subscriber ruleset."); ?> + <br/><br/><?php printf(gettext("%sNote: %sIf you are a Snort VRT Paid Subscriber, the community ruleset is already built into your download of the Snort VRT rules, and there is no benefit in adding this rule set."),'<span class="red"><strong>' ,'</strong></span>'); ?></span><br></td> + </tr> + </table></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php printf(gettext("Install %sEmerging Threats%s " . "rules"), '<strong>' , '</strong>'); ?></td> - <td width="78%" class="vtable"><input name="emergingthreats" - type="checkbox" value="yes" - <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?> - ><br> - <?php echo gettext("Emerging Threats is an open source community that produces fastest " . - "moving and diverse Snort Rules."); ?></td> + <td width="78%" class="vtable"> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <tr> + <td valign="top" width="8%"><input name="emergingthreats" type="checkbox" value="yes" + <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?>> + <td><span class="vexpl"><?php echo gettext("Emerging Threats is an open source community that produces fast " . + "moving and diverse Snort Rules."); ?></span></td> + </tr> + </table> + </td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Update rules " . @@ -194,9 +230,9 @@ if ($input_errors) <?php if ($iface3 == $pconfig['autorulesupdate7']) echo "selected"; ?>> <?=htmlspecialchars($ifacename3);?></option> <?php endforeach; ?> - </select><br> - <span class="vexpl"><?php echo gettext("Please select the update times for rules."); ?><br> - <?php echo gettext("Hint: in most cases, every 12 hours is a good choice."); ?></span></td> + </select><span class="vexpl"> <?php echo gettext("Please select the update times for rules."); ?><br/><br/> + + <?php printf(gettext("%sHint%s: in most cases, every 12 hours is a good choice."), '<span class="red"><strong>','</strong></span>'); ?></span></td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Settings"); ?></td> @@ -209,40 +245,32 @@ if ($input_errors) <br/> <br/> <span class="red"><strong><?php echo gettext("Note"); ?></span>:</strong><br> - <?php echo gettext("Available space is"); ?> <strong><?php echo $snortlogCurrentDSKsize; ?>MB</strong></td> + <?php echo gettext("Available space is"); ?> <strong><?php echo $snortlogCurrentDSKsize; ?> MB</strong></td> <td width="78%" class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td colspan="2"><input name="snortloglimit" type="radio" - id="snortloglimit" value="on" -<?php if($pconfig['snortloglimit']=='on') echo 'checked'; ?>> - <strong><?php echo gettext("Enable"); ?></strong> <?php echo gettext("directory size limit"); ?> (<strong><?php echo gettext("Default"); ?></strong>)</td> - </tr> - <tr> - <td colspan="2"><input name="snortloglimit" type="radio" - id="snortloglimit" value="off" -<?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?>> <strong><?php echo gettext("Disable"); ?></strong> - <?php echo gettext("directory size limit"); ?><br> - <br> - <span class="red"><strong><?php echo gettext("Warning"); ?></span>:</strong> <?php echo gettext("Nanobsd " . - "should use no more than 10MB of space."); ?></td> - </tr> - <tr> - <td> </td> - </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td class="vncell3"><?php echo gettext("Size in"); ?> <strong>MB</strong></td> - <td class="vtable"><input name="snortloglimitsize" type="text" - class="formfld" id="snortloglimitsize" size="7" - value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> - <?php echo gettext("Default is"); ?> <strong>20%</strong> <?php echo gettext("of available space."); ?></td> - - </table> - + <table cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2"><input name="snortloglimit" type="radio" id="snortloglimit" value="on" + <?php if($pconfig['snortloglimit']=='on') echo 'checked'; ?>><span class="vexpl"> + <strong><?php echo gettext("Enable"); ?></strong> <?php echo gettext("directory size limit"); ?> (<strong><?php echo gettext("Default"); ?></strong>)</span></td> + </tr> + <tr> + <td colspan="2"><input name="snortloglimit" type="radio" id="snortloglimit" value="off" + <?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?>> <span class="vexpl"><strong><?php echo gettext("Disable"); ?></strong> + <?php echo gettext("directory size limit"); ?></span><br> + <br> + <span class="red"><strong><?php echo gettext("Warning"); ?></span>:</strong> <?php echo gettext("Nanobsd " . + "should use no more than 10MB of space."); ?></td> + </tr> + </table> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <tr> + <td><span class="vexpl"><?php echo gettext("Size in"); ?> <strong>MB</strong></span></td> + <td><input name="snortloglimitsize" type="text" class="formfld" id="snortloglimitsize" size="10" value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> + <?php printf(gettext("Default is %s20%%%s of available space."), '<strong>', '</strong>'); ?></td> + </tr> + </table> + </td> </tr> - <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove blocked hosts " . "every"); ?></td> @@ -255,10 +283,9 @@ if ($input_errors) <?php if ($iface3 == $pconfig['rm_blocked']) echo "selected"; ?>> <?=htmlspecialchars($ifacename3);?></option> <?php endforeach; ?> - </select><br> - <span class="vexpl"><?php echo gettext("Please select the amount of time you would like " . - "hosts to be blocked for."); ?><br> - <?php echo gettext("Hint: in most cases, 1 hour is a good choice."); ?></span></td> + </select> + <?php echo gettext("Please select the amount of time you would like hosts to be blocked for."); ?><br/><br/> + <?php printf(gettext("%sHint:%s in most cases, 1 hour is a good choice."), '<span class="red"><strong>', '</strong></span>'); ?></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Keep snort settings " . @@ -266,8 +293,7 @@ if ($input_errors) <td width="78%" class="vtable"><input name="forcekeepsettings" id="forcekeepsettings" type="checkbox" value="yes" <?php if ($config['installedpackages']['snortglobal']['forcekeepsettings']=="on") echo "checked"; ?> - ><br> - <?php echo gettext("Settings will not be removed during deinstall."); ?></td> + > <?php echo gettext("Settings will not be removed during deinstall."); ?></td> </tr> <tr> <td width="22%" valign="top"> @@ -279,10 +305,11 @@ if ($input_errors) <td width="22%" valign="top"> </td> <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?><br> </strong></span> <?php echo gettext("Changing any settings on this page will affect all " . - "interfaces. Please, double check if your oink code is correct and " . - "the type of snort.org account you hold."); ?></span></td> + "interfaces. Double check that your oink code is correct, and verify the " . + "type of Snort.org account you hold."); ?></span></td> </tr> </table> +</div><br/> </td></tr> </table> </form> diff --git a/config/snort/snort_interfaces_suppress.php b/config/snort/snort_interfaces_suppress.php index 93d3f2dc..8095ff37 100644 --- a/config/snort/snort_interfaces_suppress.php +++ b/config/snort/snort_interfaces_suppress.php @@ -79,12 +79,13 @@ if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array); ?> </td> </tr> -<tr><td class="tabcont"> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td><div id="mainarea"> +<table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="30%" class="listhdrr"><?php echo gettext("File Name"); ?></td> <td width="60%" class="listhdr"><?php echo gettext("Description"); ?></td> @@ -129,15 +130,16 @@ if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} width="17" height="17" border="0" title="<?php echo gettext("add a new list"); ?>"></a></td> </tr> </table> + </div> </td> </tr> </table> </td></tr> <tr> - <td colspan="3" width="100%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> + <td colspan="3" width="100%"><br/><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <p><span class="vexpl"><?php echo gettext("Here you can create event filtering and " . - "suppression for your snort package rules."); ?><br> - <?php echo gettext("Please note that you must restart a running rule so that changes can " . + "suppression for your snort package rules."); ?><br/><br/> + <?php echo gettext("Please note that you must restart a running Interface so that changes can " . "take effect."); ?></span></p></td> </tr> </table> diff --git a/config/snort/snort_interfaces_suppress_edit.php b/config/snort/snort_interfaces_suppress_edit.php index 782b9784..5e12f656 100644 --- a/config/snort/snort_interfaces_suppress_edit.php +++ b/config/snort/snort_interfaces_suppress_edit.php @@ -58,7 +58,7 @@ function is_validwhitelistname($name) { if (!is_string($name)) return false; - if (!preg_match("/[^a-zA-Z0-9\.\/]/", $name)) + if (!preg_match("/[^a-zA-Z0-9\_\.\/]/", $name)) return true; return false; @@ -88,7 +88,7 @@ if ($_POST['submit']) { $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; if (is_validwhitelistname($_POST['name']) == false) - $input_errors[] = "Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."; + $input_errors[] = "Whitelist file name may only consist of the characters \"a-z, A-Z, 0-9 and _\". Note: No Spaces or dashes. Press Cancel to reset."; /* check for name conflicts */ foreach ($a_suppress as $s_list) { @@ -141,8 +141,22 @@ if ($savemsg) ?> <form action="/snort/snort_interfaces_suppress_edit.php" name="iform" id="iform" method="post"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td class="tabcont"> -<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=/snort/snort_sync.xml"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr><td><div id="mainarea"> +<table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" class="listtopic">Add the name and description of the file.</td> </tr> @@ -151,8 +165,8 @@ if ($savemsg) <td width="78%" class="vtable"><input name="name" type="text" id="name" class="formfld unkown" size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> <span class="vexpl"> <?php echo gettext("The list name may only consist of the " . - "characters a-z, A-Z and 0-9."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> - <?php echo gettext("No Spaces."); ?> </span></td> + "characters \"a-z, A-Z, 0-9 and _\"."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> + <?php echo gettext("No Spaces or dashes."); ?> </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Description"); ?></td> @@ -205,6 +219,7 @@ if ($savemsg) </td> </tr> </table> +</div> </td></tr> </table> </form> diff --git a/config/snort/snort_interfaces_whitelist.php b/config/snort/snort_interfaces_whitelist.php index f90cbe1f..73c9efda 100644 --- a/config/snort/snort_interfaces_whitelist.php +++ b/config/snort/snort_interfaces_whitelist.php @@ -85,13 +85,14 @@ if ($savemsg) print_info_box($savemsg); $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), true, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array); ?> </td> </tr> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td width="20%" class="listhdrr">File Name</td> <td width="40%" class="listhdrr">Values</td> @@ -150,19 +151,25 @@ if ($savemsg) print_info_box($savemsg); </td> </tr> </table> + </div> </td> </tr> </table> <br> -<table width="100%" border="0" cellpadding="0" - cellspacing="0"> +<table width="100%" border="0" cellpadding="1" + cellspacing="1"> + <tr> <td width="100%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <p><span class="vexpl"><?php echo gettext("Here you can create whitelist files for your " . "snort package rules."); ?><br> <?php echo gettext("Please add all the ips or networks you want to protect against snort " . "block decisions."); ?><br> <?php echo gettext("Remember that the default whitelist only includes local networks."); ?><br> - <?php echo gettext("Be careful, it is very easy to get locked out of you system."); ?></span></p></td> + <?php echo gettext("Be careful, it is very easy to get locked out of your system."); ?></span></p></td> + </tr> + <tr> + <td width="100%"><span class="vexpl"><?php echo gettext("Remember you must restart Snort on the interface for changes to take effect!"); ?></span></td> + </tr> </table> </form> <?php include("fend.inc"); ?> diff --git a/config/snort/snort_interfaces_whitelist_edit.php b/config/snort/snort_interfaces_whitelist_edit.php index 378530ba..fc157375 100644 --- a/config/snort/snort_interfaces_whitelist_edit.php +++ b/config/snort/snort_interfaces_whitelist_edit.php @@ -66,7 +66,7 @@ function is_validwhitelistname($name) { if (!is_string($name)) return false; - if (!preg_match("/[^a-zA-Z0-9\.\/]/", $name)) + if (!preg_match("/[^a-zA-Z0-9\_\.\/]/", $name)) return true; return false; @@ -80,6 +80,7 @@ if (isset($id) && $a_whitelist[$id]) { $pconfig['detail'] = $a_whitelist[$id]['detail']; $pconfig['address'] = $a_whitelist[$id]['address']; $pconfig['descr'] = html_entity_decode($a_whitelist[$id]['descr']); + $pconfig['localnets'] = $a_whitelist[$id]['localnets']; $pconfig['wanips'] = $a_whitelist[$id]['wanips']; $pconfig['wangateips'] = $a_whitelist[$id]['wangateips']; $pconfig['wandnsips'] = $a_whitelist[$id]['wandnsips']; @@ -102,7 +103,7 @@ if ($_POST['submit']) { $input_errors[] = gettext("Whitelist file names may not be named defaultwhitelist."); if (is_validwhitelistname($_POST['name']) == false) - $input_errors[] = gettext("Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."); + $input_errors[] = gettext("Whitelist file name may only consist of the characters \"a-z, A-Z, 0-9 and _\". Note: No Spaces or dashes. Press Cancel to reset."); /* check for name conflicts */ foreach ($a_whitelist as $w_list) { @@ -124,6 +125,7 @@ if ($_POST['submit']) { /* post user input */ $w_list['name'] = $_POST['name']; $w_list['uuid'] = $whitelist_uuid; + $w_list['localnets'] = $_POST['localnets']? 'yes' : 'no'; $w_list['wanips'] = $_POST['wanips']? 'yes' : 'no'; $w_list['wangateips'] = $_POST['wangateips']? 'yes' : 'no'; $w_list['wandnsips'] = $_POST['wandnsips']? 'yes' : 'no'; @@ -168,8 +170,23 @@ if ($savemsg) </script> <form action="snort_interfaces_whitelist_edit.php" method="post" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td class="tabcont"> -<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), true, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); +?> + </td> +</tr> +<tr><td><div id="mainarea"> +<table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add the name and " . "description of the file."); ?></td> @@ -179,8 +196,8 @@ if ($savemsg) <td class="vtable"><input name="name" type="text" id="name" size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> <span class="vexpl"> <?php echo gettext("The list name may only consist of the " . - "characters a-z, A-Z and 0-9."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> - <?php echo gettext("No Spaces."); ?> </span></td> + "characters \"a-z, A-Z, 0-9 and _\"."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> + <?php echo gettext("No Spaces or dashes."); ?> </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Description"); ?></td> @@ -190,24 +207,33 @@ if ($savemsg) "reference (not parsed)."); ?> </span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add auto generated ips."); ?></td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add auto-generated IP Addresses."); ?></td> + </tr> + + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Local Networks"); ?></td> + <td width="78%" class="vtable"><input name="localnets" type="checkbox" + id="localnets" size="40" value="yes" + <?php if($pconfig['localnets'] == 'yes'){ echo "checked";} if($pconfig['localnets'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add firewall Local Networks to the list (excluding WAN)."); ?> </span></td> </tr> + <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("WAN IPs"); ?></td> <td width="78%" class="vtable"><input name="wanips" type="checkbox" id="wanips" size="40" value="yes" <?php if($pconfig['wanips'] == 'yes'){ echo "checked";} if($pconfig['wanips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> <?php echo gettext("Add WAN IPs to the list."); ?> </span></td> + <span class="vexpl"> <?php echo gettext("Add WAN interface IPs to the list."); ?> </span></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Wan Gateways"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("WAN Gateways"); ?></td> <td width="78%" class="vtable"><input name="wangateips" type="checkbox" id="wangateips" size="40" value="yes" <?php if($pconfig['wangateips'] == 'yes'){ echo "checked";} if($pconfig['wangateips'] == ''){ echo "checked";} ?> /> <span class="vexpl"> <?php echo gettext("Add WAN Gateways to the list."); ?> </span></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Wan DNS servers"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("WAN DNS servers"); ?></td> <td width="78%" class="vtable"><input name="wandnsips" type="checkbox" id="wandnsips" size="40" value="yes" <?php if($pconfig['wandnsips'] == 'yes'){ echo "checked";} if($pconfig['wandnsips'] == ''){ echo "checked";} ?> /> @@ -228,11 +254,11 @@ if ($savemsg) <span class="vexpl"> <?php echo gettext("Add VPN Addresses to the list."); ?> </span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add your own custom ips."); ?></td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add custom IP Addresses from configured Aliases."); ?></td> </tr> <tr> <td width="22%" valign="top" class="vncellreq"> - <div id="addressnetworkport"><?php echo gettext("Alias of IP's"); ?></div> + <div id="addressnetworkport"><?php echo gettext("Alias Name:"); ?></div> </td> <td width="78%" class="vtable"> <input autocomplete="off" name="address" type="text" class="formfldalias" id="address" size="30" value="<?=htmlspecialchars($pconfig['address']);?>" /> @@ -247,6 +273,7 @@ if ($savemsg) </td> </tr> </table> +</div> </td></tr> </table> </form> diff --git a/config/snort/snort_list_view.php b/config/snort/snort_list_view.php new file mode 100644 index 00000000..b7de064b --- /dev/null +++ b/config/snort/snort_list_view.php @@ -0,0 +1,103 @@ +<?php +/* + * snort_list_view.php + * + * Copyright (C) 2004, 2005 Scott Ullrich + * Copyright (C) 2011 Ermal Luci + * All rights reserved. + * + * Adapted for FreeNAS by Volker Theile (votdev@gmx.de) + * Copyright (C) 2006-2009 Volker Theile + * + * Adapted for Pfsense Snort package by Robert Zelaya + * Copyright (C) 2008-2009 Robert Zelaya + * + * 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("guiconfig.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +global $g, $config; + +$contents = ''; + +$id = $_GET['id']; +$wlist = $_GET['wlist']; +$type = $_GET['type']; + +if (isset($id) && isset($wlist)) { + $a_rule = $config['installedpackages']['snortglobal']['rule'][$id]; + if ($type == "whitelist") { + $list = snort_build_list($a_rule, $wlist); + $contents = implode("\n", $list); + } + elseif ($type == "suppress") { + $list = snort_find_list($wlist, $type); + $contents = str_replace("\r", "", base64_decode($list['suppresspassthru'])); + } + else + $contents = gettext("\n\nERROR -- Requested List Type entity is not valid!"); +} +else + $contents = gettext("\n\nERROR -- Supplied interface or List entity is not valid!"); + +$pgtitle = array(gettext("Snort"), gettext(ucfirst($type) . " Viewer")); +?> + +<?php include("head.inc");?> + +<body link="#000000" vlink="#000000" alink="#000000"> +<?php if ($savemsg) print_info_box($savemsg); ?> +<?php // include("fbegin.inc");?> + +<form action="snort_whitelist_view.php" method="post"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td class="tabcont"> + <table width="100%" cellpadding="0" cellspacing="6" bgcolor="#eeeeee"> + <tr> + <td class="pgtitle" colspan="2">Snort: <?php echo gettext(ucfirst($type) . " Viewer"); ?></td> + </tr> + <tr> + <td align="left" width="20%"> + <input type="button" class="formbtn" value="Return" onclick="window.close()"> + </td> + <td align="right"> + <b><?php echo gettext(ucfirst($type) . ": ") . '</b> ' . $_GET['wlist']; ?> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="label"> + <div style="background: #eeeeee; width:100%; height:100%;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> + <textarea style="width:100%; height:100%;" readonly wrap="off" rows="25" cols="80" name="code2"><?=$contents;?></textarea> + </div> + </td> + </tr> + </table> + </td> +</tr> +</table> +</form> +<?php // include("fend.inc");?> +</body> +</html> diff --git a/config/snort/snort_log_view.php b/config/snort/snort_log_view.php new file mode 100644 index 00000000..4fc8d990 --- /dev/null +++ b/config/snort/snort_log_view.php @@ -0,0 +1,89 @@ +<?php +/* + * snort_log_view.php + * + * Copyright (C) 2004, 2005 Scott Ullrich + * Copyright (C) 2011 Ermal Luci + * All rights reserved. + * + * Adapted for FreeNAS by Volker Theile (votdev@gmx.de) + * Copyright (C) 2006-2009 Volker Theile + * + * Adapted for Pfsense Snort package by Robert Zelaya + * Copyright (C) 2008-2009 Robert Zelaya + * + * 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("guiconfig.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +$contents = ''; + +// Read the contents of the argument passed to us. +// Is it a fully qualified path and file? +if (file_exists($_GET['logfile'])) + $contents = file_get_contents($_GET['logfile']); +// It is not something we can display, so print an error. +else + $contents = gettext("\n\nERROR -- File: {$_GET['logfile']} not found!"); + +$pgtitle = array(gettext("Snort"), gettext("Log File Viewer")); +?> + +<?php include("head.inc");?> + +<body link="#000000" vlink="#000000" alink="#000000"> +<?php if ($savemsg) print_info_box($savemsg); ?> +<?php // include("fbegin.inc");?> + +<form action="snort_log_view.php" method="post"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td class="tabcont"> + <table width="100%" cellpadding="0" cellspacing="6" bgcolor="#eeeeee"> + <tr> + <td class="pgtitle" colspan="2">Snort: Log File Viewer</td> + </tr> + <tr> + <td align="left" width="20%"> + <input type="button" class="formbtn" value="Return" onclick="window.close()"> + </td> + <td align="right"> + <b><?php echo gettext("Log File: ") . '</b> ' . $_GET['logfile']; ?> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="label"> + <div style="background: #eeeeee; width:100%; height:100%;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> + <textarea style="width:100%; height:100%;" readonly wrap="off" rows="33" cols="80" name="code2"><?=$contents;?></textarea> + </div> + </td> + </tr> + </table> + </td> +</tr> +</table> +</form> +<?php // include("fend.inc");?> +</body> +</html> diff --git a/config/snort/snort_preprocessors.php b/config/snort/snort_preprocessors.php index 7d0348e9..b813e8bf 100755 --- a/config/snort/snort_preprocessors.php +++ b/config/snort/snort_preprocessors.php @@ -34,7 +34,13 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g; +global $g, $rebuild_rules; +$snortlogdir = SNORTLOGDIR; + +if (!is_array($config['installedpackages']['snortglobal'])) { + $config['installedpackages']['snortglobal'] = array(); +} +$vrt_enabled = $config['installedpackages']['snortglobal']['snortdownload']; if (!is_array($config['installedpackages']['snortglobal']['rule'])) { $config['installedpackages']['snortglobal']['rule'] = array(); @@ -53,20 +59,41 @@ $pconfig = array(); if (isset($id) && $a_nat[$id]) { $pconfig = $a_nat[$id]; - /* new options */ + /* Get current values from config for page form fields */ $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; $pconfig['server_flow_depth'] = $a_nat[$id]['server_flow_depth']; $pconfig['http_server_profile'] = $a_nat[$id]['http_server_profile']; $pconfig['client_flow_depth'] = $a_nat[$id]['client_flow_depth']; + $pconfig['stream5_reassembly'] = $a_nat[$id]['stream5_reassembly']; + $pconfig['stream5_require_3whs'] = $a_nat[$id]['stream5_require_3whs']; + $pconfig['stream5_track_tcp'] = $a_nat[$id]['stream5_track_tcp']; + $pconfig['stream5_track_udp'] = $a_nat[$id]['stream5_track_udp']; + $pconfig['stream5_track_icmp'] = $a_nat[$id]['stream5_track_icmp']; $pconfig['max_queued_bytes'] = $a_nat[$id]['max_queued_bytes']; $pconfig['max_queued_segs'] = $a_nat[$id]['max_queued_segs']; + $pconfig['stream5_overlap_limit'] = $a_nat[$id]['stream5_overlap_limit']; + $pconfig['stream5_policy'] = $a_nat[$id]['stream5_policy']; $pconfig['stream5_mem_cap'] = $a_nat[$id]['stream5_mem_cap']; + $pconfig['stream5_tcp_timeout'] = $a_nat[$id]['stream5_tcp_timeout']; + $pconfig['stream5_udp_timeout'] = $a_nat[$id]['stream5_udp_timeout']; + $pconfig['stream5_icmp_timeout'] = $a_nat[$id]['stream5_icmp_timeout']; + $pconfig['stream5_no_reassemble_async'] = $a_nat[$id]['stream5_no_reassemble_async']; + $pconfig['stream5_dont_store_lg_pkts'] = $a_nat[$id]['stream5_dont_store_lg_pkts']; $pconfig['http_inspect'] = $a_nat[$id]['http_inspect']; + $pconfig['http_inspect_memcap'] = $a_nat[$id]['http_inspect_memcap']; + $pconfig['http_inspect_enable_xff'] = $a_nat[$id]['http_inspect_enable_xff']; + $pconfig['http_inspect_log_uri'] = $a_nat[$id]['http_inspect_log_uri']; + $pconfig['http_inspect_log_hostname'] = $a_nat[$id]['http_inspect_log_hostname']; $pconfig['noalert_http_inspect'] = $a_nat[$id]['noalert_http_inspect']; $pconfig['other_preprocs'] = $a_nat[$id]['other_preprocs']; $pconfig['ftp_preprocessor'] = $a_nat[$id]['ftp_preprocessor']; $pconfig['smtp_preprocessor'] = $a_nat[$id]['smtp_preprocessor']; $pconfig['sf_portscan'] = $a_nat[$id]['sf_portscan']; + $pconfig['pscan_protocol'] = $a_nat[$id]['pscan_protocol']; + $pconfig['pscan_type'] = $a_nat[$id]['pscan_type']; + $pconfig['pscan_sense_level'] = $a_nat[$id]['pscan_sense_level']; + $pconfig['pscan_memcap'] = $a_nat[$id]['pscan_memcap']; + $pconfig['pscan_ignore_scanners'] = $a_nat[$id]['pscan_ignore_scanners']; $pconfig['dce_rpc_2'] = $a_nat[$id]['dce_rpc_2']; $pconfig['dns_preprocessor'] = $a_nat[$id]['dns_preprocessor']; $pconfig['sensitive_data'] = $a_nat[$id]['sensitive_data']; @@ -77,25 +104,190 @@ if (isset($id) && $a_nat[$id]) { $pconfig['dnp3_preproc'] = $a_nat[$id]['dnp3_preproc']; $pconfig['modbus_preproc'] = $a_nat[$id]['modbus_preproc']; $pconfig['gtp_preproc'] = $a_nat[$id]['gtp_preproc']; + $pconfig['preproc_auto_rule_disable'] = $a_nat[$id]['preproc_auto_rule_disable']; + $pconfig['protect_preproc_rules'] = $a_nat[$id]['protect_preproc_rules']; + $pconfig['frag3_detection'] = $a_nat[$id]['frag3_detection']; + $pconfig['frag3_overlap_limit'] = $a_nat[$id]['frag3_overlap_limit']; + $pconfig['frag3_min_frag_len'] = $a_nat[$id]['frag3_min_frag_len']; + $pconfig['frag3_policy'] = $a_nat[$id]['frag3_policy']; + $pconfig['frag3_max_frags'] = $a_nat[$id]['frag3_max_frags']; + $pconfig['frag3_memcap'] = $a_nat[$id]['frag3_memcap']; + $pconfig['frag3_timeout'] = $a_nat[$id]['frag3_timeout']; + + /* If not using the Snort VRT rules, then disable */ + /* the Sensitive Data (sdf) preprocessor. */ + if ($vrt_enabled == "off") + $pconfig['sensitive_data'] = "off"; + + /************************************************************/ + /* To keep new users from shooting themselves in the foot */ + /* enable the most common required preprocessors by default */ + /* and set reasonable values for any options. */ + /************************************************************/ + if (empty($pconfig['ftp_preprocessor'])) + $pconfig['ftp_preprocessor'] = 'on'; + if (empty($pconfig['smtp_preprocessor'])) + $pconfig['smtp_preprocessor'] = 'on'; + if (empty($pconfig['dce_rpc_2'])) + $pconfig['dce_rpc_2'] = 'on'; + if (empty($pconfig['dns_preprocessor'])) + $pconfig['dns_preprocessor'] = 'on'; + if (empty($pconfig['ssl_preproc'])) + $pconfig['ssl_preproc'] = 'on'; + if (empty($pconfig['pop_preproc'])) + $pconfig['pop_preproc'] = 'on'; + if (empty($pconfig['imap_preproc'])) + $pconfig['imap_preproc'] = 'on'; + if (empty($pconfig['sip_preproc'])) + $pconfig['sip_preproc'] = 'on'; + if (empty($pconfig['other_preprocs'])) + $pconfig['other_preprocs'] = 'on'; + if (empty($pconfig['http_inspect_memcap'])) + $pconfig['http_inspect_memcap'] = "150994944"; + if (empty($pconfig['frag3_overlap_limit'])) + $pconfig['frag3_overlap_limit'] = '0'; + if (empty($pconfig['frag3_min_frag_len'])) + $pconfig['frag3_min_frag_len'] = '0'; + if (empty($pconfig['frag3_max_frags'])) + $pconfig['frag3_max_frags'] = '8192'; + if (empty($pconfig['frag3_policy'])) + $pconfig['frag3_policy'] = 'bsd'; + if (empty($pconfig['frag3_memcap'])) + $pconfig['frag3_memcap'] = '4194304'; + if (empty($pconfig['frag3_timeout'])) + $pconfig['frag3_timeout'] = '60'; + if (empty($pconfig['frag3_detection'])) + $pconfig['frag3_detection'] = 'on'; + if (empty($pconfig['stream5_reassembly'])) + $pconfig['stream5_reassembly'] = 'on'; + if (empty($pconfig['stream5_track_tcp'])) + $pconfig['stream5_track_tcp'] = 'on'; + if (empty($pconfig['stream5_track_udp'])) + $pconfig['stream5_track_udp'] = 'on'; + if (empty($pconfig['stream5_track_icmp'])) + $pconfig['stream5_track_icmp'] = 'off'; + if (empty($pconfig['stream5_require_3whs'])) + $pconfig['stream5_require_3whs'] = 'off'; + if (empty($pconfig['stream5_overlap_limit'])) + $pconfig['stream5_overlap_limit'] = '0'; + if (empty($pconfig['stream5_tcp_timeout'])) + $pconfig['stream5_tcp_timeout'] = '30'; + if (empty($pconfig['stream5_udp_timeout'])) + $pconfig['stream5_udp_timeout'] = '30'; + if (empty($pconfig['stream5_icmp_timeout'])) + $pconfig['stream5_icmp_timeout'] = '30'; + if (empty($pconfig['stream5_no_reassemble_async'])) + $pconfig['stream5_no_reassemble_async'] = 'off'; + if (empty($pconfig['stream5_dont_store_lg_pkts'])) + $pconfig['stream5_dont_store_lg_pkts'] = 'off'; + if (empty($pconfig['stream5_policy'])) + $pconfig['stream5_policy'] = 'bsd'; + if (empty($pconfig['pscan_protocol'])) + $pconfig['pscan_protocol'] = 'all'; + if (empty($pconfig['pscan_type'])) + $pconfig['pscan_type'] = 'all'; + if (empty($pconfig['pscan_memcap'])) + $pconfig['pscan_memcap'] = '10000000'; + if (empty($pconfig['pscan_sense_level'])) + $pconfig['pscan_sense_level'] = 'medium'; } -if ($_POST) { +/* Define the "disabled_preproc_rules.log" file for this interface */ +$iface = snort_get_friendly_interface($pconfig['interface']); +$disabled_rules_log = "{$snortlogdir}/{$iface}_disabled_preproc_rules.log"; + +if ($_POST['ResetAll']) { + + /* Reset all the preprocessor settings to defaults */ + $pconfig['perform_stat'] = "off"; + $pconfig['server_flow_depth'] = "300"; + $pconfig['http_server_profile'] = "all"; + $pconfig['client_flow_depth'] = "300"; + $pconfig['stream5_reassembly'] = "on"; + $pconfig['stream5_require_3whs'] = "off"; + $pconfig['stream5_track_tcp'] = "on"; + $pconfig['stream5_track_udp'] = "on"; + $pconfig['stream5_track_icmp'] = "off"; + $pconfig['max_queued_bytes'] = "1048576"; + $pconfig['max_queued_segs'] = "2621"; + $pconfig['stream5_overlap_limit'] = "0"; + $pconfig['stream5_policy'] = "bsd"; + $pconfig['stream5_mem_cap'] = "8388608"; + $pconfig['stream5_tcp_timeout'] = "30"; + $pconfig['stream5_udp_timeout'] = "30"; + $pconfig['stream5_icmp_timeout'] = "30"; + $pconfig['stream5_no_reassemble_async'] = "off"; + $pconfig['stream5_dont_store_lg_pkts'] = "off"; + $pconfig['http_inspect'] = "on"; + $pconfig['http_inspect_enable_xff'] = "off"; + $pconfig['http_inspect_log_uri'] = "off"; + $pconfig['http_inspect_log_hostname'] = "off"; + $pconfig['noalert_http_inspect'] = "on"; + $pconfig['http_inspect_memcap'] = "150994944"; + $pconfig['other_preprocs'] = "on"; + $pconfig['ftp_preprocessor'] = "on"; + $pconfig['smtp_preprocessor'] = "on"; + $pconfig['sf_portscan'] = "off"; + $pconfig['pscan_protocol'] = "all"; + $pconfig['pscan_type'] = "all"; + $pconfig['pscan_sense_level'] = "medium"; + $pconfig['pscan_ignore_scanners'] = ""; + $pconfig['pscan_memcap'] = '10000000'; + $pconfig['dce_rpc_2'] = "on"; + $pconfig['dns_preprocessor'] = "on"; + $pconfig['sensitive_data'] = "off"; + $pconfig['ssl_preproc'] = "on"; + $pconfig['pop_preproc'] = "on"; + $pconfig['imap_preproc'] = "on"; + $pconfig['sip_preproc'] = "on"; + $pconfig['dnp3_preproc'] = "off"; + $pconfig['modbus_preproc'] = "off"; + $pconfig['gtp_preproc'] = "off"; + $pconfig['preproc_auto_rule_disable'] = "off"; + $pconfig['protect_preproc_rules'] = "off"; + $pconfig['frag3_detection'] = "on"; + $pconfig['frag3_overlap_limit'] = "0"; + $pconfig['frag3_min_frag_len'] = "0"; + $pconfig['frag3_policy'] = "bsd"; + $pconfig['frag3_max_frags'] = "8192"; + $pconfig['frag3_memcap'] = "4194304"; + $pconfig['frag3_timeout'] = "60"; + + /* Log a message at the top of the page to inform the user */ + $savemsg = "All preprocessor settings have been reset to the defaults."; +} +elseif ($_POST['Submit']) { $natent = array(); $natent = $pconfig; if ($_POST['pscan_ignore_scanners'] && !is_alias($_POST['pscan_ignore_scanners'])) - $input_errors[] = "Only aliases are allowed"; + $input_errors[] = "Only aliases are allowed for the Portscan IGNORE_SCANNERS option."; /* if no errors write to conf */ if (!$input_errors) { /* post new options */ - if ($_POST['server_flow_depth'] != "") { $natent['server_flow_depth'] = $_POST['server_flow_depth']; }else{ $natent['server_flow_depth'] = ""; } + if ($_POST['server_flow_depth'] != "") { $natent['server_flow_depth'] = $_POST['server_flow_depth']; }else{ $natent['server_flow_depth'] = "300"; } if ($_POST['http_server_profile'] != "") { $natent['http_server_profile'] = $_POST['http_server_profile']; }else{ $natent['http_server_profile'] = "all"; } - if ($_POST['client_flow_depth'] != "") { $natent['client_flow_depth'] = $_POST['client_flow_depth']; }else{ $natent['client_flow_depth'] = ""; } - if ($_POST['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $_POST['max_queued_bytes']; }else{ $natent['max_queued_bytes'] = ""; } - if ($_POST['max_queued_segs'] != "") { $natent['max_queued_segs'] = $_POST['max_queued_segs']; }else{ $natent['max_queued_segs'] = ""; } - if ($_POST['stream5_mem_cap'] != "") { $natent['stream5_mem_cap'] = $_POST['stream5_mem_cap']; }else{ $natent['stream5_mem_cap'] = ""; } + if ($_POST['client_flow_depth'] != "") { $natent['client_flow_depth'] = $_POST['client_flow_depth']; }else{ $natent['client_flow_depth'] = "300"; } + if ($_POST['http_inspect_memcap'] != "") { $natent['http_inspect_memcap'] = $_POST['http_inspect_memcap']; }else{ $natent['http_inspect_memcap'] = "150994944"; } + if ($_POST['stream5_overlap_limit'] != "") { $natent['stream5_overlap_limit'] = $_POST['stream5_overlap_limit']; }else{ $natent['stream5_overlap_limit'] = "0"; } + if ($_POST['stream5_policy'] != "") { $natent['stream5_policy'] = $_POST['stream5_policy']; }else{ $natent['stream5_policy'] = "bsd"; } + if ($_POST['stream5_mem_cap'] != "") { $natent['stream5_mem_cap'] = $_POST['stream5_mem_cap']; }else{ $natent['stream5_mem_cap'] = "8388608"; } + if ($_POST['stream5_tcp_timeout'] != "") { $natent['stream5_tcp_timeout'] = $_POST['stream5_tcp_timeout']; }else{ $natent['stream5_tcp_timeout'] = "30"; } + if ($_POST['stream5_udp_timeout'] != "") { $natent['stream5_udp_timeout'] = $_POST['stream5_udp_timeout']; }else{ $natent['stream5_udp_timeout'] = "30"; } + if ($_POST['stream5_icmp_timeout'] != "") { $natent['stream5_icmp_timeout'] = $_POST['stream5_icmp_timeout']; }else{ $natent['stream5_icmp_timeout'] = "30"; } + if ($_POST['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $_POST['max_queued_bytes']; }else{ $natent['max_queued_bytes'] = "1048576"; } + if ($_POST['max_queued_segs'] != "") { $natent['max_queued_segs'] = $_POST['max_queued_segs']; }else{ $natent['max_queued_segs'] = "2621"; } + if ($_POST['pscan_protocol'] != "") { $natent['pscan_protocol'] = $_POST['pscan_protocol']; }else{ $natent['pscan_protocol'] = "all"; } + if ($_POST['pscan_type'] != "") { $natent['pscan_type'] = $_POST['pscan_type']; }else{ $natent['pscan_type'] = "all"; } + if ($_POST['pscan_memcap'] != "") { $natent['pscan_memcap'] = $_POST['pscan_memcap']; }else{ $natent['pscan_memcap'] = "10000000"; } if ($_POST['pscan_sense_level'] != "") { $natent['pscan_sense_level'] = $_POST['pscan_sense_level']; }else{ $natent['pscan_sense_level'] = "medium"; } + if ($_POST['frag3_overlap_limit'] != "") { $natent['frag3_overlap_limit'] = $_POST['frag3_overlap_limit']; }else{ $natent['frag3_overlap_limit'] = "0"; } + if ($_POST['frag3_min_frag_len'] != "") { $natent['frag3_min_frag_len'] = $_POST['frag3_min_frag_len']; }else{ $natent['frag3_min_frag_len'] = "0"; } + if ($_POST['frag3_policy'] != "") { $natent['frag3_policy'] = $_POST['frag3_policy']; }else{ $natent['frag3_policy'] = "bsd"; } + if ($_POST['frag3_max_frags'] != "") { $natent['frag3_max_frags'] = $_POST['frag3_max_frags']; }else{ $natent['frag3_max_frags'] = "8192"; } + if ($_POST['frag3_memcap'] != "") { $natent['frag3_memcap'] = $_POST['frag3_memcap']; }else{ $natent['frag3_memcap'] = "4194304"; } + if ($_POST['frag3_timeout'] != "") { $natent['frag3_timeout'] = $_POST['frag3_timeout']; }else{ $natent['frag3_timeout'] = "60"; } if ($_POST['pscan_ignore_scanners']) $natent['pscan_ignore_scanners'] = $_POST['pscan_ignore_scanners']; @@ -104,6 +296,9 @@ if ($_POST) { $natent['perform_stat'] = $_POST['perform_stat'] ? 'on' : 'off'; $natent['http_inspect'] = $_POST['http_inspect'] ? 'on' : 'off'; + $natent['http_inspect_enable_xff'] = $_POST['http_inspect_enable_xff'] ? 'on' : 'off'; + $natent['http_inspect_log_uri'] = $_POST['http_inspect_log_uri'] ? 'on' : 'off'; + $natent['http_inspect_log_hostname'] = $_POST['http_inspect_log_hostname'] ? 'on' : 'off'; $natent['noalert_http_inspect'] = $_POST['noalert_http_inspect'] ? 'on' : 'off'; $natent['other_preprocs'] = $_POST['other_preprocs'] ? 'on' : 'off'; $natent['ftp_preprocessor'] = $_POST['ftp_preprocessor'] ? 'on' : 'off'; @@ -120,6 +315,20 @@ if ($_POST) { $natent['sip_preproc'] = $_POST['sip_preproc'] ? 'on' : 'off'; $natent['modbus_preproc'] = $_POST['modbus_preproc'] ? 'on' : 'off'; $natent['gtp_preproc'] = $_POST['gtp_preproc'] ? 'on' : 'off'; + $natent['preproc_auto_rule_disable'] = $_POST['preproc_auto_rule_disable'] ? 'on' : 'off'; + $natent['protect_preproc_rules'] = $_POST['protect_preproc_rules'] ? 'on' : 'off'; + $natent['frag3_detection'] = $_POST['frag3_detection'] ? 'on' : 'off'; + $natent['stream5_reassembly'] = $_POST['stream5_reassembly'] ? 'on' : 'off'; + $natent['stream5_track_tcp'] = $_POST['stream5_track_tcp'] ? 'on' : 'off'; + $natent['stream5_track_udp'] = $_POST['stream5_track_udp'] ? 'on' : 'off'; + $natent['stream5_track_icmp'] = $_POST['stream5_track_icmp'] ? 'on' : 'off'; + $natent['stream5_require_3whs'] = $_POST['stream5_require_3whs'] ? 'on' : 'off'; + $natent['stream5_no_reassemble_async'] = $_POST['stream5_no_reassemble_async'] ? 'on' : 'off'; + $natent['stream5_dont_store_lg_pkts'] = $_POST['stream5_dont_store_lg_pkts'] ? 'on' : 'off'; + + /* If 'preproc_auto_rule_disable' is off, then clear log file */ + if ($natent['preproc_auto_rule_disable'] == 'off') + @unlink("{$disabled_rules_log}"); if (isset($id) && $a_nat[$id]) $a_nat[$id] = $natent; @@ -132,8 +341,15 @@ if ($_POST) { write_config(); - $if_real = snort_get_real_interface($pconfig['interface']); - sync_snort_package_config(); + /* Set flag to rebuild rules for this interface */ + $rebuild_rules = "on"; + + /*************************************************/ + /* Update the snort conf file and rebuild the */ + /* rules for this interface. */ + /*************************************************/ + snort_generate_conf($natent); + $rebuild_rules = "off"; /* after click go to this page */ header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); @@ -147,10 +363,10 @@ if ($_POST) { } $if_friendly = snort_get_friendly_interface($pconfig['interface']); -$pgtitle = "Snort: Interface {$if_real} Preprocessors and Flow"; +$pgtitle = "Snort: Interface {$if_friendly}: Preprocessors and Flow"; include_once("head.inc"); ?> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC" onload="enable_change_all()"> <?php include("fbegin.inc"); ?> <?php if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} @@ -172,40 +388,97 @@ include_once("head.inc"); </script> <script type="text/javascript" src="/javascript/suggestions.js"> </script> + <form action="snort_preprocessors.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td>'; + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface "); $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), true, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), true, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> -<tr><td class="tabcont"> -<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr><td><div id="mainarea"> +<table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td colspan="2" align="center" valign="middle"> - <span class="red"><strong><?php echo gettext("NOTE"); ?></strong></span><br> + <td colspan="2" align="left" valign="middle"> <?php echo gettext("Rules may be dependent on preprocessors! Disabling preprocessors may result in "); ?> - <?php echo gettext("dependent rules being automatically disabled."); ?><br> - <?php echo gettext("Defaults will be used when there is no user input."); ?><br></td> + <?php echo gettext("Snort start failures unless dependent rules are also disabled."); ?> + <?php echo gettext("The Auto-Rule Disable feature can be used, but note the warning about compromising protection. " . + "Defaults will be used where no user input is provided."); ?></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Performance Statistics"); ?></td> + + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Preprocessors Configuration"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> - <td width="78%" class="vtable"><input name="perform_stat" - type="checkbox" value="on" - <?php if ($pconfig['perform_stat']=="on") echo "checked"; ?> - onClick="enable_change(false)"> <?php echo gettext("Collect Performance Statistics for this interface."); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable Performance Stats"); ?></td> + <td width="78%" class="vtable"><input name="perform_stat" type="checkbox" value="on" + <?php if ($pconfig['perform_stat']=="on") echo "checked"; ?>> + <?php echo gettext("Collect Performance Statistics for this interface."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Protect Customized Preprocessor Rules"); ?></td> + <td width="78%" class="vtable"><input name="protect_preproc_rules" type="checkbox" value="on" + <?php if ($pconfig['protect_preproc_rules']=="on") echo "checked "; + if ($vrt_enabled <> 'on') echo "disabled"; ?>> + <?php echo gettext("Check this box if you maintain customized preprocessor text rules files for this interface."); ?> + <table width="100%" border="0" cellpadding="2" cellpadding="2"> + <tr> + <td width="3%"> </td> + <td><?php echo gettext("Enable this only if you use customized preprocessor text rules files and " . + "you do not want them overwritten by automatic Snort VRT rule updates. " . + "This option is disabled when Snort VRT rules download is not enabled on the Global Settings tab."); ?><br/><br/> + <?php echo "<span class=\"red\"><strong>" . gettext("Hint: ") . "</strong></span>" . + gettext("Most users should leave this unchecked."); ?></td> + </tr> + </table> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Auto Rule Disable"); ?></td> + <td width="78%" class="vtable"><input name="preproc_auto_rule_disable" type="checkbox" value="on" + <?php if ($pconfig['preproc_auto_rule_disable']=="on") echo "checked"; ?>> + <?php echo gettext("Auto-disable text rules dependent on disabled preprocessors for this interface. "); + echo gettext("Default is ") . '<strong>' . gettext("Not Checked"); ?></strong>.<br/> + <table width="100%" border="0" cellpadding="2" cellpadding="2"> + <tr> + <td width="3%"> </td> + <td><span class="red"><strong><?php echo gettext("Warning: "); ?></strong></span> + <?php echo gettext("Enabling this option allows Snort to automatically disable any text rules " . + "containing rule options or content modifiers that are dependent upon the preprocessors " . + "you have not enabled. This may facilitate starting Snort without errors related to " . + "disabled preprocessors, but can substantially compromise the level of protection by " . + "automatically disabling detection rules."); ?></td> + </tr> + <?php if (file_exists($disabled_rules_log) && filesize($disabled_rules_log) > 0): ?> + <tr> + <td width="3%"> </td> + <td class="vexpl"><input type="button" class="formbtn" value="View" onclick="wopen('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$disabled_rules_log;?>','FileViewer',800,600)"/> + <?php echo gettext("Click to view the list of currently auto-disabled rules"); ?></td> + </tr> + <?php endif; ?> + </table> + </td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("HTTP Inspect Settings"); ?></td> @@ -213,10 +486,57 @@ include_once("head.inc"); <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> <td width="78%" class="vtable"><input name="http_inspect" - type="checkbox" value="on" - <?php if ($pconfig['http_inspect']=="on") echo "checked"; ?> - onClick="enable_change(false)"> <?php echo gettext("Use HTTP Inspect to " . - "Normalize/Decode and detect HTTP traffic and protocol anomalies."); ?></td> + type="checkbox" value="on" id="http_inspect" onclick="http_inspect_enable_change()" + <?php if ($pconfig['http_inspect']=="on" || empty($pconfig['http_inspect'])) echo "checked"; ?>> + <?php echo gettext("Use HTTP Inspect to " . + "Normalize/Decode and detect HTTP traffic and protocol anomalies. Default is "); ?> + <strong><?php echo gettext("Checked"); ?></strong>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable XFF/True-Client-IP"); ?></td> + <td width="78%" class="vtable"><input name="http_inspect_enable_xff" + type="checkbox" value="on" id="http_inspect_enable_xff" + <?php if ($pconfig['http_inspect_enable_xff']=="on") echo "checked"; ?>> + <?php echo gettext("Log original client IP present in X-Forwarded-For or True-Client-IP " . + "HTTP headers. Default is "); ?> + <strong><?php echo gettext("Not Checked"); ?></strong>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable URI Logging"); ?></td> + <td width="78%" class="vtable"><input name="http_inspect_log_uri" + type="checkbox" value="on" id="http_inspect_log_uri" + <?php if ($pconfig['http_inspect_log_uri']=="on") echo "checked"; ?>> + <?php echo gettext("Parse URI data from the HTTP request and log it with other session data." . + " Default is "); ?> + <strong><?php echo gettext("Not Checked"); ?></strong>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable Hostname Logging"); ?></td> + <td width="78%" class="vtable"><input name="http_inspect_log_hostname" + type="checkbox" value="on" id="http_inspect_log_hostname" + <?php if ($pconfig['http_inspect_log_hostname']=="on") echo "checked"; ?>> + <?php echo gettext("Parse Hostname data from the HTTP request and log it with other session data." . + " Default is "); ?> + <strong><?php echo gettext("Not Checked"); ?></strong>.</td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("HTTP Inspect Memory Cap"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="http_inspect_memcap" type="text" class="formfld" + id="http_inspect_memcap" size="6" + value="<?=htmlspecialchars($pconfig['http_inspect_memcap']);?>"> + <?php echo gettext("Max memory in bytes to use for URI and Hostname logging. Min is ") . + "<strong>" . gettext("2304") . "</strong>" . gettext(" and Max is ") . "<strong>" . + gettext("603979776") . "</strong>" . gettext(" (576 MB)"); ?>.</td> + </tr> + </table> + <?php echo gettext("Maximum amount of memory the preprocessor will use for logging the URI and Hostname data. The default " . + "value is ") . "<strong>" . gettext("150,994,944") . "</strong>" . gettext(" (144 MB)."); ?> + <?php echo gettext(" This option determines the maximum HTTP sessions that will log URI and Hostname data at any given instant. ") . + gettext(" Max Logged Sessions = MEMCAP / 2304"); ?>.<br/> + </td> </tr> <tr> <td valign="top" class="vncell"><?php echo gettext("HTTP server flow depth"); ?></td> @@ -224,16 +544,16 @@ include_once("head.inc"); <table cellpadding="0" cellspacing="0"> <tr> <td><input name="server_flow_depth" type="text" class="formfld" - id="flow_depth" size="6" + id="server_flow_depth" size="6" value="<?=htmlspecialchars($pconfig['server_flow_depth']);?>"> <?php echo gettext("<strong>-1</strong> " . "to <strong>65535</strong> (<strong>-1</strong> disables HTTP " . "inspect, <strong>0</strong> enables all HTTP inspect)"); ?></td> </tr> </table> <?php echo gettext("Amount of HTTP server response payload to inspect. Snort's " . - "performance may increase by adjusting this value."); ?><br> + "performance may increase by adjusting this value."); ?><br/> <?php echo gettext("Setting this value too low may cause false negatives. Values above 0 " . - "are specified in bytes. Recommended setting is maximum (65535). Default value is <strong>300</strong>"); ?><br> + "are specified in bytes. Recommended setting is maximum (65535). Default value is <strong>300</strong>"); ?><br/> </td> </tr> <tr> @@ -241,16 +561,16 @@ include_once("head.inc"); <td width="78%" class="vtable"> <select name="http_server_profile" class="formselect" id="http_server_profile"> <?php - $profile = array('All', 'Apache', 'IIS', 'IIS_4.0', 'IIS_5.0'); + $profile = array('All', 'Apache', 'IIS', 'IIS4_0', 'IIS5_0'); foreach ($profile as $val): ?> <option value="<?=strtolower($val);?>" <?php if (strtolower($val) == $pconfig['http_server_profile']) echo "selected"; ?>> <?=gettext($val);?></option> <?php endforeach; ?> - </select> <?php echo gettext("Choose the profile type of the protected web server."); ?><br> - <?php echo gettext(" The default is <strong>All</strong>. "); ?> - <?php echo gettext("IIS_4.0 and IIS_5.0 are identical to IIS except they alert on the "); ?> - <?php echo gettext("double decoding vulnerability present in those two versions."); ?><br> + </select> <?php echo gettext("Choose the profile type of the protected web server. The default is ") . + "<strong>" . gettext("All") . "</strong>"; ?><br/> + <?php echo gettext("IIS_4.0 and IIS_5.0 are identical to IIS except they alert on the ") . + gettext("double decoding vulnerability present in those versions."); ?><br/> </td> </tr> <tr> @@ -259,7 +579,7 @@ include_once("head.inc"); <table cellpadding="0" cellspacing="0"> <tr> <td><input name="client_flow_depth" type="text" class="formfld" - id="flow_depth" size="6" + id="client_flow_depth" size="6" value="<?=htmlspecialchars($pconfig['client_flow_depth']);?>"> <?php echo gettext("<strong>-1</strong> " . "to <strong>1460</strong> (<strong>-1</strong> disables HTTP " . "inspect, <strong>0</strong> enables all HTTP inspect)"); ?></td> @@ -268,21 +588,175 @@ include_once("head.inc"); <?php echo gettext("Amount of raw HTTP client request payload to inspect. Snort's " . "performance may increase by adjusting this value."); ?><br> <?php echo gettext("Setting this value too low may cause false negatives. Values above 0 " . - "are specified in bytes. Recommended setting is maximum (1460). Default value is <strong>300</strong>"); ?><br> + "are specified in bytes. Recommended setting is maximum (1460). Default value is <strong>300</strong>"); ?><br/> </td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Disable HTTP Alerts"); ?></td> <td width="78%" class="vtable"><input name="noalert_http_inspect" - type="checkbox" value="on" - <?php if ($pconfig['noalert_http_inspect']=="on") echo "checked"; ?> - onClick="enable_change(false)"> <?php echo gettext("Tick to turn off alerts from the HTTP Inspect " . - "preprocessor. This has no effect on HTTP rules in the rule set."); ?></td> + type="checkbox" value="on" id="noalert_http_inspect" + <?php if ($pconfig['noalert_http_inspect']=="on" || empty($pconfig['noalert_http_inspect'])) echo "checked"; ?> + onClick="enable_change(false)"> <?php echo gettext("Turn off alerts from HTTP Inspect " . + "preprocessor. This has no effect on HTTP rules. Default is "); ?> + <strong><?php echo gettext("Checked"); ?></strong>.</td> + </tr> + + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Frag3 Settings"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> + <td width="78%" class="vtable"><input name="frag3_detection" type="checkbox" value="on" onclick="frag3_enable_change()" + <?php if ($pconfig['frag3_detection']=="on") echo "checked "; ?> + onClick="enable_change(false)"> + <?php echo gettext("Use Frag3 Engine to detect IDS evasion attempts via target-based IP packet fragmentation. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="frag3_memcap" type="text" class="formfld" + id="frag3_memcap" size="6" + value="<?=htmlspecialchars($pconfig['frag3_memcap']);?>"> + <?php echo gettext("Memory cap (in bytes) for self preservation."); ?>.</td> + </tr> + </table> + <?php echo gettext("The maximum amount of memory allocated for Frag3 fragment reassembly. Default value is ") . + "<strong>" . gettext("4MB") . "</strong>"; ?>.<br/> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Maximum Fragments"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="frag3_max_frags" type="text" class="formfld" + id="frag3_max_frags" size="6" + value="<?=htmlspecialchars($pconfig['frag3_max_frags']);?>"> + <?php echo gettext("Maximum simultaneous fragments to track."); ?></td> + </tr> + </table> + <?php echo gettext("The maximum number of simultaneous fragments to track. Default value is ") . + "<strong>8192</strong>."; ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Overlap Limit"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="frag3_overlap_limit" type="text" class="formfld" + id="frag3_overlap_limit" size="6" + value="<?=htmlspecialchars($pconfig['frag3_overlap_limit']);?>"> + <?php echo gettext("Minimum is ") . "<strong>0</strong>" . gettext(" (unlimited), values greater than zero set the overlapped fragments per packet limit."); ?></td> + </tr> + </table> + <?php echo gettext("Sets the limit for the number of overlapping fragments allowed per packet. Default value is ") . + "<strong>0</strong>" . gettext(" (unlimited)."); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Minimum Fragment Length"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="frag3_min_frag_len" type="text" class="formfld" + id="frag3_min_frag_len" size="6" + value="<?=htmlspecialchars($pconfig['frag3_min_frag_len']);?>"> + <?php echo gettext("Minimum is ") . "<strong>0</strong>" . gettext(" (check is disabled). Fragments smaller than or equal to this limit are considered malicious."); ?></td> + </tr> + </table> + <?php echo gettext("Defines smallest fragment size (payload size) that should be considered valid. Default value is ") . + "<strong>0</strong>" . gettext(" (check is disabled)."); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Timeout"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="frag3_timeout" type="text" class="formfld" + id="frag3_timeout" size="6" + value="<?=htmlspecialchars($pconfig['frag3_timeout']);?>"> + <?php echo gettext("Timeout period in seconds for fragments in the engine."); ?></td> + </tr> + </table> + <?php echo gettext("Fragments in the engine for longer than this period will be automatically dropped. Default value is ") . + "<strong>" . gettext("60 ") . "</strong>" . gettext("seconds."); ?><br/> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Target Policy"); ?> </td> + <td width="78%" class="vtable"> + <select name="frag3_policy" class="formselect" id="frag3_policy"> + <?php + $profile = array( 'BSD', 'BSD-Right', 'First', 'Last', 'Linux', 'Solaris', 'Windows' ); + foreach ($profile as $val): ?> + <option value="<?=strtolower($val);?>" + <?php if (strtolower($val) == $pconfig['frag3_policy']) echo "selected"; ?>> + <?=gettext($val);?></option> + <?php endforeach; ?> + </select> <?php echo gettext("Choose the IP fragmentation target policy appropriate for the protected hosts. The default is ") . + "<strong>" . gettext("BSD") . "</strong>"; ?>.<br/> + <?php echo gettext("Available OS targets are BSD, BSD-Right, First, Last, Linux, Solaris and Windows."); ?><br/></td> + </td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Stream5 Settings"); ?></td> </tr> <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> + <td width="78%" class="vtable"><input name="stream5_reassembly" type="checkbox" value="on" onclick="stream5_enable_change()" + <?php if ($pconfig['stream5_reassembly']=="on") echo "checked "; ?>"> + <?php echo gettext("Use Stream5 session reassembly for TCP, UDP and/or ICMP traffic. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Protocol Tracking"); ?></td> + <td width="78%" class="vtable"> + <input name="stream5_track_tcp" type="checkbox" value="on" id="stream5_track_tcp" + <?php if ($pconfig['stream5_track_tcp']=="on") echo "checked"; ?>> + <?php echo gettext("Track and reassemble TCP sessions. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?> + <br/> + <input name="stream5_track_udp" type="checkbox" value="on" id="stream5_track_udp" + <?php if ($pconfig['stream5_track_udp']=="on") echo "checked"; ?>> + <?php echo gettext("Track and reassemble UDP sessions. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?> + <br/> + <input name="stream5_track_icmp" type="checkbox" value="on" id="stream5_track_icmp" + <?php if ($pconfig['stream5_track_icmp']=="on") echo "checked"; ?>> + <?php echo gettext("Track and reassemble ICMP sessions. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>."; ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Require 3-Way Handshake"); ?></td> + <td width="78%" class="vtable"><input name="stream5_require_3whs" type="checkbox" value="on" + <?php if ($pconfig['stream5_require_3whs']=="on") echo "checked "; ?>> + <?php echo gettext("Establish sessions only on completion of SYN/SYN-ACK/ACK handshake. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>"; ?>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Do Not Reassemble Async"); ?></td> + <td width="78%" class="vtable"><input name="stream5_no_reassemble_async" type="checkbox" value="on" + <?php if ($pconfig['stream5_no_reassemble_async']=="on") echo "checked "; ?>> + <?php echo gettext("Do not queue packets for reassembly if traffic has not been seen in both directions. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>"; ?>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Do Not Store Large TCP Packets"); ?></td> + <td width="78%" class="vtable"> + <input name="stream5_dont_store_lg_pkts" type="checkbox" value="on" + <?php if ($pconfig['stream5_dont_store_lg_pkts']=="on") echo "checked "; ?>> + <?php echo gettext("Do not queue large packets in reassembly buffer to increase performance. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>"; ?>.<br/> + <?php echo "<span class=\"red\"><strong>" . gettext("Warning: ") . "</strong></span>" . + gettext("Enabing this option could result in missed packets. Recommended setting is not checked."); ?></td> + </tr> + <tr> <td valign="top" class="vncell"><?php echo gettext("Max Queued Bytes"); ?></td> <td class="vtable"> <table cellpadding="0" cellspacing="0"> @@ -292,11 +766,11 @@ include_once("head.inc"); value="<?=htmlspecialchars($pconfig['max_queued_bytes']);?>"> <?php echo gettext("Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> " . "( default value is <strong>1048576</strong>, <strong>0</strong> " . - "means Maximum )"); ?></td> + "means Maximum )"); ?>.</td> </tr> </table> <?php echo gettext("The number of bytes to be queued for reassembly for TCP sessions in " . - "memory. Default value is <strong>1048576</strong>"); ?><br> + "memory. Default value is <strong>1048576</strong>"); ?>.<br> </td> </tr> <tr> @@ -309,11 +783,11 @@ include_once("head.inc"); value="<?=htmlspecialchars($pconfig['max_queued_segs']);?>"> <?php echo gettext("Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> " . "( default value is <strong>2621</strong>, <strong>0</strong> means " . - "Maximum )"); ?></td> + "Maximum )"); ?>.</td> </tr> </table> <?php echo gettext("The number of segments to be queued for reassembly for TCP sessions " . - "in memory. Default value is <strong>2621</strong>"); ?><br> + "in memory. Default value is <strong>2621</strong>"); ?>.<br> </td> </tr> <tr> @@ -325,25 +799,152 @@ include_once("head.inc"); id="stream5_mem_cap" size="6" value="<?=htmlspecialchars($pconfig['stream5_mem_cap']);?>"> <?php echo gettext("Minimum is <strong>32768</strong>, Maximum is <strong>1073741824</strong> " . - "( default value is <strong>8388608</strong>) "); ?></td> + "( default value is <strong>8388608</strong>) "); ?>.</td> </tr> </table> <?php echo gettext("The memory cap in bytes for TCP packet storage " . - "in RAM. Default value is <strong>8388608</strong> (8 MB)"); ?><br> + "in RAM. Default value is <strong>8388608</strong> (8 MB)"); ?>.<br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Overlap Limit"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="stream5_overlap_limit" type="text" class="formfld" + id="stream5_overlap_limit" size="6" + value="<?=htmlspecialchars($pconfig['stream5_overlap_limit']);?>"> + <?php echo gettext("Minimum is ") . "<strong>0</strong>" . gettext(" (unlimited), and the maximum is ") . + "<strong>255</strong>."; ?></td> + </tr> + </table> + <?php echo gettext("Sets the limit for the number of overlapping fragments allowed per packet. Default value is ") . + "<strong>0</strong>" . gettext(" (unlimited)."); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("TCP Session Timeout"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="stream5_tcp_timeout" type="text" class="formfld" + id="stream5_tcp_timeout" size="6" + value="<?=htmlspecialchars($pconfig['stream5_tcp_timeout']);?>"> + <?php echo gettext("TCP Session timeout in seconds. Minimum is ") . "<strong>1</strong>" . gettext(" and the maximum is ") . + "<strong>86400</strong>" . gettext(" (approximately 1 day)"); ?>.</td> + </tr> + </table> + <?php echo gettext("Sets the session reassembly timeout period for TCP packets. Default value is ") . + "<strong>30</strong>" . gettext(" seconds."); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("UDP Session Timeout"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="stream5_udp_timeout" type="text" class="formfld" + id="stream5_udp_timeout" size="6" + value="<?=htmlspecialchars($pconfig['stream5_udp_timeout']);?>"> + <?php echo gettext("UDP Session timeout in seconds. Minimum is ") . "<strong>1</strong>" . gettext(" and the maximum is ") . + "<strong>86400</strong>" . gettext(" (approximately 1 day)"); ?>.</td> + </tr> + </table> + <?php echo gettext("Sets the session reassembly timeout period for UDP packets. Default value is ") . + "<strong>30</strong>" . gettext(" seconds."); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("ICMP Session Timeout"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="stream5_icmp_timeout" type="text" class="formfld" + id="stream5_icmp_timeout" size="6" + value="<?=htmlspecialchars($pconfig['stream5_icmp_timeout']);?>"> + <?php echo gettext("ICMP Session timeout in seconds. Minimum is ") . "<strong>1</strong>" . gettext(" and the maximum is ") . + "<strong>86400</strong>" . gettext(" (approximately 1 day)"); ?>.</td> + </tr> + </table> + <?php echo gettext("Sets the session reassembly timeout period for ICMP packets. Default value is ") . + "<strong>30</strong>" . gettext(" seconds."); ?><br> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("IP Target Policy"); ?> </td> + <td width="78%" class="vtable"> + <select name="stream5_policy" class="formselect" id="stream5_policy"> + <?php + $profile = array( 'BSD', 'First', 'HPUX', 'HPUX10', 'Irix', 'Last', 'Linux', 'MacOS', 'Old-Linux', + 'Solaris', 'Vista', 'Windows', 'Win2003' ); + foreach ($profile as $val): ?> + <option value="<?=strtolower($val);?>" + <?php if (strtolower($val) == $pconfig['stream5_policy']) echo "selected"; ?>> + <?=gettext($val);?></option> + <?php endforeach; ?> + </select> <?php echo gettext("Choose the TCP reassembly target policy appropriate for the protected hosts. The default is ") . + "<strong>" . gettext("BSD") . "</strong>"; ?>.<br/> + <?php echo gettext("Available OS targets are BSD, First, HPUX, HPUX10, Irix, Last, Linux, MacOS, Old Linux, Solaris, Vista, Windows, and Win2003 Server."); ?><br/></td> </td> </tr> - <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Portscan Settings"); ?></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("Portscan Detection"); ?></td> - <td width="78%" class="vtable"><input name="sf_portscan" - type="checkbox" value="on" - <?php if ($pconfig['sf_portscan']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Detects various types of portscans and portsweeps."); ?></td> + <td width="78%" class="vtable"><input name="sf_portscan" onclick="sf_portscan_enable_change()" + type="checkbox" value="on" id="sf_portscan" + <?php if ($pconfig['sf_portscan']=="on") echo "checked"; ?>> + <?php echo gettext("Use Portscan Detection to detect various types of port scans and sweeps. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>"; ?>.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Protocol"); ?> </td> + <td width="78%" class="vtable"> + <select name="pscan_protocol" class="formselect" id="pscan_protocol"> + <?php + $protos = array('all', 'tcp', 'udp', 'icmp', 'ip'); + foreach ($protos as $val): ?> + <option value="<?=$val;?>" + <?php if ($val == $pconfig['pscan_protocol']) echo "selected"; ?>> + <?=gettext($val);?></option> + <?php endforeach; ?> + </select> <?php echo gettext("Choose the Portscan protocol type to alert for (all, tcp, udp, icmp or ip). Default is ") . + "<strong>" . gettext("all") . "</strong>."; ?><br/> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Scan Type"); ?> </td> + <td width="78%" class="vtable"> + <select name="pscan_type" class="formselect" id="pscan_type"> + <?php + $protos = array('all', 'portscan', 'portsweep', 'decoy_portscan', 'distributed_portscan'); + foreach ($protos as $val): ?> + <option value="<?=$val;?>" + <?php if ($val == $pconfig['pscan_type']) echo "selected"; ?>> + <?=gettext($val);?></option> + <?php endforeach; ?> + </select> <?php echo gettext("Choose the Portscan scan type to alert for. Default is ") . + "<strong>" . gettext("all") . "</strong>."; ?><br/> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td><?php echo gettext("PORTSCAN: one->one scan; one host scans multiple ports on another host."); ?></td> + </tr> + <tr> + <td><?php echo gettext("PORTSWEEP: one->many scan; one host scans a single port on multiple hosts."); ?></td> + </tr> + <tr> + <td><?php echo gettext("DECOY_PORTSCAN: one->one scan; attacker has spoofed source address inter-mixed with real scanning address."); ?></td> + </tr> + <tr> + <td><?php echo gettext("DISTRIBUTED_PORTSCAN: many->one scan; multiple hosts query one host for open services."); ?></td> + </tr> + <tr> + <td><?php echo gettext("ALL: alerts for all of the above scan types."); ?></td> + </tr> + </table> + </td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Sensitivity"); ?> </td> @@ -356,22 +957,51 @@ include_once("head.inc"); <?php if ($val == $pconfig['pscan_sense_level']) echo "selected"; ?>> <?=gettext(ucfirst($val));?></option> <?php endforeach; ?> - </select><br> - <?php echo gettext("LOW: alerts generated on error packets from the target host; "); ?> - <?php echo gettext("this setting should see few false positives. "); ?><br> - <?php echo gettext("MEDIUM: tracks connection counts, so will generate filtered alerts; may "); ?> - <?php echo gettext("false positive on active hosts."); ?><br> - <?php echo gettext("HIGH: tracks hosts using a time window; will catch some slow scans, but is "); ?> - <?php echo gettext("very sensitive to active hosts."); ?><br/> + </select> <?php echo gettext("Choose the Portscan sensitivity level (Low, Medium, High). Default is ") . + "<strong>" . gettext("Medium") . "</strong>."; ?><br/> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td><?php echo gettext("LOW: alerts generated on error packets from the target host; "); ?> + <?php echo gettext("this setting should see few false positives. "); ?></td> + </tr> + <tr> + <td><?php echo gettext("MEDIUM: tracks connection counts, so will generate filtered alerts; may "); ?> + <?php echo gettext("false positive on active hosts."); ?></td> + </tr> + <tr> + <td><?php echo gettext("HIGH: tracks hosts using a time window; will catch some slow scans, but is "); ?> + <?php echo gettext("very sensitive to active hosts."); ?></td> + </tr> + </table> </td> </tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Ignore Scanners"); ?> </td> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="pscan_memcap" type="text" class="formfld" + id="pscan_memcap" size="6" + value="<?=htmlspecialchars($pconfig['pscan_memcap']);?>"> + <?php echo gettext("Maximum memory in bytes to allocate for portscan detection. ") . + gettext("Default is ") . "<strong>" . gettext("10000000") . "</strong>" . + gettext(" (10 MB)"); ?>.</td> + </tr> + </table> + <?php echo gettext("The maximum number of bytes to allocate for portscan detection. The higher this number, ") . + gettext("the more nodes that can be tracked. Default is ") . + "<strong>10,000,000</strong>" . gettext(" bytes. (10 MB)"); ?><br> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Ignore Scanners"); ?></td> <td width="78%" class="vtable"> <input name="pscan_ignore_scanners" type="text" size="40" autocomplete="off" class="formfldalias" id="pscan_ignore_scanners" - value="<?=$pconfig['pscan_ignore_scanners'];?>"> <br><?php echo gettext("Ignores the specified entity as a source of scan alerts. Entity must be a defined alias.");?><br> - <?php echo gettext("Default value: \$HOME_NET."); ?><?php echo gettext(" Leave " . - "blank for default value."); ?> + value="<?=$pconfig['pscan_ignore_scanners'];?>"> <?php echo gettext("Leave blank for default. ") . + gettext("Default value is ") . "<strong>" . gettext("\$HOME_NET") . "</strong>"; ?>.<br/> + <?php echo gettext("Ignores the specified entity as a source of scan alerts. Entity must be a defined alias."); ?><br/> </td> + </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Preprocessor Settings"); ?></td> </tr> @@ -380,71 +1010,70 @@ include_once("head.inc"); <?php echo gettext("RPC Decode and Back Orifice detector"); ?></td> <td width="78%" class="vtable"><input name="other_preprocs" type="checkbox" value="on" - <?php if ($pconfig['other_preprocs']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Normalize/Decode RPC traffic and detects Back Orifice traffic on the network."); ?></td> + <?php if ($pconfig['other_preprocs']=="on") echo "checked"; ?>> + <?php echo gettext("Normalize/Decode RPC traffic and detects Back Orifice traffic on the network. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("FTP and Telnet Normalizer"); ?></td> <td width="78%" class="vtable"><input name="ftp_preprocessor" type="checkbox" value="on" - <?php if ($pconfig['ftp_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Normalize/Decode FTP and Telnet traffic and protocol anomalies."); ?></td> + <?php if ($pconfig['ftp_preprocessor']=="on") echo "checked"; ?>> + <?php echo gettext("Normalize/Decode FTP and Telnet traffic and protocol anomalies. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("POP Normalizer"); ?></td> <td width="78%" class="vtable"><input name="pop_preproc" type="checkbox" value="on" - <?php if ($pconfig['pop_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Normalize/Decode POP protocol for enforcement and buffer overflows."); ?></td> + <?php if ($pconfig['pop_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("Normalize/Decode POP protocol for enforcement and buffer overflows. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("IMAP Normalizer"); ?></td> <td width="78%" class="vtable"><input name="imap_preproc" type="checkbox" value="on" - <?php if ($pconfig['imap_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Normalize/Decode IMAP protocol for enforcement and buffer overflows."); ?></td> + <?php if ($pconfig['imap_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("Normalize/Decode IMAP protocol for enforcement and buffer overflows. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("SMTP Normalizer"); ?></td> <td width="78%" class="vtable"><input name="smtp_preprocessor" type="checkbox" value="on" - <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Normalize/Decode SMTP protocol for enforcement and buffer overflows."); ?></td> + <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?>> + <?php echo gettext("Normalize/Decode SMTP protocol for enforcement and buffer overflows. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("DCE/RPC2 Detection"); ?></td> <td width="78%" class="vtable"><input name="dce_rpc_2" type="checkbox" value="on" - <?php if ($pconfig['dce_rpc_2']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC traffic."); ?></td> + <?php if ($pconfig['dce_rpc_2']=="on") echo "checked"; ?>> + <?php echo gettext("The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC traffic. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("SIP Detection"); ?></td> <td width="78%" class="vtable"><input name="sip_preproc" type="checkbox" value="on" - <?php if ($pconfig['sip_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("The SIP preprocessor decodes SIP traffic and detects some vulnerabilities."); ?></td> + <?php if ($pconfig['sip_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("The SIP preprocessor decodes SIP traffic and detects some vulnerabilities. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("GTP Detection"); ?></td> <td width="78%" class="vtable"><input name="gtp_preproc" type="checkbox" value="on" - <?php if ($pconfig['gtp_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> + <?php if ($pconfig['gtp_preproc']=="on") echo "checked"; ?>> <?php echo gettext("The GTP preprocessor decodes GPRS Tunneling Protocol traffic and detects intrusion attempts."); ?></td> </tr> <tr> @@ -452,26 +1081,30 @@ include_once("head.inc"); <?php echo gettext("DNS Detection"); ?></td> <td width="78%" class="vtable"><input name="dns_preprocessor" type="checkbox" value="on" - <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("The DNS preprocessor decodes DNS Response traffic and detects some vulnerabilities."); ?></td> + <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?>> + <?php echo gettext("The DNS preprocessor decodes DNS Response traffic and detects vulnerabilities. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("SSL Data"); ?></td> <td width="78%" class="vtable"> <input name="ssl_preproc" type="checkbox" value="on" - <?php if ($pconfig['ssl_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("SSL data searches for irregularities during SSL protocol exchange"); ?> - </td> + <?php if ($pconfig['ssl_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("SSL data searches for irregularities during SSL protocol exchange. Default is ") . + "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("Sensitive Data"); ?></td> <td width="78%" class="vtable"> <input name="sensitive_data" type="checkbox" value="on" - <?php if ($pconfig['sensitive_data']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Sensitive data searches for credit card or Social Security numbers in data"); ?> + <?php if ($pconfig['sensitive_data'] == "on") + echo "checked"; + elseif ($vrt_enabled == "off") + echo "disabled"; + ?>> + <?php echo gettext("Sensitive data searches for credit card or Social Security numbers and e-mail addresses in data."); ?> + <br/> + <span class="red"><strong><?php echo gettext("Note: "); ?></strong></span><?php echo gettext("To enable this preprocessor, you must select the Snort VRT rules on the Global Settings tab."); ?> </td> </tr> <tr> @@ -481,35 +1114,39 @@ include_once("head.inc"); <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("Modbus Detection"); ?></td> <td width="78%" class="vtable"> <input name="modbus_preproc" type="checkbox" value="on" - <?php if ($pconfig['modbus_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("Modbus is a protocol used in SCADA networks. The default port is TCP 502. If your network does " . - "not contain Modbus-enabled devices, you should leave this preprocessor disabled."); ?> + <?php if ($pconfig['modbus_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("Modbus is a protocol used in SCADA networks. The default port is TCP 502.") . "<br/>" . + gettext("If your network does not contain Modbus-enabled devices, you should leave this preprocessor disabled."); ?> </td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("DNP3 Detection"); ?></td> <td width="78%" class="vtable"> <input name="dnp3_preproc" type="checkbox" value="on" - <?php if ($pconfig['dnp3_preproc']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - <?php echo gettext("DNP3 is a protocol used in SCADA networks. The default port is TCP 20000. If your network does " . - "not contain DNP3-enabled devices, you should leave this preprocessor disabled."); ?> + <?php if ($pconfig['dnp3_preproc']=="on") echo "checked"; ?>> + <?php echo gettext("DNP3 is a protocol used in SCADA networks. The default port is TCP 20000.") . "<br/>" . + gettext("If your network does not contain DNP3-enabled devices, you should leave this preprocessor disabled."); ?> </td> </tr> <tr> <td width="22%" valign="top"> </td> <td width="78%"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input name="id" type="hidden" value="<?=$id;?>"></td> + <input name="Submit" type="submit" class="formbtn" value="Save" title="<?php echo + gettext("Save preprocessor settings"); ?>"/> + <input name="id" type="hidden" value="<?=$id;?>"> + <input name="ResetAll" type="submit" class="formbtn" value="Reset" title="<?php echo + gettext("Reset all settings to defaults") . "\" onclick=\"return confirm('" . + gettext("WARNING: This will reset ALL preprocessor settings to their defaults. Click OK to continue or CANCEL to quit.") . + "')\""; ?>/></td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> - <br> - <?php echo gettext("Please save your settings before you click Start."); ?> </td> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note: "); ?></strong></span> + <?php echo gettext("Please save your settings before you exit. Preprocessor changes will rebuild the rules file. This "); ?> + </br><?php echo gettext("may take several seconds. Snort must also be restarted to activate any changes made on this screen."); ?></td> </tr> </table> +</div> </td></tr></table> </form> <script type="text/javascript"> @@ -545,6 +1182,119 @@ function createAutoSuggest() { setTimeout("createAutoSuggest();", 500); +function frag3_enable_change() { + if (!document.iform.frag3_detection.checked) { + var msg = "WARNING: Disabling the Frag3 preprocessor is not recommended!\n\n"; + msg = msg + "Snort may fail to start because of other dependent preprocessors or "; + msg = msg + "rule options. Are you sure you want to disable it?\n\n"; + msg = msg + "Click OK to disable Frag3, or CANCEL to quit."; + if (!confirm(msg)) { + document.iform.frag3_detection.checked=true; + } + } + var endis = !(document.iform.frag3_detection.checked); + document.iform.frag3_overlap_limit.disabled=endis; + document.iform.frag3_min_frag_len.disabled=endis; + document.iform.frag3_policy.disabled=endis; + document.iform.frag3_max_frags.disabled=endis; + document.iform.frag3_memcap.disabled=endis; + document.iform.frag3_timeout.disabled=endis; +} + +function http_inspect_enable_change() { + var endis = !(document.iform.http_inspect.checked); + document.iform.http_inspect_enable_xff.disabled=endis; + document.iform.server_flow_depth.disabled=endis; + document.iform.client_flow_depth.disabled=endis; + document.iform.http_server_profile.disabled=endis; + document.iform.http_inspect_memcap.disabled=endis; + document.iform.http_inspect_log_uri.disabled=endis; + document.iform.http_inspect_log_hostname.disabled=endis; +} + +function sf_portscan_enable_change() { + var endis = !(document.iform.sf_portscan.checked); + document.iform.pscan_protocol.disabled=endis; + document.iform.pscan_type.disabled=endis; + document.iform.pscan_memcap.disabled=endis; + document.iform.pscan_sense_level.disabled=endis; + document.iform.pscan_ignore_scanners.disabled=endis; +} + +function stream5_enable_change() { + if (!document.iform.stream5_reassembly.checked) { + var msg = "WARNING: Stream5 is a critical preprocessor, and disabling it is not recommended! "; + msg = msg + "The following preprocessors require Stream5 and will be automatically disabled if currently enabled:\n\n"; + msg = msg + " SMTP\t\tPOP\t\tSIP\n"; + msg = msg + " SENSITIVE_DATA\tSF_PORTSCAN\tDCE/RPC 2\n"; + msg = msg + " IMAP\t\tDNS\t\tSSL\n"; + msg = msg + " GTP\t\tDNP3\t\tMODBUS\n\n"; + msg = msg + "Snort may fail to start because of other preprocessors or rule options dependent on Stream5. "; + msg = msg + "Are you sure you want to disable it?\n\n"; + msg = msg + "Click OK to disable Stream5, or CANCEL to quit."; + if (!confirm(msg)) { + document.iform.stream5_reassembly.checked=true; + } + else { + alert("If Snort fails to start with Stream5 disabled, examine the system log for clues."); + document.iform.smtp_preprocessor.checked=false; + document.iform.dce_rpc_2.checked=false; + document.iform.sip_preproc.checked=false; + document.iform.sensitive_data.checked=false; + document.iform.imap_preproc.checked=false; + document.iform.pop_preproc.checked=false; + document.iform.ssl_preproc.checked=false; + document.iform.dns_preprocessor.checked=false; + document.iform.modbus_preproc.checked=false; + document.iform.dnp3_preproc.checked=false; + document.iform.sf_portscan.checked=false; + sf_portscan_enable_change(); + } + } + + var endis = !(document.iform.stream5_reassembly.checked); + document.iform.max_queued_bytes.disabled=endis; + document.iform.max_queued_segs.disabled=endis; + document.iform.stream5_mem_cap.disabled=endis; + document.iform.stream5_policy.disabled=endis; + document.iform.stream5_overlap_limit.disabled=endis; + document.iform.stream5_no_reassemble_async.disabled=endis; + document.iform.stream5_dont_store_lg_pkts.disabled=endis; + document.iform.stream5_tcp_timeout.disabled=endis; + document.iform.stream5_udp_timeout.disabled=endis; + document.iform.stream5_icmp_timeout.disabled=endis; +} + +function enable_change_all() { + http_inspect_enable_change(); + sf_portscan_enable_change(); + + // Enable/Disable Frag3 settings + var endis = !(document.iform.frag3_detection.checked); + document.iform.frag3_overlap_limit.disabled=endis; + document.iform.frag3_min_frag_len.disabled=endis; + document.iform.frag3_policy.disabled=endis; + document.iform.frag3_max_frags.disabled=endis; + document.iform.frag3_memcap.disabled=endis; + document.iform.frag3_timeout.disabled=endis; + + // Enable/Disable Stream5 settings + endis = !(document.iform.stream5_reassembly.checked); + document.iform.max_queued_bytes.disabled=endis; + document.iform.max_queued_segs.disabled=endis; + document.iform.stream5_mem_cap.disabled=endis; + document.iform.stream5_policy.disabled=endis; + document.iform.stream5_overlap_limit.disabled=endis; + document.iform.stream5_no_reassemble_async.disabled=endis; + document.iform.stream5_dont_store_lg_pkts.disabled=endis; + document.iform.stream5_tcp_timeout.disabled=endis; + document.iform.stream5_udp_timeout.disabled=endis; + document.iform.stream5_icmp_timeout.disabled=endis; +} + +// Set initial state of form controls +enable_change_all(); + </script> <?php include("fend.inc"); ?> </body> diff --git a/config/snort/snort_rules.php b/config/snort/snort_rules.php index 7457632d..2ef529b9 100755 --- a/config/snort/snort_rules.php +++ b/config/snort/snort_rules.php @@ -33,7 +33,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g, $flowbit_rules_file; +global $g, $flowbit_rules_file, $rebuild_rules; $snortdir = SNORTDIR; $rules_map = array(); @@ -67,10 +67,42 @@ function truncate($string, $length) { * truncation was necessary. * ********************************/ if (strlen($string) > $length) - $string = substr($string, 0, ($length - 3)) . "..."; + $string = substr($string, 0, ($length - 2)) . "..."; return $string; } +function add_title_attribute($tag, $title) { + + /******************************** + * This function adds a "title" * + * attribute to the passed tag * + * and sets the value to the * + * value specified by "$title". * + ********************************/ + $result = ""; + if (empty($tag)) { + // If passed an empty element tag, then + // just create a <span> tag with title + $result = "<span title=\"" . $title . "\">"; + } + else { + // Find the ending ">" for the element tag + $pos = strpos($tag, ">"); + if ($pos !== false) { + // We found the ">" delimter, so add "title" + // attribute and close the element tag + $result = substr($tag, 0, $pos) . " title=\"" . $title . "\">"; + } + else { + // We did not find the ">" delimiter, so + // something is wrong, just return the + // tag "as-is" + $result = $tag; + } + } + return $result; +} + /* convert fake interfaces to real */ $if_real = snort_get_real_interface($pconfig['interface']); $snort_uuid = $a_rule[$id]['uuid']; @@ -92,6 +124,11 @@ if (empty($categories[0]) && ($currentruleset != "custom.rules")) { $currentruleset = "custom.rules"; } +/* One last sanity check -- if the rules directory is empty, default to loading custom rules */ +$tmp = glob("{$snortdir}/rules/*.rules"); +if (empty($tmp)) + $currentruleset = "custom.rules"; + $ruledir = "{$snortdir}/rules"; $rulefile = "{$ruledir}/{$currentruleset}"; if ($currentruleset != 'custom.rules') { @@ -100,7 +137,7 @@ if ($currentruleset != 'custom.rules') { if (substr($currentruleset, 0, 10) == "IPS Policy") $rules_map = snort_load_vrt_policy($a_rule[$id]['ips_policy']); elseif (!file_exists($rulefile)) - $input_errors[] = "{$currentruleset} seems to be missing!!! Please go to the Category tab and save the rule set again to regenerate it."; + $input_errors[] = gettext("{$currentruleset} seems to be missing!!! Please verify rules files have been downloaded, then go to the Categories tab and save the rule set again."); else $rules_map = snort_load_rules_map($rulefile); } @@ -207,10 +244,22 @@ if ($_GET['act'] == "resetall" && !empty($rules_map)) { exit; } +if ($_POST['clear']) { + unset($a_rule[$id]['customrules']); + write_config(); + $rebuild_rules = "on"; + snort_generate_conf($a_rule[$id]); + $rebuild_rules = "off"; + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); + exit; +} + if ($_POST['customrules']) { $a_rule[$id]['customrules'] = base64_encode($_POST['customrules']); write_config(); - sync_snort_package_config(); + $rebuild_rules = "on"; + snort_generate_conf($a_rule[$id]); + $rebuild_rules = "off"; $output = ""; $retcode = ""; exec("snort -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -T 2>&1", $output, $retcode); @@ -221,11 +270,31 @@ if ($_POST['customrules']) { for($i = $start; $i > $end; $i--) $error .= $output[$i]; $input_errors[] = "Custom rules have errors:\n {$error}"; - } else { + } + else { header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); exit; } -} else if ($_POST) { +} + +else if ($_POST['apply']) { + + /* Save new configuration */ + write_config(); + + /*************************************************/ + /* Update the snort conf file and rebuild the */ + /* rules for this interface. */ + /*************************************************/ + $rebuild_rules = "on"; + snort_generate_conf($a_rule[$id]); + $rebuild_rules = "off"; + + /* Return to this same page */ + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); + exit; +} +else if($_POST) { unset($a_rule[$id]['customrules']); write_config(); header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); @@ -263,241 +332,289 @@ function go() if (destination) location.href = destination; } -function popup(url) + +function wopen(url, name, w, h) { - params = 'width='+screen.width; - params += ', height='+screen.height; - params += ', top=0, left=0' - params += ', fullscreen=yes'; - - newwin=window.open(url,'windowname4', params); - if (window.focus) {newwin.focus()} - return false; +// Fudge factors for window decoration space. +// In my tests these work well on all platforms & browsers. +w += 32; +h += 96; + var win = window.open(url, + name, + 'width=' + w + ', height=' + h + ', ' + + 'location=no, menubar=no, ' + + 'status=no, toolbar=no, scrollbars=yes, resizable=yes'); + win.resizeTo(w, h); + win.focus(); } + </script> <form action="/snort/snort_rules.php" method="post" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td> -<?php + <tr><td> + <?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td class="tabnavtbl">'; + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface ");; $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); -?> -</td></tr> -<tr> - <td> - <table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td width="3%" class="list"> </td> - <td class="listhdr" colspan="4"> - <br/>Category: - <select id="selectbox" name="selectbox" class="formselect" onChange="go()"> - <option value='?id=<?=$id;?>&openruleset=custom.rules'>custom.rules</option> - <?php - $files = explode("||", $pconfig['rulesets']); - if ($a_rule[$id]['ips_policy_enable'] == 'on') - $files[] = "IPS Policy - " . ucfirst($a_rule[$id]['ips_policy']); - natcasesort($files); - foreach ($files as $value) { - if ($snortdownload != 'on' && substr($value, 0, 6) == "snort_") - continue; - if ($emergingdownload != 'on' && substr($value, 0, 8) == "emerging") - continue; - if (empty($value)) - continue; - echo "<option value='?id={$id}&openruleset={$value}' "; - if ($value == $currentruleset) - echo "selected"; - echo ">{$value}</option>\n"; - } - ?> - </select> - <br/> - </td> - <td class="listhdr" colspan="3" valign="middle"> -<?php if ($currentruleset != 'custom.rules'): ?> - <?php echo "<a href='?id={$id}&openruleset={$currentruleset}&act=resetcategory'> - <img src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\" - onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"' - onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_x_mo.gif\"' border='0' - title='" . gettext("Click to remove enable/disable changes for rules in the selected category only") . "'></a>"?> - <?php echo gettext("Remove Enable/Disable changes in the current Category");?><br> - <?php echo "<a href='?id={$id}&openruleset={$currentruleset}&act=resetall'> - <img src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\" - onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"' - onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_x_mo.gif\"' border='0' - title='" . gettext("Click to remove all enable/disable changes for rules in all categories") . "'></a>"?> - <?php echo gettext("Remove all Enable/Disable changes in all Categories");?> -<?php endif;?> - </td> - <td width="3%" class="list"> </td> - </tr> -<?php if ($currentruleset == 'custom.rules'): ?> - <tr> - <td width="3%" class="list"> </td> - <td colspan="7" valign="top" class="vtable"> - <input type='hidden' name='openruleset' value='custom.rules'> - <input type='hidden' name='id' value='<?=$id;?>'> - - <textarea wrap="on" cols="85" rows="40" name="customrules"><?=$pconfig['customrules'];?></textarea> - </td> - <td width="3%" class="list"> </td> - </tr> - <tr> - <td width="3%" class="list"> </td> - <td colspan="7" class="vtable"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input type="button" class="formbtn" value="Cancel" onclick="history.back()"> - </td> - <td width="3%" class="list"> </td> - </tr> -<?php else: ?> - <tr> - <td width="3%" class="list"> </td> - <td colspan="7" class="listhdr" > </td> - <td width="3%" align="center" valign="middle" class="listt"><a href="javascript: void(0)" - onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$currentruleset;?>')"> - <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_service_restart.gif" <?php - echo "onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_services_restart_mo.gif\"' - onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_service_restart.gif\"' ";?> - title="<?php echo gettext("Click to view all rules"); ?>" width="17" height="17" border="0"></a></td> - </tr> - <tr id="frheader"> - <td width="3%" class="list"> </td> - <td width="9%" class="listhdrr"><?php echo gettext("SID"); ?></td> - <td width="2%" class="listhdrr"><?php echo gettext("Proto"); ?></td> - <td width="14%" class="listhdrr"><?php echo gettext("Source"); ?></td> - <td width="12%" class="listhdrr"><?php echo gettext("Port"); ?></td> - <td width="14%" class="listhdrr"><?php echo gettext("Destination"); ?></td> - <td width="12%" class="listhdrr"><?php echo gettext("Port"); ?></td> - <td width="31%" class="listhdrr"><?php echo gettext("Message"); ?></td> - <td width="3%" class="list"> </td> - </tr> -<?php - foreach (array_keys($rules_map) as $k1) { - foreach (array_keys($rules_map[$k1]) as $k2) { - $sid = snort_get_sid($rules_map[$k1][$k2]['rule']); - $gid = snort_get_gid($rules_map[$k1][$k2]['rule']); - if (isset($disablesid[$sid])) { - $textss = "<span class=\"gray\">"; - $textse = "</span>"; - $iconb = "icon_reject_d.gif"; - } - elseif (($rules_map[$k1][$k2]['disabled'] == 1) && (!isset($enablesid[$sid]))) { - $textss = "<span class=\"gray\">"; - $textse = "</span>"; - $iconb = "icon_block_d.gif"; - } - elseif (isset($enablesid[$sid])) { - $textss = $textse = ""; - $iconb = "icon_reject.gif"; - } - else { - $textss = $textse = ""; - $iconb = "icon_block.gif"; - } - - // Pick off the first section of the rule (prior to the start of the MSG field), - // and then use a REGX split to isolate the remaining fields into an array. - $tmp = substr($rules_map[$k1][$k2]['rule'], 0, strpos($rules_map[$k1][$k2]['rule'], "(")); - $tmp = trim(preg_replace('/^\s*#+\s*/', '', $tmp)); - $rule_content = preg_split('/[\s]+/', $tmp); - - $protocol = truncate($rule_content[1], 5); //protocol location - $source = truncate($rule_content[2], 13); //source location - $source_port = truncate($rule_content[3], 11); //source port location - $destination = truncate($rule_content[5], 13); //destination location - $destination_port = truncate($rule_content[6], 11); //destination port location - $message = snort_get_msg($rules_map[$k1][$k2]['rule']); - - echo "<tr><td width=\"3%\" class=\"listt\" align=\"center\" valign=\"middle\"> $textss - <a href='?id={$id}&openruleset={$currentruleset}&act=toggle&ids={$sid}'> - <img src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" - width=\"10\" height=\"10\" border=\"0\" - title='" . gettext("Click to toggle enabled/disabled state") . "'></a> - $textse - </td> - <td width=\"9%\" class=\"listlr\"> - $textss $sid $textse - </td> - <td width=\"2%\" class=\"listlr\"> - $textss $protocol $textse - </td> - <td width=\"14%\" class=\"listlr\"> - $textss $source $textse - </td> - <td width=\"12%\" class=\"listlr\"> - $textss $source_port $textse - </td> - <td width=\"14%\" class=\"listlr\"> - $textss $destination $textse - </td> - <td width=\"12%\" class=\"listlr\"> - $textss $destination_port $textse - </td> - <td width=\"31%\" class=\"listbg\" style=\"word-break:break-all;\"><font color=\"white\"> - $textss $message $textse - </td>"; ?> - <td width="3%" align="center" valign="middle" nowrap class="listt"> - <a href="javascript: void(0)" - onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$currentruleset;?>&ids=<?=$sid;?>&gid=<?=$gid;?>')"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_right.gif" - title="<?php echo gettext("Click to view rule"); ?>" width="17" height="17" border="0"></a> - <!-- Codes by Quackit.com --> - </td> - </tr> -<?php - } - } -?> - - </table> - </td> -</tr> -<?php endif;?> -<tr> - <td colspan="9"> -<?php if ($currentruleset != 'custom.rules'): ?> - <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="1"> - <tr> - <td width="16"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" - width="11" height="11"></td> - <td><?php echo gettext("Rule default is Enabled"); ?></td> - </tr> - <tr> - <td><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_block_d.gif" - width="11" height="11"></td> - <td nowrap><?php echo gettext("Rule default is Disabled"); ?></td> - </tr> - <tr> - <td><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_reject.gif" - width="11" height="11"></td> - <td nowrap><?php echo gettext("Rule changed to Enabled by user"); ?></td> - </tr> - <tr> - <td><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_reject_d.gif" - width="11" height="11"></td> - <td nowrap><?php echo gettext("Rule changed to Disabled by user"); ?></td> - </tr> - </table> -<?php endif;?> + </td></tr> + <tr><td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="4" cellspacing="0"> + <tr> + <td class="listtopic"><?php echo gettext("Available Rule Categories"); ?></td> + </tr> + + <tr> + <td class="vncell" height="30px"><strong><?php echo gettext("Category:"); ?></strong> <select id="selectbox" name="selectbox" class="formselect" onChange="go()"> + <option value='?id=<?=$id;?>&openruleset=custom.rules'>custom.rules</option> + <?php + $files = explode("||", $pconfig['rulesets']); + if ($a_rule[$id]['ips_policy_enable'] == 'on') + $files[] = "IPS Policy - " . ucfirst($a_rule[$id]['ips_policy']); + natcasesort($files); + foreach ($files as $value) { + if ($snortdownload != 'on' && substr($value, 0, 6) == "snort_") + continue; + if ($emergingdownload != 'on' && substr($value, 0, 8) == "emerging") + continue; + if (empty($value)) + continue; + echo "<option value='?id={$id}&openruleset={$value}' "; + if ($value == $currentruleset) + echo "selected"; + echo ">{$value}</option>\n"; + } + ?> + </select> <?php echo gettext("Select the rule category to view"); ?> + </td> + </tr> + + <?php if ($currentruleset == 'custom.rules'): ?> + <tr> + <td class="listtopic"><?php echo gettext("Defined Custom Rules"); ?></td> + </tr> + <tr> + <td valign="top" class="vtable"> + <input type='hidden' name='openruleset' value='custom.rules'> + <input type='hidden' name='id' value='<?=$id;?>'> + <textarea wrap="soft" cols="90" rows="40" name="customrules"><?=$pconfig['customrules'];?></textarea> + </td> + </tr> + <tr> + <td> + <input name="Submit" type="submit" class="formbtn" value="<?php echo gettext(" Save "); ?>" title=" <?php echo gettext("Save custom rules"); ?>"/> + <input type="button" class="formbtn" value=" <?php echo gettext("Cancel"); ?>" onclick="history.back()" title="<?php echo gettext("Cancel changes and return to last page"); ?>"/> + <input name="clear" type="submit" class="formbtn" id="clear" value="<?php echo gettext("Clear"); ?>" onclick="return confirm('<?php echo gettext("This will erase all custom rules for the interface. Are you sure?"); ?>')" title="<?php echo gettext("Deletes all custom rules"); ?>"/> + </td> + </tr> + <?php else: ?> + <tr> + <td class="listtopic"><?php echo gettext("Rule Signature ID (SID) Enable/Disable Overrides"); ?></td> + </tr> + <tr> + <td class="vncell"> + <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td width="55%" valign="middle" rowspan="2"><input type="submit" name="apply" id="apply" value="<?php echo gettext("Apply"); ?>" class="formbtn" + title="<?php echo gettext("Click to rebuild the rules with your changes"); ?>"/> + <input type='hidden' name='id' value='<?=$id;?>'/></td> + <td class="vexpl" valign="middle"><?php echo "<a href='?id={$id}&openruleset={$currentruleset}&act=resetcategory'> + <img src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\" width=\"15\" height=\"15\" + onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"' + onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_x_mo.gif\"' border='0' + title='" . gettext("Click to remove enable/disable changes for rules in the selected category only") . "'></a>"?> + <?php echo gettext("Remove Enable/Disable changes in the current Category"); ?></td> + </tr> + <tr> + <td class="vexpl" valign="middle"><?php echo "<a href='?id={$id}&openruleset={$currentruleset}&act=resetall'> + <img src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\" width=\"15\" height=\"15\" + onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"' + onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_x_mo.gif\"' border='0' + title='" . gettext("Click to remove all enable/disable changes for rules in all categories") . "'></a>"?> + <?php echo gettext("Remove all Enable/Disable changes in all Categories"); ?></td> + </tr> + <tr> + <td colspan="2" class="vexpl" valign="middle"><span class="red"><strong><?php echo gettext("Note: ") . "</strong></span>" . + gettext("Snort must be restarted to activate any SID enable/disable changes."); ?></td> + </tr> + </table> + </td> + </tr> + + <tr> + <td class="listtopic"><?php echo gettext("Selected Category's Rules"); ?></td> + </tr> + <tr> + <td> + <table id="myTable" class="sortable" style="table-layout: fixed;" width="100%" border="0" cellpadding="0" cellspacing="0"> + <colgroup> + <col width="15" align="left" valign="middle"> + <col width="9%" align="center" axis="number"> + <col width="60" align="center" axis="string"> + <col width="14%" align="center" axis="string"> + <col width="11%" align="center" axis="string"> + <col width="14%" align="center" axis="string"> + <col width="11%" align="center" axis="string"> + <col axis="string"> + <col width="22" align="right" valign="middle"> + </colgroup> + <thead> + <th class="list"> </th> + <th class="listhdrr"><?php echo gettext("SID"); ?></th> + <th class="listhdrr"><?php echo gettext("Proto"); ?></th> + <th class="listhdrr"><?php echo gettext("Source"); ?></th> + <th class="listhdrr"><?php echo gettext("Port"); ?></th> + <th class="listhdrr"><?php echo gettext("Destination"); ?></th> + <th class="listhdrr"><?php echo gettext("Port"); ?></th> + <th class="listhdrr"><?php echo gettext("Message"); ?></th> + <th class="list"><a href="javascript: void(0)" + onclick="wopen('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$currentruleset;?>','FileViewer',800,600)"> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_service_restart.gif" <?php + echo "onmouseover='this.src=\"../themes/{$g['theme']}/images/icons/icon_services_restart_mo.gif\"' + onmouseout='this.src=\"../themes/{$g['theme']}/images/icons/icon_service_restart.gif\"' ";?> + title="<?php echo gettext("Click to view full text of all the category rules"); ?>" width="17" height="17" border="0"></a></th> + </thead> + <tbody> + + <?php + foreach ($rules_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + $sid = snort_get_sid($v['rule']); + $gid = snort_get_gid($v['rule']); + if (isset($disablesid[$sid])) { + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $iconb = "icon_reject_d.gif"; + } + elseif (($v['disabled'] == 1) && (!isset($enablesid[$sid]))) { + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $iconb = "icon_block_d.gif"; + } + elseif (isset($enablesid[$sid])) { + $textss = $textse = ""; + $iconb = "icon_reject.gif"; + } + else { + $textss = $textse = ""; + $iconb = "icon_block.gif"; + } + + // Pick off the first section of the rule (prior to the start of the MSG field), + // and then use a REGX split to isolate the remaining fields into an array. + $tmp = substr($v['rule'], 0, strpos($v['rule'], "(")); + $tmp = trim(preg_replace('/^\s*#+\s*/', '', $tmp)); + $rule_content = preg_split('/[\s]+/', $tmp); + + // Create custom <span> tags for the fields we truncate so we can + // have a "title" attribute for tooltips to show the full string. + $srcspan = add_title_attribute($textss, $rule_content[2]); + $srcprtspan = add_title_attribute($textss, $rule_content[3]); + $dstspan = add_title_attribute($textss, $rule_content[5]); + $dstprtspan = add_title_attribute($textss, $rule_content[6]); + + $protocol = $rule_content[1]; //protocol field + $source = truncate($rule_content[2], 14); //source field + $source_port = truncate($rule_content[3], 10); //source port field + $destination = truncate($rule_content[5], 14); //destination field + $destination_port = truncate($rule_content[6], 10); //destination port field + $message = snort_get_msg($v['rule']); + + echo "<tr><td class=\"listt\" align=\"left\" valign=\"middle\"> $textss + <a href='?id={$id}&openruleset={$currentruleset}&act=toggle&ids={$sid}'> + <img src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" + width=\"11\" height=\"11\" border=\"0\" + title='" . gettext("Click to toggle enabled/disabled state") . "'></a> + $textse + </td> + <td class=\"listlr\" align=\"center\"> + {$textss}{$sid}{$textse} + </td> + <td class=\"listlr\" align=\"center\"> + {$textss}{$protocol}{$textse} + </td> + <td class=\"listlr\" align=\"center\"> + {$srcspan}{$source}{$textse} + </td> + <td class=\"listlr\" align=\"center\"> + {$srcprtspan}{$source_port}{$textse} + </td> + <td class=\"listlr\" align=\"center\"> + {$dstspan}{$destination}{$textse} + </td> + <td class=\"listlr\" align=\"center\"> + {$dstprtspan}{$destination_port}{$textse} + </td> + <td class=\"listbg\" style=\"word-wrap:break-word; whitespace:pre-line;\"><font color=\"white\"> + {$textss}{$message}{$textse} + </td>"; + ?> + <td align="right" valign="middle" nowrap class="listt"> + <a href="javascript: void(0)" + onclick="wopen('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$currentruleset;?>&ids=<?=$sid;?>&gid=<?=$gid;?>','FileViewer',800,600)"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_right.gif" + title="<?php echo gettext("Click to view the entire rule text"); ?>" width="17" height="17" border="0"></a> + </td> + </tr> + <?php + } + } + unset($rulem, $v); + ?> + </tbody> + </table> + </td> + </tr> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="1"> + <tr> + <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" + width="11" height="11"></td> + <td><?php echo gettext("Rule default is Enabled"); ?></td> + </tr> + <tr> + <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_block_d.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule default is Disabled"); ?></td> + </tr> + <tr> + <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_reject.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule changed to Enabled by user"); ?></td> + </tr> + <tr> + <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_reject_d.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule changed to Disabled by user"); ?></td> + </tr> + </table> + </td> + </tr> + <?php endif;?> + </table> + </div> </td> -</tr> -</table> -</td> -</tr> + </tr> </table> </form> <?php include("fend.inc"); ?> diff --git a/config/snort/snort_rules_edit.php b/config/snort/snort_rules_edit.php index ab1a24b2..a1f45c07 100755 --- a/config/snort/snort_rules_edit.php +++ b/config/snort/snort_rules_edit.php @@ -62,6 +62,7 @@ $if_real = snort_get_real_interface($pconfig['interface']); $snort_uuid = $a_rule[$id]['uuid']; $file = $_GET['openruleset']; $contents = ''; +$wrap_flag = "off"; // Read the contents of the argument passed to us. // It may be an IPS policy string, an individual SID, @@ -69,8 +70,10 @@ $contents = ''; // Test for the special case of an IPS Policy file. if (substr($file, 0, 10) == "IPS Policy") { $rules_map = snort_load_vrt_policy($a_rule[$id]['ips_policy']); - if (isset($_GET['ids'])) + if (isset($_GET['ids'])) { $contents = $rules_map[$_GET['gid']][trim($_GET['ids'])]['rule']; + $wrap_flag = "soft"; + } else { $contents = "# Snort IPS Policy - " . ucfirst($a_rule[$id]['ips_policy']) . "\n\n"; foreach (array_keys($rules_map) as $k1) { @@ -86,6 +89,7 @@ if (substr($file, 0, 10) == "IPS Policy") { elseif (isset($_GET['ids'])) { $rules_map = snort_load_rules_map("{$snortdir}/rules/{$file}"); $contents = $rules_map[$_GET['gid']][trim($_GET['ids'])]['rule']; + $wrap_flag = "soft"; } // Is it our special flowbit rules file? elseif ($file == $flowbit_rules_file) @@ -102,14 +106,14 @@ else { exit; } -$pgtitle = array(gettext("Advanced"), gettext("File Viewer")); +$pgtitle = array(gettext("Snort"), gettext("File Viewer")); ?> <?php include("head.inc");?> <body link="#000000" vlink="#000000" alink="#000000"> <?php if ($savemsg) print_info_box($savemsg); ?> -<?php include("fbegin.inc");?> +<?php // include("fbegin.inc");?> <form action="snort_rules_edit.php" method="post"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> @@ -117,14 +121,20 @@ $pgtitle = array(gettext("Advanced"), gettext("File Viewer")); <td class="tabcont"> <table width="100%" cellpadding="0" cellspacing="6" bgcolor="#eeeeee"> <tr> - <td> + <td class="pgtitle" colspan="2">Snort: Rules Viewer</td> + </tr> + <tr> + <td width="20%"> <input type="button" class="formbtn" value="Return" onclick="window.close()"> </td> + <td align="right"> + <b><?php echo gettext("Rules File: ") . '</b> ' . $file; ?> + </td> </tr> <tr> - <td valign="top" class="label"> - <div style="background: #eeeeee;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> - <textarea wrap="off" rows="33" cols="90" name="code2"><?=$contents;?></textarea> + <td valign="top" class="label" colspan="2"> + <div style="background: #eeeeee; width:100%; height:100%;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> + <textarea style="width:100%; height:100%;" wrap="<?=$wrap_flag?>" rows="33" cols="80" name="code2"><?=$contents;?></textarea> </div> </td> </tr> @@ -133,6 +143,6 @@ $pgtitle = array(gettext("Advanced"), gettext("File Viewer")); </tr> </table> </form> -<?php include("fend.inc");?> +<?php // include("fend.inc");?> </body> </html> diff --git a/config/snort/snort_rules_flowbits.php b/config/snort/snort_rules_flowbits.php new file mode 100644 index 00000000..0b836813 --- /dev/null +++ b/config/snort/snort_rules_flowbits.php @@ -0,0 +1,277 @@ +<?php +/* + * snort_rules_flowbits.php + * Copyright (C) 2004 Scott Ullrich + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * originially part of m0n0wall (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * modified for the pfsense snort package + * Copyright (C) 2009-2010 Robert Zelaya. + * 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("guiconfig.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +global $g, $flowbit_rules_file, $rebuild_rules; + +$snortdir = SNORTDIR; +$rules_map = array(); +$supplist = array(); + +if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + $config['installedpackages']['snortglobal']['rule'] = array(); +} +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; +} + +$if_real = snort_get_real_interface($a_nat[$id]['interface']); +$snort_uuid = $a_nat[$id]['uuid']; + +/* We should normally never get to this page if Auto-Flowbits are disabled, but just in case... */ +if ($a_nat[$id]['autoflowbitrules'] == 'on') { + if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}") && + filesize("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}") > 0) { + $rules_map = snort_load_rules_map("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}"); + } + else + $savemsg = "There are no flowbit-required rules necessary for the current enforcing rule set."; +} +else + $input_errors[] = "Auto-Flowbit rule generation is disabled for this interface!"; + +if ($_GET['act'] == "addsuppress" && is_numeric($_GET['sidid']) && is_numeric($_GET['gen_id'])) { + $descr = snort_get_msg($rules_map[$_GET['gen_id']][$_GET['sidid']]['rule']); + if (empty($descr)) + $suppress = "suppress gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']}\n"; + else + $suppress = "# {$descr}\nsuppress gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']}"; + if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + $config['installedpackages']['snortglobal']['suppress'] = array(); + if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + $config['installedpackages']['snortglobal']['suppress']['item'] = array(); + $a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; + + if (empty($a_nat[$id]['suppresslistname']) || $a_nat[$id]['suppresslistname'] == 'default') { + $s_list = array(); + $s_list['name'] = $a_nat[$id]['interface'] . "suppress"; + $s_list['uuid'] = uniqid(); + $s_list['descr'] = "Auto-generated list for alert suppression"; + $s_list['suppresspassthru'] = base64_encode($suppress); + $a_suppress[] = $s_list; + $a_nat[$id]['suppresslistname'] = $s_list['name']; + } else { + foreach ($a_suppress as $a_id => $alist) { + if ($alist['name'] == $a_nat[$id]['suppresslistname']) { + if (!empty($alist['suppresspassthru'])) { + $tmplist = base64_decode($alist['suppresspassthru']); + $tmplist .= "\n{$suppress}"; + $alist['suppresspassthru'] = base64_encode($tmplist); + $a_suppress[$a_id] = $alist; + } + } + } + } + write_config(); + $rebuild_rules = "off"; + sync_snort_package_config(); + $savemsg = "Wrote suppress rule for gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']} to the {$a_nat[$id]['suppresslistname']} Suppression List."; +} + +function truncate($string, $length) { + + /******************************** + * This function truncates the * + * passed string to the length * + * specified adding ellipsis if * + * truncation was necessary. * + ********************************/ + if (strlen($string) > $length) + $string = substr($string, 0, ($length - 3)) . "..."; + return $string; +} + +/* Load up an array with the current Suppression List GID,SID values */ +$supplist = snort_load_suppress_sigs($a_nat[$id]); + +$if_friendly = snort_get_friendly_interface($a_nat[$id]['interface']); +$pgtitle = "Services: Snort: {$if_friendly} Flowbit Rules"; +include_once("head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC" > + +<?php +include("fbegin.inc"); +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} +if ($input_errors) print_input_errors($input_errors); +if ($savemsg) + print_info_box($savemsg); +?> +<form action="snort_rules_flowbits.php" method="post" name="iform" id="iform"> +<div id="mainarea"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> +<td class="tabcont"> +<table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td valign="middle" class="listtopic"><?php echo gettext("Auto-Generated Flowbit-Required Rules"); ?></td> + </tr> + <tr> + <td width="78%" class="vncell"> + <?php echo gettext("The rules listed below are required to be included in the rules set ") . + gettext("because they set flowbits that are checked and relied upon by rules in the enforcing rules set. ") . + gettext("If these dependent flowbits are not set, then some of your chosen rules may not fire. ") . + gettext("Enabling all the rules that set these dependent flowbits ensures your chosen rules fire as intended. ") . + gettext("Most flowbits rules contain the \"noalert\" keyword to prevent an alert from firing ") . + gettext("when the flowbit is detected. For those flowbit rules that do not contain the \"noalert\" option, click the ") . + gettext("icon displayed beside the Signature ID (SID) to add the alert to the Suppression List if desired."); ?></td> + </tr> + <tr> + <td valign="middle" class="listtopic"><?php echo gettext("Flowbit-Required Rules for {$if_friendly}"); ?></td> + </tr> + <tr> + <td width="78%" class="vncell"> + <table width="100%" border="0 cellspacing="2" cellpadding="0"> + <tr> + <td width="17px"><img src="../themes/<?=$g['theme']?>/images/icons/icon_plus.gif" width='12' height='12' border='0'/></td> + <td><span class="vexpl"><?php echo gettext("Alert is Not Suppressed"); ?></span></td> + <td rowspan="3" align="right"><input id="cancelbutton" name="cancelbutton" type="button" class="formbtn" onclick="history.back()" <?php + echo "value=\"" . gettext("Return") . "\" title=\"" . gettext("Return to previous page") . "\""; ?>/></td> + </tr> + <tr> + <td width="17px"><img src="../themes/<?=$g['theme']?>/images/icons/icon_plus_d.gif" width='12' height='12' border='0'/></td> + <td><span class="vexpl"><?php echo gettext("Alert has been Suppressed"); ?></span></td> + </tr> + <tr> + <td width="17px"> </td> + <td colspan="2" class="vexpl"><?php echo "<span class=\"red\"><strong>" . + gettext("Note: ") . "</strong></span>". gettext("the icon is only ") . + gettext("displayed for flowbit rules without the \"noalert\" option."); ?></td> + </tr> + </table> + </td> + </tr> + <tr> + <td> + <table id="myTable" width="100%" class="sortable" border="1" cellpadding="0" cellspacing="0"> + <colgroup> + <col width="11%" axis="number"> + <col width="10%" axis="string"> + <col width="14%" axis="string"> + <col width="14%" axis="string"> + <col width="20%" axis="string"> + <col axis="string"> + </colgroup> + <thead> + <th class="listhdrr" axis="number"><?php echo gettext("SID"); ?></th> + <td class="listhdrr" axis="string"><?php echo gettext("Proto"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("Source"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("Destination"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("Flowbits"); ?></th> + <th class="listhdrr" axis="string"><?php echo gettext("Message"); ?></th> + <thead> + <tbody> + <?php + $count = 0; + foreach ($rules_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + $sid = snort_get_sid($v['rule']); + $gid = snort_get_gid($v['rule']); + + // Pick off the first section of the rule (prior to the start of the MSG field), + // and then use a REGX split to isolate the remaining fields into an array. + $tmp = substr($v['rule'], 0, strpos($v['rule'], "(")); + $tmp = trim(preg_replace('/^\s*#+\s*/', '', $tmp)); + $rule_content = preg_split('/[\s]+/', $tmp); + + $protocol = $rule_content[1]; //protocol + $source = truncate($rule_content[2], 14); //source + $destination = truncate($rule_content[5], 14); //destination + $message = snort_get_msg($v['rule']); + $flowbits = implode("; ", snort_get_flowbits($v['rule'])); + if (strstr($flowbits, "noalert")) + $supplink = ""; + else { + if (!isset($supplist[$gid][$sid])) { + $supplink = "<a href=\"?id={$id}&act=addsuppress&sidid={$sid}&gen_id={$gid}\">"; + $supplink .= "<img src=\"../themes/{$g['theme']}/images/icons/icon_plus.gif\""; + $supplink .= "width='12' height='12' border='0' title='"; + $supplink .= gettext("Click to add to Suppress List") . "'/></a>"; + } + else { + $supplink .= "<img src=\"../themes/{$g['theme']}/images/icons/icon_plus_d.gif\""; + $supplink .= "width='12' height='12' border='0' title='"; + $supplink .= gettext("Alert has been suppressed") . "'/>"; + } + } + + // Use "echo" to write the table HTML row-by-row. + echo "<tr>" . + "<td class=\"listr\">{$sid} {$supplink}</td>" . + "<td class=\"listr\">{$protocol}</td>" . + "<td class=\"listr\"><span title=\"{$rule_content[2]}\">{$source}</span></td>" . + "<td class=\"listr\"><span title=\"{$rule_content[5]}\">{$destination}</span></td>" . + "<td class=\"listr\" style=\"word-wrap:break-word; word-break:normal;\">{$flowbits}</td>" . + "<td class=\"listr\" style=\"word-wrap:break-word; word-break:normal;\">{$message}</td>" . + "</tr>"; + $count++; + } + } + unset($rulem, $v); + ?> + </tbody> + </table> + </td> + </tr> + <?php if ($count > 20): ?> + <tr> + <td align="center" valign="middle"> + <input id="cancelbutton" name="cancelbutton" type="button" class="formbtn" onclick="history.back()" <?php + echo "value=\"" . gettext("Return") . "\" title=\"" . gettext("Return to previous page") . "\""; ?>/> + <input name="id" type="hidden" value="<?=$id;?>" /> + </td> + </tr> + <?php endif; ?> +</table> +</td> +</tr> +</table> +</div> +</form> +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/snort/snort_rulesets.php b/config/snort/snort_rulesets.php index 23a24bea..fce1616b 100755 --- a/config/snort/snort_rulesets.php +++ b/config/snort/snort_rulesets.php @@ -32,7 +32,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g, $flowbit_rules_file; +global $g, $flowbit_rules_file, $rebuild_rules; $snortdir = SNORTDIR; @@ -62,13 +62,30 @@ $if_real = snort_get_real_interface($pconfig['interface']); $snort_uuid = $a_nat[$id]['uuid']; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingdownload = $config['installedpackages']['snortglobal']['emergingthreats']; +$snortcommunitydownload = $config['installedpackages']['snortglobal']['snortcommunityrules']; + +$no_emerging_files = false; +$no_snort_files = false; +$no_community_files = false; + +/* Test rule categories currently downloaded to $SNORTDIR/rules and set appropriate flags */ +$test = glob("{$snortdir}/rules/emerging-*.rules"); +if (empty($test)) + $no_emerging_files = true; +$test = glob("{$snortdir}/rules/snort_*.rules"); +if (empty($test)) + $no_snort_files = true; +if (!file_exists("{$snortdir}/rules/GPLv2_community.rules")) + $no_community_files = true; if (($snortdownload == 'off') || ($a_nat[$id]['ips_policy_enable'] != 'on')) $policy_select_disable = "disabled"; if ($a_nat[$id]['autoflowbitrules'] == 'on') { - if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}")) - $btn_view_flowb_rules = ""; + if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}") && + filesize("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}") > 0) { + $btn_view_flowb_rules = " title=\"" . gettext("View flowbit-required rules") . "\""; + } else $btn_view_flowb_rules = " disabled"; } @@ -119,7 +136,14 @@ if ($_POST["Submit"]) { } write_config(); - sync_snort_package_config(); + + /*************************************************/ + /* Update the snort conf file and rebuild the */ + /* rules for this interface. */ + /*************************************************/ + $rebuild_rules = "on"; + snort_generate_conf($a_nat[$id]); + $rebuild_rules = "off"; header("Location: /snort/snort_rulesets.php?id=$id"); exit; @@ -142,6 +166,11 @@ if ($_POST['selectall']) { foreach ($files as $file) $rulesets[] = basename($file); } + if ($snortcommunitydownload == 'on') { + $files = glob("{$snortdir}/rules/sc_*.rules"); + foreach ($files as $file) + $rulesets[] = basename($file); + } if ($snortdownload == 'on') { $files = glob("{$snortdir}/rules/snort*.rules"); foreach ($files as $file) @@ -193,6 +222,22 @@ function popup(url) if (window.focus) {newwin.focus()} return false; } + +function wopen(url, name, w, h) +{ +// Fudge factors for window decoration space. +// In my tests these work well on all platforms & browsers. +w += 32; +h += 96; + var win = window.open(url, + name, + 'width=' + w + ', height=' + h + ', ' + + 'location=no, menubar=no, ' + + 'status=no, toolbar=no, scrollbars=yes, resizable=yes'); + win.resizeTo(w, h); + win.focus(); +} + function enable_change() { var endis = !(document.iform.ips_policy_enable.checked); @@ -210,18 +255,30 @@ function enable_change() <form action="snort_rulesets.php" method="post" name="iform" id="iform"> <input type="hidden" name="id" id="id" value="<?=$id;?>" /> -<table width="99%" border="0" cellpadding="0" cellspacing="0"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> -<?php - $tab_array = array(); - $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tab_array[] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); - $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); - $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); - display_top_tabs($tab_array); +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array); + echo '</td></tr>'; + echo '<tr><td class="tabnavtbl">'; + $menu_iface=($if_friendly?substr($if_friendly,0,5)." ":"Iface "); + $tab_array = array(); + $tab_array[] = array($menu_iface . gettext("Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); ?> </td></tr> <tr> @@ -233,12 +290,15 @@ function enable_change() $iscfgdirempty = array(); if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/custom.rules")) $iscfgdirempty = (array)("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/custom.rules"); - if (empty($isrulesfolderempty) && empty($iscfgdirempty)): + if (empty($isrulesfolderempty)): ?> <tr> - <td> - <?php printf(gettext("# The rules directory is empty. %s/rules"), $snortdir); ?> <br/> - <?php echo gettext("Please go to the Updates tab to download/fetch the rules configured."); ?> + <td class="vexpl"><br/> + <?php printf(gettext("# The rules directory is empty: %s%s/rules%s"), '<strong>',$snortdir,'</strong>'); ?> <br/><br/> + <?php echo gettext("Please go to the ") . '<a href="snort_download_updates.php"><strong>' . gettext("Updates") . + '</strong></a>' . gettext(" tab to download the rules configured on the ") . + '<a href="snort_interfaces_global.php"><strong>' . gettext("Global") . + '</strong></a>' . gettext(" tab."); ?> </td> </tr> <?php else: @@ -251,35 +311,38 @@ function enable_change() ?> <tr> <td> - <table id="sortabletable1" class="sortable" width="100%" border="0" + <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td colspan="6" class="listtopic"><?php echo gettext("Automatic flowbit resolution"); ?><br/></td> </tr> <tr> <td colspan="6" valign="center" class="listn"> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <table width="100%" border="0" cellpadding="2" cellspacing="2"> <tr> <td width="15%" class="listn"><?php echo gettext("Resolve Flowbits"); ?></td> - <td width="85%"><input name="autoflowbits" id="autoflowbitrules" type="checkbox" value="on" <?php if ($a_nat[$id]['autoflowbitrules'] == "on") echo "checked"; ?>/></td> + <td width="85%"><input name="autoflowbits" id="autoflowbitrules" type="checkbox" value="on" + <?php if ($a_nat[$id]['autoflowbitrules'] == "on" || empty($a_nat[$id]['autoflowbitrules'])) echo "checked"; ?>/> + <span class="vexpl"><?php echo gettext("If checked, Snort will auto-enable rules required for checked flowbits. "); + echo gettext("The Default is "); ?><strong><?php echo gettext("Checked."); ?></strong></span></td> </tr> <tr> <td width="15%" class="vncell"> </td> <td width="85%" class="vtable"> - <?php echo gettext("If ticked, Snort will examine the enabled rules in your chosen " . + <?php echo gettext("Snort will examine the enabled rules in your chosen " . "rule categories for checked flowbits. Any rules that set these dependent flowbits will " . - "be automatically enabled and added to the list of files in the interface rules directory."); ?><br/><br/></td> + "be automatically enabled and added to the list of files in the interface rules directory."); ?><br/></td> </tr> <tr> <td width="15%" class="listn"><?php echo gettext("Auto Flowbit Rules"); ?></td> - <td width="85%"><input type="button" class="formbtn" value="View" onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$flowbit_rules_file;?>')" <?php echo $btn_view_flowb_rules; ?>/></td> + <td width="85%"><input type="button" class="formbtns" value="View" onclick="parent.location='snort_rules_flowbits.php?id=<?=$id;?>'" <?php echo $btn_view_flowb_rules; ?>/> + <span class="vexpl"><?php echo gettext("Click to view auto-enabled rules required to satisfy flowbit dependencies"); ?></span></td> </tr> <tr> <td width="15%"> </td> <td width="85%"> - <?php echo gettext("Click to view auto-enabled rules required to satisfy flowbit " . - "dependencies from the selected rule categories below. Auto-enabled rules generating unwanted alerts " . - "should have their GID:SID added to the Suppression List for the interface."); ?><br/><br/></td> + <?php printf(gettext("%sNote: %sAuto-enabled rules generating unwanted alerts should have their GID:SID added to the Suppression List for the interface."), '<span class="red"><strong>', '</strong></span>'); ?> + <br/></td> </tr> </table> </td> @@ -289,20 +352,20 @@ function enable_change() </tr> <tr> <td colspan="6" valign="center" class="listn"> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <table width="100%" border="0" cellpadding="2" cellspacing="2"> <tr> <td width="15%" class="listn"><?php echo gettext("Use IPS Policy"); ?></td> <td width="85%"><input name="ips_policy_enable" id="ips_policy_enable" type="checkbox" value="on" <?php if ($a_nat[$id]['ips_policy_enable'] == "on") echo "checked"; ?> - <?php if ($snortdownload == "off") echo "disabled" ?> onClick="enable_change()"/></td> + <?php if ($snortdownload == "off") echo "disabled" ?> onClick="enable_change()"/> <span class="vexpl"> + <?php echo gettext("If checked, Snort will use rules from the pre-defined IPS policy selected below."); ?></span></td> </tr> <tr> <td width="15%" class="vncell"> </td> <td width="85%" class="vtable"> - <?php echo gettext("If ticked, Snort will use rules from the pre-defined IPS policy " . - "selected below. You must be using the Snort VRT rules to use this option."); ?><br/> + <?php printf(gettext("%sNote:%s You must be using the Snort VRT rules to use this option."),'<span class="red"><strong>','</strong></span>'); ?> <?php echo gettext("Selecting this option disables manual selection of Snort VRT categories in the list below, " . "although Emerging Threats categories may still be selected if enabled on the Global Settings tab. " . - "These will be added to the pre-defined Snort IPS policy rules from the Snort VRT."); ?><br><br/></td> + "These will be added to the pre-defined Snort IPS policy rules from the Snort VRT."); ?><br/></td> </tr> <tr> <td width="15%" class="listn"><?php echo gettext("IPS Policy"); ?></td> @@ -311,43 +374,83 @@ function enable_change() <option value="balanced" <?php if ($pconfig['ips_policy'] == "balanced") echo "selected"; ?>><?php echo gettext("Balanced"); ?></option> <option value="security" <?php if ($pconfig['ips_policy'] == "security") echo "selected"; ?>><?php echo gettext("Security"); ?></option> </select> - </td> + <span class="vexpl"><?php echo gettext("Snort IPS policies are: Connectivity, Balanced or Security."); ?></span></td> </tr> <tr> <td width="15%"> </td> <td width="85%"> - <?php echo gettext("Snort IPS policies are: Connectivity, Balanced or Security. " . - "Connectivity blocks most major threats with few or no false positives. Balanced is a good starter policy. It " . - "is speedy, has good base coverage level, and covers most threats of the day. It includes all rules in Connectivity. " . - "Security is a stringent policy. It contains everything in the first two plus policy-type rules such as Flash in an Excel file."); ?><br/><br/></td> + <?php echo gettext("Connectivity blocks most major threats with few or no false positives. " . + "Balanced is a good starter policy. It is speedy, has good base coverage level, and covers " . + "most threats of the day. It includes all rules in Connectivity." . + "Security is a stringent policy. It contains everything in the first two " . + "plus policy-type rules such as Flash in an Excel file."); ?><br/></td> </tr> </table> </td> </tr> <tr> - <td colspan="6" class="listtopic"><?php echo gettext("Check the rulesets that you would like Snort to load at startup."); ?><br/></td> + <td colspan="6" class="listtopic"><?php echo gettext("Select the rulesets you would like Snort to load at startup"); ?><br/></td> + </tr> + <tr> + <td colspan="6"> + <table width=90% align="center" border="0" cellpadding="2" cellspacing="0"> + <tr height="45px"> + <td valign="middle"><input value="Select All" class="formbtns" type="submit" name="selectall" id="selectall" title="<?php echo gettext("Add all to enforcing rules"); ?>"/></td> + <td valign="middle"><input value="Unselect All" class="formbtns" type="submit" name="unselectall" id="unselectall" title="<?php echo gettext("Remove all from enforcing rules"); ?>"/></td> + <td valign="middle"><input value=" Save " class="formbtns" type="submit" name="Submit" id="Submit" title="<?php echo gettext("Save changes to enforcing rules and rebuild"); ?>"/></td> + <td valign="middle"><span class="vexpl"><?php echo gettext("Click to save changes and auto-resolve flowbit rules (if option is selected above)"); ?></span></td> + </tr> + </table> + </tr> + <?php if ($no_community_files) + $msg_community = "NOTE: Snort Community Rules have not been downloaded. Perform a Rules Update to enable them."; + else + $msg_community = "Snort GPLv2 Community Rules (VRT certified)"; + ?> + <?php if ($snortcommunitydownload == 'on'): ?> + <tr id="frheader"> + <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> + <td colspan="5" class="listhdrr"><?php echo gettext('Ruleset: Snort GPLv2 Community Rules');?></td> + </tr> + <?php if (in_array("GPLv2_community.rules", $enabled_rulesets_array)): ?> + <tr> + <td width="5" class="listr" align="center" valign="top"> + <input type="checkbox" name="toenable[]" value="GPLv2_community.rules" checked="checked"/></td> + <td colspan="5" class="listr"><a href='snort_rules.php?id=<?=$id;?>&openruleset=GPLv2_community.rules'><?php echo gettext("{$msg_community}"); ?></a></td> </tr> + <?php else: ?> <tr> - <td colspan="1" align="middle" valign="center"><br/><input value="Select All" type="submit" name="selectall" id="selectall" /><br/></td> - <td colspan="1" align="middle" valign="center"><br/><input value="Unselect All" type="submit" name="unselectall" id="selectall" /><br/></td> - <td colspan="1" align="middle" valign="center"><br/><input value="Save" class="formbtn" type="submit" name="Submit" id="Submit" /></td> - <td colspan="3" valign="center"><?php echo gettext("Click to save changes and auto-resolve flowbit rules (if option is selected above)"); ?><br/></td> + <td width="5" class="listr" align="center" valign="top"> + <input type="checkbox" name="toenable[]" value="GPLv2_community.rules" <?php if ($snortcommunitydownload == 'off') echo "disabled"; ?>/></td> + <td colspan="5" class="listr"><?php echo gettext("{$msg_community}"); ?></td> </tr> - <tr> <td colspan="6"> </td> </tr> + + <?php endif; ?> + <?php endif; ?> + + <?php if ($no_emerging_files) + $msg_emerging = "downloaded."; + else + $msg_emerging = "enabled."; + if ($no_snort_files) + $msg_snort = "downloaded."; + else + $msg_snort = "enabled."; + ?> <tr id="frheader"> - <?php if ($emergingdownload == 'on'): ?> - <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> + <?php if ($emergingdownload == 'on' && !$no_emerging_files): ?> + <td width="5%" class="listhdrr" align="center"><?php echo gettext("Enabled"); ?></td> <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Emerging Threats');?></td> <?php else: ?> - <td colspan="2" width="30%" class="listhdrr"><?php echo gettext("Emerging rules have not been enabled"); ?></td> + <td colspan="2" align="center" width="30%" class="listhdrr"><?php echo gettext("Emerging Threats rules not {$msg_emerging}"); ?></td> <?php endif; ?> - <?php if ($snortdownload == 'on'): ?> - <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> - <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort');?></td> - <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> - <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort SO');?></td> + <?php if ($snortdownload == 'on' && !$no_snort_files): ?> + <td width="5%" class="listhdrr" align="center"><?php echo gettext("Enabled"); ?></td> + <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort Text Rules');?></td> + <td width="5%" class="listhdrr" align="center"><?php echo gettext("Enabled"); ?></td> + <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort SO Rules');?></td> <?php else: ?> - <td colspan="2" width="60%" class="listhdrr"><?php echo gettext("Snort rules have not been enabled"); ?></td> + <td colspan="4" align="center" width="60%" class="listhdrr"><?php echo gettext("Snort VRT rules have not been {$msg_snort}"); ?></td> <?php endif; ?> </tr> <?php @@ -451,11 +554,11 @@ function enable_change() </td> </tr> <tr> -<td colspan="6" class="vtable"> <br/></td> +<td colspan="6" class="vexpl"> <br/></td> </tr> <tr> - <td colspan="2" align="middle" valign="center"><br/><input value="Save" type="submit" name="Submit" id="Submit" class="formbtn" /></td> - <td colspan="4" valign="center"> <br><br/></td> + <td colspan="6" align="center" valign="middle"> + <input value="Save" type="submit" name="Submit" id="Submit" class="formbtn" title=" <?php echo gettext("Click to Save changes and rebuild rules"); ?>"/></td> </tr> <?php endif; ?> </table> diff --git a/config/snort/snort_sync.xml b/config/snort/snort_sync.xml new file mode 100755 index 00000000..14a13321 --- /dev/null +++ b/config/snort/snort_sync.xml @@ -0,0 +1,193 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> +<![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* +snortsync.xml +part of pfSense (http://www.pfSense.com) +Copyright (C) 2013 Marcello Coutinho +based on pfblocker_sync.xml +All rights reserved. + +Based on m0n0wall (http://m0n0.ch/wall) +Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. +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. +*/ +/* ========================================================================== */ +]]></copyright> + <description><![CDATA[Describe your package here]]></description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>snortsync</name> + <version>1.0</version> + <title>Snort: XMLRPC Sync (EXPERIMENTAL)</title> + <include_file>/usr/local/pkg/snort/snort.inc</include_file> + <tabs> + <tab> + <text>Snort Interfaces</text> + <url>/snort/snort_interfaces.php</url> + </tab> + <tab> + <text>Global Settings</text> + <url>/snort/snort_interfaces_global.php</url> + </tab> + <tab> + <text>Updates</text> + <url>/snort/snort_download_updates.php</url> + </tab> + <tab> + <text>Alerts</text> + <url>/snort/snort_alerts.php</url> + </tab> + <tab> + <text>Blocked</text> + <url>/snort/snort_blocked.php</url> + </tab> + <tab> + <text>Whitelists</text> + <url>/snort/snort_interfaces_whitelist.php</url> + </tab> + <tab> + <text>Suppress</text> + <url>/snort/snort_interfaces_suppress.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=snort/snort_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>Snort Package XMLRPC Sync Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable Sync</fielddescr> + <fieldname>varsynconchanges</fieldname> + <description><![CDATA[All changes will be synced with apply config to the IPs listed below if this option is checked.<br/><br/> + <b>Important:</b> While using "Sync to hosts defined below", only sync from host A to B, A to C but <b>do not</B> enable XMLRPC sync <b>to</b> A. This will result in a loop!]]></description> + <type>select</type> + <required/> + <default_value>disabled</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>XMLRPC Timeout</fielddescr> + <fieldname>varsynctimeout</fieldname> + <description><![CDATA[Timeout in seconds for the XMLRPC timeout. Default: 150]]></description> + <type>input</type> + <default_value>150</default_value> + <size>5</size> + </field> + + <field> + <fielddescr>Refresh Rule Sets</fielddescr> + <fieldname>vardownloadrules</fieldname> + <description><![CDATA[Ask target hosts to refresh rule sets files on each sync operation.<br/><br/> + During each Snort package sync operation, ask the target remote host to check for + a new set of posted rule sets files and refresh the local copies if necessary. The default is + to refresh the files if newer versions have been posted.<br/><br/> + <b>Note: </b>The sync process will wait for the rules download and rebuild to finish on the target remote host before returning.]]></description> + <type>select</type> + <default_value>yes</default_value> + <options> + <option><name>Signal target host to refresh rules files</name><value>yes</value></option> + <option><name>Do NOT ask target host to refresh rules files</name><value>no</value></option> + </options> + </field> + + <field> + <fielddescr>Replication Targets</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>Enable</fielddescr> + <fieldname>varsyncdestinenable</fieldname> + <description><![CDATA[Enable this host as a replication target]]></description> + <type>checkbox</type> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Protocol</fielddescr> + <fieldname>varsyncprotocol</fieldname> + <description><![CDATA[Choose the protocol of the destination host. Probably <b>http</b> or <b>https</b>]]></description> + <type>select</type> + <default_value>HTTP</default_value> + <options> + <option><name>HTTP</name><value>http</value></option> + <option><name>HTTPS</name><value>https</value></option> + </options> + </rowhelperfield> + <rowhelperfield> + <fielddescr>IP-Address</fielddescr> + <fieldname>varsyncipaddress</fieldname> + <description><![CDATA[IP Address of the destination host.]]></description> + <type>input</type> + <size>15</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Port</fielddescr> + <fieldname>varsyncport</fieldname> + <description><![CDATA[Choose the sync port of the destination host.]]></description> + <type>input</type> + <size>3</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Admin Password</fielddescr> + <fieldname>varsyncpassword</fieldname> + <description><![CDATA[Password of the user "admin" on the destination host.]]></description> + <type>password</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Start Snort</fielddescr> + <fieldname>varsyncsnortstart</fieldname> + <description><![CDATA[Start Snort on target host if not already running.]]></description> + <type>checkbox</type> + <value>ON</value> + </rowhelperfield> + </rowhelper> + </field> + <field> + <name>WARNING: This feature is considered experimental and not recommended for production use</name> + <type>listtopic</type> + </field> + </fields> + <custom_delete_php_command> + </custom_delete_php_command> + <custom_php_resync_config_command> + write_config();snort_sync_on_changes(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid/squid.inc b/config/squid/squid.inc index bd0c8634..34186407 100644 --- a/config/squid/squid.inc +++ b/config/squid/squid.inc @@ -295,7 +295,7 @@ function squid_before_form_general($pkg) { } $field = &$pkg['fields']['field'][$i]; - for ($i = 0; $i < count($values) - 1; $i++) + for ($i = 0; $i < count($values); $i++) $field['options']['option'][] = array('name' => $names[$i], 'value' => $values[$i]); } diff --git a/config/squid-reverse/proxy_monitor.sh b/config/squid3/31/proxy_monitor.sh index e69de29b..e69de29b 100644 --- a/config/squid-reverse/proxy_monitor.sh +++ b/config/squid3/31/proxy_monitor.sh diff --git a/config/squid-reverse/sqpmon.sh b/config/squid3/31/sqpmon.sh index 244b3b61..244b3b61 100644 --- a/config/squid-reverse/sqpmon.sh +++ b/config/squid3/31/sqpmon.sh diff --git a/config/squid-reverse/squid.inc b/config/squid3/31/squid.inc index fef9590c..0256d078 100644 --- a/config/squid-reverse/squid.inc +++ b/config/squid3/31/squid.inc @@ -5,7 +5,7 @@ Copyright (C) 2006-2009 Scott Ullrich Copyright (C) 2006 Fernando Lemos Copyright (C) 2012 Martin Fuchs - Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012-2013 Marcello Coutinho Copyright (C) 2013 Gekkenhuis All rights reserved. @@ -225,6 +225,20 @@ function squid_install_command() { $config['installedpackages']['squidnac']['config'][0]['blacklist'] = $settingsnac['blacklist']; } } + + if(! empty($settingsnac['block_user_agent'])) { + if(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'])) { + if(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']; + } + } /*Migrate reverse settings*/ if (is_array($config['installedpackages']['squidreverse'])){ @@ -1078,6 +1092,8 @@ EOD; 'banned_hosts' => 'src', 'whitelist' => 'dstdom_regex -i', 'blacklist' => 'dstdom_regex -i', + 'block_user_agent' => 'browser -i', + 'block_reply_mime_type' => 'rep_mime_type -i', ); foreach ($options as $option => $directive) { $contents = sq_text_area_decode($settings[$option]); @@ -1291,6 +1307,18 @@ function squid_resync_auth() { $conf .= "http_access deny blacklist\n"; } } + if(! empty($settingsnac['block_user_agent'])) { + if (squid_is_valid_acl('block_user_agent')) { + $conf .= "# Block access with user agents and browsers\n"; + $conf .= "http_access deny block_user_agent\n"; + } + } + if(! empty($settingsnac['block_reply_mime_type'])) { + if (squid_is_valid_acl('block_reply_mime_type')) { + $conf .= "# Block access with mime type in the reply\n"; + $conf .= "http_reply_access deny block_reply_mime_type\n"; + } + } $transparent_proxy = ($settingsconfig['transparent_proxy'] == 'on'); $auth_method = (($settings['auth_method'] && !$transparent_proxy) ? $settings['auth_method'] : 'none'); @@ -1823,27 +1851,54 @@ EOD; /* Uses XMLRPC to synchronize the changes to a remote node */ function squid_sync_on_changes() { global $config, $g; - - log_error("[squid] xmlrpc sync is starting."); - $synconchanges = $config['installedpackages']['squidsync']['config'][0]['synconchanges']; - if(!$synconchanges) - return; - foreach ($config['installedpackages']['squidsync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - $sync_to_ip = $sh['ipaddress']; - $password = $sh['password']; - if($sh['username']) - $username = $sh['username']; - else - $username = 'admin'; - if($password && $sync_to_ip) - squid_do_xmlrpc_sync($sync_to_ip, $username, $password); + if (is_array($config['installedpackages']['squidsync']['config'])){ + $squid_sync=$config['installedpackages']['squidsync']['config'][0]; + $synconchanges = $squid_sync['synconchanges']; + $synctimeout = $squid_sync['synctimeout']; + switch ($synconchanges){ + case "manual": + if (is_array($squid_sync[row])){ + $rs=$squid_sync[row]; + } + else{ + log_error("[squid] xmlrpc sync is enabled but there is no hosts to push on squid config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + } + else{ + log_error("[squid] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[squid] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($password && $sync_to_ip) + squid_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout); + } + log_error("[squid] xmlrpc sync is ending."); } - } - log_error("[squid] xmlrpc sync is ending."); + } } /* Do the actual XMLRPC sync */ -function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { +function squid_do_xmlrpc_sync($sync_to_ip, $username, $password, $synctimeout) { global $config, $g; if(!$username) @@ -1855,6 +1910,10 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { if(!$sync_to_ip) return; + if(!$synctimeout) + $synctimeout=250; + + $xmlrpc_sync_neighbor = $sync_to_ip; if($config['system']['webgui']['protocol'] != "") { $synchronizetoip = $config['system']['webgui']['protocol']; @@ -1897,15 +1956,15 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { $cli->setCredentials($username, $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 250 seconds */ - $resp = $cli->send($msg, "250"); + /* send our XMLRPC message and timeout after defined sync timeout value*/ + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "squid Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "squid Settings Sync", ""); @@ -1927,14 +1986,14 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); if(!$resp) { $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "squid Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, $synctimeout); $error = "An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "squid Settings Sync", ""); @@ -1943,5 +2002,4 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { } } - ?> diff --git a/config/squid-reverse/squid.xml b/config/squid3/31/squid.xml index bcfd5fb3..aa76c0f1 100644 --- a/config/squid-reverse/squid.xml +++ b/config/squid3/31/squid.xml @@ -111,112 +111,112 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid.inc</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse_general.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse_general.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse_peer.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse_peer.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse_uri.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse_uri.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse_sync.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse_sync.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_sync.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_sync.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_cache.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_cache.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_nac.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_nac.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_ng.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_ng.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_ng.inc</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_ng.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_traffic.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_traffic.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_upstream.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_upstream.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse.inc</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_auth.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_auth.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_users.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_users.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/sqpmon.sh</item> + <item>http://www.pfsense.org/packages/config/squid3/31/sqpmon.sh</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/swapstate_check.php</item> + <item>http://www.pfsense.org/packages/config/squid3/31/swapstate_check.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_reverse_redir.xml</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_reverse_redir.xml</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_monitor.php</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_monitor.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_monitor_data.php</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_monitor_data.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/</prefix> <chmod>0755</chmod> - <item>http://www.pfsense.org/packages/config/squid-reverse/squid_log_parser.php</item> + <item>http://www.pfsense.org/packages/config/squid3/31/squid_log_parser.php</item> </additional_files_needed> <fields> diff --git a/config/squid-reverse/squid_auth.inc b/config/squid3/31/squid_auth.inc index 7c99a01b..7c99a01b 100644 --- a/config/squid-reverse/squid_auth.inc +++ b/config/squid3/31/squid_auth.inc diff --git a/config/squid-reverse/squid_auth.xml b/config/squid3/31/squid_auth.xml index 307669c5..307669c5 100644 --- a/config/squid-reverse/squid_auth.xml +++ b/config/squid3/31/squid_auth.xml diff --git a/config/squid-reverse/squid_cache.xml b/config/squid3/31/squid_cache.xml index 7f371f49..7f371f49 100644 --- a/config/squid-reverse/squid_cache.xml +++ b/config/squid3/31/squid_cache.xml diff --git a/config/squid-reverse/squid_extauth.xml b/config/squid3/31/squid_extauth.xml index 41d9f633..41d9f633 100644 --- a/config/squid-reverse/squid_extauth.xml +++ b/config/squid3/31/squid_extauth.xml diff --git a/config/squid-reverse/squid_log_parser.php b/config/squid3/31/squid_log_parser.php index f6cd7de8..f6cd7de8 100755 --- a/config/squid-reverse/squid_log_parser.php +++ b/config/squid3/31/squid_log_parser.php diff --git a/config/squid-reverse/squid_monitor.php b/config/squid3/31/squid_monitor.php index 86c7d33a..86c7d33a 100644 --- a/config/squid-reverse/squid_monitor.php +++ b/config/squid3/31/squid_monitor.php diff --git a/config/squid-reverse/squid_monitor_data.php b/config/squid3/31/squid_monitor_data.php index 7e27919d..7e27919d 100644 --- a/config/squid-reverse/squid_monitor_data.php +++ b/config/squid3/31/squid_monitor_data.php diff --git a/config/squid-reverse/squid_nac.xml b/config/squid3/31/squid_nac.xml index bc4a278e..659d626f 100644 --- a/config/squid-reverse/squid_nac.xml +++ b/config/squid3/31/squid_nac.xml @@ -139,6 +139,24 @@ <encoding>base64</encoding> </field> <field> + <fielddescr>Block user agents</fielddescr> + <fieldname>block_user_agent</fieldname> + <description>Enter each user agent on a new line that will be blocked to the users that are allowed to use the proxy. You also can use regular expressions.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Block MIME types (reply only)</fielddescr> + <fieldname>block_reply_mime_type</fieldname> + <description>Enter each MIME type on a new line that will be blocked to the users that are allowed to use the proxy. You also can use regular expressions. Useful to block javascript (application/x-javascript).</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> <name>Squid Allowed ports</name> <type>listtopic</type> </field> diff --git a/config/squid-reverse/squid_ng.inc b/config/squid3/31/squid_ng.inc index 0e1e0515..0e1e0515 100644 --- a/config/squid-reverse/squid_ng.inc +++ b/config/squid3/31/squid_ng.inc diff --git a/config/squid-reverse/squid_ng.xml b/config/squid3/31/squid_ng.xml index 142536d6..142536d6 100644 --- a/config/squid-reverse/squid_ng.xml +++ b/config/squid3/31/squid_ng.xml diff --git a/config/squid-reverse/squid_reverse.inc b/config/squid3/31/squid_reverse.inc index eb2d4c73..eb2d4c73 100644 --- a/config/squid-reverse/squid_reverse.inc +++ b/config/squid3/31/squid_reverse.inc diff --git a/config/squid-reverse/squid_reverse.xml b/config/squid3/31/squid_reverse.xml index ce09f8e7..ce09f8e7 100644 --- a/config/squid-reverse/squid_reverse.xml +++ b/config/squid3/31/squid_reverse.xml diff --git a/config/squid-reverse/squid_reverse_general.xml b/config/squid3/31/squid_reverse_general.xml index 2211bb20..2211bb20 100644 --- a/config/squid-reverse/squid_reverse_general.xml +++ b/config/squid3/31/squid_reverse_general.xml diff --git a/config/squid-reverse/squid_reverse_peer.xml b/config/squid3/31/squid_reverse_peer.xml index abfbf19b..abfbf19b 100644 --- a/config/squid-reverse/squid_reverse_peer.xml +++ b/config/squid3/31/squid_reverse_peer.xml diff --git a/config/squid-reverse/squid_reverse_redir.xml b/config/squid3/31/squid_reverse_redir.xml index de25f56a..de25f56a 100644 --- a/config/squid-reverse/squid_reverse_redir.xml +++ b/config/squid3/31/squid_reverse_redir.xml diff --git a/config/squid-reverse/squid_reverse_sync.xml b/config/squid3/31/squid_reverse_sync.xml index db5e6145..041576b8 100755 --- a/config/squid-reverse/squid_reverse_sync.xml +++ b/config/squid3/31/squid_reverse_sync.xml @@ -9,7 +9,7 @@ /* squid_sync.xml part of the sarg package for pfSense - Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012-2013 Marcello Coutinho All rights reserved. */ /* ========================================================================== */ @@ -17,7 +17,7 @@ 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, + 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 @@ -80,8 +80,30 @@ <field> <fielddescr>Automatically sync squid configuration changes</fielddescr> <fieldname>synconchanges</fieldname> - <description>Automatically sync squid(normal and reverse) changes to the hosts defined below.</description> - <type>checkbox</type> + <description>Select a sync method for squid.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr>Remote Server</fielddescr> diff --git a/config/squid-reverse/squid_reverse_uri.xml b/config/squid3/31/squid_reverse_uri.xml index 1232cfe3..1232cfe3 100644 --- a/config/squid-reverse/squid_reverse_uri.xml +++ b/config/squid3/31/squid_reverse_uri.xml diff --git a/config/squid-reverse/squid_sync.xml b/config/squid3/31/squid_sync.xml index 62a726f4..cdd91e78 100755 --- a/config/squid-reverse/squid_sync.xml +++ b/config/squid3/31/squid_sync.xml @@ -9,7 +9,7 @@ /* squid_sync.xml part of the sarg package for pfSense - Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012-2013 Marcello Coutinho All rights reserved. */ /* ========================================================================== */ @@ -92,8 +92,30 @@ <field> <fielddescr>Automatically sync squid configuration changes</fielddescr> <fieldname>synconchanges</fieldname> - <description>Automatically sync squid(normal and reverse) changes to the hosts defined below.</description> - <type>checkbox</type> + <description>Select a sync method for squid.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> </field> <field> <fielddescr>Remote Server</fielddescr> diff --git a/config/squid-reverse/squid_traffic.xml b/config/squid3/31/squid_traffic.xml index 62269792..62269792 100644 --- a/config/squid-reverse/squid_traffic.xml +++ b/config/squid3/31/squid_traffic.xml diff --git a/config/squid-reverse/squid_upstream.xml b/config/squid3/31/squid_upstream.xml index 049d301c..049d301c 100644 --- a/config/squid-reverse/squid_upstream.xml +++ b/config/squid3/31/squid_upstream.xml diff --git a/config/squid-reverse/squid_users.xml b/config/squid3/31/squid_users.xml index 791a5fa9..791a5fa9 100644 --- a/config/squid-reverse/squid_users.xml +++ b/config/squid3/31/squid_users.xml diff --git a/config/squid-reverse/swapstate_check.php b/config/squid3/31/swapstate_check.php index 6ecfff3c..6ecfff3c 100644 --- a/config/squid-reverse/swapstate_check.php +++ b/config/squid3/31/swapstate_check.php diff --git a/config/squid3/33/sqpmon.sh b/config/squid3/33/sqpmon.sh new file mode 100644 index 00000000..244b3b61 --- /dev/null +++ b/config/squid3/33/sqpmon.sh @@ -0,0 +1,75 @@ +#!/bin/sh +# $Id$ */ +# +# sqpmon.sh +# Copyright (C) 2006 Scott Ullrich +# 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. +# + +if [ `pgrep -f "sqpmon.sh"|wc -l` -ge 1 ]; then + exit 0 +fi + +set -e + +LOOP_SLEEP=55 + +if [ -f /var/run/squid_alarm ]; then + rm /var/run/squid_alarm +fi + +# Sleep 5 seconds on startup not to mangle with existing boot scripts. +sleep 5 + +# Squid monitor 1.2 +while [ /bin/true ]; do + if [ ! -f /var/run/squid_alarm ]; then + NUM_PROCS=`ps auxw | grep "[s]quid -f"|awk '{print $2}'| wc -l | awk '{ print $1 }'` + if [ $NUM_PROCS -lt 1 ]; then + # squid is down + echo "Squid has exited. Reconfiguring filter." | \ + logger -p daemon.info -i -t Squid_Alarm + echo "Attempting restart..." | logger -p daemon.info -i -t Squid_Alarm + /usr/local/etc/rc.d/squid.sh start + sleep 3 + echo "Reconfiguring filter..." | logger -p daemon.info -i -t Squid_Alarm + /etc/rc.filter_configure + touch /var/run/squid_alarm + fi + fi + NUM_PROCS=`ps auxw | grep "[s]quid -f"|awk '{print $2}'| wc -l | awk '{ print $1 }'` + if [ $NUM_PROCS -gt 0 ]; then + if [ -f /var/run/squid_alarm ]; then + echo "Squid has resumed. Reconfiguring filter." | \ + logger -p daemon.info -i -t Squid_Alarm + /etc/rc.filter_configure + rm /var/run/squid_alarm + fi + fi + sleep $LOOP_SLEEP +done + +if [ -f /var/run/squid_alarm ]; then + rm /var/run/squid_alarm +fi diff --git a/config/squid3/33/squid.inc b/config/squid3/33/squid.inc new file mode 100755 index 00000000..1da86847 --- /dev/null +++ b/config/squid3/33/squid.inc @@ -0,0 +1,2353 @@ +<?php +/* $Id$ */ +/* + squid.inc + Copyright (C) 2006-2009 Scott Ullrich + Copyright (C) 2006 Fernando Lemos + Copyright (C) 2012 Martin Fuchs + Copyright (C) 2012-2013 Marcello Coutinho + Copyright (C) 2013 Gekkenhuis + 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('globals.inc'); +require_once('config.inc'); +require_once('util.inc'); +require_once('pfsense-utils.inc'); +require_once('pkg-utils.inc'); +require_once('service-utils.inc'); + +if(!function_exists("filter_configure")) + require_once("filter.inc"); + +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('SQUID_LOCALBASE', '/usr/pbi/squid-' . php_uname("m")); +else + define('SQUID_LOCALBASE','/usr/local'); + +define('SQUID_CONFBASE', SQUID_LOCALBASE .'/etc/squid'); +define('SQUID_CONFFILE', SQUID_CONFBASE . '/squid.conf'); +define('SQUID_BASE', '/var/squid/'); +define('SQUID_ACLDIR', '/var/squid/acl'); +define('SQUID_PASSWD', '/var/etc/squid.passwd'); +define('SQUID_LIB','/var/squid/lib'); +define('SQUID_SSL_DB','/var/squid/lib/ssl_db'); + +$valid_acls = array(); + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + + function sq_text_area_decode($text){ + return preg_replace('/\r\n/', "\n",base64_decode($text)); +} + + +function squid_get_real_interface_address($iface) { + global $config; + + $iface = convert_friendly_interface_to_real_interface_name($iface); + $line = trim(shell_exec("ifconfig $iface | grep inet | grep -v inet6")); + list($dummy, $ip, $dummy2, $netmask) = explode(" ", $line); + + return array($ip, long2ip(hexdec($netmask))); +} + +function squid_chown_recursive($dir, $user, $group) { + chown($dir, $user); + chgrp($dir, $group); + $handle = opendir($dir) ; + while (($item = readdir($handle)) !== false) { + if (($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); + } + } + } +} + +/* setup cache */ +function squid_dash_z() { + global $config; + + //Do nothing if there is no cache config + if (!is_array($config['installedpackages']['squidcache']['config'])) + return; + + $settings = $config['installedpackages']['squidcache']['config'][0]; + + // If the cache system is null, there is no need to initialize the (irrelevant) cache dir. + if ($settings['harddisk_cache_system'] == "null") + return; + + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + + if(!is_dir($cachedir.'/')) { + log_error("Creating Squid cache dir $cachedir"); + make_dirs($cachedir); + // Double check permissions here, should be safe to recurse cache dir if it's small here. + mwexec("/usr/sbin/chown -R proxy:proxy $cachedir"); + } + + if(!is_dir($cachedir.'/00/')) { + log_error("Creating squid cache subdirs in $cachedir"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -k shutdown -f " . SQUID_CONFFILE); + sleep(5); + mwexec(SQUID_LOCALBASE. "/sbin/squid -k kill -f " . SQUID_CONFFILE); + // Double check permissions here, should be safe to recurse cache dir if it's small here. + mwexec("/usr/sbin/chown -R proxy:proxy $cachedir"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -z -f " . SQUID_CONFFILE); + } + + if(file_exists("/var/squid/cache/swap.state")) { + chown("/var/squid/cache/swap.state", "proxy"); + chgrp("/var/squid/cache/swap.state", "proxy"); + exec("chmod a+rw /var/squid/cache/swap.state"); + } + +} + +function squid_is_valid_acl($acl) { + global $valid_acls; + if(!is_array($valid_acls)) + return; + return in_array($acl, $valid_acls); +} + +function squid_install_command() { + global $config; + global $g; + update_status("Checking if there is configuration to migrate... One moment please..."); + /* 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]; + + /* Set storage system */ + if ($g['platform'] == "nanobsd") { + $config['installedpackages']['squidcache']['config'][0]['harddisk_cache_system'] = 'null'; + } + + /* migrate auth settings */ + if (!empty($settingsauth['no_auth_hosts'])) { + if(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'])) { + if(strstr($settingscache['donotcache'], ",")) { + $settingscache['donotcache'] = base64_encode(implode("\n", explode(",", $settingscache['donotcache']))); + $config['installedpackages']['squidcache']['config'][0]['donotcache'] = $settingscache['donotcache']; + } + } + + /* migrate nac settings */ + if(! empty($settingsnac['allowed_subnets'])) { + if(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'])) { + if(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'])) { + if(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'])) { + if(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'])) { + if(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'])) { + if(strstr($settingsnac['whitelist'], ",")) { + $settingsnac['whitelist'] = base64_encode(implode("\n", explode(",", $settingsnac['whitelist']))); + $config['installedpackages']['squidnac']['config'][0]['whitelist'] = $settingsnac['whitelist']; + } + } + + if(! empty($settingsnac['blacklist'])) { + if(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'])) { + if(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'])) { + if(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']; + } + } + + /*Migrate reverse settings*/ + if (is_array($config['installedpackages']['squidreverse'])){ + $old_reverse_settings=$config['installedpackages']['squidreverse']['config'][0]; + + //Settings + if (!is_array($config['installedpackages']['squidreversegeneral'])){ + $config['installedpackages']['squidreversegeneral']['config'][0]=$old_reverse_settings; + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_cache_peer']); + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_uri']); + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_acl']); + } + + //PEERS + if (!is_array($config['installedpackages']['squidreversepeer'])){ + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_cache_peer'])) as $cache_peers) + foreach (explode(";",$cache_peers) as $cache_peer) + $config['installedpackages']['squidreversepeer']['config'][]=array('description'=>'migrated', + 'enable'=> 'on', + 'name'=> $cache_peer[0], + 'port'=> $cache_peer[1], + 'protocol' => $cache_peer[2]); + } + + //MAPPINGS + if (!is_array($config['installedpackages']['squidreverseuri'])){ + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_acl'])) as $acls){ + foreach (explode(";",$acls) as $acl) + array_push(${'peer_'.$acl[0]},$acl[1]); + } + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_uri'])) as $uris) + foreach (explode(";",$uris) as $uri){ + $peer_list=(is_array(${'peer_'.$uri[0]})?implode(",",${'peer_'.$uri[0]}):""); + $config['installedpackages']['squidreverseuri']['config'][]=array('description'=>'migrated', + 'enable'=> 'on', + 'name'=> $uri[0], + 'uri'=> $uri[1], + 'vhost' => $uri[2], + 'peers'=>$peer_list); + } + } + } + + update_status("Writing configuration... One moment please..."); + + write_config(); + + /* create cache */ + update_status("Creating squid cache pools... One moment please..."); + squid_dash_z(); + /* make sure pinger is executable */ + if(file_exists(SQUID_LOCALBASE. "/libexec/squid/pinger")) + exec("/bin/chmod a+x ". SQUID_LOCALBASE. "/libexec/squid/pinger"); + if(file_exists("/usr/local/etc/rc.d/squid")) + exec("/bin/rm /usr/local/etc/rc.d/squid"); + squid_write_rcfile(); + if(file_exists("/usr/local/pkg/swapstate_check.php")) + exec("/bin/chmod a+x /usr/local/pkg/swapstate_check.php"); + write_rcfile(array( + "file" => "sqp_monitor.sh", + "start" => "/usr/local/pkg/sqpmon.sh &", + "stop" => "ps awux | grep \"sqpmon\" | grep -v \"grep\" | grep -v \"php\" | awk '{ print $2 }' | xargs kill")); + + foreach (array( SQUID_CONFBASE, + SQUID_ACLDIR, + SQUID_BASE, + SQUID_LIB, + SQUID_SSL_DB ) as $dir) { + make_dirs($dir); + squid_chown_recursive($dir, 'proxy', 'proxy'); + } + + /* kill any running proxy alarm scripts */ + update_status("Checking for running processes... One moment please..."); + log_error("Stopping any running proxy monitors"); + mwexec("/usr/local/etc/rc.d/sqp_monitor.sh stop"); + sleep(1); + + if (!file_exists(SQUID_CONFBASE . '/mime.conf') && file_exists(SQUID_CONFBASE . '/mime.conf.default')) + copy(SQUID_CONFBASE . '/mime.conf.default', SQUID_CONFBASE . '/mime.conf'); + + update_status("Checking cache... One moment please..."); + squid_dash_z(); + + if (!is_service_running('squid')) { + update_status("Starting... One moment please..."); + log_error("Starting Squid"); + mwexec_bg(SQUID_LOCALBASE. "/sbin/squid -f " . SQUID_CONFFILE); + } else { + update_status("Reloading Squid for configuration sync... One moment please..."); + log_error("Reloading Squid for configuration sync"); + mwexec_bg(SQUID_LOCALBASE. "/sbin/squid -k reconfigure -f " . SQUID_CONFFILE); + } + + /* restart proxy alarm scripts */ + log_error("Starting a proxy monitor script"); + mwexec_bg("/usr/local/etc/rc.d/sqp_monitor.sh start"); + + update_status("Reconfiguring filter... One moment please..."); + filter_configure(); +} + +function squid_deinstall_command() { + global $config, $g; + $plswait_txt = "This operation may take quite some time, please be patient. Do not press stop or attempt to navigate away from this page during this process."; + squid_install_cron(false); + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); + update_status("Removing swap.state ... One moment please..."); + update_output_window("$plswait_txt"); + mwexec('rm -rf $cachedir/swap.state'); + mwexec('rm -rf $logdir'); + update_status("Finishing package cleanup."); + mwexec("/usr/local/etc/rc.d/sqp_monitor.sh stop"); + mwexec('rm -f /usr/local/etc/rc.d/sqp_monitor.sh'); + mwexec("ps awux | grep \"squid\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); + mwexec("ps awux | grep \"dnsserver\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); + mwexec("ps awux | grep \"unlinkd\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); + update_status("Reloading filter..."); + filter_configure(); +} + +function squid_before_form_general($pkg) { + $values = get_dir(SQUID_CONFBASE . '/errors/'); + // Get rid of '..' and '.' and ... + array_shift($values); + array_shift($values); + array_shift($values); + array_shift($values); + + $name = array(); + foreach ($values as $value) + $names[] = implode(" ", explode("_", $value)); + + $i = 0; + foreach ($pkg['fields']['field'] as $field) { + if ($field['fieldname'] == 'error_language') + break; + $i++; + } + $field = &$pkg['fields']['field'][$i]; + + for ($i = 0; $i < count($values) - 1; $i++) + $field['options']['option'][] = array('name' => $names[$i], 'value' => $values[$i]); +} + +function squid_validate_general($post, $input_errors) { + global $config; + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings = array(); + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + $port = $post['proxy_port'] ? $post['proxy_port'] : $port; + + $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'; + + if (substr($post['log_dir'], -1, 1) == '/') + $input_errors[] = 'You may not end log location with an / mark'; + + if ($post['log_dir']{0} != '/') + $input_errors[] = 'You must start log location with a / mark'; + if (strlen($post['log_dir']) <= 3) + $input_errors[] = "That is not a valid log location dir"; + + $log_rotate = trim($post['log_rotate']); + if (!empty($log_rotate) && (!is_numeric($log_rotate) or ($log_rotate < 1))) + + $input_errors[] = 'You must enter a valid number of days in the \'Log rotate\' field'; + + $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 webgui"; + } + + if (($post['ssl_proxy'] == 'on') && ( $post['dca'] == '')) { + $input_errors[] = "SSL interception cannot be enabled without a CA."; + } + + 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[] = "The entry '$host' is not a valid IP address, hostname, or alias"; + } + } + 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[] = "The entry '$host' is not a valid IP address, hostname, or alias"; + } + } + + 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; + }} +} + +function squid_validate_upstream($post, $input_errors) { + if ($post['enabled'] == 'on') { + $addr = trim($post['proxyaddr']); + if (empty($addr)) + $input_errors[] = 'The field \'Hostname\' 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 field '$name' is required"; + else { + if (!is_port($port)) + $input_errors[] = "The field '$name' must contain a valid port number, between 0 and 65535"; + } + } + } +} + +function squid_validate_cache($post, $input_errors) { + $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_numeric($value) || ($value < 0)) + $input_errors[] = "You must enter a valid value for '$field'"; + } + + $value = trim($post['minimum_object_size']); + if (!is_numeric($value) || ($value < 0)) + $input_errors[] = 'You must enter a valid value for \'Minimum object size\''; + + if (!empty($post['cache_swap_low'])) { + $value = trim($post['cache_swap_low']); + if (!is_numeric($value) || ($value > 100)) + $input_errors[] = 'You must enter a valid value for \'Low-water-mark\''; + } + + if (!empty($post['cache_swap_high'])) { + $value = trim($post['cache_swap_high']); + if (!is_numeric($value) || ($value > 100)) + $input_errors[] = 'You must enter a valid value for \'High-water-mark\''; + } + + 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 host name"; + } + } + + squid_dash_z(); + +} + +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)) + $input_errors[] = "The subnet '$subnet' is not a valid CIDR range"; + } + + 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[] = "The mac '$mac' is not a valid MAC address"; + } + } + + foreach (explode(",", $post['timelist']) as $time) { + $time = trim($time); + if (!empty($time) && !squid_is_timerange($time)) + $input_errors[] = "The time range '$time' is not a valid time range"; + } + + if(!empty($post['ext_cachemanager'])) { + $extmgr = explode(";", ($post['ext_cachemanager'])); + foreach ($extmgr as $mgr) { + if (!is_ipaddr($mgr)) + $input_errors[] = 'You must enter a valid IP address in the \'External Cache Manager\' field'; + }} +} + +function squid_validate_traffic($post, $input_errors) { + $num_fields = array( 'max_download_size' => 'Maximum download size', + 'max_upload_size' => 'Maximum upload size', + 'perhost_throttling' => 'Per-host bandwidth throttling', + 'overall_throttling' => 'Overall bandwidth throttling', + ); + foreach ($num_fields as $field => $name) { + $value = trim($post[$field]); + if (!is_numeric($value) || ($value < 0)) + $input_errors[] = "The field '$name' must contain a positive number"; + } + + if (!empty($post['quick_abort_min'])) { + $value = trim($post['quick_abort_min']); + if (!is_numeric($value)) + $input_errors[] = "The field 'Finish when remaining KB' must contain a positive number"; + } + + if (!empty($post['quick_abort_max'])) { + $value = trim($post['quick_abort_max']); + if (!is_numeric($value)) + $input_errors[] = "The field 'Abort when remaining KB' must contain a positive number"; + } + + if (!empty($post['quick_abort_pct'])) { + $value = trim($post['quick_abort_pct']); + if (!is_numeric($value) || ($value > 100)) + $input_errors[] = "The field 'Finish when remaining %' must contain a percentage"; + } +} + +function squid_validate_reverse($post, $input_errors) { + + if(!empty($post['reverse_ip'])) { + $reverse_ip = explode(";", ($post['reverse_ip'])); + foreach ($reverse_ip as $reip) { + if (!is_ipaddr($reip)) + $input_errors[] = 'You must enter a valid IP address in the \'User-defined reverse-proxy IPs\' field'; + break; + }} + + $fqdn = trim($post['reverse_external_fqdn']); + if (!empty($fqdn) && !is_domain($fqdn)) + $input_errors[] = 'The field \'external FQDN\' must contain a valid domain name'; + + $port = trim($post['reverse_http_port']); + if (!empty($port) && !is_port($port)) + $input_errors[] = 'The field \'reverse HTTP port\' must contain a valid port number'; + + $port = trim($post['reverse_https_port']); + if (!empty($port) && !is_port($port)) + $input_errors[] = 'The field \'reverse HTTPS port\' must contain a valid port number'; + + if ($post['reverse_ssl_cert'] == 'none') + $input_errors[] = 'A valid certificate for the external interface must be selected'; + + if (($post['reverse_https'] != 'on') && ($post['reverse_owa'] == 'on')) { + $input_errors[] = "You have to enable reverse HTTPS before enabling OWA support."; + } + +/* + if (!is_cert($post['reverse_int_ca'])) + $input_errors[] = 'A valid certificate for the external interface must be selected'; +*/ + + $rowa = trim($post['reverse_owa_ip']); + if (!empty($rowa) && !is_ipaddr($rowa)) + $input_errors[] = 'The field \'OWA frontend IP address\' must contain a valid IP address'; + + + $contents = $post['reverse_cache_peer']; + if(!empty($contents)) { + $defs = explode("\r\n", ($contents)); + foreach ($defs as $def) { + $cfg = explode(";",($def)); + if (!is_ipaddr($cfg[1])) + $input_errors[] = "please choose a valid IP in the cache peer configuration."; + if (!is_port($cfg[2])) + $input_errors[] = "please choose a valid port in the cache peer configuration."; + if (($cfg[3] != 'HTTPS') && ($cfg[3] != 'HTTP')) + $input_errors[] = "please choose HTTP or HTTPS in the cache peer configuration."; + }} + + +} + +function squid_validate_auth($post, $input_errors) { + $num_fields = array( array('auth_processes', 'Authentication processes', 1), + array('auth_ttl', 'Authentication TTL', 0), + ); + foreach ($num_fields as $field) { + $value = trim($post[$field[0]]); + if (!empty($value) && (!is_numeric($value) || ($value < $field[2]))) + $input_errors[] = "The field '{$field[1]}' must contain a valid number greater than {$field[2]}"; + } + + $auth_method = $post['auth_method']; + if (($auth_method != 'none') && ($auth_method != 'local')) { + $server = trim($post['auth_server']); + if (empty($server)) + $input_errors[] = 'The field \'Authentication server\' is required'; + else if (!is_ipaddr($server) && !is_domain($server)) + $input_errors[] = 'The field \'Authentication server\' must contain a valid IP address or domain name'; + + $port = trim($post['auth_server_port']); + if (!empty($port) && !is_port($port)) + $input_errors[] = 'The field \'Authentication server port\' must contain a valid port number'; + + switch ($auth_method) { + case 'ldap': + $user = trim($post['ldap_user']); + if (empty($user)) + $input_errors[] = 'The field \'LDAP server user DN\' is required'; + else if (!$user) + $input_errors[] = 'The field \'LDAP server user DN\' must be a valid domain name'; + break; + case 'radius': + $secret = trim($post['radius_secret']); + if (empty($secret)) + $input_errors[] = 'The field \'RADIUS secret\' is required'; + break; + case 'msnt': + foreach (explode(",", trim($post['msnt_secondary'])) as $server) { + if (!empty($server) && !is_ipaddr($server) && !is_domain($server)) + $input_errors[] = "The host '$server' is not a valid IP address or domain name"; + } + break; + } + + $no_auth = explode("\n", $post['no_auth_hosts']); + foreach ($no_auth as $host) { + $host = trim($host); + if (!empty($host) && !is_subnet($host)) + $input_errors[] = "The host '$host' is not a valid CIDR range"; + } + } +} + +function squid_install_cron($should_install) { + global $config, $g; + if($g['booting']==true) + return; + $rotate_is_installed = false; + $swapstate_is_installed = false; + + if(!$config['cron']['item']) + return; + + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + + $x=0; + $rotate_job_id=-1; + $swapstate_job_id=-1; + foreach($config['cron']['item'] as $item) { + if(strstr($item['task_name'], "squid_rotate_logs")) { + $rotate_job_id = $x; + } elseif(strstr($item['task_name'], "squid_check_swapstate")) { + $swapstate_job_id = $x; + } + $x++; + } + $need_write = false; + switch($should_install) { + case true: + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + if($rotate_job_id < 0) { + $cron_item = array(); + $cron_item['task_name'] = "squid_rotate_logs"; + $cron_item['minute'] = "0"; + $cron_item['hour'] = "0"; + $cron_item['mday'] = "*"; + $cron_item['month'] = "*"; + $cron_item['wday'] = "*"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; ". SQUID_LOCALBASE."/sbin/squid -k rotate -f " . SQUID_CONFFILE; + /* Add this cron_item as a new entry at the end of the item array. */ + $config['cron']['item'][] = $cron_item; + $need_write = true; + } + if($swapstate_job_id < 0) { + $cron_item = array(); + $cron_item['task_name'] = "squid_check_swapstate"; + $cron_item['minute'] = "*/15"; + $cron_item['hour'] = "*"; + $cron_item['mday'] = "*"; + $cron_item['month'] = "*"; + $cron_item['wday'] = "*"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/local/pkg/swapstate_check.php"; + /* Add this cron_item as a new entry at the end of the item array. */ + $config['cron']['item'][] = $cron_item; + $need_write = true; + } + if ($need_write) { + parse_config(true); + write_config("Adding Squid Cron Jobs"); + } + break; + case false: + if($rotate_job_id >= 0) { + unset($config['cron']['item'][$rotate_job_id]); + $need_write = true; + } + if($swapstate_job_id >= 0) { + unset($config['cron']['item'][$swapstate_job_id]); + $need_write = true; + } + if ($need_write) { + parse_config(true); + write_config("Removing Squid Cron Jobs"); + } + break; + } + configure_cron(); +} + +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("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; + } + } + } +} + +function squid_resync_general() { + global $g, $config, $valid_acls; + + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings=array(); + $conf = "# This file is automatically generated by pfSense\n"; + $conf .= "# Do not edit manually !\n\n"; + #Check ssl interception + if (($settings['ssl_proxy'] == 'on')) { + squid_check_ca_hashes(); + $srv_cert = lookup_ca($settings["dca"]); + if ($srv_cert != false) { + if(base64_decode($srv_cert['prv'])) { + #check if ssl_db was initilized by squid + if (! file_exists("/var/squid/lib/ssl_db/serial")){ + if (is_dir("/var/squid/lib/ssl_db")){ + mwexec("/bin/rm -rf /var/squid/lib/ssl_db"); + } + mwexec(SQUID_LOCALBASE."/libexec/squid/ssl_crtd -c -s /var/squid/lib/ssl_db/"); + } + #force squid user permission on /var/squid/lib/ssl_db/ + squid_chown_recursive("/var/squid/lib/ssl_db/", 'proxy', 'proxy'); + # cert, key, version, cipher,options, clientca, cafile, capath, crlfile, dhparams,sslflags, and sslcontext + $crt_pk=SQUID_CONFBASE."/serverkey.pem"; + $crt_capath=SQUID_LOCALBASE."/share/certs/"; + file_put_contents($crt_pk,base64_decode($srv_cert['prv']).base64_decode($srv_cert['crt'])); + $sslcrtd_children= ($settings['sslcrtd_children'] ? $settings['sslcrtd_children'] : 5); + $ssl_interception.="ssl-bump generate-host-certificates=on dynamic_cert_mem_cache_size=".($sslcrtd_children*2)."MB cert={$crt_pk} capath={$crt_capath}\n"; + $interception_checks = "sslcrtd_program ".SQUID_LOCALBASE."/libexec/squid/ssl_crtd -s /var/squid/lib/ssl_db -M 4MB -b 2048\n"; + $interception_checks .= "sslcrtd_children {$sslcrtd_children}\n"; + $interception_checks .= "sslproxy_capath {$crt_capath}\n"; + if (preg_match("/sslproxy_cert_error/",$settings["interception_checks"])) + $interception_checks.="sslproxy_cert_error allow all\n"; + if (preg_match("/sslproxy_flags/",$settings["interception_checks"])) + $interception_checks.="sslproxy_flags DONT_VERIFY_PEER\n"; + if ($settings["interception_adapt"] != ""){ + foreach (explode(",",$settings["interception_adapt"]) as $adapt) + $interception_checks.="sslproxy_cert_adapt {$adapt} all\n"; + } + } + } + } + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + $ssl_port = ($settings['ssl_proxy_port'] ? $settings['ssl_proxy_port'] : 3127); + +#Read assigned interfaces + $real_ifaces = array(); + + if($settings['active_interface']) + $proxy_ifaces = explode(",", $settings['active_interface']); + else + $proxy_ifaces=array("lan"); + + if ($settings['transparent_proxy']=="on"){ + $transparent_ifaces = explode(",", $settings['transparent_active_interface']); + foreach ($transparent_ifaces as $t_iface){ + $t_iface_ip = squid_get_real_interface_address($t_iface); + if($t_iface_ip[0]) + $real_ifaces[]=$t_iface_ip; + } + } + else{ + $transparent_ifaces=array(); + } + + if ($settings['ssl_proxy']=="on"){ + $ssl_ifaces = explode(",", $settings['ssl_active_interface']); + foreach ($ssl_ifaces as $s_iface){ + $s_iface_ip = squid_get_real_interface_address($s_iface); + if($s_iface_ip[0]) + $real_ifaces[]=$s_iface_ip; + } + } + else{ + $ssl_ifaces=array(); + } + + #check all proxy interfaces selected + foreach ($proxy_ifaces as $iface) { + $iface_ip = squid_get_real_interface_address($iface); + if($iface_ip[0]) { + $real_ifaces[]=$iface_ip; + if (in_array($iface,$ssl_ifaces)) + $conf .= "http_port {$iface_ip[0]}:{$port} {$ssl_interception}\n"; + else + $conf .= "http_port {$iface_ip[0]}:{$port}\n"; + } + } + + if (($settings['transparent_proxy'] == 'on')) { + if ($settings['ssl_proxy'] == "on" && count($ssl_ifaces)>0){ + $conf .= "http_port 127.0.0.1:{$port} intercept {$ssl_interception}\n"; + $conf .= "https_port 127.0.0.1:{$ssl_port} intercept {$ssl_interception}\n"; + } + else{ + $conf .= "http_port 127.0.0.1:{$port} intercept\n"; + } + } + $icp_port = ($settings['icp_port'] ? $settings['icp_port'] : 7); + $dns_v4_first= ($settings['dns_v4_first'] == "on" ? "on" : "off" ); + $pidfile = "{$g['varrun_path']}/squid.pid"; + $language = ($settings['error_language'] ? $settings['error_language'] : 'en'); + $icondir = SQUID_CONFBASE . '/icons'; + $hostname = ($settings['visible_hostname'] ? $settings['visible_hostname'] : 'localhost'); + $email = ($settings['admin_email'] ? $settings['admin_email'] : 'admin@localhost'); + + $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); + if (! is_dir($logdir)){ + make_dirs($logdir); + squid_chown_recursive($logdir, 'proxy', 'proxy'); + } + $logdir_cache = $logdir . '/cache.log'; + $logdir_access = ($settings['log_enabled'] == 'on' ? $logdir . '/access.log' : '/dev/null'); + + $conf .= <<< EOD +icp_port {$icp_port} +dns_v4_first {$dns_v4_first} +pid_filename {$pidfile} +cache_effective_user proxy +cache_effective_group proxy +error_default_language {$language} +icon_directory {$icondir} +visible_hostname {$hostname} +cache_mgr {$email} +access_log {$logdir_access} +cache_log {$logdir_cache} +cache_store_log none +{$interception_checks} + +EOD; + +// Per squid docs, setting logfile_rotate to 0 is safe and causes a simple close/reopen. +// Rotating also ensures that swap.state is rewritten, so is useful even if the logs +// are not being rotated. +$rotate = empty($settings['log_rotate']) ? 0 : $settings['log_rotate']; +$conf .= "logfile_rotate {$rotate}\n"; +squid_install_cron(true); + + $conf .= <<< EOD +shutdown_lifetime 3 seconds + +EOD; + + if ($settings['allow_interface'] == 'on') { + $src = ''; + foreach ($real_ifaces as $iface) { + list($ip, $mask) = $iface; + $ip = long2ip(ip2long($ip) & ip2long($mask)); + $mask = 32-log((ip2long($mask) ^ ip2long('255.255.255.255'))+1,2); + if (!preg_match("@$ip/$mask@",$src)) + $src .= " $ip/$mask"; + } + $conf .= "# Allow local network(s) on interface(s)\n"; + $conf .= "acl localnet src $src\n"; + $valid_acls[] = 'localnet'; + } + if ($settings['disable_xforward']) $conf .= "forwarded_for off\n"; + if ($settings['disable_via']) $conf .= "via off\n"; + if ($settings['disable_squidversion']) $conf .= "httpd_suppress_version_string on\n"; + if (!empty($settings['uri_whitespace'])) $conf .= "uri_whitespace {$settings['uri_whitespace']}\n"; + else $conf .= "uri_whitespace strip\n"; //only used for first run + + if(!empty($settings['dns_nameservers'])) { + $altdns = explode(";", ($settings['dns_nameservers'])); + $conf .= "dns_nameservers "; + foreach ($altdns as $dnssrv) { + $conf .= $dnssrv." "; + } +// $conf .= "\n"; //Kill blank line after DNS-Servers + } + + return $conf; +} + + +function squid_resync_cache() { + global $config, $g; + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + //apply cache settings + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + $disk_cache_size = ($settings['harddisk_cache_size'] ? $settings['harddisk_cache_size'] : 100); + $level1 = ($settings['level1_subdirs'] ? $settings['level1_subdirs'] : 16); + $memory_cache_size = ($settings['memory_cache_size'] ? $settings['memory_cache_size'] : 8); + $max_objsize = ($settings['maximum_object_size'] ? $settings['maximum_object_size']." KB" : "10 KB"); + $min_objsize = ($settings['minimum_object_size'] ? $settings['minimum_object_size'] : 0); + $max_objsize_in_mem = ($settings['maximum_objsize_in_mem'] ? $settings['maximum_objsize_in_mem'] : 32); + $cache_policy = ($settings['cache_replacement_policy'] ? $settings['cache_replacement_policy'] : 'heap LFUDA'); + $memory_policy = ($settings['memory_replacement_policy'] ? $settings['memory_replacement_policy'] : 'heap GDSF'); + $offline_mode = ($settings['enable_offline'] == 'on' ? 'on' : 'off'); + $conf = ''; + if (!isset($settings['harddisk_cache_system'])) { + if ($g['platform'] == "nanobsd" || !is_array ($config['installedpackages']['squidcache']['config'])) + $disk_cache_system = 'null'; + else + $disk_cache_system = 'ufs'; + } + else{ + $disk_cache_system = $settings['harddisk_cache_system']; + } + #'null' storage type dropped. In-memory cache is always present. Remove all cache_dir options to prevent on-disk caching. + if ($disk_cache_system != "null") { + $disk_cache_opts = "cache_dir {$disk_cache_system} {$cachedir} {$disk_cache_size} {$level1} 256"; + } +//check dynamic content +if(empty($settings['cache_dynamic_content'])){ + $conf.='acl dynamic urlpath_regex cgi-bin \?'."\n"; + $conf.="cache deny dynamic\n"; +} +else{ + if(preg_match('/youtube/',$settings['refresh_patterns'])){ + $conf.=<<< EOC +# Break HTTP standard for flash videos. Keep them in cache even if asked not to. +refresh_pattern -i \.flv$ 10080 90% 999999 ignore-no-cache override-expire ignore-private + +# Let the clients favorite video site through with full caching +acl youtube dstdomain .youtube.com +cache allow youtube + +EOC; + } + if(preg_match('/windows/',$settings['refresh_patterns'])){ + $conf.=<<< EOC + +# Windows Update refresh_pattern +range_offset_limit -1 +refresh_pattern -i microsoft.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims +refresh_pattern -i windowsupdate.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims +refresh_pattern -i my.windowsupdate.website.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims + +EOC; + } + +if(preg_match('/symantec/',$settings['refresh_patterns'])){ + $conf.=<<< EOC + +# Symantec refresh_pattern +range_offset_limit -1 +refresh_pattern liveupdate.symantecliveupdate.com/.*\.(cab|exe|dll|msi) 10080 100% 43200 reload-into-ims +refresh_pattern symantecliveupdate.com/.*\.(cab|exe|dll|msi) 10080 100% 43200 reload-into-ims + +EOC; + } +if(preg_match('/avast/',$settings['refresh_patterns'])){ + $conf.=<<< EOC + +# Avast refresh_pattern +range_offset_limit -1 +refresh_pattern avast.com/.*\.(vpu|cab|stamp|exe) 10080 100% 43200 reload-into-ims + +EOC; + } +if(preg_match('/avira/',$settings['refresh_patterns'])){ + $conf.=<<< EOC + +# Avira refresh_pattern +range_offset_limit -1 +refresh_pattern personal.avira-update.com/.*\.(cab|exe|dll|msi|gz) 10080 100% 43200 reload-into-ims + +EOC; + } + $refresh_conf=<<< EOC + +# Add any of your own refresh_pattern entries above these. +refresh_pattern ^ftp: 1440 20% 10080 +refresh_pattern ^gopher: 1440 0% 1440 +refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 +refresh_pattern . 0 20% 4320 + +EOC; +} + + If ($settings['custom_refresh_patterns'] !="") + $conf .= sq_text_area_decode($settings['custom_refresh_patterns'])."\n"; + + $conf .= <<< EOD + +cache_mem $memory_cache_size MB +maximum_object_size_in_memory {$max_objsize_in_mem} KB +memory_replacement_policy {$memory_policy} +cache_replacement_policy {$cache_policy} +$disk_cache_opts +minimum_object_size {$min_objsize} KB +maximum_object_size {$max_objsize} +offline_mode {$offline_mode} + +EOD; + + if (!empty($settings['cache_swap_low'])) $conf .= "cache_swap_low {$settings['cache_swap_low']}\n"; + if (!empty($settings['cache_swap_high'])) $conf .= "cache_swap_high {$settings['cache_swap_high']}\n"; + + $donotcache = sq_text_area_decode($settings['donotcache']); + if (!empty($donotcache)) { + file_put_contents(SQUID_ACLDIR . '/donotcache.acl', $donotcache); + $conf .= 'acl donotcache dstdomain "' . SQUID_ACLDIR . "/donotcache.acl\"\n"; + $conf .= "cache deny donotcache\n"; + } + elseif (file_exists(SQUID_ACLDIR . '/donotcache.acl')) { + unlink(SQUID_ACLDIR . '/donotcache.acl'); + } + $conf .= "cache allow all\n"; + return $conf.$refresh_conf; +} + +function squid_resync_upstream() { + global $config; + $conf = "\n#Remote proxies\n"; + if (is_array($config['installedpackages']['squidremote']['config'])) + foreach ($config['installedpackages']['squidremote']['config'] as $settings){ + if ($settings['enable'] == 'on') { + $conf .= "cache_peer {$settings['proxyaddr']} {$settings['hierarchy']} {$settings['proxyport']} "; + if ($settings['icpport'] == '7') + $conf .= "{$settings['icpport']} {$settings['icpoptions']} {$settings['peermethod']} {$settings['allowmiss']} "; + else + $conf .= "{$settings['icpport']} "; + #auth settings + if (!empty($settings['username']) && !empty($settings['password'])){ + $conf .= " login={$settings['username']}:{$settings['password']}"; + } + else{ + $conf .= "{$settings['authoption']} "; + } + #other options settings + if (!empty($settings['weight'])) + $conf .= "weight={$settings['weight']} "; + if (!empty($settings['basetime'])) + $conf .= "basetime={$settings['basetime']} "; + if (!empty($settings['ttl'])) + $conf .= "ttl={$settings['ttl']} "; + if (!empty($settings['nodelay'])) + $conf .= "no-delay"; + } + $conf .= "\n"; + } + return $conf; +} + +function squid_resync_redirector() { + global $config; + + $httpav_enabled = ($config['installedpackages']['clamav']['config'][0]['scan_http'] == 'on'); + if ($httpav_enabled) { + $conf = "url_rewrite_program /usr/local/bin/squirm\n"; + } else { + $conf = "# No redirector configured\n"; + } + return $conf; +} + +function squid_resync_nac() { + global $config, $valid_acls; + + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + if (is_array($config['installedpackages']['squidnac'])) + $settings = $config['installedpackages']['squidnac']['config'][0]; + else + $settings = array(); + $webgui_port = $config['system']['webgui']['port']; + $addtl_ports = $settings['addtl_ports']; + $addtl_sslports = $settings['addtl_sslports']; + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + $ssl_port = ($settings['ssl_proxy_port'] ? $settings['ssl_proxy_port'] : 3127); + $conf = <<< EOD + +# Setup some default acls +# From 3.2 further configuration cleanups have been done to make things easier and safer. The manager, localhost, and to_localhost ACL definitions are now built-in. +# acl localhost src 127.0.0.1/32 +acl allsrc src all +acl safeports port 21 70 80 210 280 443 488 563 591 631 777 901 $webgui_port $port $ssl_port 1025-65535 $addtl_ports +acl sslports port 443 563 $webgui_port $addtl_sslports + +# From 3.2 further configuration cleanups have been done to make things easier and safer. The manager, localhost, and to_localhost ACL definitions are now built-in. +#acl manager proto cache_object + +acl purge method PURGE +acl connect method CONNECT + +# Define protocols used for redirects +acl HTTP proto HTTP +acl HTTPS proto HTTPS + +EOD; + + $allowed_subnets = preg_replace("/\s+/"," ",sq_text_area_decode($settings['allowed_subnets'])); + #$allowed = ""; + #foreach ($allowed_subnets as $subnet) { + # if(!empty($subnet)) { + # $subnet = trim($subnet); + # $allowed .= "$subnet "; + # } + #} + if (!empty($allowed_subnets)) { + $conf .= "acl allowed_subnets src $allowed_subnets\n"; + $valid_acls[] = 'allowed_subnets'; + } + + $options = array( 'unrestricted_hosts' => 'src', + 'banned_hosts' => 'src', + 'whitelist' => 'dstdom_regex -i', + 'blacklist' => 'dstdom_regex -i', + 'block_user_agent' => 'browser -i', + 'block_reply_mime_type' => 'rep_mime_type -i', + ); + foreach ($options as $option => $directive) { + $contents = sq_text_area_decode($settings[$option]); + if (!empty($contents)) { + file_put_contents(SQUID_ACLDIR . "/$option.acl", $contents); + $conf .= "acl $option $directive \"" . SQUID_ACLDIR . "/$option.acl\"\n"; + $valid_acls[] = $option; + } + elseif (file_exists(SQUID_ACLDIR . "/$option.acl")) { + unlink(SQUID_ACLDIR . "/$option.acl"); + } + } + + $conf .= <<< EOD +http_access allow manager localhost + +EOD; + + if (is_array($config['installedpackages']['squidcache'])){ + $settings_ch = $config['installedpackages']['squidcache']['config'][0]; + if(!empty($settings_ch['ext_cachemanager'])) { + $extmgr = explode(";", ($settings_ch['ext_cachemanager'])); + $conf .= "\n# Allow external cache managers\n"; + foreach ($extmgr as $mgr) { + $conf .= "acl ext_manager src {$mgr}\n"; + } + $conf .= "http_access allow manager ext_manager\n"; + } + } + + $conf .= <<< EOD + +http_access deny manager +http_access allow purge localhost +http_access deny purge +http_access deny !safeports +http_access deny CONNECT !sslports + +# Always allow localhost connections +# From 3.2 further configuration cleanups have been done to make things easier and safer. +# The manager, localhost, and to_localhost ACL definitions are now built-in. +# http_access allow localhost + +EOD; + + return $conf; +} + +function squid_resync_antivirus(){ + global $config; + + if (is_array($config['installedpackages']['squidantivirus'])) + $antivirus_config = $config['installedpackages']['squidantivirus']['config'][0]; + else + $antivirus_config = array(); + + if ($antivirus_config['enable']=="on"){ + switch ($antivirus_config['client_info']){ + case "both": + $icap_send_client_ip="on"; + $icap_send_client_username="on"; + break; + case "IP": + $icap_send_client_ip="on"; + $icap_send_client_username="off"; + break; + case "username": + $icap_send_client_ip="off"; + $icap_send_client_username="on"; + break; + case "none": + $icap_send_client_ip="off"; + $icap_send_client_username="off"; + break; + } + if (is_array($config['installedpackages']['squid'])) + $squid_config=$config['installedpackages']['squid']['config'][0]; + $clwarn="clwarn.cgi.en_EN"; + if (preg_match("/de/i",$squid_config['error_language'])) + $clwarn="clwarn.cgi.de_DE"; + if (preg_match("/ru/i",$squid_config['error_language'])) + $clwarn="clwarn.cgi.ru_RU"; + if (preg_match("/fr/i",$squid_config['error_language'])) + $clwarn="clwarn.cgi.fr_FR"; + if (preg_match("/pt_br/i",$squid_config['error_language'])) + $clwarn="clwarn.cgi.pt_BR"; + copy(SQUID_LOCALBASE."/libexec/squidclamav/{$clwarn}","/usr/local/www/clwarn.cgi"); + + $conf = <<< EOF +icap_enable on +icap_send_client_ip {$icap_send_client_ip} +icap_send_client_username {$icap_send_client_username} +icap_client_username_encode off +icap_client_username_header X-Authenticated-User +icap_preview_enable on +icap_preview_size 1024 + +icap_service service_req reqmod_precache bypass=0 icap://127.0.0.1:1344/squidclamav +icap_service service_resp respmod_precache bypass=0 icap://127.0.0.1:1344/squidclamav + +adaptation_access service_req allow all +adaptation_access service_resp allow all + +EOF; + #check if icap is enabled on rc.conf.local + if (file_exists("/etc/rc.conf.local")){ + $rc_old_file=file("/etc/rc.conf.local"); + foreach ($rc_old_file as $rc_line){ + if (preg_match("/^(c_icap_enable|clamav_clamd_enable)/",$rc_line,$matches)){ + $rc_file.=$matches[1].'="YES"'."\n"; + ${$matches[1]}="ok"; + } + else + $rc_file.=$rc_line; + } + } + if (!isset($c_icap_enable)) + $rc_file.='c_icap_enable="YES"'."\n"; + if (!isset($clamav_clamd_enable)) + $rc_file.='clamav_clamd_enable="YES"'."\n"; + file_put_contents("/etc/rc.conf.local",$rc_file,LOCK_EX); + + #patch sample files to pfsense dirs + #squidclamav.conf + if (!file_exists(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.sample")) + if (file_exists(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.default")){ + $sample_file=file_get_contents(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.default"); + $clamav_m[0]="@/var/run/clamav/clamd.ctl@"; + $clamav_r[0]="/var/run/clamav/clamd.sock"; + file_put_contents(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.sample",preg_replace($clamav_m,$clamav_r,$sample_file),LOCK_EX); + } + #c-icap.conf + if (!file_exists(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.sample")) + if (file_exists(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.default")){ + $sample_file=file_get_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.default"); + if (! preg_match ("/squidclamav/")) + $sample_file.="\nService squidclamav squidclamav.so\n"; + + file_put_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.sample",$sample_file,LOCK_EX); + } + $loadsample=0; + if ($antivirus_config['squidclamav'] =="" && file_exists(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.sample")){ + $config['installedpackages']['squidantivirus']['config'][0]['squidclamav']=base64_encode(file_get_contents(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf.sample")); + $loadsample++; + } + if ($antivirus_config['c-icap_conf'] =="" && file_exists(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.sample")){ + $config['installedpackages']['squidantivirus']['config'][0]['c-icap_conf']=base64_encode(file_get_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf.sample")); + $loadsample++; + } + if ($antivirus_config['squidclamav'] =="" && file_exists(SQUID_LOCALBASE."/etc/c-icap/c-icap.magic.default")){ + $config['installedpackages']['squidantivirus']['config'][0]['c-icap_magic']=base64_encode(file_get_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.magic.default")); + $loadsample++; + } + if($loadsample > 0){ + write_config(); + $antivirus_config = $config['installedpackages']['squidantivirus']['config'][0]; + } + #check dirs + $dirs=array("/var/run/c-icap" => "clamav", + "/var/log/c-icap" => "clamav", + "/var/log/clamav" => "clamav", + "/var/run/clamav" => "clamav", + "/var/db/clamav" => "clamav"); + foreach ($dirs as $dir_path => $dir_user){ + if (!is_dir($dir_path)) + make_dirs($dir_path); + squid_chown_recursive($dir_path, $dir_user, $dir_user); + } + + #check startup scripts on pfsense > 2.1 + if (preg_match("/usr.pbi/",SQUID_LOCALBASE)){ + $rcd_files = scandir(SQUID_LOCALBASE."/etc/rc.d"); + foreach($rcd_files as $rcd_file) + if (!file_exists("/usr/local/etc/rc.d/{$rcd_file}")) + symlink (SQUID_LOCALBASE."/etc/rc.d/{$rcd_file}","/usr/local/etc/rc.d/{$rcd_file}"); + } + + #write advanced icap config files + file_put_contents(SQUID_LOCALBASE."/etc/c-icap/squidclamav.conf",base64_decode($antivirus_config['squidclamav']),LOCK_EX); + file_put_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.conf",base64_decode($antivirus_config['c-icap_conf']),LOCK_EX); + file_put_contents(SQUID_LOCALBASE."/etc/c-icap/c-icap.magic",base64_decode($antivirus_config['c-icap_magic']),LOCK_EX); + + #check antivirus daemons + #check icap + if (is_process_running("c-icap")){ + mwexec('/bin/echo -n "reconfigure" > /var/run/c-icap/c-icap.ctl'); + } + else{ + #check c-icap user on startup file + $c_icap_rcfile="/usr/local/etc/rc.d/c-icap"; + if (file_exists($c_icap_rcfile)){ + $sample_file=file_get_contents($c_icap_rcfile); + $cicapm[0]="@c_icap_user=.*}@"; + $cicapr[0]='c_icap_user="clamav"}'; + file_put_contents($c_icap_rcfile,preg_replace($cicapm,$cicapr,$sample_file),LOCK_EX); + } + mwexec("/usr/local/etc/rc.d/c-icap start"); + } + #check clamav + if (is_process_running("clamd")) + mwexec_bg("/usr/local/etc/rc.d/clamav-clamd reload"); + else + mwexec("/usr/local/etc/rc.d/clamav-clamd start"); + } +return $conf; +} + +function squid_resync_traffic() { + global $config, $valid_acls; + + if(!is_array($valid_acls)) + return; + if (is_array($config['installedpackages']['squidtraffic'])) + $settings = $config['installedpackages']['squidtraffic']['config'][0]; + else + $settings = array(); + + $conf = ''; + if (!empty($settings['quick_abort_min']) || ($settings['quick_abort_min']) == "0") + $conf .= "quick_abort_min {$settings['quick_abort_min']} KB\n"; + if (!empty($settings['quick_abort_max']) || ($settings['quick_abort_max']) == "0") + $conf .= "quick_abort_max {$settings['quick_abort_max']} KB\n"; + if (!empty($settings['quick_abort_pct'])) + $conf .= "quick_abort_pct {$settings['quick_abort_pct']}\n"; + + $up_limit = ($settings['max_upload_size'] ? $settings['max_upload_size'] : 0); + $down_limit = ($settings['max_download_size'] ? $settings['max_download_size'] : 0); + $conf .= "request_body_max_size $up_limit KB\n"; + if ($down_limit != 0) + $conf .= 'reply_body_max_size ' . $down_limit . " KB allsrc \n"; + + + // Only apply throttling past 10MB + // XXX: Should this really be hardcoded? + $threshold = 10 * 1024 * 1024; + $overall = $settings['overall_throttling']; + if (!isset($overall) || ($overall == 0)) + $overall = -1; + else + $overall *= 1024; + $perhost = $settings['perhost_throttling']; + if (!isset($perhost) || ($perhost == 0)) + $perhost = -1; + else + $perhost *= 1024; + $conf .= <<< EOD +delay_pools 1 +delay_class 1 2 +delay_parameters 1 $overall/$overall $perhost/$perhost +delay_initial_bucket_level 100 + +EOD; + + if(! empty($settings['unrestricted_hosts'])) { + foreach (array('unrestricted_hosts') as $item) { + if (in_array($item, $valid_acls)) + $conf .= "# Do not throttle unrestricted hosts\n"; + $conf .= "delay_access 1 deny $item\n"; + } + } + + if ($settings['throttle_specific'] == 'on') { + $exts = array(); + $binaries = 'bin,cab,sea,ar,arj,tar,tgz,gz,tbz,bz2,zip,7z,exe,com'; + $cdimages = 'iso,bin,mds,nrg,gho,bwt,b5t,pqi'; + $multimedia = 'aiff?,asf,avi,divx,mov,mp3,mp4,wmv,mpe?g,qt,ra?m'; + foreach (array( 'throttle_binaries' => $binaries, + 'throttle_cdimages' => $cdimages, + 'throttle_multimedia' => $multimedia) as $field => $set) { + if ($settings[$field] == 'on') + $exts = array_merge($exts, explode(",", $set)); + } + + foreach (explode(",", $settings['throttle_others']) as $ext) { + if (!empty($ext)) $exts[] = $ext; + } + + $contents = ''; + foreach ($exts as $ext) + $contents .= "\.$ext\$\n"; + file_put_contents(SQUID_ACLDIR . '/throttle_exts.acl', $contents); + + $conf .= "# Throttle extensions matched in the url\n"; + $conf .= "acl throttle_exts urlpath_regex -i \"" . SQUID_ACLDIR . "/throttle_exts.acl\"\n"; + $conf .= "delay_access 1 allow throttle_exts\n"; + $conf .= "delay_access 1 deny allsrc\n"; + } + else + $conf .= "delay_access 1 allow allsrc\n"; + + return $conf; +} + +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; +} + +#squid reverse +include('/usr/local/pkg/squid_reverse.inc'); + +function squid_resync_auth() { + global $config, $valid_acls; + + if (is_array($config['installedpackages']['squidauth']['config'])) + $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); + + if (is_array($config['installedpackages']['squidnac']['config'])) + $settingsnac = $config['installedpackages']['squidnac']['config'][0]; + else + $settingsnac = array(); + + if (is_array($config['installedpackages']['squid']['config'])) + $settingsconfig = $config['installedpackages']['squid']['config'][0]; + else + $settingsconfig = array(); + + $conf = ''; + + // SSL interception acl options part 1 + if ($settingsconfig['ssl_proxy'] == "on" && ! empty($settingsnac['whitelist'])){ + $conf .= "always_direct allow whitelist\n"; + $conf .= "ssl_bump none whitelist\n"; + } + + // Package integration + if(!empty($settingsconfig['custom_options'])){ + $co_preg[0]='/;/'; + $co_rep[0]="\n"; + $co_preg[1]="/redirect_program/"; + $co_rep[1]="url_rewrite_program"; + $co_preg[2]="/redirector_bypass/"; + $co_rep[2]="url_rewrite_bypass"; + $conf.="# Package Integration\n".preg_replace($co_preg,$co_rep,$settingsconfig['custom_options'])."\n\n"; + } + + // Custom User Options + $conf .= "# Custom options\n".sq_text_area_decode($settingsconfig['custom_options_squid3'])."\n\n"; + + // Deny the banned guys before allowing the good guys + if(! empty($settingsnac['banned_hosts'])) { + if (squid_is_valid_acl('banned_hosts')) { + $conf .= "# These hosts are banned\n"; + $conf .= "http_access deny banned_hosts\n"; + } + } + if(! empty($settingsnac['banned_macs'])) { + if (squid_is_valid_acl('banned_macs')) { + $conf .= "# These macs are banned\n"; + $conf .= "http_access deny banned_macs\n"; + } + } + + // Unrestricted hosts take precedence over blacklist + if(! empty($settingsnac['unrestricted_hosts'])) { + if (squid_is_valid_acl('unrestricted_hosts') && $settings['unrestricted_auth']!= "on") { + $conf .= "# These hosts do not have any restrictions\n"; + $conf .= "http_access allow unrestricted_hosts\n"; + } + } + if(! empty($settingsnac['unrestricted_macs'])) { + if (squid_is_valid_acl('unrestricted_macs')) { + $conf .= "# These hosts do not have any restrictions\n"; + $conf .= "http_access allow unrestricted_macs\n"; + } + } + + // Whitelist and blacklist also take precedence over other allow rules + if(! empty($settingsnac['whitelist'])) { + if (squid_is_valid_acl('whitelist')) { + $conf .= "# Always allow access to whitelist domains\n"; + $conf .= "http_access allow whitelist\n"; + } + } + if(! empty($settingsnac['blacklist'])) { + if (squid_is_valid_acl('blacklist')) { + $conf .= "# Block access to blacklist domains\n"; + $conf .= "http_access deny blacklist\n"; + } + } + if(! empty($settingsnac['block_user_agent'])) { + if (squid_is_valid_acl('block_user_agent')) { + $conf .= "# Block access with user agents and browsers\n"; + $conf .= "http_access deny block_user_agent\n"; + } + } + if(! empty($settingsnac['block_reply_mime_type'])) { + if (squid_is_valid_acl('block_reply_mime_type')) { + $conf .= "# Block access with mime type in the reply\n"; + $conf .= "http_reply_access deny block_reply_mime_type\n"; + } + } + + // SSL interception acl options part 2 + if ($settingsconfig['ssl_proxy'] == "on"){ + $conf .= "always_direct allow all\n"; + $conf .= "ssl_bump server-first all\n"; + } + + // Include squidguard denied acl log in squid + if ($settingsconfig['log_sqd']) + $conf .= "acl sglog url_regex -i sgr=ACCESSDENIED\n"; + + $transparent_proxy = ($settingsconfig['transparent_proxy'] == 'on'); + $auth_method = (($settings['auth_method'] && !$transparent_proxy) ? $settings['auth_method'] : 'none'); + // Allow the remaining ACLs if no authentication is set + if ($auth_method == 'none') { + // Include squidguard denied acl log in squid + if ($settingsconfig['log_sqd']) + $conf .="http_access deny sglog\n"; + + $conf .="# Setup allowed acls\n"; + $allowed = array('allowed_subnets'); + if ($settingsconfig['allow_interface'] == 'on') { + $conf .= "# Allow local network(s) on interface(s)\n"; + $allowed[] = "localnet"; + } + $allowed = array_filter($allowed, 'squid_is_valid_acl'); + foreach ($allowed as $acl) + $conf .= "http_access allow $acl\n"; + } + else { + $noauth = implode(' ', explode("\n", base64_decode($settings['no_auth_hosts']))); + if (!empty($noauth)) { + $conf .= "acl noauth src $noauth\n"; + $valid_acls[] = 'noauth'; + } + + // Set up the external authentication programs + $auth_ttl = ($settings['auth_ttl'] ? $settings['auth_ttl'] : 60); + $processes = ($settings['auth_processes'] ? $settings['auth_processes'] : 5); + $prompt = ($settings['auth_prompt'] ? $settings['auth_prompt'] : 'Please enter your credentials to access the proxy'); + switch ($auth_method) { + case 'local': + $conf .= 'auth_param basic program '.SQUID_LOCALBASE.'/libexec/squid/basic_ncsa_auth ' . SQUID_PASSWD . "\n"; + break; + case 'ldap': + $port = (isset($settings['auth_server_port']) ? ":{$settings['auth_server_port']}" : ''); + $password = (isset($settings['ldap_pass']) ? "-w {$settings['ldap_pass']}" : ''); + $conf .= "auth_param basic program " . SQUID_LOCALBASE . "/libexec/squid/basic_ldap_auth -v {$settings['ldap_version']} -b {$settings['ldap_basedomain']} -D {$settings['ldap_user']} $password -f \"{$settings['ldap_filter']}\" -u {$settings['ldap_userattribute']} -P {$settings['auth_server']}$port\n"; + break; + case 'radius': + $port = (isset($settings['auth_server_port']) ? "-p {$settings['auth_server_port']}" : ''); + $conf .= "auth_param basic program ". SQUID_LOCALBASE . "/libexec/squid/basic_radius_auth -w {$settings['radius_secret']} -h {$settings['auth_server']} $port\n"; + break; + case 'msnt': + $conf .= "auth_param basic program ". SQUID_LOCALBASE . "/libexec/squid/basic_msnt_auth\n"; + squid_resync_msnt(); + break; + } + $conf .= <<< EOD +auth_param basic children $processes +auth_param basic realm $prompt +auth_param basic credentialsttl $auth_ttl minutes +acl password proxy_auth REQUIRED + +EOD; + + // Onto the ACLs + $password = array('localnet', 'allowed_subnets'); + $passwordless = array('unrestricted_hosts'); + if ($settings['unrestricted_auth'] == 'on') { + // Even the unrestricted hosts should authenticate + $password = array_merge($password, $passwordless); + $passwordless = array(); + } + $passwordless[] = 'noauth'; + $password = array_filter($password, 'squid_is_valid_acl'); + $passwordless = array_filter($passwordless, 'squid_is_valid_acl'); + + // Allow the ACLs that don't need to authenticate + foreach ($passwordless as $acl) + $conf .= "http_access allow $acl\n"; + + // Include squidguard denied acl log in squid + if ($settingsconfig['log_sqd']) + $conf .="http_access deny password sglog\n"; + + // Allow the other ACLs as long as they authenticate + foreach ($password as $acl) + $conf .= "http_access allow password $acl\n"; + } + + $conf .= "# Default block all to be sure\n"; + $conf .= "http_access deny allsrc\n"; + + return $conf; +} + +function squid_resync_users() { + global $config; + + $users = $config['installedpackages']['squidusers']['config']; + $contents = ''; + if (is_array($users)) { + foreach ($users as $user) + $contents .= $user['username'] . ':' . crypt($user['password'], base64_encode($user['password'])) . "\n"; + } + file_put_contents(SQUID_PASSWD, $contents); + chown(SQUID_PASSWD, 'proxy'); + chmod(SQUID_PASSWD, 0600); +} + +function squid_resync_msnt() { + global $config; + + if (is_array($config['installedpackages']['squidauth'])) + $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); + $pdcserver = $settings['auth_server']; + $bdcserver = str_replace(',',' ',$settings['msnt_secondary']); + $ntdomain = $settings['auth_ntdomain']; + + file_put_contents(SQUID_CONFBASE."/msntauth.conf","server {$pdcserver} {$bdcserver} {$ntdomain}"); + chown(SQUID_CONFBASE."/msntauth.conf", 'proxy'); + chmod(SQUID_CONFBASE."/msntauth.conf", 0600); +} + +function squid_resync($via_rpc="no") { + global $config; + + # detect boot process + if (is_array($_POST)){ + if (preg_match("/\w+/",$_POST['__csrf_magic'])) + unset($boot_process); + else + $boot_process="on"; + } + + log_error("[Squid] - Squid_resync function call pr:".is_process_running('squid')." bp:".isset($boot_process)." rpc:".$via_rpc); + + if (is_process_running('squid') && isset($boot_process) && $via_rpc=="no") + return; + + conf_mount_rw(); + foreach (array( SQUID_CONFBASE, + SQUID_ACLDIR, + SQUID_BASE, + SQUID_LIB, + SQUID_SSL_DB ) as $dir) { + make_dirs($dir); + chown($dir, 'proxy'); + chgrp($dir, 'proxy'); + squid_chown_recursive($dir, 'proxy', 'proxy'); + } + $conf = squid_resync_general() . "\n"; + $conf .= squid_resync_cache() . "\n"; + $conf .= squid_resync_redirector() . "\n"; + $conf .= squid_resync_upstream() . "\n"; + $conf .= squid_resync_nac() . "\n"; + $conf .= squid_resync_traffic() . "\n"; + $conf .= squid_resync_reverse() . "\n"; + $conf .= squid_resync_auth()."\n"; + $conf .= squid_resync_antivirus(); + squid_resync_users(); + squid_write_rcfile(); + + if(!isset($boot_process) || $via_rpc="yes") + squid_sync_on_changes(); + + #write config file + file_put_contents(SQUID_CONFBASE . '/squid.conf', $conf); + + /* make sure pinger is executable */ + if(file_exists(SQUID_LOCALBASE . "/libexec/squid/pinger")) + exec("chmod a+x " . SQUID_LOCALBASE . "/libexec/squid/pinger"); + + $log_dir=""; + #check if squid is enabled + if (is_array($config['installedpackages']['squid']['config'])){ + if ($config['installedpackages']['squid']['config'][0]['active_interface']!= "") + $log_dir = $config['installedpackages']['squid']['config'][0]['log_dir'].'/'; + } + #check if squidreverse is enabled + else if (is_array($config['installedpackages']['squidreversegeneral']['config'])){ + if ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_interface'] != "") + $log_dir="/var/squid/logs/"; + } + #do not start squid if there is no log dir + if ($log_dir != ""){ + if(!is_dir($log_dir)) { + log_error("Creating squid log dir $log_dir"); + make_dirs($log_dir); + squid_chown_recursive($log_dir, 'proxy', 'proxy'); + } + + squid_dash_z(); + + if (!is_service_running('squid')) { + log_error("Starting Squid"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -f " . SQUID_CONFFILE); + } + else { + if (!isset($boot_process)){ + log_error("Reloading Squid for configuration sync"); + mwexec(SQUID_LOCALBASE . "/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); + } + filter_configure(); + } + conf_mount_ro(); +} + +function squid_print_javascript_auth() { + global $config; + $transparent_proxy = ($config['installedpackages']['squid']['config'][0]['transparent_proxy'] == 'on'); + + // No authentication for transparent proxy + if ($transparent_proxy) { + $javascript = <<< EOD +<script language="JavaScript"> +<!-- +function on_auth_method_changed() { + document.iform.auth_method.disabled = 1; + document.iform.auth_server.disabled = 1; + document.iform.auth_ntdomain.disabled = 1; + document.iform.auth_server_port.disabled = 1; + document.iform.ldap_user.disabled = 1; + document.iform.ldap_version.disabled = 1; + document.iform.ldap_userattribute.disabled = 1; + document.iform.ldap_filter.disabled = 1; + document.iform.ldap_pass.disabled = 1; + document.iform.ldap_basedomain.disabled = 1; + document.iform.radius_secret.disabled = 1; + document.iform.msnt_secondary.disabled = 1; + document.iform.auth_prompt.disabled = 1; + document.iform.auth_processes.disabled = 1; + document.iform.auth_ttl.disabled = 1; + document.iform.unrestricted_auth.disabled = 1; + document.iform.no_auth_hosts.disabled = 1; +} +--> +</script> + +EOD; + } + else { + $javascript = <<< EOD +<script language="JavaScript"> +<!-- +function on_auth_method_changed() { + var field = document.iform.auth_method; + var auth_method = field.options[field.selectedIndex].value; + + if (auth_method == 'none') { + document.iform.auth_server.disabled = 1; + document.iform.auth_server_port.disabled = 1; + document.iform.auth_ntdomain.disabled = 1; + document.iform.ldap_user.disabled = 1; + document.iform.ldap_version.disabled = 1; + document.iform.ldap_userattribute.disabled = 1; + document.iform.ldap_filter.disabled = 1; + document.iform.ldap_pass.disabled = 1; + document.iform.ldap_basedomain.disabled = 1; + document.iform.radius_secret.disabled = 1; + document.iform.msnt_secondary.disabled = 1; + document.iform.auth_prompt.disabled = 1; + document.iform.auth_processes.disabled = 1; + document.iform.auth_ttl.disabled = 1; + document.iform.unrestricted_auth.disabled = 1; + document.iform.no_auth_hosts.disabled = 1; + } + else { + document.iform.auth_prompt.disabled = 0; + document.iform.auth_processes.disabled = 0; + document.iform.auth_ttl.disabled = 0; + document.iform.unrestricted_auth.disabled = 0; + document.iform.no_auth_hosts.disabled = 0; + } + + switch (auth_method) { + case 'local': + document.iform.auth_server.disabled = 1; + document.iform.auth_server_port.disabled = 1; + document.iform.auth_ntdomain.disabled = 1; + document.iform.ldap_user.disabled = 1; + document.iform.ldap_pass.disabled = 1; + document.iform.ldap_version.disabled = 1; + document.iform.ldap_userattribute.disabled = 1; + document.iform.ldap_filter.disabled = 1; + document.iform.ldap_basedomain.disabled = 1; + document.iform.radius_secret.disabled = 1; + document.iform.msnt_secondary.disabled = 1; + break; + case 'ldap': + document.iform.auth_server.disabled = 0; + document.iform.auth_server_port.disabled = 0; + document.iform.ldap_user.disabled = 0; + document.iform.ldap_pass.disabled = 0; + document.iform.ldap_version.disabled = 0; + document.iform.ldap_userattribute.disabled = 0; + document.iform.ldap_filter.disabled = 0; + document.iform.ldap_basedomain.disabled = 0; + document.iform.radius_secret.disabled = 1; + document.iform.msnt_secondary.disabled = 1; + document.iform.auth_ntdomain.disabled = 1; + break; + case 'radius': + document.iform.auth_server.disabled = 0; + document.iform.auth_server_port.disabled = 0; + document.iform.ldap_user.disabled = 1; + document.iform.ldap_pass.disabled = 1; + document.iform.ldap_version.disabled = 1; + document.iform.ldap_userattribute.disabled = 1; + document.iform.ldap_filter.disabled = 1; + document.iform.ldap_basedomain.disabled = 1; + document.iform.radius_secret.disabled = 0; + document.iform.msnt_secondary.disabled = 1; + document.iform.auth_ntdomain.disabled = 1; + break; + case 'msnt': + document.iform.auth_server.disabled = 0; + document.iform.auth_server_port.disabled = 1; + document.iform.auth_ntdomain.disabled = 0; + document.iform.ldap_user.disabled = 1; + document.iform.ldap_pass.disabled = 1; + document.iform.ldap_version.disabled = 1; + document.iform.ldap_userattribute.disabled = 1; + document.iform.ldap_filter.disabled = 1; + document.iform.ldap_basedomain.disabled = 1; + document.iform.radius_secret.disabled = 1; + document.iform.msnt_secondary.disabled = 0; + break; + } +} +--> +</script> + +EOD; + } + + print($javascript); +} + +function squid_print_javascript_auth2() { + print("<script language=\"JavaScript\">on_auth_method_changed()</script>\n"); +} + +function squid_generate_rules($type) { + global $config; + $squid_conf = $config['installedpackages']['squid']['config'][0]; + + //check captive portal option + $cp_file='/etc/inc/captiveportal.inc'; + $pfsense_version=preg_replace("/\s/","",file_get_contents("/etc/version")); + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + $cp_inc = file($cp_file); + $new_cp_inc=""; + $found_rule=0; + foreach ($cp_inc as $line){ + $new_line=$line; + //remove applied squid patch + if (preg_match('/} set 1 skipto 65314/',$line)){ + $found_rule++; + $new_line =""; + } + //add squid patch option based on current config + if (preg_match('/set 1 pass ip from any to/',$line) && $squid_conf['patch_cp']){ + $found_rule++; + $new_line = "\t".'$cprules .= "add {$rulenum} set 1 skipto 65314 ip from any to {$ips} '.$port.' in\n";'."\n"; + $new_line .= $line; + } + if (preg_match('/set 1 pass ip from {/',$line) && $squid_conf['patch_cp']){ + $found_rule++; + $new_line = "\t".'$cprules .= "add {$rulenum} set 1 skipto 65314 ip from {$ips} '.$port.' to any out\n";'."\n"; + $new_line .= $line; + } + $new_cp_inc .= $new_line; + } + if (!file_exists('/root/'.$pfsense_version.'.captiveportal.inc.backup')) { + copy ($cp_file,'/root/'.$pfsense_version.'.captiveportal.inc.backup'); + } + if($found_rule > 0){ + file_put_contents($cp_file,$new_cp_inc, LOCK_EX); + } + + //normal squid rule check + if (($squid_conf['transparent_proxy'] != 'on') || ($squid_conf['allow_interface'] != 'on')) { + return; + } + + if (!is_service_running('squid')) { + log_error("SQUID is installed but not started. Not installing \"{$type}\" rules."); + return; + } + #Read assigned interfaces + $proxy_ifaces = explode(",", $squid_conf['active_interface']); + $proxy_ifaces = array_map('convert_friendly_interface_to_real_interface_name', $proxy_ifaces); + if ($squid_conf['transparent_proxy']=="on"){ + $transparent_ifaces = explode(",", $squid_conf['transparent_active_interface']); + $transparent_ifaces = array_map('convert_friendly_interface_to_real_interface_name', $transparent_ifaces); + } + else{ + $transparent_ifaces=array(); + } + if ($squid_conf['ssl_proxy'] == "on"){ + $ssl_ifaces = explode(",", $squid_conf['ssl_active_interface']); + $ssl_ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ssl_ifaces); + } + else{ + $ssl_ifaces=array(); + } + + $port = ($squid_conf['proxy_port'] ? $squid_conf['proxy_port'] : 3128); + $ssl_port = ($squid_conf['ssl_proxy_port'] ? $squid_conf['ssl_proxy_port'] : 3127); + + $fw_aliases = filter_generate_aliases(); + if(strstr($fw_aliases, "pptp =")) + $PPTP_ALIAS = "\$pptp"; + else + $PPTP_ALIAS = "\$PPTP"; + if(strstr($fw_aliases, "PPPoE =")) + $PPPOE_ALIAS = "\$PPPoE"; + else + $PPPOE_ALIAS = "\$pppoe"; + + #define ports based on transparent options and ssl filtering + $pf_rule_port=($squid_conf['ssl_proxy'] == "on" ? "{80,443}" : "80"); + switch($type) { + case 'nat': + $rules .= "\n# Setup Squid proxy redirect\n"; + if ($squid_conf['private_subnet_proxy_off'] == 'on') { + foreach ($transparent_ifaces as $iface) { + $pf_transparent_rule_port=(in_array($iface,$ssl_ifaces) ? "{80,443}" : "80"); + $rules .= "no rdr on $iface proto tcp from any to { 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8 } port {$pf_transparent_rule_port}\n"; + } + /* Handle PPPOE case */ + if(($config['pppoe']['mode'] == "server" && $config['pppoe']['localip']) || (function_exists("is_pppoe_server_enabled") && is_pppoe_server_enabled())) { + $rules .= "no rdr on $PPPOE_ALIAS proto tcp from any to { 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8 } port {$pf_rule_port}\n"; + } + /* Handle PPTP case */ + if($config['pptpd']['mode'] == "server" && $config['pptpd']['localip']) { + $rules .= "no rdr on $PPTP_ALIAS proto tcp from any to { 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8 } port {$pf_rule_port}\n"; + } + } + if (!empty($squid_conf['defined_ip_proxy_off'])) { + $defined_ip_proxy_off = explode(";", $squid_conf['defined_ip_proxy_off']); + $exempt_ip = ""; + foreach ($defined_ip_proxy_off as $ip_proxy_off) { + if(!empty($ip_proxy_off)) { + $ip_proxy_off = trim($ip_proxy_off); + if (is_alias($ip_proxy_off)) + $ip_proxy_off = '$'.$ip_proxy_off; + $exempt_ip .= ", $ip_proxy_off"; + } + } + $exempt_ip = substr($exempt_ip,2); + foreach ($transparent_ifaces as $iface) { + $pf_transparent_rule_port=(in_array($iface,$ssl_ifaces) ? "{80,443}" : "80"); + $rules .= "no rdr on $iface proto tcp from { $exempt_ip } to any port {$pf_transparent_rule_port}\n"; + } + /* Handle PPPOE case */ + if(($config['pppoe']['mode'] == "server" && $config['pppoe']['localip']) || (function_exists("is_pppoe_server_enabled") && is_pppoe_server_enabled())) { + $rules .= "no rdr on $PPPOE_ALIAS proto tcp from { $exempt_ip } to any port {$pf_rule_port}\n"; + } + /* Handle PPTP case */ + if($config['pptpd']['mode'] == "server" && $config['pptpd']['localip']) { + $rules .= "no rdr on $PPTP_ALIAS proto tcp from { $exempt_ip } to any port {$pf_rule_port}\n"; + } + } + if (!empty($squid_conf['defined_ip_proxy_off_dest'])) { + $defined_ip_proxy_off_dest = explode(";", $squid_conf['defined_ip_proxy_off_dest']); + $exempt_dest = ""; + foreach ($defined_ip_proxy_off_dest as $ip_proxy_off_dest) { + if(!empty($ip_proxy_off_dest)) { + $ip_proxy_off_dest = trim($ip_proxy_off_dest); + if (is_alias($ip_proxy_off_dest)) + $ip_proxy_off_dest = '$'.$ip_proxy_off_dest; + $exempt_dest .= ", $ip_proxy_off_dest"; + } + } + $exempt_dest = substr($exempt_dest,2); + foreach ($transparent_ifaces as $iface) { + $pf_transparent_rule_port=(in_array($iface,$ssl_ifaces) ? "{80,443}" : "80"); + $rules .= "no rdr on $iface proto tcp from any to { $exempt_dest } port {$pf_transparent_rule_port}\n"; + } + /* Handle PPPOE case */ + if(($config['pppoe']['mode'] == "server" && $config['pppoe']['localip']) || (function_exists("is_pppoe_server_enabled") && is_pppoe_server_enabled())) { + $rules .= "no rdr on $PPPOE_ALIAS proto tcp from any to { $exempt_dest } port {$pf_rule_port}\n"; + } + /* Handle PPTP case */ + if($config['pptpd']['mode'] == "server" && $config['pptpd']['localip']) { + $rules .= "no rdr on $PPTP_ALIAS proto tcp from any to { $exempt_dest } port {$pf_rule_port}\n"; + } + } + foreach ($transparent_ifaces as $t_iface) { + $pf_transparent_rule_port=(in_array($t_iface,$ssl_ifaces) ? "{80,443}" : "80"); + $rules .= "rdr on $t_iface proto tcp from any to !($t_iface) port 80 -> 127.0.0.1 port {$port}\n"; + if (in_array($t_iface,$ssl_ifaces)) + $rules .= "rdr on $t_iface proto tcp from any to !($t_iface) port 443 -> 127.0.0.1 port {$ssl_port}\n"; + } + /* Handle PPPOE case */ + if(($config['pppoe']['mode'] == "server" && $config['pppoe']['localip']) || (function_exists("is_pppoe_server_enabled") && is_pppoe_server_enabled())) { + $rules .= "rdr on $PPPOE_ALIAS proto tcp from any to !127.0.0.1 port {$pf_rule_port} -> 127.0.0.1 port {$port}\n"; + } + /* Handle PPTP case */ + if($config['pptpd']['mode'] == "server" && $config['pptpd']['localip']) { + $rules .= "rdr on $PPTP_ALIAS proto tcp from any to !127.0.0.1 port {$pf_rule_port} -> 127.0.0.1 port {$port}\n"; + } + $rules .= "\n"; + break; + case 'filter': + case 'rule': + foreach ($transparent_ifaces as $iface) { + $pf_transparent_rule_port=(in_array($iface,$ssl_ifaces) ? "{80,443,{$port},{$ssl_port}}" : "{80,{$port}}"); + $rules .= "# Setup squid pass rules for proxy\n"; + $rules .= "pass in quick on $iface proto tcp from any to !($iface) port {$pf_transparent_rule_port} flags S/SA keep state\n"; + #$rules .= "pass in quick on $iface proto tcp from any to !($iface) port {$port} flags S/SA keep state\n"; + $rules .= "\n"; + }; + if($config['pppoe']['mode'] == "server" && $config['pppoe']['localip']) { + $rules .= "pass in quick on $PPPOE_ALIAS proto tcp from any to !127.0.0.1 port {$port} flags S/SA keep state\n"; + } + if($config['pptpd']['mode'] == "server" && $config['pptpd']['localip']) { + $rules .= "pass in quick on $PPTP_ALIAS proto tcp from any to !127.0.0.1 port {$port} flags S/SA keep state\n"; + } + break; + default: + break; + } + + return $rules; +} + +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_local_base = SQUID_LOCALBASE; + $rc = array(); + $rc['file'] = 'squid.sh'; + $rc['start'] = <<<EOD +if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then + {$squid_local_base}/sbin/squid -f {$squid_conffile_var} +fi + +EOD; + + $rc['stop'] = <<<EOD +{$squid_local_base}/sbin/squid -k shutdown -f {$squid_conffile_var} +# Just to be sure... +sleep 5 +killall -9 squid 2>/dev/null +killall pinger 2>/dev/null + +EOD; + $rc['restart'] = <<<EOD +if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then + {$squid_local_base}/sbin/squid -f {$squid_conffile_var} + else + {$squid_local_base}/sbin/squid -k reconfigure -f {$squid_conffile_var} + fi + +EOD; + conf_mount_rw(); + write_rcfile($rc); + conf_mount_ro(); +} + +/* Uses XMLRPC to synchronize the changes to a remote node */ +function squid_sync_on_changes() { + global $config, $g; + if (is_array($config['installedpackages']['squidsync']['config'])){ + $squid_sync=$config['installedpackages']['squidsync']['config'][0]; + $synconchanges = $squid_sync['synconchanges']; + $synctimeout = $squid_sync['synctimeout']; + switch ($synconchanges){ + case "manual": + if (is_array($squid_sync[row])){ + $rs=$squid_sync[row]; + } + else{ + log_error("[squid] xmlrpc sync is enabled but there is no hosts to push on squid config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['ipaddress']=$system_carp['synchronizetoip']; + $rs[0]['username']=$system_carp['username']; + $rs[0]['password']=$system_carp['password']; + } + else{ + log_error("[squid] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[squid] xmlrpc sync is starting."); + foreach($rs as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($password && $sync_to_ip) + squid_do_xmlrpc_sync($sync_to_ip, $username, $password,$synctimeout); + } + log_error("[squid] xmlrpc sync is ending."); + } + } +} +/* Do the actual XMLRPC sync */ +function squid_do_xmlrpc_sync($sync_to_ip, $username, $password, $synctimeout) { + global $config, $g; + + if(!$username) + return; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + + if(!$synctimeout) + $synctimeout=250; + + + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['squid'] = $config['installedpackages']['squid']; + $xml['squidupstream'] = $config['installedpackages']['squidupstream']; + $xml['squidcache'] = $config['installedpackages']['squidcache']; + $xml['squidantivirus'] = $config['installedpackages']['squidanitivirus']; + $xml['squidnac'] = $config['installedpackages']['squidnac']; + $xml['squidtraffic'] = $config['installedpackages']['squidtraffic']; + $xml['squidreversegeneral'] = $config['installedpackages']['squidreversegeneral']; + $xml['squidreversepeer'] = $config['installedpackages']['squidreversepeer']; + $xml['squidreverseuri'] = $config['installedpackages']['squidreverseuri']; + $xml['squidauth'] = $config['installedpackages']['squidauth']; + $xml['squidusers'] = $config['installedpackages']['squidusers']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("[Squid] Beginning squid XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after defined sync timeout value*/ + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, $synctimeout); + $error = "An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } else { + log_error("[Squid] XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell squid to reload our settings on the destination sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/squid.inc');\n"; + $execcmd .= "squid_resync('yes');"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("[Squid] XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, $synctimeout); + if(!$resp) { + $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, $synctimeout); + $error = "[Squid] An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } else { + log_error("squid XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } + +} +?> diff --git a/config/squid3/33/squid.xml b/config/squid3/33/squid.xml new file mode 100644 index 00000000..d64aabb9 --- /dev/null +++ b/config/squid3/33/squid.xml @@ -0,0 +1,557 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squid</name> + <version>3.3.4</version> + <title>Proxy server: General settings</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <menu> + <name>Proxy server</name> + <tooltiptext>Modify the proxy server's settings</tooltiptext> + <section>Services</section> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </menu> + <menu> + <name>Reverse Proxy</name> + <tooltiptext>Modify the proxy reverse server's settings</tooltiptext> + <section>Services</section> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + </menu> + <service> + <name>squid</name> + <rcfile>squid.sh</rcfile> + <executable>squid</executable> + <description>Proxy server Service</description> + </service> + <service> + <name>clamd</name> + <rcfile>clamav-clamd</rcfile> + <executable>clamd</executable> + <description>Clamav Antivirus</description> + </service> + <service> + <name>c-icap</name> + <rcfile>c-icap</rcfile> + <executable>c-icap</executable> + <description>Icap inteface for squid and clamav integration</description> + </service> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <!-- Installation --> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse_general.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse_peer.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse_uri.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse_sync.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_sync.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_cache.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_nac.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_ng.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_ng.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_traffic.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_upstream.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_auth.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_users.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_antivirus.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/sqpmon.sh</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/swapstate_check.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_reverse_redir.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_monitor.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_monitor_data.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid3/33/squid_log_parser.php</item> + </additional_files_needed> + + <fields> + <field> + <name>Squid General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Proxy interface(s)</fielddescr> + <fieldname>active_interface</fieldname> + <description>The interface(s) the proxy server will bind to.</description> + <type>interfaces_selection</type> + <required/> + <default_value>lan</default_value> + <multiple/> + </field> + <field> + <fielddescr>Proxy port</fielddescr> + <fieldname>proxy_port</fieldname> + <description>This is the port the proxy server will listen on.</description> + <type>input</type> + <size>5</size> + <required/> + <default_value>3128</default_value> + </field> + <field> + <fielddescr>ICP port</fielddescr> + <fieldname>icp_port</fieldname> + <description>This is the port the Proxy Server will send and receive ICP queries to and from neighbor caches. Leave this blank if you don't want the proxy server to communicate with neighbor caches through ICP.</description> + <type>input</type> + <size>5</size> + </field> + + <field> + <fielddescr>Allow users on interface</fielddescr> + <fieldname>allow_interface</fieldname> + <description>If this field is checked, the users connected to the interface selected in the 'Proxy interface' field will be allowed to use the proxy, i.e., there will be no need to add the interface's subnet to the list of allowed subnets. This is just a shortcut.</description> + <type>checkbox</type> + <required/> + <default_value>on</default_value> + </field> + <field> + <fielddescr>Patch captive portal</fielddescr> + <fieldname>patch_cp</fieldname> + <description><![CDATA[Enable this option to force captive portal to non transparent proxy users.<br> + <strong>NOTE:</strong> You may need to reapply captive portal config after changing this option.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Resolv dns v4 first</fielddescr> + <fieldname>dns_v4_first</fieldname> + <description><![CDATA[Enable this option to force dns v4 lookup first. This option is very usefull if you have problems to access https sites.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Use alternate DNS-servers for the proxy-server</fielddescr> + <fieldname>dns_nameservers</fieldname> + <description>If you want to use other DNS-servers than the DNS-forwarder, enter the IPs here, separated by semi-colons (;).</description> + <type>input</type> + <size>70</size> + </field> + <field> + <name>Transparent Proxy Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Transparent HTTP proxy</fielddescr> + <fieldname>transparent_proxy</fieldname> + <description><![CDATA[Enable transparent mode to forward all requests for destination port 80 to the proxy server without any additional configuration necessary.<br> + <strong>NOTE:</strong> Transparent mode will filter ssl(port 443) if enable men-in-the-middle options below.<br> + To filter both http and https protocol without intercepting ssl connections, enable WPAD/PAC options on your dns/dhcp.]]></description> + <type>checkbox</type> + <enablefields>transparent_active_interface,private_subnet_proxy_off,defined_ip_proxy_off,defined_ip_proxy_off_dest</enablefields> + <required/> + </field> + <field> + <fielddescr>Transparent Proxy interface(s)</fielddescr> + <fieldname>transparent_active_interface</fieldname> + <description>The interface(s) the proxy server will transparent intercept requests.</description> + <type>interfaces_selection</type> + <required/> + <default_value>lan</default_value> + <multiple/> + </field> + <field> + <fielddescr>Bypass proxy for Private Address destination</fielddescr> + <fieldname>private_subnet_proxy_off</fieldname> + <description>Do not forward traffic to Private Address Space (RFC 1918) <b>destination</b> through the proxy server but directly through the firewall.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Bypass proxy for these source IPs</fielddescr> + <fieldname>defined_ip_proxy_off</fieldname> + <description>Do not forward traffic from these <b>source</b> IPs, CIDR nets, hostnames, or aliases through the proxy server but directly through the firewall. Separate by semi-colons (;). [Applies only to transparent mode]</description> + <type>input</type> + <size>70</size> + </field> + <field> + <fielddescr>Bypass proxy for these destination IPs</fielddescr> + <fieldname>defined_ip_proxy_off_dest</fieldname> + <description>Do not proxy traffic going to these <b>destination</b> IPs, CIDR nets, hostnames, or aliases, but let it pass directly through the firewall. Separate by semi-colons (;). [Applies only to transparent mode]</description> + <type>input</type> + <size>70</size> + </field> + <field> + <name>SSL man in the middle Filtering</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>HTTPS/SSL interception</fielddescr> + <fieldname>ssl_proxy</fieldname> + <description><![CDATA[Enable SSL filtering.]]></description> + <type>checkbox</type> + <enablefields>ssl_active_interface,dcert,sslcrtd_children,ssl_proxy_port,interception_checks</enablefields> + </field> + <field> + <fielddescr>SSL Intercept interface(s)</fielddescr> + <fieldname>ssl_active_interface</fieldname> + <description>The interface(s) the proxy server will intercept ssl requests.</description> + <type>interfaces_selection</type> + <required/> + <default_value>lan</default_value> + <multiple/> + </field> + <field> + <fielddescr>SSL Proxy port</fielddescr> + <fieldname>ssl_proxy_port</fieldname> + <description>This is the port the proxy server will listen on to intercept ssl while using transparent proxy.</description> + <type>input</type> + <size>5</size> + <default_value>3129</default_value> + </field> + <field> + <fielddescr>CA</fielddescr> + <fieldname>dca</fieldname> + <description><![CDATA[Select Certificate Authority to use when SSL interception is enabled.<br> + To create a CA on pfsense, go to <strong>system -> Cert Manager<strong><br> + Install the CA crt as an trusted ca on each computer you want to filter ssl to avoid ssl error on each connection.]]></description> + <type>select_source</type> + <source><![CDATA[$config['ca']]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + <field> + <fielddescr>sslcrtd children</fielddescr> + <fieldname>sslcrtd_children</fieldname> + <description><![CDATA[This is the number of ssl crt deamon children to start. Default value is 5.<br> + if Squid is used in busy environments this may need to be increased, as well as the number of 'sslcrtd_children']]></description> + <type>input</type> + <size>2</size> + <default_value>5</default_value> + </field> + <field> + <fielddescr>Remote Cert checks</fielddescr> + <fieldname>interception_checks</fieldname> + <description><![CDATA[Select remote ssl cert checks to do.<br>Defaul is to do not select any of these options.]]></description> + <type>select</type> + <options> + <option><name>Accept remote server certificate Erros</name><value>sslproxy_cert_error</value></option> + <option><name>Do not verify remote certificate</name><value>sslproxy_flags</value></option> + </options> + <multiple/> + <size>3</size> + </field> + <field> + <fielddescr>Certificate adapt</fielddescr> + <fieldname>interception_adapt</fieldname> + <description><![CDATA[Pass original SSL server certificate information to the user. Allow the user to make an informed decision on whether to trust the server certificate.<br>Hint: Set subject CN<br><a target=_new href='http://wiki.squid-cache.org/Features/MimicSslServerCert'>wiki doc with reference</a>]]></description> + <type>select</type> + <options> + <option><name>Sets the "Not After" (setValidAfter).</name><value>setValidAfter</value></option> + <option><name>Sets the "Not Before" (setValidBefore).</name><value>setValidBefore</value></option> + <option><name>Sets CN property (setCommonName)</name><value>setCommonName</value></option> + </options> + <multiple/> + <size>3</size> + </field> + <field> + <name>Logging Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enabled logging</fielddescr> + <fieldname>log_enabled</fieldname> + <description>This will enable the access log. Don't switch this on if you don't have much disk space left.</description> + <type>checkbox</type> + <enablefields>log_query_terms,log_user_agents</enablefields> + </field> + <field> + <fielddescr>Log store directory</fielddescr> + <fieldname>log_dir</fieldname> + <description>The directory where the log will be stored (note: do not end with a / mark)</description> + <type>input</type> + <size>60</size> + <required/> + <default_value>/var/squid/logs</default_value> + </field> + <field> + <fielddescr>Log rotate</fielddescr> + <fieldname>log_rotate</fieldname> + <description>Defines how many days of logfiles will be kept. Rotation is disabled if left empty.</description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Visible hostname</fielddescr> + <fieldname>visible_hostname</fieldname> + <description>This is the URL to be displayed in proxy server error messages.</description> + <type>input</type> + <size>60</size> + <default_value>localhost</default_value> + </field> + <field> + <fielddescr>Administrator email</fielddescr> + <fieldname>admin_email</fieldname> + <description>This is the email address displayed in error messages to the users.</description> + <type>input</type> + <size>60</size> + <default_value>admin@localhost</default_value> + </field> + <field> + <fielddescr>Language</fielddescr> + <fieldname>error_language</fieldname> + <description>Select the language in which the proxy server will display error messages to users.</description> + <type>select</type> + <default_value>en</default_value> + </field> + <field> + <fielddescr>Disable X-Forward</fielddescr> + <fieldname>disable_xforward</fieldname> + <description>If not set, Squid will include your system's IP address or name in the HTTP requests it forwards.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Disable VIA</fielddescr> + <fieldname>disable_via</fieldname> + <description>If not set, Squid will include a Via header in requests and replies as required by RFC2616.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Log denied pages by squidguard</fielddescr> + <fieldname>log_sqd</fieldname> + <description><![CDATA[Enable squidguard denied log to be included on squid logs.<br> + <strong>Note:</strong> This option only will work if you include this code on your sgerror.php file to force client browser send a second request to squid with denied string on url.<br><br> + $sge_prefix=(preg_match("/\?/",$cl['u'])?"&":"?");<br> + $str[] = '< iframe > src="'.$cl['u'].$sge_prefix.'sgr=ACCESSDENIED" width="1" height="1" > < /iframe >';<br><br> + removing extra space on iframe html code.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>What to do with requests that have whitespace characters in the URI</fielddescr> + <fieldname>uri_whitespace</fieldname> + <description><b> strip:</b> The whitespace characters are stripped out of the URL. This is the behavior recommended by RFC2396. <p> <b> deny:</b> The request is denied. The user receives an "Invalid Request" message.<p> <b> allow:</b> The request is allowed and the URI is not changed. The whitespace characters remain in the URI.<p> <b> encode:</b> The request is allowed and the whitespace characters are encoded according to RFC1738.<p> <b> chop:</b> The request is allowed and the URI is chopped at the first whitespace.</description> + <type>select</type> + <default_value>strip</default_value> + <options> + <option><name>strip</name><value>strip</value></option> + <option><name>deny</name><value>deny</value></option> + <option><name>allow</name><value>allow</value></option> + <option><name>encode</name><value>encode</value></option> + <option><name>chop</name><value>chop</value></option> + </options> + </field> + <field> + <fielddescr>Suppress Squid Version</fielddescr> + <fieldname>disable_squidversion</fieldname> + <description>If set, suppress Squid version string info in HTTP headers and HTML error pages.</description> + <type>checkbox</type> + </field> + <field> + <name>Custom Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Integrations</fielddescr> + <fieldname>custom_options</fieldname> + <description><![CDATA[Squid options added from packages like squidguard or havp for squid integration.]]></description> + <type>textarea</type> + <cols>78</cols> + <rows>5</rows> + </field> + <field> + <fielddescr>Custom Options</fielddescr> + <fieldname>custom_options_squid3</fieldname> + <description><![CDATA[Put your own custom options here,one per line. They'll be added to the configuration.<br> + <strong>They need to be squid.conf native options, otherwise squid will NOT work.</strong>]]></description> + <type>textarea</type> + <encoding>base64</encoding> + <cols>78</cols> + <rows>10</rows> + </field> + </fields> + <custom_php_command_before_form> + squid_before_form_general(&$pkg); + </custom_php_command_before_form> + <custom_add_php_command> + squid_resync(); + </custom_add_php_command> + <custom_php_validation_command> + squid_validate_general($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + unlink_if_exists("/usr/local/etc/rc.d/squid"); + </custom_php_resync_config_command> + <custom_php_install_command> + update_status("Checking Squid cache... One moment please..."); + update_output_window("This operation may take quite some time, please be patient. Do not press stop or attempt to navigate away from this page during this process."); + squid_install_command(); + squid_resync(); + exec("/bin/rm -f /usr/local/etc/rc.d/squid"); + </custom_php_install_command> + <custom_php_deinstall_command> + squid_deinstall_command(); + exec("/bin/rm -f /usr/local/etc/rc.d/squid*"); + </custom_php_deinstall_command> + <filter_rules_needed>squid_generate_rules</filter_rules_needed> +</packagegui> diff --git a/config/squid3/33/squid_antivirus.xml b/config/squid3/33/squid_antivirus.xml new file mode 100755 index 00000000..67319297 --- /dev/null +++ b/config/squid3/33/squid_antivirus.xml @@ -0,0 +1,158 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_antivirus.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidantivirus</name> + <version>none</version> + <title>Proxy server: Antivirus</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + <active/> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Clamav anti-virus integration using c-icap</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <description>Enable squid antivirus check using clamav.</description> + <enablefields>max_check_size,Timeout,MaxKeepAliveRequests,KeepAliveTimeout,StartServers,MaxServers</enablefields> + <type>checkbox</type> + </field> + <field> + <fielddescr>Client forward options</fielddescr> + <fieldname>client_info</fieldname> + <description><![CDATA[Select what client info to forward to clamav.]]></description> + <type>select</type> + <default_value>strip</default_value> + <options> + <option><name>Send Both client username and ip info(Default)</name><value>both</value></option> + <option><name>Send only client username</name><value>username</value></option> + <option><name>Send only client ip</name><value>ip</value></option> + <option><name>Do not send client info</name><value>none</value></option> + </options> + </field> + <field> + <name>Advanced options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>squidclamav.conf</fielddescr> + <fieldname>squidclamav</fieldname> + <description>squidclamav.conf file. Leave empty to load sample file. Edit only if you know what are you doing.</description> + <type>textarea</type> + <encoding>base64</encoding> + <cols>75</cols> + <rows>15</rows> + </field> + <field> + <fielddescr>c-icap.conf</fielddescr> + <fieldname>c-icap_conf</fieldname> + <description>c-icap.conf file. Leave empty to load sample file. Edit only if you know what are you doing.</description> + <type>textarea</type> + <encoding>base64</encoding> + <cols>75</cols> + <rows>15</rows> + </field> + <field> + <fielddescr>c-icap.magic</fielddescr> + <fieldname>c-icap_magic</fieldname> + <description>c-icap.conf file. Leave empty to load sample file. Edit only if you know what are you doing.</description> + <type>textarea</type> + <encoding>base64</encoding> + <cols>75</cols> + <rows>15</rows> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/squid_auth.inc b/config/squid3/33/squid_auth.inc index 7c99a01b..7c99a01b 100644 --- a/config/squid3/squid_auth.inc +++ b/config/squid3/33/squid_auth.inc diff --git a/config/squid3/33/squid_auth.xml b/config/squid3/33/squid_auth.xml new file mode 100755 index 00000000..111085a8 --- /dev/null +++ b/config/squid3/33/squid_auth.xml @@ -0,0 +1,269 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidauth</name> + <version>none</version> + <title>Proxy server: Authentication</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Authentication General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Authentication method</fielddescr> + <fieldname>auth_method</fieldname> + <description>Select an authentication method. This will allow users to be authenticated by local or external services.</description> + <type>select</type> + <required/> + <default_value>none</default_value> + <options> + <option><name>None</name><value>none</value></option> + <option><name>Local</name><value>local</value></option> + <option><name>LDAP</name><value>ldap</value></option> + <option><name>RADIUS</name><value>radius</value></option> + <option><name>NT domain</name><value>msnt</value></option> + </options> + <onchange>on_auth_method_changed()</onchange> + </field> + <field> + <fielddescr>Authentication server</fielddescr> + <fieldname>auth_server</fieldname> + <description>Enter here the IP or hostname of the server that will perform the authentication.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Authentication server port</fielddescr> + <fieldname>auth_server_port</fieldname> + <description>Enter here the port to use to connect to the authentication server. Leave this field blank to use the authentication method's default port.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Authentication prompt</fielddescr> + <fieldname>auth_prompt</fieldname> + <description>This string will be displayed at the top of the authentication request window.</description> + <type>input</type> + <default_value>Please enter your credentials to access the proxy</default_value> + </field> + <field> + <fielddescr>Authentication processes</fielddescr> + <fieldname>auth_processes</fieldname> + <description>The number of authenticator processes to spawn. If many authentications are expected within a short timeframe, increase this number accordingly.</description> + <type>input</type> + <size>60</size> + <default_value>5</default_value> + </field> + <field> + <fielddescr>Authentication TTL</fielddescr> + <fieldname>auth_ttl</fieldname> + <description>This specifies for how long (in minutes) the proxy server assumes an externally validated username and password combination is valid (Time To Live). When the TTL expires, the user will be prompted for credentials again.</description> + <type>input</type> + <size>60</size> + <default_value>60</default_value> + </field> + <field> + <fielddescr>Requiere authentication for unrestricted hosts</fielddescr> + <fieldname>unrestricted_auth</fieldname> + <description>If this option is enabled, even users tagged as unrestricted through access control are required to authenticate to use the proxy.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Subnets that don't need authentication</fielddescr> + <fieldname>no_auth_hosts</fieldname> + <description>Enter each subnet or IP address on a new line (in CIDR format, e.g.: 10.5.0.0/16, 192.168.1.50/32) that should not be asked for authentication to access the proxy.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <name>Squid Authentication Ldap Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>LDAP version</fielddescr> + <fieldname>ldap_version</fieldname> + <description>Enter LDAP protocol version (2 or 3).</description> + <type>select</type> + <default_value>2</default_value> + <options> + <option><name>2</name><value>2</value></option> + <option><name>3</name><value>3</value></option> + </options> + </field> + <field> + <fielddescr>LDAP server user DN</fielddescr> + <fieldname>ldap_user</fieldname> + <description>Enter here the user DN to use to connect to the LDAP server.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>LDAP password</fielddescr> + <fieldname>ldap_pass</fieldname> + <description>Enter here the password to use to connect to the LDAP server.</description> + <type>password</type> + <size>60</size> + </field> + <field> + <fielddescr>LDAP base domain</fielddescr> + <fieldname>ldap_basedomain</fieldname> + <description>For LDAP authentication, enter here the base domain in the LDAP server.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>LDAP username DN attribute</fielddescr> + <fieldname>ldap_userattribute</fieldname> + <description>Enter LDAP username DN attibute.</description> + <type>input</type> + <size>60</size> + <default_value>uid</default_value> + </field> + <field> + <fielddescr>LDAP search filter</fielddescr> + <fieldname>ldap_filter</fieldname> + <description>Enter LDAP search filter.</description> + <type>input</type> + <size>60</size> + <default_value>(&(objectClass=person)(uid=%s))</default_value> + </field> + <field> + <name>Squid Authentication NT Domain Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>NT domain</fielddescr> + <fieldname>auth_ntdomain</fieldname> + <description>Enter here the NT domain.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Secondary NT servers</fielddescr> + <fieldname>msnt_secondary</fieldname> + <description>Comma-separated list of secondary servers to be used for NT domain authentication.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <name>Squid Authentication Radius Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>RADIUS secret</fielddescr> + <fieldname>radius_secret</fieldname> + <description>The RADIUS secret for RADIUS authentication.</description> + <type>password</type> + <size>60</size> + </field> + </fields> + <custom_php_validation_command> + squid_validate_auth($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_after_form_command> + squid_print_javascript_auth2(); + </custom_php_after_form_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> + <custom_php_before_form_command> + squid_print_javascript_auth2(); + </custom_php_before_form_command> + <custom_php_after_head_command> + $transparent_proxy = ($config['installedpackages']['squid']['config'][0]['transparent_proxy'] == 'on'); + if($transparent_proxy) + $input_errors[] = "Authentication cannot be enabled while transparent proxy mode is enabled"; + squid_print_javascript_auth(); + </custom_php_after_head_command> +</packagegui> diff --git a/config/squid3/33/squid_cache.xml b/config/squid3/33/squid_cache.xml new file mode 100755 index 00000000..26d6463c --- /dev/null +++ b/config/squid3/33/squid_cache.xml @@ -0,0 +1,311 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidcache</name> + <version>none</version> + <title>Proxy server: Cache management</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> +<tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Cache General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Cache replacement policy</fielddescr> + <fieldname>cache_replacement_policy</fieldname> + <description>The cache replacement policy decides which objects will remain in cache and which objects are replaced to create space for the new objects. The default policy for cache replacement is LFUDA. Please see the type descriptions specified in the memory replacement policy for additional detail.</description> + <type>select</type> + <default_value>heap LFUDA</default_value> + <options> + <option><name>LRU</name><value>lru</value></option> + <option><name>Heap LFUDA</name><value>heap LFUDA</value></option> + <option><name>Heap GDSF</name><value>heap GDSF</value></option> + <option><name>Heap LRU</name><value>heap LRU</value></option> + </options> + </field> + <field> + <fielddescr>Low-water-mark in %</fielddescr> + <fieldname>cache_swap_low</fieldname> + <description>Cache replacement begins when the swap usage is above the low-low-water mark and attempts to maintain utilisation near the low-water-mark.</description> + <type>input</type> + <size>5</size> + <default_value>90</default_value> + </field> + <field> + <fielddescr>High-water-mark in %</fielddescr> + <fieldname>cache_swap_high</fieldname> + <description>As swap utilisation gets close to the high-water-mark object eviction becomes more aggressive.</description> + <type>input</type> + <size>5</size> + <default_value>95</default_value> + </field> + <field> + <fielddescr>Do not cache</fielddescr> + <fieldname>donotcache</fieldname> + <description>Enter each domain or IP address on a new line that should never be cached.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Enable offline mode</fielddescr> + <fieldname>enable_offline</fieldname> + <description>Enable this option and the proxy server will never try to validate cached objects. The offline mode gives access to more cached information than the proposed feature would allow (stale cached versions, where the origin server should have been contacted).</description> + <type>checkbox</type> + <required/> + </field> + <field> + <fielddescr>External Cache-Managers</fielddescr> + <fieldname>ext_cachemanager</fieldname> + <description>Enter the IPs for the external Cache Managers to be allowed here, separated by semi-colons (;).</description> + <type>input</type> + <size>60</size> + </field> + <field> + <name>Squid Hard disk cacheSettings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Hard disk cache size</fielddescr> + <fieldname>harddisk_cache_size</fieldname> + <description>This is the amount of disk space (in megabytes) to use for cached objects.</description> + <type>input</type> + <required/> + <size>10</size> + <default_value>100</default_value> + </field> + <field> + <fielddescr>Hard disk cache system</fielddescr> + <fieldname>harddisk_cache_system</fieldname> + <description>This specifies the kind of storage system to use. <p> <b> ufs </b> is the old well-known Squid storage format that has always been there. <p> <b> aufs </b> uses POSIX-threads to avoid blocking the main Squid process on disk-I/O. (Formerly known as async-io.) <p> <b> diskd </b> uses a separate process to avoid blocking the main Squid process on disk-I/O. <p> <b> null </b> Does not use any storage. Ideal for Embedded/NanoBSD.</description> + <type>select</type> + <default_value>ufs</default_value> + <options> + <option><name>ufs</name><value>ufs</value></option> + <option><name>aufs</name><value>aufs</value></option> + <option><name>diskd</name><value>diskd</value></option> + <option><name>null</name><value>null</value></option> + </options> + </field> + <field> + <fielddescr>Level 1 subdirectories</fielddescr> + <fieldname>level1_subdirs</fieldname> + <description>Each level-1 directory contains 256 subdirectories, so a value of 256 level-1 directories will use a total of 65536 directories for the hard disk cache. This will significantly slow down the startup process of the proxy service, but can speed up the caching under certain conditions.</description> + <type>select</type> + <default_value>16</default_value> + <options> + <option><name>4</name><value>4</value></option> + <option><name>8</name><value>8</value></option> + <option><name>16</name><value>16</value></option> + <option><name>32</name><value>32</value></option> + <option><name>64</name><value>64</value></option> + <option><name>128</name><value>128</value></option> + <option><name>256</name><value>256</value></option> + </options> + </field> + <field> + <fielddescr>Hard disk cache location</fielddescr> + <fieldname>harddisk_cache_location</fieldname> + <description>This is the directory where the cache will be stored. (note: do not end with a /). If you change this location, squid needs to make a new cache, this could take a while</description> + <type>input</type> + <size>60</size> + <required/> + <default_value>/var/squid/cache</default_value> + </field> + <field> + <fielddescr>Minimum object size</fielddescr> + <fieldname>minimum_object_size</fieldname> + <description>Objects smaller than the size specified (in kilobytes) will not be saved on disk. The default value is 0, meaning there is no minimum.</description> + <type>input</type> + <required /> + <size>10</size> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Maximum object size</fielddescr> + <fieldname>maximum_object_size</fieldname> + <description>Objects larger than the size specified (in kilobytes) will not be saved on disk. If you wish to increase speed more than you want to save bandwidth, this should be set to a low value.</description> + <type>input</type> + <required/> + <size>10</size> + <default_value>4</default_value> + </field> + <field> + <name>Squid Memory Cache Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Memory cache size</fielddescr> + <fieldname>memory_cache_size</fieldname> + <description>This is the amount of physical RAM (in megabytes) to be used for negative cache and in-transit objects. This value should not exceed more than 50% of the installed RAM. The minimum value is 1MB.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>8</default_value> + </field> + <field> + <fielddescr>Maximum object size in RAM</fielddescr> + <fieldname>maximum_objsize_in_mem</fieldname> + <description>Objects smaller than the size specified (in kilobytes) will be saved in RAM. Default is 32.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>32</default_value> + </field> + <field> + <fielddescr>Memory replacement policy</fielddescr> + <fieldname>memory_replacement_policy</fieldname> + <description>The memory replacement policy determines which objects are purged from memory when space is needed. The default policy for memory replacement is GDSF. <p> <b> LRU: Last Recently Used Policy </b> - The LRU policies keep recently referenced objects. i.e., it replaces the object that has not been accessed for the longest time. <p> <b> Heap GDSF: Greedy-Dual Size Frequency </b> - The Heap GDSF policy optimizes object-hit rate by keeping smaller, popular objects in cache. It achieves a lower byte hit rate than LFUDA though, since it evicts larger (possibly popular) objects. <p> <b> Heap LFUDA: Least Frequently Used with Dynamic Aging </b> - The Heap LFUDA policy keeps popular objects in cache regardless of their size and thus optimizes byte hit rate at the expense of hit rate since one large, popular object will prevent many smaller, slightly less popular objects from being cached. <p> <b> Heap LRU: Last Recently Used </b> - Works like LRU, but uses a heap instead. <p> Note: If using the LFUDA replacement policy, the value of Maximum Object Size should be increased above its default of 12KB to maximize the potential byte hit rate improvement of LFUDA.</description> + <type>select</type> + <default_value>heap GDSF</default_value> + <options> + <option><name>LRU</name><value>lru</value></option> + <option><name>Heap LFUDA</name><value>heap LFUDA</value></option> + <option><name>Heap GDSF</name><value>heap GDSF</value></option> + <option><name>Heap LRU</name><value>heap LRU</value></option> + </options> + </field> + <field> + <name>Dynamic and Update Content</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Cache Dynamic Content</fielddescr> + <fieldname>cache_dynamic_content</fieldname> + <description><![CDATA[Select this option to <a target=_new href='http://wiki.squid-cache.org/ConfigExamples/DynamicContent'>enable caching of dynamic content.</a><br> + ]]></description> + <type>checkbox</type> + <size>10</size> + </field> + <field> + <fielddescr>Refresh Patterns</fielddescr> + <fieldname>refresh_patterns</fieldname> + <description><![CDATA[With dynamic cache enabled, you can also apply squid wiki refresh_patterns to sites like <a target=_new href='http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube'>Youtube</a> and <a target=_new href='http://wiki.squid-cache.org/SquidFaq/WindowsUpdate'>windowsupdate</a><br> + <br><strong>Notes:</strong><br> + Squid wiki suggests 'Finish transfer if less than x KB remaining' on 'traffic mgmt' squid tab to -1 but you can apply your own values to control cache.<br><br> + set Maximum download size on 'traffic mgmt' squid tab to a value that fits patterns your are applying.<br>Microsoft may need 200Mb and youtube 4GB.]]></description> + <type>select</type> + <default_value>none</default_value> + <options> + <option><name>Youtube</name><value>youtube</value></option> + <option><name>Windows Update</name><value>windows</value></option> + <option><name>Symantec Antivirus</name><value>symantec</value></option> + <option><name>Avira</name><value>avira</value></option> + <option><name>Avast</name><value>avast</value></option> + </options> + <multiple/> + <size>06</size> + </field> + <field> + <fielddescr>Custom refresh_patterns</fielddescr> + <fieldname>custom_refresh_patterns</fieldname> + <description>Enter custom refresh_patterns for better dynamic cache. This options will be included only if dynamic cache is enabled.</description> + <type>textarea</type> + <cols>67</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + </fields> + <custom_php_command_before_form> + if($_POST['harddisk_cache_size'] != $config['installedpackages']['squidcache']['config'][0]['harddisk_cache_size']) { + $needs_dash_z = true; + } + </custom_php_command_before_form> + <custom_php_validation_command> + squid_validate_cache($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + if($needs_dash_z) + squid_dash_z(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_cpauth.php b/config/squid3/33/squid_cpauth.php new file mode 100644 index 00000000..e0971c5d --- /dev/null +++ b/config/squid3/33/squid_cpauth.php @@ -0,0 +1,24 @@ +#!/usr/local/bin/php -q +<?php + +$NONINTERACTIVE_SCRIPT = TRUE; + +$fp = fopen('php://stdin', 'r'); +while($args = split(" ",trim(fgets($fp, 4096)))){ + print captive_ip_to_username($args); +} + +function captive_ip_to_username($args){ + $current_sessions = file("/var/db/captiveportal.db"); + foreach($current_sessions as $session){ + list($a, $b, $IP_Address, $Mac_Address, $Username) = explode(",", $session,5); + #this test allow access if user's ip is listed on captive portal + #args array has (ip, site, protocol and port) passed by squid helper + #include a more complex test here to allow or deny access based on username returned + # this script will not return username to squid logs + if($IP_Address == $args[0]) return "OK\n"; + } + return "ERR\n"; +} + +?> diff --git a/config/squid3/squid_extauth.xml b/config/squid3/33/squid_extauth.xml index 41d9f633..41d9f633 100644 --- a/config/squid3/squid_extauth.xml +++ b/config/squid3/33/squid_extauth.xml diff --git a/config/squid3/33/squid_ident.php b/config/squid3/33/squid_ident.php new file mode 100644 index 00000000..ad13beb6 --- /dev/null +++ b/config/squid3/33/squid_ident.php @@ -0,0 +1,148 @@ +#!/usr/bin/php +#http://blog.dataforce.org.uk/2010/03/Ident-Server +<?php + /** + * Simple PHP-Based inetd ident server, version 0.1. + * Copyright (c) 2010 - Shane "Dataforce" Mc Cormack + * This code is licensed under the MIT License, of which a copy can be found + * at http://www.opensource.org/licenses/mit-license.php + * + * The latest version of the code can be found at + * http://blog.dataforce.org.uk/index.php?p=news&id=135 + * + * This should be run from inetd, it will take input on stdin and write to stdout. + * + * By default users can spoof ident by having a .ident file in /home/<username>/.ident + * If this is present, it will be read. + * It should be a file with a format like so: + * + * <pid> <ident> + * <local host>:<local port>:<target host>:<target port> <ident> + * + * The first line that matches is used, any bit can be a * and it will always match, + * so "* user" is valid. In future more sophisticated matches will be permitted + * (eg 127.*) but for now its either all or nothing. + * + * Its worth noting that <target host> is the host that requests the ident, so if this + * is likely to be different than the host that was connected to, then "STRICT_HOST" will + * need to be set to false. + * + * At the moment <local host> is ignored, in future versions this might be changed, so + * it is still required. + * + * Lines with a ':' in them are assumed to be of the second format, and must contain + * all 4 sections or they will be ignored. + * + * Lines starting with a # are ignored. + * + * There are some special values that can be used as idents: + * ! = Send an error instead. + * * = Send the default ident. + * ? = Send a random ident (In future a 3rd parameter will specify the format, + * # for a number, @ for a letter, ? for either, but this is not implemented yet) + * + * In future there will also be support for /home/user/.ident.d/ directories, where + * every file will be read for the ident response untill one matches. + * This will allow multiple processes to create files rather than needing to + * lock and edit .ident + */ + + // Allow spoofing idents. + define('ALLOW_SPOOF', true); + + // Requesting host must be the same as the host that was connected to. + define('STRICT_HOST', true); + + // Error to send when '!' is used as an ident. + define('HIDE_ERROR', 'UNKNOWN-ERROR'); + + openlog('simpleIdent', LOG_PID | LOG_ODELAY, LOG_DAEMON); + + $result = 'ERROR : UNKNOWN-ERROR' . "\n"; + + $host = $_SERVER['REMOTE_HOST']; + + syslog(LOG_INFO, 'Connection from: '.$host); + + // Red in the line from the socket. + $fh = @fopen('php://stdin', 'r'); + if ($fh) { + $input = @fgets($fh); + $line = trim($input); + if ($input !== FALSE && !empty($line)) { + $result = trim($input) . ' : ' . $result; + // Get the data from it. + $bits = explode(',', $line); + $source = trim($bits[0]); + $dest = isset($bits[1]) ? trim($bits[1]) : ''; + + // Check if it is valid + if (preg_match('/^[0-9]+$/', $source) && preg_match('/^[0-9]+$/', $dest)) { + // Now actually look for this! + $match = STRICT_HOST ? ":$source .*$host:$dest " : ":$source.*:$dest"; + + $output = `netstat -napW 2>&1 | grep '$match' | awk '{print \$7}'`; + + $bits = explode('/', $output); + $pid = $bits[0]; + + if (preg_match('/^[0-9]+$/', $pid)) { + $user = `ps -o ruser=SOME-REALLY-WIDE-USERNAMES-ARE-PERMITTED-HERE $pid | tail -n 1`; + + $senduser = trim($user); + + // Look for special ident file: /home/user/.ident this is an ini-format file. + $file = '/home/'.trim($user).'/.ident'; + + if (file_exists($file)) { + $config = file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES | FILE_TEXT); + foreach ($config as $line) { + // Ignore comments. + $line = trim($line); + if (substr($line, 1) == '#') { continue; } + + // Make sure line is valid. + $bits = explode(' ', $line); + if (count($bits) == 1) { continue; } + + // Check type of line + if (strpos($bits[0], ':') !== FALSE) { + // LocalHost:LocalPort:RemoteHost:RemotePort + $match = explode(':', $bits[0]); + if (count($match) != 4) { continue; } + + if (($match[1] == '*' || $match[1] == $source) && + ($match[2] == '*' || $match[2] == $host) && + ($match[3] == '*' || $match[3] == $dest)) { + syslog(LOG_INFO, 'Spoof for '.$senduser.': '.$line); + $senduser = $bits[1]; + break; + } + } else if ($bits[0] == '*' || $bits[0] == $pid) { + syslog(LOG_INFO, 'Spoof for '.$senduser.': '.$line); + $senduser = $bits[1]; + } + } + + if ($senduser == "*") { + $senduser = trim(user); + } else if ($senduser == "?") { + $senduser = 'user'.rand(1000,9999); + } + } + + if ($senduser != "!") { + $result = $source . ', ' . $dest . ' : USERID : UNIX : ' . trim($senduser); + } else { + $result = $source . ', ' . $dest . ' : ERROR : ' . HIDE_ERROR; + } + } + } + } + } + + echo $result; + syslog(LOG_INFO, 'Result: '.$result); + closelog(); + exit(0); +?> diff --git a/config/squid3/33/squid_log_parser.php b/config/squid3/33/squid_log_parser.php new file mode 100755 index 00000000..f6cd7de8 --- /dev/null +++ b/config/squid3/33/squid_log_parser.php @@ -0,0 +1,57 @@ +#!/usr/local/bin/php -q +<?php +/* ========================================================================== */ +/* + squid_log_parser.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + 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. + */ +/* ========================================================================== */ + +# ------------------------------------------------------------------------------ +# Simple Squid Log parser to rewrite line with date/time human readable +# Usage: cat /var/squid/log/access.log | parser_squid_log.php +# ------------------------------------------------------------------------------ + +$logline = fopen("php://stdin", "r"); +while(!feof($logline)) { + $line = fgets($logline); + $line = rtrim($line); + if ($line != "") { + $fields = explode(' ', $line); + // Apply date format + $fields[0] = date("d.m.Y H:i:s",$fields[0]); + foreach($fields as $field) { + // Write the Squid log line with date/time human readable + echo "{$field} "; + } + echo "\n"; + } +} +fclose($logline); +?>
\ No newline at end of file diff --git a/config/squid3/33/squid_monitor.php b/config/squid3/33/squid_monitor.php new file mode 100755 index 00000000..3a7b1d01 --- /dev/null +++ b/config/squid3/33/squid_monitor.php @@ -0,0 +1,199 @@ +<?php +/* ========================================================================== */ +/* + squid_monitor.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + 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("/etc/inc/util.inc"); +require_once("/etc/inc/functions.inc"); +require_once("/etc/inc/pkg-utils.inc"); +require_once("/etc/inc/globals.inc"); +require_once("guiconfig.inc"); + +$pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); +if(strstr($pfSversion, "1.2")) + $one_two = true; + +$pgtitle = "Status: Proxy Monitor"; +include("head.inc"); +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<?php include("fbegin.inc"); ?> + +<?php if($one_two): ?> + + <p class="pgtitle"><?=$pgtitle?></font></p> + +<?php endif; ?> + +<?php if ($savemsg) print_info_box($savemsg); ?> + +<!-- Function to call programs logs --> +<script language="JavaScript"> + function showLog(content,url,program) + { + new PeriodicalExecuter(function(pe) { + new Ajax.Updater(content, url, { + method: 'post', + asynchronous: true, + evalScripts: true, + parameters: { maxlines: $('maxlines').getValue(), + strfilter: $('strfilter').getValue(), + program: program } + }) + }, 1) + } +</script> +<div id="mainlevel"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> + <?php + $tab_array = array(); + if ($_REQUEST["menu"]=="reverse"){ + $tab_array[] = array(gettext("General"), false, "/pkg_edit.php?xml=squid_reverse_general.xml&id=0"); + $tab_array[] = array(gettext("Web Servers"), false, "/pkg.php?xml=squid_reverse_peer.xml"); + $tab_array[] = array(gettext("Mappings"), false, "/pkg.php?xml=squid_reverse_uri.xml"); + $tab_array[] = array(gettext("Redirects"), false, "/pkg.php?xml=squid_reverse_redir.xml"); + $tab_array[] = array(gettext("Real time"), true, "/squid_monitor.php?menu=reverse"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=squid_reverse_sync.xml"); + } + else{ + $tab_array[] = array(gettext("General"), false, "/pkg_edit.php?xml=squid.xml&id=0"); + $tab_array[] = array(gettext("Remote Cache"), false, "/pkg.php?xml=squid_upstream.xml"); + $tab_array[] = array(gettext("Local Cache"), false, "/pkg_edit.php?xml=squid_cache.xml&id=0"); + $tab_array[] = array(gettext("Antivirus"), false, "/pkg_edit.php?xml=antivirus.xml&id=0"); + $tab_array[] = array(gettext("ACLs"), false, "/pkg_edit.php?xml=squid_nac.xml&id=0"); + $tab_array[] = array(gettext("Traffic Mgmt"), false, "/pkg_edit.php?xml=squid_traffic.xml&id=0"); + $tab_array[] = array(gettext("Authentication"), false, "/pkg_edit.php?xml=squid_auth.xml&id=0"); + $tab_array[] = array(gettext("Users"), false, "/pkg.php?xml=squid_users.xml"); + $tab_array[] = array(gettext("Real time"), true, "/squid_monitor.php"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=squid_sync.xml"); + } + display_top_tabs($tab_array); + ?> +</td></tr> + <tr> + <td> +<div id="mainarea" style="padding-top: 0px; padding-bottom: 0px; "> + <form id="paramsForm" name="paramsForm" method="post"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> + <tbody> + <tr> + <td width="22%" valign="top" class="vncellreq">Max lines:</td> + <td width="78%" class="vtable"> + <select name="maxlines" id="maxlines"> + <option value="5">5 lines</option> + <option value="10" selected="selected">10 lines</option> + <option value="15">15 lines</option> + <option value="20">20 lines</option> + <option value="25">25 lines</option> + <option value="100">100 lines</option> + <option value="200">200 lines</option> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq">String filter:</td> + <td width="78%" class="vtable"> + <input name="strfilter" type="text" class="formfld search" id="strfilter" size="50" value=""> + <br/> + <span class="vexpl"> + <?=gettext("Enter a grep like string/pattern to filterlog.");?><br> + <?=gettext("eg. username, ip addr, url.");?><br> + <?=gettext("Use <b>!</b> to invert the sense of matching, to select non-matching lines.");?> + </span> + </td> + </tr> + </tbody> + </table> + </form> + + <!-- Squid Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="6" class="listtopic"><center><?=gettext("Squid Logs"); ?><center></td> + </tr> + <tbody id="squidView"> + <script language="JavaScript"> + // Call function to show squid log + showLog('squidView', 'squid_monitor_data.php','squid'); + </script> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> +<?php if ($_REQUEST["menu"]!="reverse"){?> + <!-- SquidGuard Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="5" class="listtopic"><center><?=gettext("SquidGuard Logs"); ?><center></td> + </tr> + <tbody id="sguardView"> + <script language="JavaScript"> + // Call function to show squidGuard log + showLog('sguardView', 'squid_monitor_data.php','sguard'); + </script> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> +</div> +<?php }?> +</td> +</tr> +</table> +</div> + + +<?php +include("fend.inc"); +?> + +</body> +</html> diff --git a/config/squid3/33/squid_monitor_data.php b/config/squid3/33/squid_monitor_data.php new file mode 100755 index 00000000..7e27919d --- /dev/null +++ b/config/squid3/33/squid_monitor_data.php @@ -0,0 +1,175 @@ +<?php +/* ========================================================================== */ +/* + squid_monitor_data.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + 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. + */ +/* ========================================================================== */ +# ------------------------------------------------------------------------------ +# Defines +# ------------------------------------------------------------------------------ +require_once("guiconfig.inc"); + +# ------------------------------------------------------------------------------ +# Requests +# ------------------------------------------------------------------------------ +if ($_POST) { + # Actions + $filter = preg_replace('/(@|!|>|<)/',"",htmlspecialchars($_POST['strfilter'])); + $program = strtolower($_POST['program']); + switch ($program) { + case 'squid': + // Define log file + $log='/var/squid/logs/access.log'; + //show table headers + show_tds(array("Date","IP","Status","Address","User","Destination")); + //fetch lines + $logarr=fetch_log($log); + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\s+/", $logent); + + // Apply date format to first line + //$logline[0] = date("d.m.Y H:i:s",$logline[0]); + + // Word wrap the URL + $logline[7] = htmlentities($logline[7]); + $logline[7] = html_autowrap($logline[7]); + + // Remove /(slash) in destination row + $logline_dest = preg_split("/\//", $logline[9]); + + // Apply filter and color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + echo "<tr valign=\"top\">\n"; + echo "<td class=\"listlr\" nowrap>{$logline[0]} {$logline[1]}</td>\n"; + echo "<td class=\"listr\">{$logline[3]}</td>\n"; + echo "<td class=\"listr\">{$logline[4]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$logline[7]}</td>\n"; + echo "<td class=\"listr\">{$logline[8]}</td>\n"; + echo "<td class=\"listr\">{$logline_dest[1]}</td>\n"; + echo "</tr>\n"; + } + break; + case 'sguard'; + $log='/var/squidGuard/log/block.log'; + //show table headers + show_tds(array("Date-Time","ACL","Address","Host","User")); + //fetch lines + $logarr=fetch_log($log); + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\s+/", $logent); + + // Apply time format + $logline[0] = date("d.m.Y", strtotime($logline[0])); + + // Word wrap the URL + $logline[4] = htmlentities($logline[4]); + $logline[4] = html_autowrap($logline[4]); + + + // Apply filter color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + + + echo "<tr>\n"; + echo "<td class=\"listlr\" nowrap>{$logline[0]} {$logline[1]}</td>\n"; + echo "<td class=\"listr\">{$logline[3]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$logline[4]}</td>\n"; + echo "<td class=\"listr\">{$logline[5]}</td>\n"; + echo "<td class=\"listr\">{$logline[6]}</td>\n"; + echo "</tr>\n"; + } + break; + } +} + +# ------------------------------------------------------------------------------ +# Functions +# ------------------------------------------------------------------------------ + +// From SquidGuard Package +function html_autowrap($cont) +{ + # split strings + $p = 0; + $pstep = 25; + $str = $cont; + $cont = ''; + for ( $p = 0; $p < strlen($str); $p += $pstep ) { + $s = substr( $str, $p, $pstep ); + if ( !$s ) break; + $cont .= $s . "<wbr/>"; + } + return $cont; +} + + +// Show Squid Logs +function fetch_log($log){ + global $filter,$program; + // Get Data from form post + $lines = $_POST['maxlines']; + if (preg_match("/!/",htmlspecialchars($_POST['strfilter']))) + $grep_arg="-iv"; + else + $grep_arg="-i"; + + //Check program to execute or no the parser + if($program == "squid") + $parser = "| php -q squid_log_parser.php"; + else + $parser = ""; + + // Get logs based in filter expression + if($filter != "") { + exec("tail -2000 {$log} | /usr/bin/grep {$grep_arg} " . escapeshellarg($filter). " | tail -r -n {$lines} {$parser} " , $logarr); + } + else { + exec("tail -r -n {$lines} {$log} {$parser}", $logarr); + } + // return logs + return $logarr; +}; + +function show_tds($tds){ + echo "<tr valign='top'>\n"; + foreach ($tds as $td){ + echo "<td class='listhdrr'>".gettext($td)."</td>\n"; + } + echo "</tr>\n"; +} + +?> diff --git a/config/squid3/33/squid_nac.xml b/config/squid3/33/squid_nac.xml new file mode 100755 index 00000000..bffefb61 --- /dev/null +++ b/config/squid3/33/squid_nac.xml @@ -0,0 +1,191 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidnac</name> + <version>none</version> + <title>Proxy server: Access control</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Access Control Lists</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Allowed subnets</fielddescr> + <fieldname>allowed_subnets</fieldname> + <description>Enter each subnet on a new line that is allowed to use the proxy. The subnets must be expressed as CIDR ranges (e.g.: 192.168.1.0/24). Note that the proxy interface subnet is already an allowed subnet. All the other subnets won't be able to use the proxy.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Unrestricted IPs</fielddescr> + <fieldname>unrestricted_hosts</fieldname> + <description>Enter unrestricted IP address / network(in CIDR format) on a new line that is not to be filtered out by the other access control directives set in this page.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Banned host addresses</fielddescr> + <fieldname>banned_hosts</fieldname> + <description>Enter each IP address / network(in CIDR format) on a new line that is not to be allowed to use the proxy.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Whitelist</fielddescr> + <fieldname>whitelist</fieldname> + <description>Enter each destination domain on a new line that will be accessable to the users that are allowed to use the proxy. You also can use regular expressions.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Blacklist</fielddescr> + <fieldname>blacklist</fieldname> + <description>Enter each destination domain on a new line that will be blocked to the users that are allowed to use the proxy. You also can use regular expressions.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Block user agents</fielddescr> + <fieldname>block_user_agent</fieldname> + <description>Enter each user agent on a new line that will be blocked to the users that are allowed to use the proxy. You also can use regular expressions.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Block MIME types (reply only)</fielddescr> + <fieldname>block_reply_mime_type</fieldname> + <description>Enter each MIME type on a new line that will be blocked to the users that are allowed to use the proxy. You also can use regular expressions. Useful to block javascript (application/x-javascript).</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <name>Squid Allowed ports</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>acl safeports</fielddescr> + <fieldname>addtl_ports</fieldname> + <description>This is a space-separated list of "safe ports" in addition to the already defined list: 21 70 80 210 280 443 488 563 591 631 777 901 1025-65535</description> + <type>input</type> + <size>60</size> + <default_value></default_value> + </field> + <field> + <fielddescr>acl sslports</fielddescr> + <fieldname>addtl_sslports</fieldname> + <description>This is a space-separated list of ports to allow SSL "CONNECT" in addition to the already defined list: 443 563</description> + <type>input</type> + <size>60</size> + <default_value></default_value> + </field> + </fields> + <custom_php_validation_command> + squid_validate_nac($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_ng.inc b/config/squid3/33/squid_ng.inc new file mode 100755 index 00000000..0e1e0515 --- /dev/null +++ b/config/squid3/33/squid_ng.inc @@ -0,0 +1,1070 @@ +<?php +/* $Id$ */ + +/* + squid_ng.inc + part of pfSense (www.pfSense.com) + + Copyright (C) 2005 Michael Capp <michael.capp@gmail.com> + 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. + +*/ + +if(!function_exists("filter_configure")) + require_once("filter.inc"); + +function global_write_squid_config() +{ + global $config; + conf_mount_rw(); + config_lock(); + + /* define squid configuration file in variable for replace function */ + $squidconfig = "/usr/local/etc/squid/squid.conf"; + + /* squid.xml values */ + $active_interface = $config['installedpackages']['squid']['config'][0]['active_interface']; + $transparent_proxy = $config['installedpackages']['squid']['config'][0]['transparent_proxy']; + $log_enabled = $config['installedpackages']['squid']['config'][0]['log_enabled']; + $urlfilter_enable = $config['installedpackages']['squid']['config'][0]['urlfilter_enable']; + $accesslog_disabled = $config['installedpackages']['squid']['config'][0]['accesslog_disabled']; + $log_query_terms = $config['installedpackages']['squid']['config'][0]['log_query_terms']; + $log_user_agents = $config['installedpackages']['squid']['config'][0]['log_user_agents']; + $proxy_port = $config['installedpackages']['squid']['config'][0]['proxy_port']; + $visible_hostname = $config['installedpackages']['squid']['config'][0]['visible_hostname']; + $cache_admin_email = $config['installedpackages']['squid']['config'][0]['cache_admin_email']; + $error_language = $config['installedpackages']['squid']['config'][0]['error_language']; + $cachemgr_enabled = $config['installedpackages']['squid']['config'][0]['cachemgr_enabled']; + + /* squid_upstream.xml values */ + $proxy_forwarding = $config['installedpackages']['squidupstream']['config'][0]['proxy_forwarding']; + $client_ip_forwarding = $config['installedpackages']['squidupstream']['config'][0]['client_ip_forwarding']; + $user_forwarding = $config['installedpackages']['squidupstream']['config'][0]['user_forwarding']; + $upstream_proxy = $config['installedpackages']['squidupstream']['config'][0]['upstream_proxy']; + $upstream_proxy_port = $config['installedpackages']['squidupstream']['config'][0]['upstream_proxy_port']; + $upstream_username = $config['installedpackages']['squidupstream']['config'][0]['upstream_username']; + $upstream_password = $config['installedpackages']['squidupstream']['config'][0]['upstream_psasword']; + + /* squid_cache.xml values */ + $memory_cache_size = $config['installedpackages']['squidcache']['config'][0]['memory_cache_size']; + $harddisk_cache_size = $config['installedpackages']['squidcache']['config'][0]['harddisk_cache_size']; + $minimum_object_size = $config['installedpackages']['squidcache']['config'][0]['minimum_object_size']; + $maximum_object_size = $config['installedpackages']['squidcache']['config'][0]['maximum_object_size']; + $level_subdirs = $config['installedpackages']['squidcache']['config'][0]['level_subdirs']; + $memory_replacement = $config['installedpackages']['squidcache']['config'][0]['memory_replacement']; + $cache_replacement = $config['installedpackages']['squidcache']['config'][0]['cache_replacement']; + $domain = $config['installedpackages']['squidcache']['config'][0]['domain']; + $enable_offline = $config['installedpackages']['squidcache']['config'][0]['enable_offline']; + + /* squid_nac.xml values */ + $allowed_subnets = $config['installedpackages']['squidnac']['config'][0]['allowed_subnets']; + $unrestricted_ip_addr = $config['installedpackages']['squidnac']['config'][0]['unrestricted_ip_address']; + $unrestricted_mac_addr = $config['installedpackages']['squidnac']['config'][0]['unrestricted_mac_addresses']; + $banned_ip_addr = $config['installedpackages']['squidnac']['config'][0]['banned_ip_addresses']; + $banned_mac_addr = $config['installedpackages']['squidnac']['config'][0]['banned_mac_addresses']; + $override_hosts = $config['installedpackages']['squidnac']['config'][0]['override_hosts']; + + /* squid_traffic.xml values */ + $max_download_size = $config['installedpackages']['squidtraffic']['config'][0]['max_download_size']; + $max_upload_size = $config['installedpackages']['squidtraffic']['config'][0]['max_upload_size']; + $dl_overall = $config['installedpackages']['squidtraffic']['config'][0]['dl_overall']; + $dl_per_host = $config['installedpackages']['squidtraffic']['config'][0]['dl_per_host']; + $throttle_binary_files = $config['installedpackages']['squidtraffic']['config'][0]['throttle_binary_files']; + $throttle_cd_images = $config['installedpackages']['squidtraffic']['config'][0]['throttle_cd_images']; + $throttle_multimedia = $config['installedpackages']['squidtraffic']['config'][0]['throttle_multimedia']; + + /* squid_auth.xml values */ + $auth_method = $config['installedpackages']['squidauth']['config'][0]['auth_method']; + $auth_processes = $config['installedpackages']['squidauth']['config'][0]['auth_processes']; + $auth_cache_ttl = $config['installedpackages']['squidauth']['config'][0]['auth_cache_ttl']; + $limit_ip_addr = $config['installedpackages']['squidauth']['config'][0]['limit_ip_addr']; + $user_ip_cache_ttl = $config['installedpackages']['squidauth']['config'][0]['user_ip_cache_ttl']; + $req_unrestricted_auth = $config['installedpackages']['squidauth']['config'][0]['req_unrestricted_auth']; + $auth_realm_prompt = $config['installedpackages']['squidauth']['config'][0]['auth_realm_prompt']; + $no_domain_auth = $config['installedpackages']['squidauth']['config'][0]['no_domain_auth']; + $min_pass_length = $config['installedpackages']['squidauth']['config'][0]['min_pass_length']; + $bypass_extended = $config['installedpackages']['squidauth']['config'][0]['bypass_extended']; + + /* squid_extauth.xml (ldap) values */ + $ldap_basedn = $config['installedpackages']['squidextldapauth']['config'][0]['ldap_basedn']; + $ldap_server = $config['installedpackages']['squidextldapauth']['config'][0]['ldap_server']; + $ldap_type = $config['installedpackages']['squidextldapauth']['config'][0]['ldap_type']; + $ldap_port = $config['installedpackages']['squidextldapauth']['config'][0]['ldap_port']; + $bind_dn_username = $config['installedpackages']['squidextldapauth']['config'][0]['bind_dn_username']; + $bind_dn_password = $config['installedpackages']['squidextldapauth']['config'][0]['bind_dn_password']; + + /* squid_extauth.xml (radius) values */ + $radius_server = $config['installedpackages']['squidextradiusauth']['config'][0]['radius_server']; + $radius_port = $config['installedpackages']['squidextradiusauth']['config'][0]['radius_port']; + $radius_identifier = $config['installedpackages']['squidextradiusauth']['config'][0]['radius_identifier']; + $radius_secret = $config['installedpackages']['squidextradiusauth']['config'][0]['radius_secret']; + + /* static variable assignments for directory mapping */ + $acldir = "/usr/local/etc/squid/advanced/acls"; + $ncsadir = "/usr/local/etc/squid/advanced/ncsa"; + $ntlmdir = "/usr/local/etc/squid/advanced/ntlm"; + $radiusdir = "/usr/local/etc/squid/advanced/radius"; + + $fout = fopen($squidconfig, "w"); + + $config_array = array('shutdown_lifetime 5 seconds' . "\n\n"); + + if (isset($cachemgr_enabled) && ($cachemgr_enabled == "on")) { + mwexec("cp /usr/local/libexec/squid/cachemgr.cgi /usr/local/www/cachemgr.cgi"); + mwexec("chmod a+rx /usr/local/www/cachemgr.cgi"); + } else { + mwexec("rm -f /usr/local/www/cachemgr.cgi"); + } + unset($cachemgr_enabled); + + if (!isset($icp_port) or ($icp_port == "")) { + $icp_port = "3130"; + } + $config_array[] = 'icp_port ' . $icp_port . "\n"; + unset($icp_port); + + if(!isset($proxy_port) or ($proxy_port == "")) { + $proxy_port = "3128"; + } + + if (isset($transparent_proxy) && ($transparent_proxy != "on")) { + $int = convert_friendly_interface_to_real_interface_name($active_interface); + $listen_ip = find_interface_ip($int); + + $config_array[] = 'http_port ' . $listen_ip . ':' . $proxy_port . "\n\n"; + $config_array[] = 'acl QUERY urlpath_regex cgi-bin \?' . "\n"; + $config_array[] = 'no_cache deny QUERY' . "\n\n"; + } + $config_array[] = 'http_port 127.0.0.1:' . $proxy_port . "\n\n"; + unset($proxy_port); + + if (isset($domain) && ($domain !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/dst_nocache.acl","w"); + + $domain_array = split("; ",$domain); + foreach ($domain_array as $no_cache_domain) { + fwrite($aclout, $no_cache_domain . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl no_cache_domains dstdomain "' . $acldir . '/dst_nocache.acl"' . "\n"; + $config_array[] = 'no_cache deny no_cache_domains' . "\n\n"; + } + unset($no_cache_domain); + unset($domain_array); + unset($domain); + + $config_array[] = 'cache_effective_user squid' . "\n"; + $config_array[] = 'cache_effective_group squid' . "\n\n"; + $config_array[] = 'pid_filename /var/run/squid.pid' . "\n\n"; + + if (!isset($memory_cache_size) or ($memory_cache_size == "")) { + $memory_cache_size = "8"; + } + $config_array[] = 'cache_mem ' . $memory_cache_size . ' MB' . "\n"; + unset($memory_cache_size); + + if (!isset($harddisk_cache_size) or ($harddisk_cache_size == "")) { + $harddisk_cache_size = "500"; + } + + if (!isset($level_subdirs) or ($level_subdirs == "")) { + $level_subdirs = "16"; + } + + $config_array[] = 'cache_dir diskd /var/squid/cache ' . $harddisk_cache_size . ' ' . $level_subdirs . ' 256' . "\n\n"; + unset($harddisk_cache_size); + unset($level_subdirs); + + if (!isset($error_language) or ($error_language == "")) { + $error_language = "English"; + } + $config_array[] = 'error_directory /usr/local/etc/squid/errors/' . $error_language . "\n\n"; + unset($error_language); + + if (isset($offline_mode) && ($offline_mode == "on")) { + $config_array[] = 'offline_mode on' . "\n\n"; + } else { + $config_array[] = 'offline_mode off' . "\n\n"; + } + + if (!isset($memory_replacement) or ($memory_replacement == "")) { + $memory_replacement = "heap GDSF"; + } + $config_array[] = 'memory_replacement_policy ' . $memory_replacement . "\n"; + unset($memory_replacement); + + if (!isset($cache_replacement) or ($cache_replacement == "")) { + $cache_replacement="heap GDSF"; + } + $config_array[] = 'cache_replacement_policy ' . $cache_replacement . "\n\n"; + unset($cache_replacement); + + if (isset($accesslog_disabled) && ($accesslog_disabled == "on")) { + $config_array[] = 'cache_access_log none' . "\n"; + } else { + $config_array[] = 'cache_access_log /var/log/access.log' . "\n"; + } + $config_array[] = 'cache_log /var/log/cache.log' . "\n"; + $config_array[] = 'cache_store_log none' . "\n"; + unset($accesslog_disabled); + unset($log_enabled); + + if (isset($log_query_terms) && ($log_query_terms == "on")) { + $config_array[] = 'strip_query_terms off' . "\n"; + } else { + $config_array[] = 'strip_query_terms on' . "\n"; + } + unset($log_query_terms); + + $config_array[] = 'useragent_log /var/log/useragent.log' . "\n\n"; + unset($log_user_agents); + + $config_array[] = 'log_mime_hdrs off' . "\n"; + $config_array[] = 'emulate_httpd_log on' . "\n"; + + switch ($user_forwarding) { + case "on": + $config_array[] = 'forwarded_for on' . "\n\n"; + break; + case "off": + $config_array[] = 'forwarded_for off' . "\n\n"; + break; + default: + $config_array[] = 'forwarded_for off' . "\n\n"; + break; + } + unset($user_forwarding); + + switch ($auth_method) { + case "none": + break; + case "local_auth": + $config_array[] = 'auth_param basic program /usr/local/libexec/squid/ncsa_auth /usr/local/etc/squid/advanced/ncsa/passwd' . "\n"; + if (!isset($auth_processes) or ($auth_processes == "")) { + $auth_processes = "5"; + } + $config_array[] = 'auth_param basic children ' . $auth_processes . "\n"; + + if (!isset($auth_realm_prompt) or ($auth_realm_prompt == "")) { + $auth_realm_prompt = "pfSense Advanced Proxy"; + } + $config_array[] = 'auth_param basic realm ' . $auth_realm_prompt . "\n"; + + if (!isset($auth_cache_ttl) or ($auth_cache_ttl == "")) { + $auth_cache_ttl = "60"; + } + $config_array[] = 'auth_param basic credentialsttl ' . $auth_cache_ttl . ' minutes' . "\n\n"; + $config_array[] = 'acl for_inetusers proxy_auth REQUIRED' . "\n\n"; + + unset($auth_realm_prompt); + unset($auth_processes); + unset($auth_cache_ttl); + + break; + case "radius_auth"; + $config_array[] = 'auth_param basic program /usr/local/libexec/squid/squid_rad_auth -h ' . $radius_server . ' -p ' . $radius_port . ' -i ' . $radius_identifier . ' -w ' . $radius_secret . "\n"; + if (!isset($auth_processes) or ($auth_processes == "")) { + $auth_processes = "5"; + } + $config_array[] = 'auth_param basic children ' . $auth_processes . "\n"; + + if (!isset($auth_realm_prompt) or ($auth_realm_prompt == "")) { + $auth_realm_prompt = "pfSense Advanced Proxy"; + } + $config_array[] = 'auth_param basic realm ' . $auth_realm_prompt . "\n"; + + if (!isset($auth_cache_ttl) or ($auth_cache_ttl == "")) { + $auth_cache_ttl = "60"; + } + $config_array[] = 'auth_param basic credentialsttl ' . $auth_cache_ttl . ' minutes' . "\n\n"; + $config_array[] = 'acl for_inetusers proxy_auth REQUIRED' . "\n\n"; + + unset($auth_realm_prompt); + unset($auth_processes); + unset($auth_cache_ttl); + + break; + case "ldap_bind"; + $config_array[] = 'auth_param basic program /usr/local/libexec/squid_ldap_auth -b "' . $ldap_basedn . '" -D "' . $bind_dn_username . '" -w "' . $bind_dn_password . '" -f "(&(objectClass=person)(cn=%s))" -u -cn -P "' . $ldap_server . ":" . $ldap_port . "\n"; + $config_array[] = 'auth_param basic program /usr/local/libexec/squid/squid_ldap_auth'; + $config_array[] = ' -b "' . $ldap_basedn . '"'; + $config_array[] = ' -D "' . $bind_dn_username . '"'; + $config_array[] = " -w " . $bind_dn_password; + $config_array[] = ' -f "(&(objectClass=person)(cn=%s))"'; + $config_array[] = " -u cn -P " . $ldap_server . ":" . $ldap_port . "\n"; + + if (!isset($auth_processes) or ($auth_processes == "")) { + $auth_processes = "5"; + } + $config_array[] = 'auth_param basic children ' . $auth_processes . "\n"; + + if (!isset($auth_realm_prompt) or ($auth_realm_prompt == "")) { + $auth_realm_prompt = "pfSense Advanced Proxy"; + } + $config_array[] = 'auth_param basic realm ' . $auth_realm_prompt . "\n"; + + if (!isset($auth_cache_ttl) or ($auth_cache_ttl == "")) { + $auth_cache_ttl = "60"; + } + $config_array[] = 'auth_param basic credentialsttl ' . $auth_cache_ttl . ' minutes' . "\n\n"; + $config_array[] = 'acl for_inetusers proxy_auth REQUIRED' . "\n\n"; + + unset($auth_realm_prompt); + unset($auth_processes); + unset($auth_cache_ttl); + + break; + case "windows_auth"; + break; + } + + if (isset($throttle_binary_files) && ($throttle_binary_files == "on")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $binary_out = "\.bin$\n\.cab$\n\.gz$\n\.rar$\n\.sea$\n\.tar$\n\.tgz$\n\.zip$\n"; + + $throttle_out = fopen($acldir . "/dst_throttle_binary.acl", "w"); + fwrite($throttle_out, $binary_out); + fclose($throttle_out); + $config_array[] = 'acl for_throttled_binary url_regex -i "' . $acldir . '/dst_throttle_binary.acl"' . "\n"; + } else { + if (file_exists($acldir . "/dst_throttle_binary.acl")) unlink($acldir . "/dst_throttle_binary.acl"); + } + unset($throttle_binary_files); + unset($throttle_out); + unset($binary_out); + + if (isset($throttle_cd_images) && ($throttle_cd_images == "on")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $cd_out = "\.b5t$\n\.bin$\n\.bwt$\n\.cdi$\n\.cue$\n\.gho$\n\.img$\n\.iso$\n\.mds$\n\.nrg$\n\.pqi$\n"; + + $throttle_out = fopen($acldir . "/dst_throttle_cd.acl","w"); + fwrite($throttle_out, $cd_out); + fclose($throttle_out); + $config_array[] = 'acl for_throttled_cd url_regex -i "' . $acldir . '/dst_throttle_cd.acl"' . "\n"; + } else { + if (file_exists($acldir . "/dst_throttle_cd.acl")) { + unlink($acldir . "/dst_throttle_cd.acl"); + } + } + unset($throttle_cd_images); + unset($throttle_out); + unset($cd_out); + + if (isset($throttle_multimedia) && ($throttle_multimedia == "on")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $multimedia_out = "\.aiff?$\n\.asf$\n\.avi$\n\.divx$\n\.mov$\n\.mp3$\n\.mpe?g$\n\.qt$\n\.ra?m$\n"; + + $throttle_out = fopen($acldir . "/dst_throttle_multimedia.acl","w"); + fwrite($throttle_out, $multimedia_out); + fclose($throttle_out); + $config_array[] = 'acl for_throttled_multimedia url_regex -i "' . $acldir . '/dst_throttle_multimedia.acl"' . "\n"; + } else { + if (file_exists($acldir . "/dst_throttle_multimedia.acl")) { + unlink($acldir . "/dst_throttle_multimedia.acl"); + } + } + unset($throttle_multimedia); + unset($multimedia_out); + unset($throttle_out); + + $config_array[] = 'acl within_timeframe time MTWHFAS 00:00-24:00' . "\n\n"; + + /* obtain interface subnet and address for Squid rules */ + $lactive_interface = strtolower($active_interface); + + $lancfg = $config['interfaces'][$lactive_interface]; + $lanif = $lancfg['if']; + $lanip = $lancfg['ipaddr']; + $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); + $lansn = $lancfg['subnet']; + + $config_array[] = 'acl all src 0.0.0.0/0.0.0.0' . "\n"; + $config_array[] = 'acl localnet src ' . $lansa . '/' . $lansn . "\n"; + $config_array[] = 'acl localhost src 127.0.0.1/255.255.255.255' . "\n"; + $config_array[] = 'acl SSL_ports port 443 563 873 # https, snews, rsync' . "\n"; + $config_array[] = 'acl Safe_ports port 80 # http' . "\n"; + $config_array[] = 'acl Safe_ports port 21 # ftp' . "\n"; + $config_array[] = 'acl Safe_ports port 443 563 873 # https, snews, rsync' . "\n"; + $config_array[] = 'acl Safe_ports port 70 # gopher' . "\n"; + $config_array[] = 'acl Safe_ports port 210 # wais' . "\n"; + $config_array[] = 'acl Safe_ports port 1025-65535 # unregistered ports' . "\n"; + $config_array[] = 'acl Safe_ports port 280 # http-mgmt' . "\n"; + $config_array[] = 'acl Safe_ports port 488 # gss-http' . "\n"; + $config_array[] = 'acl Safe_ports port 591 # filemaker' . "\n"; + $config_array[] = 'acl Safe_ports port 777 # multiling http' . "\n"; + $config_array[] = 'acl Safe_ports port 800 # Squids port (for icons)' . "\n\n"; + + /* allow access through proxy for custom admin port */ + $custom_port = $config['system']['webgui']['port']; + if (isset($custom_port) && ($custom_port !== "")) { + $config_array[] = 'acl pf_admin_port port ' . $custom_port . "\n"; + unset($custom_port); + } else { + $admin_protocol = $config['system']['webgui']['protocol']; + switch ($admin_protocol) { + case "http"; + $config_array[] = 'acl pf_admin_port port 80' ."\n"; + break; + case "https"; + $config_array[] = 'acl pf_admin_port port 443' . "\n"; + break; + default; + $config_array[] = 'acl pf_admin_port port 80' . "\n"; + break; + } + unset($admin_protocol); + } + + /* define override hosts as specified in squid_nac.xml */ + if (isset($override_hosts) && ($override_hosts !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/src_override_hosts.acl", "w"); + + $override_hosts_array = split("; ", $override_hosts); + foreach ($override_hosts_array as $ind_override_host) { + fwrite($aclout, $ind_override_host . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl override_hosts src "/usr/local/etc/squid/advanced/acls/src_override_hosts.acl"' . "\n"; + } + /* clear variables */ + unset($override_hosts_array); + unset($ind_override_host); + unset($override_hosts); + + /* define subnets allowed to utilize proxy service */ + if (isset($allowed_subnets) && ($allowed_subnets !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + mwexec("touch {$acldir}/src_subnets.acl"); + } + + $aclout = fopen($acldir . "/src_subnets.acl","w"); + + $allowed_subnets_array = split("; ",$allowed_subnets); + foreach ($allowed_subnets_array as $ind_allowed_subnets) { + fwrite($aclout, $ind_allowed_subnets . "\n"); + } + + fclose($aclout); + } else { + + $aclout = fopen($acldir . "/src_subnets.acl","w"); + fwrite($aclout, $lansa . "/" . $lansn . "\n"); + fclose($aclout); + } + + $config_array[] = 'acl pf_networks src "/usr/local/etc/squid/advanced/acls/src_subnets.acl"' . "\n"; + + unset($allowed_subnets_array); + unset($ind_allowed_subnets); + unset($allowed_subnets); + + /* define ip addresses that have 'unrestricted' access */ + if (isset($unrestricted_ip_addr) && ($unrestricted_ip_addr !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/src_unrestricted_ip.acl","w"); + + $unrestricted_ip_array = split("; ",$unrestricted_ip_addr); + foreach ($unrestricted_ip_array as $ind_unrestricted_ip) { + fwrite($aclout, $ind_unrestricted_ip . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl pf_unrestricted_ip src "/usr/local/etc/squid/advanced/acls/src_unrestricted_ip.acl"' . "\n"; + } + unset($unrestricted_ip_array); + unset($unrestricted_ip_addr); + unset($ind_unrestricted_ip); + + /* define mac addresses that have 'unrestricted' access */ + if (isset($unrestricted_mac_addr) && ($unrestricted_mac_addr !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/src_unrestricted_mac.acl","w"); + + $unrestricted_mac_array = split("; ",$unrestricted_mac_addr); + foreach ($unrestricted_mac_array as $ind_unrestricted_mac) { + fwrite($aclout, $ind_unrestricted_mac . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl pf_unrestricted_mac src "/usr/local/etc/squid/advanced/acls/src_unrestricted_mac.acl"' . "\n"; + } + unset($unrestricted_mac_array); + unset($unrestricted_mac_addr); + unset($ind_unrestricted_mac); + + /* define ip addresses that are banned from using the proxy service */ + if (isset($banned_ip_addr) && ($banned_ip_addr !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/src_banned_ip.acl","w"); + + $banned_ip_array = split("; ",$banned_ip_addr); + foreach ($banned_ip_array as $ind_banned_ip) { + fwrite($aclout, $ind_banned_ip . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl pf_banned_ip src "/usr/local/etc/squid/advanced/acls/src_banned_ip.acl"' . "\n"; + } + unset($banned_ip_array); + unset($banned_ip_addr); + unset($ind_banned_ip); + + /* define mac addresses that are banned from using the proxy service */ + if (isset($banned_mac_addr) && ($banned_mac_addr !== "")) { + if (!file_exists($acldir)) { + mwexec("/bin/mkdir -p " . $acldir); + } + + $aclout = fopen($acldir . "/src_banned_mac.acl","w"); + + $banned_mac_array = split("; ",$banned_mac_addr); + foreach ($banned_mac_array as $ind_banned_mac) { + fwrite($aclout, $ind_banned_mac . "\n"); + } + + fclose($aclout); + + $config_array[] = 'acl pf_banned_mac src "/usr/local/etc/squid/advanced/acls/src_banned_mac.acl"' . "\n"; + } + unset($banned_mac_array); + unset($banned_mac_addr); + unset($ind_banned_mac); + + $config_array[] = 'acl pf_ips dst ' . $lanip . "\n"; + $config_array[] = 'acl CONNECT method CONNECT' . "\n\n"; + + if (isset($auth_method) && ($auth_method == "none")) { + $config_array[] = 'http_access allow localnet' . "\n"; + } + $config_array[] = 'http_access allow localhost' . "\n"; + + if (isset($override_hosts) && ($override_hosts !== "")) { + $config_array[] = 'http_access allow override_hosts' . "\n"; + } + $config_array[] = "\n"; + + switch ($config['system']['webgui']['protocol']) { + case "http": + $config_array[] = 'http_access allow pf_ips' . "\n"; + $config_array[] = 'http_access allow pf_admin_port' . "\n"; + $config_array[] = 'http_access deny !pf_networks' . "\n\n"; + break; + case "https": + $config_array[] = 'http_access allow CONNECT pf_ips' . "\n"; + $config_array[] = 'http_access allow CONNECT pf_admin_port' . "\n"; + $config_array[] = 'http_access deny CONNECT !pf_networks' . "\n\n"; + break; + } + + $config_array[] = 'http_access deny !Safe_ports' . "\n"; + $config_array[] = 'http_access deny CONNECT !SSL_ports' . "\n\n"; + + if (isset($auth_method) && ($auth_method != "none")) { + $config_array[] = 'http_access allow pf_networks for_inetusers within_timeframe' . "\n"; + } + + $config_array[] = 'http_access deny all' . "\n\n"; + + if (isset($dl_overall) && ($dl_overall !== "") and isset($dl_per_host) && ($dl_per_host == "")) { + $config_array[] = 'delay_pools 1' . "\n"; + $config_array[] = 'delay_class 1 3' . "\n"; + + if ($dl_overall == "unlimited") { + $config_array[] = 'delay_parameters 1 -1/-1 -1/-1 ' . ($dl_overall * 125) . '/' . ($dl_overall * 250) . "\n"; + } else { + $config_array[] = 'delay_parameters 1 ' . ($dl_overall * 125) . '/' . ($dl_overall * 250) . ' -1/-1 -1/-1' . "\n"; + } + + /* if no unrestricted ip addresses are defined; this line is ignored */ + if (isset($unrestricted_ip_addr) && ($unrestricted_ip_addr == "")) $config_array[] = 'delay_access 1 deny pf_unrestricted_ip' . "\n"; + + /* this will define bandwidth delay restrictions for specified throttles */ + if (isset($throttle_binary_files) && ($throttle_binary_files == "on")) { + $config_array[] = 'delay_access 1 allow all for_throttled_binary' . "\n"; + } + if (isset($throttle_cd_images) && ($throttle_cd_images == "on")) { + $config_array[] = 'delay_access 1 allow all for_throttled_cd' . "\n"; + } + if (isset($throttle_multimedia) && ($throttle_multimedia == "on")) { + $config_array[] = 'delay_access 1 allow all for_throttled_multimedia' . "\n"; + } else { + $config_array[] = 'delay_access 1 allow all' . "\n"; + } + $config_array[] = 'delay_initial_bucket_level 100%' . "\n\n"; + } + + if (isset($dl_per_host) && ($dl_per_host !== "") and isset($dl_overall) && ($dl_overall == "")) { + $config_array[] = 'delay_pools 1' . "\n"; + $config_array[] = 'delay_class 1 3' . "\n"; + + if ($dl_per_host == "unlimited") { + $config_array[] = 'delay_parameters 1 ' . ($dl_per_host * 125) . '/' . ($dl_per_host * 250) . '-1/-1 -1/-1' . "\n"; + } else { + $config_array[] = 'delay_parameters 1 -1/-1 -1/-1 ' . ($dl_per_host * 125) . '/' . ($dl_per_host * 250) . "\n"; + } + + /* if no unrestricted ip addresses are defined; this line is ignored */ + if (isset($unrestricted_ip_addr) && ($unrestricted_ip_addr !== "")) $config_array[] = 'delay_access 1 deny pf_unrestricted_ip' . "\n"; + + /* this will define bandwidth delay restrictions for specified throttles */ + if ($throttle_binary_files == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_binary' . "\n"; + } + if ($throttle_cd_images == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_cd' . "\n"; + } + if ($throttle_multimedia == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_multimedia' ."\n"; + } else { + $config_array[] = 'delay_access 1 allow all' . "\n"; + } + $config_array[] = 'delay_initial_bucket_level 100%' . "\n\n\n"; + } + + if (isset($dl_overall) && ($dl_overall !== "") and isset($dl_per_host) && ($dl_per_host !== "")) { + /* if no bandwidth restrictions are specified, then these parameters are not necessary */ + if ($dl_overall !== "unlimited" and $dl_per_host !== "unlimited") { + + if ((isset($dl_overall) && ($dl_overall == "unlimited")) and (isset($dl_per_host) && ($dl_per_host !== ""))) { + $config_array[] = 'delay_pools 1' . "\n"; + $config_array[] = 'delay_class 1 3' . "\n"; + $config_array[] = 'delay_parameters 1 -1/-1 -1/-1 ' . ($dl_per_host * 125) . '/' . ($dl_overall * 250) . "\n"; + } elseif (isset($dl_overall) && ($dl_overall !== "") and isset($dl_per_host) && ($dl_per_host == "unlimited")) { + $config_array[] = 'delay_pools 1' . "\n"; + $config_array[] = 'delay_class 1 3' . "\n"; + $config_array[] = 'delay_parameters 1 ' . ($dl_overall * 125) . '/' . ($dl_overall * 250) . ' -1/-1 -1/-1' . "\n"; + } + } + + if ($dl_overall !== "unlimited" and $dl_per_host !== "unlimited") { + + /* if no unrestricted ip addresses are defined; this line is ignored */ + if (isset($unrestricted_ip_addr) && ($unrestricted_ip_addr !== "")) $config_array[] = 'delay_access 1 deny pf_unrestricted_ip' . "\n"; + + /* this will define bandwidth delay restrictions for specified throttles */ + if ($throttle_binary_files == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_binary' . "\n"; + } + if ($throttle_cd_images == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_cd' . "\n"; + } + if ($throttle_multimedia == "on") { + $config_array[] = 'delay_access 1 allow all for_throttled_multimedia' . "\n"; + } else { + $config_array[] = 'delay_access 1 allow all' . "\n"; + } + $config_array[] = 'delay_initial_bucket_level 100%' . "\n\n"; + } + } + + $config_array[] = 'header_access X-Forwarded-For deny all' . "\n"; + $config_array[] = 'header_access Via deny all' . "\n\n"; + + /* TODO: acl customization for snmp support */ + /* fwrite($fout, "\n"); */ + + if (isset($urlfilter_enable) && ($urlfilter_enable == "on")) { + $config_array[] = 'redirect_program /usr/sbin/squidGuard' . "\n"; + $config_array[] = 'redirect_children 5' . "\n\n"; + } + + if (isset($max_upload_size) && ($max_upload_size != "")) { + $config_array[] = 'request_body_max_size ' . $max_download_size . 'KB' . "\n"; + } + + if (isset($max_download_size) && ($max_download_size != "")) { + if (isset($unrestricted_ip_addr) && ($unrestricted_ip_addr !== "")) $config_array[] = 'reply_body_max_size 0 allow pf_unrestricted_ip' . "\n"; + /* fwrite($fout, "#reply_body_max_size 0 allow for_extended_users\n"); */ + $config_array[] = 'reply_body_max_size ' . $max_download_size * 1024 . ' allow all' . "\n\n"; + } + + /* set default value for maximum_object_size */ + if (!isset($maximum_object_size) or ($maximum_object_size == "")) { + $maximum_object_size = "4096"; + } + + /* set default value for minimum_object_size */ + if (!isset($minimum_object_size) or ($minimum_object_size == "")) { + $minimum_object_size = "0"; + } + $config_array[] = 'maximum_object_size ' . $maximum_object_size . ' KB' . "\n"; + $config_array[] = 'minimum_object_size ' . $minimum_object_size . ' KB' . "\n\n"; + + if (isset($proxy_forwarding) && ($proxy_forwarding == "on")) { + $config_array[] = 'cache_peer ' . $upstream_proxy . ' parent ' . $upstream_proxy_port . ' 3130 login=' . upstream_username . ':' . upstream_password . ' default no-query' . "\n"; + $config_array[] = 'never_direct allow all' . "\n"; + } + unset($proxy_forwarding); + + + /* define default ruleset for transparent proxy operation */ + if (isset($transparent_proxy) && ($transparent_proxy == "on")) { + $config_array[] = 'httpd_accel_host virtual' . "\n"; + $config_array[] = 'httpd_accel_port 80' . "\n"; + $config_array[] = 'httpd_accel_with_proxy on' . "\n"; + $config_array[] = 'httpd_accel_uses_host_header on' . "\n\n"; + } + unset($transparent_proxy); + + + /* define visible hostname */ + if (isset($visible_hostname) && ($visible_hostname !== "")) { + $config_array[] = 'visible_hostname ' . $visible_hostname . "\n"; + } + unset($visible_hostname); + + /* define cache administrators email address within error messages */ + if (isset($cache_admin_email) && ($cache_admin_email !== "")) { + $config_array[] = 'cache_mgr ' . $cache_admin_email . "\n\n"; + } + unset($cache_admin_email); + + /* write configuration file */ + foreach ($config_array as $config_item) + { + fwrite($fout, trim($config_item)); + + if (stristr($config_item, "\n")) + { + for ($i = 1; $i < count(explode("\n", $config_item)); $i++) + { + fwrite($fout, "\n"); + } + } + + } + fclose($fout); + + conf_mount_ro(); + config_unlock(); + + touch($squidconfig); +} /* end function write_squid_config */ + +function squid3_custom_php_install_command() { + /* write initial static config for transparent proxy */ + write_static_squid_config(); + + touch("/tmp/squid3_custom_php_install_command"); + + /* make sure this all exists, see: + * http://forum.pfsense.org/index.php?topic=23.msg2391#msg2391 + */ + update_output_window("Setting up Squid environment..."); + mwexec("mkdir -p /var/squid"); + mwexec("chown squid:squid /var/squid"); + mwexec("mkdir -p /var/squid/logs"); + mwexec("chown squid:squid /var/squid/logs"); + mwexec("mkdir -p /var/squid/cache"); + mwexec("chown squid:squid /var/squid/cache"); + mwexec("mkdir -p /usr/local/etc/squid/advanced"); + mwexec("chown squid:squid /usr/local/etc/squid/advanced"); + mwexec("mkdir -p /usr/local/etc/squid/advanced/acls"); + mwexec("chown squid:squid /usr/local/etc/squid/advanced/acls"); + mwexec("touch /usr/local/etc/squid/advanced/acls/src_subnets.acl"); + mwexec("chown squid:squid /usr/local/etc/squid/advanced/acls/src_subnets.acl"); + mwexec("touch /usr/local/etc/squid/advanced/acls/src_unrestricted_ip.acl"); + mwexec("chown squid:squid /usr/local/etc/squid/advanced/acls/src_unrestricted_ip.acl"); + mwexec("cp /usr/local/etc/squid/mime.conf.default /usr/local/etc/squid/mime.conf"); + + + /* set a few extra items noted by regan */ + update_output_window("Creating logs and setting user information..."); + $fdsquid = fopen("/usr/local/etc/rc.d/aSquid.sh", "w"); + fwrite($fdsquid, "#/bin/sh\n"); + fwrite($fdsquid, "# \n"); + fwrite($fdsquid, "# This file was created by the pfSense package system\n"); + fwrite($fdsquid, "# Sets up squid option on each bootup that are not persistent\n"); + fwrite($fdsquid, "# \n\n"); + fwrite($fdsquid, "chown squid:wheel /dev/pf\n"); + fwrite($fdsquid, "chmod ug+rw /dev/pf\n"); + fwrite($fdsquid, "touch /var/log/useragent.log\n"); + fwrite($fdsquid, "touch /var/log/access.log\n"); + fwrite($fdsquid, "touch /var/log/cache.log\n"); + fwrite($fdsquid, "chown squid:wheel /var/log/cache.log\n"); + fwrite($fdsquid, "chown squid:wheel /var/log/access.log\n"); + fwrite($fdsquid, "chown squid:wheel /var/log/useragent.log\n"); + fwrite($fdsquid, "\n"); + fclose($fdsquid); + mwexec("chmod a+rx /usr/local/etc/rc.d/aSquid.sh"); + mwexec("/usr/local/etc/rc.d/aSquid.sh"); + + update_output_window("Creating Proxy Server initialization scripts..."); + $start = "touch /tmp/ro_root_mount; /usr/local/sbin/squid -D; touch /tmp/filter_dirty"; + $stop = "/usr/local/sbin/squid -k shutdown"; + write_rcfile(array( + "file" => "squid.sh", + "start" => $start, + "stop" => $stop + ) + ); + + mwexec("chmod 755 /usr/local/etc/rc.d/squid.sh"); + + /* create log directory hierarchies if they don't exist */ + update_output_window("Creating required directory hierarchies..."); + + if (!file_exists("/var/squid/logs")) { + mwexec("mkdir -p /var/squid/logs"); + } + mwexec("/usr/sbin/chown squid:squid /var/squid/logs"); + + + if (!file_exists("/var/squid/cache")) { + mwexec("mkdir -p /var/squid/cache"); + } + mwexec("/usr/sbin/chown squid:squid /var/squid/cache"); + + if (!file_exists("/usr/local/etc/squid/advanced/acls")) { + mwexec("mkdir -p /usr/local/etc/squid/advanced/acls"); + } + mwexec("/usr/sbin/chown squid:squid /usr/local/etc/squid/advanced/acls"); + + if (!file_exists("/usr/local/etc/squid/advanced/ncsa")) { + mwexec("mkdir -p /usr/local/etc/squid/advanced/ncsa"); + } + mwexec("/usr/sbin/chown squid:squid /usr/local/etc/squid/advanced/ncsa"); + + if (!file_exists("/usr/local/etc/squid/advanced/ntlm")) { + mwexec("mkdir -p /usr/local/etc/squid/advanced/ntlm"); + } + mwexec("/usr/sbin/chown squid:squid /usr/local/etc/squid/advanced/ntlm"); + + if (!file_exists("/usr/local/etc/squid/advanced/radius")) { + mwexec("mkdir -p /usr/local/etc/squid/advanced/radius"); + } + mwexec("/usr/sbin/chown squid:squid /usr/local/etc/squid/advanced/radius"); + + $devfs_file = fopen("/etc/devfs.conf", "a"); + fwrite($devfs_file, "\n# Allow squid to query the packet filter bymaking is group-accessable. "); + fwrite($devfs_file, "own pf root:squid"); + fwrite($devfs_file, "perm pf 0640"); + fclose($devfs_file); + + update_output_window("Initializing Cache... This may take a moment..."); + mwexec("/usr/local/sbin/squid -z"); + + update_output_window("Starting Proxy Server..."); + start_service("squid"); +} + +function squid3_custom_php_deinstall_command() { + update_output_window("Stopping proxy service..."); + stop_service("squid"); + sleep(1); + /* brute force any remaining squid processes out */ + mwexec("/usr/bin/killall squid"); + mwexec("/usr/bin/killall pinger"); + update_output_window("Recursively removing directories hierarchies. If existant, log files in /var/squid/logs will remain..."); + mwexec("rm -rf /var/squid/cache"); + update_output_window("Removing configuration files..."); + unlink_if_exists("/usr/local/etc/rc.d/squid.sh"); + unlink_if_exists("/usr/local/libexec/squid"); + unlink_if_exists("/usr/local/etc/rc.d/aSquid.sh"); + mwexec("rm -f /usr/local/etc/rc.d/squid*"); + mwexec("rm -f /usr/local/www/cachemgr.cgi"); + filter_configure(); +} + +function write_static_squid_config() { + touch("/tmp/write_static_squid_config"); + global $config; + $lancfg = $config['interfaces']['lan']; + $lanif = $lancfg['if']; + $lanip = $lancfg['ipaddr']; + $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); + $lansn = $lancfg['subnet']; + + $fout = fopen("/usr/local/etc/squid/squid.conf","w"); + fwrite($fout, "#\n"); + fwrite($fout, "# This file was automatically generated by the pfSense package manager.\n"); + fwrite($fout, "# This default policy enables transparent proxy with no local disk logging.\n"); + fwrite($fout, "#\n"); + + /* set # of dns children */ + fwrite($fout, "dns_children 15\n"); + + fwrite($fout, "shutdown_lifetime 5 seconds\n"); + fwrite($fout, "icp_port 0\n"); + fwrite($fout, "\n"); + + fwrite($fout, "acl QUERY urlpath_regex cgi-bin \?\n"); + fwrite($fout, "no_cache deny QUERY\n"); + fwrite($fout, "\n"); + + fwrite($fout, "pid_filename /var/run/squid.pid\n"); + fwrite($fout, "\n"); + + fwrite($fout, "cache_mem 24 MB\n"); + fwrite($fout, "cache_dir diskd /var/squid/cache 500 16 256\n"); + fwrite($fout, "\n"); + + fwrite($fout, "error_directory /usr/local/etc/squid/errors/English\n"); + fwrite($fout, "\n"); + + fwrite($fout, "memory_replacement_policy heap GDSF\n"); + fwrite($fout, "cache_replacement_policy heap GDSF\n"); + fwrite($fout, "\n"); + + fwrite($fout, "cache_access_log none\n"); + fwrite($fout, "cache_log none\n"); + fwrite($fout, "cache_store_log none\n"); + fwrite($fout, "\n"); + + fwrite($fout, "log_mime_hdrs off\n"); + fwrite($fout, "emulate_httpd_log on\n"); + fwrite($fout, "forwarded_for off\n"); + fwrite($fout, "\n"); + + fwrite($fout, "acl within_timeframe time MTWHFAS 00:00-24:00\n"); + fwrite($fout, "\n"); + + fwrite($fout, "acl all src 0.0.0.0/0.0.0.0\n"); + fwrite($fout, "acl localnet src " . $lansa . "/" . $lansn . "\n"); + fwrite($fout, "acl localhost src 127.0.0.1/255.255.255.255\n"); + fwrite($fout, "acl SSL_ports port 443 563 873 # https, snews, rsync\n"); + fwrite($fout, "acl Safe_ports port 80 # http\n"); + fwrite($fout, "acl Safe_ports port 21 # ftp\n"); + fwrite($fout, "acl Safe_ports port 443 563 873 # https, snews, rsync\n"); + fwrite($fout, "acl Safe_ports port 70 # gopher\n"); + fwrite($fout, "acl Safe_ports port 210 # wais\n"); + fwrite($fout, "acl Safe_ports port 1025-65535 # unregistered ports\n"); + fwrite($fout, "acl Safe_ports port 280 # http-mgmt\n"); + fwrite($fout, "acl Safe_ports port 488 # gss-http\n"); + fwrite($fout, "acl Safe_ports port 591 # filemaker\n"); + fwrite($fout, "acl Safe_ports port 777 # multiling http\n"); + fwrite($fout, "acl Safe_ports port 800 # Squids port (for icons)\n"); + fwrite($fout, "\n"); + + fwrite($fout, "acl CONNECT method CONNECT\n"); + fwrite($fout, "\n"); + + fwrite($fout, "#access to squid; local machine; no restrictions\n"); + fwrite($fout, "http_access allow localnet\n"); + fwrite($fout, "http_access allow localhost\n"); + fwrite($fout, "\n"); + + fwrite($fout, "#Deny non web services\n"); + fwrite($fout, "http_access deny !Safe_ports\n"); + fwrite($fout, "http_access deny CONNECT !SSL_ports\n"); + fwrite($fout, "\n"); + + fwrite($fout, "#Set custom configured ACLs\n"); + fwrite($fout, "http_access deny all\n"); + fwrite($fout, "visible_hostname pfSense\n"); + fwrite($fout, "\n"); + + fwrite($fout, "cache_effective_user squid\n"); + fwrite($fout, "cache_effective_group squid\n"); + fwrite($fout, "\n"); + + fwrite($fout, "maximum_object_size 4096 KB\n"); + fwrite($fout, "minimum_object_size 0 KB\n"); + fwrite($fout, "\n"); + + fwrite($fout, "request_body_max_size 0 KB\n"); + fwrite($fout, "reply_body_max_size 0 allow all\n"); + fwrite($fout, "\n"); + + fwrite($fout, "httpd_accel_host virtual\n"); + fwrite($fout, "httpd_accel_port 80\n"); + fwrite($fout, "httpd_accel_with_proxy on\n"); + fwrite($fout, "httpd_accel_uses_host_header on\n"); + + fclose($fout); +} + +function mod_htpasswd() { + global $config; + conf_mount_rw(); + config_lock(); + + if (!file_exists("/usr/local/etc/squid/advanced/ncsa")) mwexec("mkdir -p /usr/local/etc/squid/advanced/ncsa"); + + $passfile = fopen("/usr/local/etc/squid/advanced/ncsa/passwd", "w+"); + + if (isset($config['installedpackages']['squidextlocalauth']['config']) && $config['installedpackages']['squidextlocalauth']['config'] != "") { + foreach($config['installedpackages']['squidextlocalauth']['config'] as $rowhelper) { + $encpass = generate_htpasswd($rowhelper['username'], $rowhelper['password']); + fwrite($passfile, $rowhelper['username'] . ":" . $encpass . "\n"); + } + } + + fclose($passfile); + + conf_mount_ro(); + config_unlock(); +} + +function generate_htpasswd($username, $password) { + $all = explode( " ", + "a b c d e f g h i j k l m n o p q r s t u v w x y z " + . "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z " + . "0 1 2 3 4 5 6 7 8 9"); + + for ($i = 0; $i < 9; $i++) { + srand((double)microtime()*1000000); + $randy = rand(0,61); + $seed .= $all[$randy]; + } + + $crypt = crypt($password, "$1$$seed"); + return $crypt; +} + +?> diff --git a/config/squid3/33/squid_ng.xml b/config/squid3/33/squid_ng.xml new file mode 100755 index 00000000..142536d6 --- /dev/null +++ b/config/squid3/33/squid_ng.xml @@ -0,0 +1,267 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squid</name> + <version>2.5.12_4</version> + <title>Services: Proxy Server</title> + <category>Security</category> + <aftersaveredirect>/pkg_edit.php?xml=squid_ng.xml&id=0</aftersaveredirect> + <include_file>/usr/local/pkg/squid_ng.inc</include_file> + <menu> + <name>Squid</name> + <tooltiptext>Modify settings for Proxy Server</tooltiptext> + <section>Services</section> + <url>/pkg_edit.php?xml=squid_ng.xml&id=0</url> + </menu> + <menu> + <name>Squid stats</name> + <tooltiptext>Show Squid statistics</tooltiptext> + <section>Services</section> + <url>/cachemgr.cgi</url> + </menu> + <service> + <name>squid</name> + <rcfile>squid.sh</rcfile> + </service> + <tabs> + <tab> + <text>General Settings</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Upstream Proxy</text> + <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url> + </tab> + <tab> + <text>Cache Mgmt</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Network Access Control</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Auth</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Extended Auth</text> + <url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url> + </tab> + </tabs> + <configpath>installedpackages->package->squidng->configuration->settings</configpath> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_cache.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_nac.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_ng.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_traffic.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_upstream.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_auth.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_auth.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/squid/squid_extauth.xml</item> + </additional_files_needed> + <fields> + <field> + <fielddescr>Proxy Listening Interface</fielddescr> + <fieldname>active_interface</fieldname> + <description>This defines the active listening interface to which the proxy server will listen for its requests.</description> + <type>interfaces_selection</type> + </field> + <field> + <fielddescr>Transparent Proxy</fielddescr> + <fieldname>transparent_proxy</fieldname> + <description>If transparent mode is enabled; all requests for destination port 80 will be forwarded to the proxy server without any additional configuration necessary.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>URL Filtering Enabled</fielddescr> + <fieldname>urlfilter_enable</fieldname> + <description>This enables the advanced functionality in conjunction with squidGuard to provide an array of URL filtering options. This squidGuard functionality can be additionally configured from Services -> Advanced Proxy Filtering</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Disable Access Log</fielddescr> + <fieldname>accesslog_disabled</fieldname> + <description>Disable the access log entirely. By default, Squid keeps a log of all requests it processes in /var/log/access.log. This can grow to be fairly large. If you do not require this logging, check this box to disable.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Log Query Terms</fielddescr> + <fieldname>log_query_terms</fieldname> + <description>This will log the complete URL rather than the part of the URL containing dynamic queries.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Log User Agents</fielddescr> + <fieldname>log_user_agents</fieldname> + <description>This will enable the useragent string to be written to a separate log. The results are not shown in the GUI and should only be used for debugging purposes.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Proxy Port</fielddescr> + <fieldname>proxy_port</fieldname> + <description>This is the port the Proxy Server will listen for client requests on. The default is 3128.</description> + <type>input</type> + <size>4</size> + <combinefieldsend>true</combinefieldsend> + </field> + <field> + <fielddescr>ICP Port</fielddescr> + <fieldname>icp_port</fieldname> + <description>This is the port the Proxy Server will send and receive ICP queries to and from neighbor caches. The default value is 0, which means this function is disabled.</description> + <type>input</type> + <size>4</size> + </field> + <field> + <fielddescr>Visible Hostname</fielddescr> + <fieldname>visible_hostname</fieldname> + <description>This URL is displayed on the Proxy Server error messages.</description> + <type>input</type> + <size>35</size> + </field> + <field> + <fielddescr>Cache Administrator E-Mail</fielddescr> + <fieldname>cache_admin_email</fieldname> + <description>This E-Mail address is displayed on the Proxy Server error messages.</description> + <type>input</type> + <size>35</size> + </field> + <field> + <fielddescr>Error Messages Language</fielddescr> + <fieldname>error_language</fieldname> + <description>Select the language in which the Proxy Server shall display error messages to users.</description> + <type>select</type> + <options> + <option><name>Bulgarian</name><value>Bulgarian</value></option> + <option><name>Catalan</name><value>Catalan</value></option> + <option><name>Czech</name><value>Czech</value></option> + <option><name>Danish</name><value>Danish</value></option> + <option><name>Dutch</name><value>Dutch</value></option> + <option><name>English</name><value>English</value></option> + <option><name>Estonian</name><value>Estonian</value></option> + <option><name>Finnish</name><value>Finnish</value></option> + <option><name>French</name><value>French</value></option> + <option><name>German</name><value>German</value></option> + <option><name>Hebrew</name><value>Hebrew</value></option> + <option><name>Hungarian</name><value>Hungarian</value></option> + <option><name>Italian</name><value>Italian</value></option> + <option><name>Japanese</name><value>Japanese</value></option> + <option><name>Korean</name><value>Korean</value></option> + <option><name>Lithuanian</name><value>Lithuanian</value></option> + <option><name>Polish</name><value>Polish</value></option> + <option><name>Portuguese</name><value>Portuguese</value></option> + <option><name>Romanian</name><value>Romanian</value></option> + <option><name>Russian-1251</name><value>Russian-1251</value></option> + <option><name>Russian-koi8-r</name><value>Russian-koi8-r</value></option> + <option><name>Serbian</name><value>Serbian</value></option> + <option><name>Simplify Chinese</name><value>Simplify Chinese</value></option> + <option><name>Slovak</name><value>Slovak</value></option> + <option><name>Spanish</name><value>Spanish</value></option> + <option><name>Swedish</name><value>Swedish</value></option> + <option><name>Traditional Chinese</name><value>Traditional Chinese</value></option> + <option><name>Turkish</name><value>Turkish</value></option> + </options> + </field> + <field> + <fielddescr>Enable cachemgr</fielddescr> + <fieldname>cachemgr_enabled</fieldname> + <description>Enable Squid's cachemgr.cgi to provide stats. Once enabled you can access this from the pfSense menus. <b>Note:</b> This page is not secured by pfSense, any user with access to the pfSense admin port can view the stats. The page prompts for a password but it only required for shutting down Squid.</description> + <type>checkbox</type> + </field> + + </fields> + <custom_add_php_command_late> + global_write_squid_config(); + mwexec("/usr/local/sbin/squid -k reconfigure"); + start_service("squid"); + </custom_add_php_command_late> + <custom_php_install_command> + squid3_custom_php_install_command(); + write_static_squid_config(); + mwexec("/usr/local/sbin/squid -k reconfigure"); + start_service("squid"); + </custom_php_install_command> + <custom_php_deinstall_command> + squid3_custom_php_deinstall_command(); + stop_service("squid"); + </custom_php_deinstall_command> +</packagegui> diff --git a/config/squid3/33/squid_reverse.inc b/config/squid3/33/squid_reverse.inc new file mode 100755 index 00000000..eb2d4c73 --- /dev/null +++ b/config/squid3/33/squid_reverse.inc @@ -0,0 +1,222 @@ +<?php +/* $Id$ */ +/* + squid_reverse.inc + Copyright (C) 2012 Martin Fuchs + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2013 Gekkenhuis + 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. +*/ + +function squid_resync_reverse() { + global $config; + //if(!is_array($valid_acls)) + // return; + + //CONFIG FILE + if (is_array($config['installedpackages']['squidreversegeneral'])) + $settings = $config['installedpackages']['squidreversegeneral']['config'][0]; + if (is_array($config['installedpackages']['squidreversepeer'])) + $reverse_peers=$config['installedpackages']['squidreversepeer']['config']; + if (is_array($config['installedpackages']['squidreverseuri'])) + $reverse_maps=$config['installedpackages']['squidreverseuri']['config']; + if (is_array($config['installedpackages']['squidreverseredir'])) + $reverse_redir=$config['installedpackages']['squidreverseredir']['config']; + + $conf = "# Reverse Proxy settings\n"; + + if(isset($settings["reverse_ssl_cert"]) && $settings["reverse_ssl_cert"] != "none") { + $svr_cert = lookup_cert($settings["reverse_ssl_cert"]); + if ($svr_cert != false) { + if(base64_decode($svr_cert['crt'])) { + file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt",sq_text_area_decode($svr_cert['crt'])); + $reverse_crt = SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt"; + } + if(base64_decode($svr_cert['prv'])) { + file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.key",sq_text_area_decode($svr_cert['prv'])); + $reverse_key = SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.key"; + } + } + } + + if (!empty($settings['reverse_int_ca'])) + file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt","\n" . sq_text_area_decode($settings['reverse_int_ca']),FILE_APPEND | LOCK_EX); + + $ifaces = ($settings['reverse_interface'] ? $settings['reverse_interface'] : 'wan'); + $real_ifaces = array(); + + #set HTTP port and defsite + $http_port=(empty($settings['reverse_http_port'])?"80":$settings['reverse_http_port']); + $http_defsite=(empty($settings['reverse_http_defsite'])?$settings['reverse_external_fqdn']:$settings['reverse_http_defsite']); + + #set HTTPS port and defsite + $https_port=(empty($settings['reverse_https_port'])?"443":$settings['reverse_https_port']); + $https_defsite=(empty($settings['reverse_https_defsite'])?$settings['reverse_external_fqdn']:$settings['reverse_https_defsite']); + + foreach (explode(",", $ifaces) as $i => $iface) { + $real_ifaces[] = squid_get_real_interface_address($iface); + if($real_ifaces[$i][0]) { + //HTTP + if (!empty($settings['reverse_http'])) + $conf .= "http_port {$real_ifaces[$i][0]}:{$http_port} accel defaultsite={$http_defsite} vhost\n"; + //HTTPS + if (!empty($settings['reverse_https'])) + $conf .= "https_port {$real_ifaces[$i][0]}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite} vhost\n"; + } + } + + if(!empty($settings['reverse_ip'])) { + $reverse_ip = explode(";", ($settings['reverse_ip'])); + foreach ($reverse_ip as $reip) { + //HTTP + if (!empty($settings['reverse_http'])) + $conf .= "http_port {$reip}:{$http_port} accel defaultsite={$http_defsite} vhost\n"; + //HTTPS + if (!empty($settings['reverse_https'])) + $conf .= "https_port {$reip}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite} vhost\n"; + } + } + + //PEERS + if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip']))) + $conf .= "cache_peer {$settings['reverse_owa_ip']} parent 443 0 proxy-only no-query originserver login=PASS connection-auth=on ssl sslflags=DONT_VERIFY_PEER front-end-https=on name=OWA_HOST_pfs\n"; + + $active_peers=array(); + if (is_array($reverse_peers)) + foreach ($reverse_peers as $rp){ + if ($rp['enable'] =="on" && $rp['name'] !="" && $rp['ip'] !="" && $rp['port'] !=""){ + $conf_peer = "#{$rp['description']}\n"; + $conf_peer .= "cache_peer {$rp['ip']} parent {$rp['port']} 0 proxy-only no-query no-digest originserver login=PASS "; + if($rp['protocol'] == 'HTTPS') + $conf_peer .= "ssl sslflags=DONT_VERIFY_PEER front-end-https=auto "; + $conf_peer .= "name=rvp_{$rp['name']}\n\n"; + + // add peer only if reverse proxy is enabled for http + if($rp['protocol'] == 'HTTP' && $settings['reverse_http'] =="on"){ + $conf .= $conf_peer; + array_push($active_peers,$rp['name']); + } + // add peer only if if reverse proxy is enabled for https + if($rp['protocol'] == 'HTTPS' && $settings['reverse_https'] =="on"){ + if (!in_array($rp['name'],$active_peers)){ + $conf .= $conf_peer; + array_push($active_peers,$rp['name']); + } + } + } + } + + //REDIRECTS + if (is_array($reverse_redir)) { + foreach ($reverse_redir as $rdr) { + if($rdr['enable'] == "on" && $rdr['name'] != "" && $rdr['pathregex'] != "" && $rdr['redirurl'] != "") { + $conf_rdr = "# Redirect: {$rdr['description']}\n"; + + if (is_array($rdr['row'])) { + foreach ($rdr['row'] as $uri) { + $conf_rdr .= "acl rdr_dst_{$rdr['name']} dstdomain {$uri['uri']}\n"; + } + } + + $conf_rdr .= "acl rdr_path_{$rdr['name']} urlpath_regex {$rdr['pathregex']}\n"; + $conf_rdr .= "deny_info {$rdr['redirurl']} rdr_path_{$rdr['name']}\n"; + + foreach (explode(',', $rdr['protocol']) as $rdr_protocol) { + if($rdr_protocol == "HTTP") { + $conf_rdr .= "http_access deny HTTP rdr_dst_{$rdr['name']} rdr_path_{$rdr['name']}\n"; + } + + if($rdr_protocol == "HTTPS") { + $conf_rdr .= "http_access deny HTTPS rdr_dst_{$rdr['name']} rdr_path_{$rdr['name']}\n"; + } + } + + $conf_rdr .= "\n"; + } + + $conf .= $conf_rdr; + } + } + + //ACLS and MAPPINGS + + //create an empty owa_dirs to populate based on user selected options + $owa_dirs=array(); + if (($settings['reverse_owa'] == 'on') && $settings['reverse_https'] =="on"){ + if(!empty($settings['reverse_owa_ip'])){ + array_push($owa_dirs,'owa','exchange','public','exchweb','ecp','OAB'); + if($settings['reverse_owa_activesync']) + array_push($owa_dirs,'Microsoft-Server-ActiveSync'); + if($settings['reverse_owa_rpchttp']) + array_push($owa_dirs,'rpc/rpcproxy.dll','rpcwithcert/rpcproxy.dll'); + if($settings['reverse_owa_autodiscover']) + array_push($owa_dirs,'autodiscover'); + if($settings['reverse_owa_webservice']){ + array_push($owa_dirs,'EWS'); + $conf .= "ignore_expect_100 on\n"; + } + } + if (is_array($owa_dirs)) + foreach ($owa_dirs as $owa_dir) + $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/$owa_dir.*$\n"; + } + //$conf .= "ssl_unclean_shutdown on"; + if (is_array($reverse_maps)) + foreach ($reverse_maps as $rm){ + if ($rm['enable'] == "on" && $rm['name']!="" && $rm['peers']!=""){ + if (is_array($rm['row'])) + foreach ($rm['row'] as $uri){ + $url_regex=($uri['uri'] == '' ? $settings['reverse_external_fqdn'] : $uri['uri'] ); + //$conf .= "acl rvm_{$rm['name']} url_regex -i {$uri['uri']}{$url_regex}.*$\n"; + $conf .= "acl rvm_{$rm['name']} url_regex -i {$url_regex}\n"; + if($rm['name'] != $last_rm_name){ + $cache_peer_never_direct_conf .= "never_direct allow rvm_{$rm['name']}\n"; + $http_access_conf .= "http_access allow rvm_{$rm['name']}\n"; + foreach (explode(',',$rm['peers']) as $map_peer) + if (in_array($map_peer,$active_peers)){ + $cache_peer_allow_conf .= "cache_peer_access rvp_{$map_peer} allow rvm_{$rm['name']}\n"; + $cache_peer_deny_conf .= "cache_peer_access rvp_{$map_peer} deny allsrc\n"; + } + $last_rm_name=$rm['name']; + } + } + } + } + + //ACCESS + if ($settings['reverse_owa'] == 'on' && !empty($settings['reverse_owa_ip']) && $settings['reverse_https'] =="on") { + $conf .= "cache_peer_access OWA_HOST_pfs allow OWA_URI_pfs\n"; + $conf .= "cache_peer_access OWA_HOST_pfs deny allsrc\n"; + $conf .= "never_direct allow OWA_URI_pfs\n"; + $conf .= "http_access allow OWA_URI_pfs\n"; + } + + $conf .= $cache_peer_allow_conf.$cache_peer_deny_conf.$cache_peer_never_direct_conf.$http_access_conf."\n"; + + if (!empty($settings['deny_info_tcp_reset'])) + $conf .= "deny_info TCP_RESET allsrc\n"; + + return $conf; +} +?> diff --git a/config/squid3/33/squid_reverse.xml b/config/squid3/33/squid_reverse.xml new file mode 100755 index 00000000..ce09f8e7 --- /dev/null +++ b/config/squid3/33/squid_reverse.xml @@ -0,0 +1,357 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidreverse</name> + <version>none</version> + <title>Proxy server: Reverse Proxy</title> + <include_file>squid.inc</include_file> + <tabs> +<tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Upstream</text> + <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url> + </tab> + <tab> + <text>Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Reverse</text> + <url>/pkg_edit.php?xml=squid_reverse.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Reverse proxy General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Reverse Proxy interface</fielddescr> + <fieldname>reverse_interface</fieldname> + <description>The interface(s) the reverse-proxy server will bind to.</description> + <type>interfaces_selection</type> + <required/> + <default_value>wan</default_value> + <multiple/> + </field> + <field> + <fielddescr>User-defined reverse-proxy IPs</fielddescr> + <fieldname>reverse_ip</fieldname> + <description>Squid will additionally bind to this user-defined IPs for reverse-proxy operation. Useful for virtual IPs such as CARP. Separate by semi-colons (;).</description> + <type>input</type> + <size>70</size> + </field> + <field> + <fielddescr>external FQDN</fielddescr> + <fieldname>reverse_external_fqdn</fieldname> + <description>The external full-qualified-domain-name of the WAN address.</description> + <type>input</type> + <required/> + <size>70</size> + </field> + <field> + <fielddescr>Reset TCP connections if request is unauthorized</fielddescr> + <fieldname>deny_info_tcp_reset</fieldname> + <description>If this field is checked, the reverse-proxy will reset the TCP connection if the request is unauthorized.</description> + <type>checkbox</type> + <default_value>on</default_value> + </field> + <field> + <name>Squid Reverse HTTP Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable HTTP reverse mode</fielddescr> + <fieldname>reverse_http</fieldname> + <description>If this field is checked, the proxy-server will act in HTTP reverse mode. <br>(You have to add a rule with destination "WAN-address")</description> + <type>checkbox</type> + <enablefields>reverse_http_port,reverse_http_defsite</enablefields> + <required/> + <default_value>off</default_value> + </field> + <field> + <fielddescr>reverse HTTP port</fielddescr> + <fieldname>reverse_http_port</fieldname> + <description>This is the port the HTTP reverse-proxy will listen on. (leave empty to use 80)</description> + <type>input</type> + <size>5</size> + <default_value>80</default_value> + </field> + <field> + <fielddescr>reverse HTTP default site</fielddescr> + <fieldname>reverse_http_defsite</fieldname> + <description>This is the HTTP reverse default site. (leave empty to use the external fqdn)</description> + <type>input</type> + <size>60</size> + </field> + <field> + <name>Squid Reverse HTTPS Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable HTTPS reverse proxy</fielddescr> + <fieldname>reverse_https</fieldname> + <description>If this field is checked, the proxy-server will act in HTTPS reverse mode. <br>(You have to add a rule with destination "WAN-address")</description> + <type>checkbox</type> + <enablefields>reverse_https_port,reverse_https_defsite,reverse_ssl_cert,reverse_int_ca,reverse_ignore_ssl_valid,reverse_owa,reverse_owa_ip,reverse_owa_webservice,reverse_owa_activesync,reverse_owa_rpchttp,reverse_owa_autodiscover,reverse_ssl_chain</enablefields> + <required/> + <default_value>off</default_value> + </field> + <field> + <fielddescr>reverse HTTPS port</fielddescr> + <fieldname>reverse_https_port</fieldname> + <description>This is the port the HTTPS reverse-proxy will listen on. (leave empty to use 443)</description> + <type>input</type> + <size>5</size> + <default_value>443</default_value> + </field> + <field> + <fielddescr>reverse HTTPS default site</fielddescr> + <fieldname>reverse_https_defsite</fieldname> + <description>This is the HTTPS reverse default site. (leave empty to use the external fqdn)</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>reverse SSL certificate</fielddescr> + <fieldname>reverse_ssl_cert</fieldname> + <description>Choose the SSL Server Certificate here.</description> + <type>select_source</type> + <source><![CDATA[$config['cert']]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + <field> + <fielddescr>intermediate CA certificate (if needed)</fielddescr> + <fieldname>reverse_int_ca</fieldname> + <description>Paste a signed certificate in X.509 PEM format here.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Ignore internal Certificate validation</fielddescr> + <fieldname>reverse_ignore_ssl_valid</fieldname> + <description>If this field is checked, internal certificate validation will be ignored.</description> + <type>checkbox</type> + <default_value>on</default_value> + </field> + <field> + <fielddescr>Enable OWA reverse proxy</fielddescr> + <fieldname>reverse_owa</fieldname> + <description>If this field is checked, squid will act as an accelerator/ SSL offloader for Outlook Web App.</description> + <type>checkbox</type> + <enablefields>reverse_owa_ip,reverse_owa_activesync,reverse_owa_rpchttp,reverse_owa_webservice,reverse_owa_autodiscover</enablefields> + </field> + <field> + <fielddescr>OWA frontend IP address</fielddescr> + <fieldname>reverse_owa_ip</fieldname> + <description>This is the internal IP Address of the OWA frontend server.</description> + <type>input</type> + <size>15</size> + </field> + <field> + <fielddescr>Enable ActiveSync</fielddescr> + <fieldname>reverse_owa_activesync</fieldname> + <description>If this field is checked, ActiveSync will be enabled.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable Outlook Anywhere</fielddescr> + <fieldname>reverse_owa_rpchttp</fieldname> + <description>If this field is checked, RPC over HTTP will be enabled.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable Exchange WebServices</fielddescr> + <fieldname>reverse_owa_webservice</fieldname> + <description><![CDATA[If this field is checked, Exchange WebServices will be enabled.<br> + <strong>There are potential DoS side effects to its use, please avoid unless you must.</strong>]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable AutoDiscover</fielddescr> + <fieldname>reverse_owa_autodiscover</fieldname> + <description>If this field is checked, AutoDiscover will be enabled.</description> + <type>checkbox</type> + </field> + <field> + <name>Squid Reverse Mappings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr><b>peer definitions</b> <br>publishing hosts</fielddescr> + <fieldname>reverse_cache_peer</fieldname> + <description><![CDATA[Enter each peer definition on a new line. Directives have to be separated by a semicolon(;).<BR> + syntax: [peer alias];[internal ip address];[port];[HTTP / HTTPS]<br> + example: HOST1;192.168.0.1;80;HTTP<br> + <strong>WRONG SYNTAX USAGE WILL RESULT IN SQUID NOT STARTING</strong>]]></description> + <type>textarea</type> + <cols>60</cols> + <rows>10</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr><b>URI definitions</b> <br>published URIs</fielddescr> + <fieldname>reverse_uri</fieldname> + <description><![CDATA[Enter each reverse acl definition on a new line. Directives have to be separated by a semicolon(;)<BR> + syntax: [group the uri belongs to];[URI to publish](;[vhost fqdn]) <BR> + (a group can contain multiple URIs, without vhost fqdn the external fqdn is used, you also can specity http:// or https://)<BR> + example: URI1;public;server.pfsense.org.<BR> + <STRONG>WRONG SYNTAX USAGE WILL RESULT IN SQUID NOT STARTING</STRONG>]]></description> + <type>textarea</type> + <cols>60</cols> + <rows>10</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr><b>ACL definitions</b> <br>published URIs</fielddescr> + <fieldname>reverse_acl</fieldname> + <description><![CDATA[Enter each reverse acl definition on a new line. Directives have to be separated by a semicolon(;). <br> + syntax: [peer alias];[uri group alias] <br>example: HOST1;URI1 <br> + <strong>WRONG SYNTAX USAGE WILL RESULT IN SQUID NOT STARTING</strong>]]></description> + <type>textarea</type> + <cols>60</cols> + <rows>10</rows> + <encoding>base64</encoding> + </field> + +<!-- + <field> + <fielddescr>internal hosts</fielddescr> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP address</fielddescr> + <fieldname>reverse_cache_peer_ip</fieldname> + <type>input</type> + <size>15</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Protocol</fielddescr> + <fieldname>reverse_cache_peer_proto</fieldname> + <type>select</type> + <options> + <option> <name>HTTP</name> <value>HTTP</value> </option> + <option> <name>HTTPS</name> <value>HTTPS</value> </option> + </options> + </rowhelperfield> + <rowhelperfield> + <fielddescr>port</fielddescr> + <fieldname>reverse_cache_peer_port</fieldname> + <type>input</type> + <size>5</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>peer name</fielddescr> + <fieldname>reverse_cache_peer_name</fieldname> + <type>input</type> + <size>25</size> + </rowhelperfield> + </rowhelper> + </field> + + <field> + <fielddescr>published URI</fielddescr> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>URI</fielddescr> + <fieldname>reverse_cache_peer_uri</fieldname> + <type>input</type> + <size>50</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>peer name</fielddescr> + <fieldname>reverse_cache_peer</fieldname> + <type>input</type> + <size>25</size> + </rowhelperfield> + </rowhelper> + </field> +--> + + </fields> + <custom_php_command_before_form> + squid_before_form_general(&$pkg); + </custom_php_command_before_form> + <custom_php_validation_command> + squid_validate_reverse($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/squid3/33/squid_reverse_general.xml b/config/squid3/33/squid_reverse_general.xml new file mode 100755 index 00000000..2211bb20 --- /dev/null +++ b/config/squid3/33/squid_reverse_general.xml @@ -0,0 +1,249 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_reverse_general.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidreversegeneral</name> + <version>none</version> + <title>Reverse Proxy server: General</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Web Servers</text> + <url>/pkg.php?xml=squid_reverse_peer.xml</url> + </tab> + <tab> + <text>Mappings</text> + <url>/pkg.php?xml=squid_reverse_uri.xml</url> + </tab> + <tab> + <text>Redirects</text> + <url>/pkg.php?xml=squid_reverse_redir.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Reverse proxy General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Reverse Proxy interface</fielddescr> + <fieldname>reverse_interface</fieldname> + <description>The interface(s) the reverse-proxy server will bind to.</description> + <type>interfaces_selection</type> + <required/> + <default_value>wan</default_value> + <multiple/> + </field> + <field> + <fielddescr>User-defined reverse-proxy IPs</fielddescr> + <fieldname>reverse_ip</fieldname> + <description>Squid will additionally bind to this user-defined IPs for reverse-proxy operation. Useful for virtual IPs such as CARP. Separate by semi-colons (;).</description> + <type>input</type> + <size>70</size> + </field> + <field> + <fielddescr>external FQDN</fielddescr> + <fieldname>reverse_external_fqdn</fieldname> + <description>The external full-qualified-domain-name of the WAN address.</description> + <type>input</type> + <required/> + <size>70</size> + </field> + <field> + <fielddescr>Reset TCP connections if request is unauthorized</fielddescr> + <fieldname>deny_info_tcp_reset</fieldname> + <description>If this field is checked, the reverse-proxy will reset the TCP connection if the request is unauthorized.</description> + <type>checkbox</type> + <default_value>on</default_value> + </field> + <field> + <name>Squid Reverse HTTP Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable HTTP reverse mode</fielddescr> + <fieldname>reverse_http</fieldname> + <description>If this field is checked, the proxy-server will act in HTTP reverse mode. <br>(You have to add a rule with destination "WAN-address")</description> + <type>checkbox</type> + <enablefields>reverse_http_port,reverse_http_defsite</enablefields> + <required/> + <default_value>off</default_value> + </field> + <field> + <fielddescr>reverse HTTP port</fielddescr> + <fieldname>reverse_http_port</fieldname> + <description>This is the port the HTTP reverse-proxy will listen on. (leave empty to use 80)</description> + <type>input</type> + <size>5</size> + <default_value>80</default_value> + </field> + <field> + <fielddescr>reverse HTTP default site</fielddescr> + <fieldname>reverse_http_defsite</fieldname> + <description>This is the HTTP reverse default site. (leave empty to use the external fqdn)</description> + <type>input</type> + <size>60</size> + </field> + <field> + <name>Squid Reverse HTTPS Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable HTTPS reverse proxy</fielddescr> + <fieldname>reverse_https</fieldname> + <description>If this field is checked, the proxy-server will act in HTTPS reverse mode. <br>(You have to add a rule with destination "WAN-address")</description> + <type>checkbox</type> + <enablefields>reverse_https_port,reverse_https_defsite,reverse_ssl_cert,reverse_int_ca,reverse_ignore_ssl_valid,reverse_owa,reverse_owa_ip,reverse_owa_webservice,reverse_owa_activesync,reverse_owa_rpchttp,reverse_owa_autodiscover,reverse_ssl_chain</enablefields> + <required/> + <default_value>off</default_value> + </field> + <field> + <fielddescr>reverse HTTPS port</fielddescr> + <fieldname>reverse_https_port</fieldname> + <description>This is the port the HTTPS reverse-proxy will listen on. (leave empty to use 443)</description> + <type>input</type> + <size>5</size> + <default_value>443</default_value> + </field> + <field> + <fielddescr>reverse HTTPS default site</fielddescr> + <fieldname>reverse_https_defsite</fieldname> + <description>This is the HTTPS reverse default site. (leave empty to use the external fqdn)</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>reverse SSL certificate</fielddescr> + <fieldname>reverse_ssl_cert</fieldname> + <description>Choose the SSL Server Certificate here.</description> + <type>select_source</type> + <source><![CDATA[$config['cert']]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + <field> + <fielddescr>intermediate CA certificate (if needed)</fielddescr> + <fieldname>reverse_int_ca</fieldname> + <description>Paste a signed certificate in X.509 PEM format here.</description> + <type>textarea</type> + <cols>50</cols> + <rows>5</rows> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Ignore internal Certificate validation</fielddescr> + <fieldname>reverse_ignore_ssl_valid</fieldname> + <description>If this field is checked, internal certificate validation will be ignored.</description> + <type>checkbox</type> + <default_value>on</default_value> + </field> + <field> + <name>OWA Reverse proxy General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable OWA reverse proxy</fielddescr> + <fieldname>reverse_owa</fieldname> + <description>If this field is checked, squid will act as an accelerator/ SSL offloader for Outlook Web App.</description> + <type>checkbox</type> + <enablefields>reverse_owa_ip,reverse_owa_activesync,reverse_owa_rpchttp,reverse_owa_webservice,reverse_owa_autodiscover</enablefields> + </field> + <field> + <fielddescr>OWA frontend IP address</fielddescr> + <fieldname>reverse_owa_ip</fieldname> + <description>This is the internal IP Address of the OWA frontend server.</description> + <type>input</type> + <size>15</size> + </field> + <field> + <fielddescr>Enable ActiveSync</fielddescr> + <fieldname>reverse_owa_activesync</fieldname> + <description>If this field is checked, ActiveSync will be enabled.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable Outlook Anywhere</fielddescr> + <fieldname>reverse_owa_rpchttp</fieldname> + <description>If this field is checked, RPC over HTTP will be enabled.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable Exchange WebServices</fielddescr> + <fieldname>reverse_owa_webservice</fieldname> + <description><![CDATA[If this field is checked, Exchange WebServices will be enabled.<br> + <strong>There are potential DoS side effects to its use, please avoid unless you must.</strong>]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable AutoDiscover</fielddescr> + <fieldname>reverse_owa_autodiscover</fieldname> + <description>If this field is checked, AutoDiscover will be enabled.</description> + <type>checkbox</type> + </field> + </fields> + <custom_php_command_before_form> + squid_before_form_general(&$pkg); + </custom_php_command_before_form> + <custom_php_validation_command> + squid_validate_reverse($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/squid3/33/squid_reverse_peer.xml b/config/squid3/33/squid_reverse_peer.xml new file mode 100755 index 00000000..abfbf19b --- /dev/null +++ b/config/squid3/33/squid_reverse_peer.xml @@ -0,0 +1,167 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_reverse_peer.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidreversepeer</name> + <version>none</version> + <title>Reverse Proxy server: Peers</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + </tab> + <tab> + <text>Web Servers</text> + <url>/pkg.php?xml=squid_reverse_peer.xml</url> + <active/> + </tab> + <tab> + <text>Mappings</text> + <url>/pkg.php?xml=squid_reverse_uri.xml</url> + </tab> + <tab> + <text>Redirects</text> + <url>/pkg.php?xml=squid_reverse_redir.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Alias</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Ip address</fielddescr> + <fieldname>ip</fieldname> + </columnitem> + <columnitem> + <fielddescr>Port</fielddescr> + <fieldname>port</fieldname> + </columnitem> + <columnitem> + <fielddescr>Protocol</fielddescr> + <fieldname>Protocol</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Squid Reverse Peer Mappings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable this peer</fielddescr> + <fieldname>enable</fieldname> + <description>If this field is checked, then this peer will be available for reverse config.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Peer Alias</fielddescr> + <fieldname>name</fieldname> + <description><![CDATA[Name to identify this peer on squid reverse conf<br> + example: HOST1]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Peer IP</fielddescr> + <fieldname>ip</fieldname> + <description><![CDATA[Ip Address of this peer.<br> + example: 192.168.0.1]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Peer Port</fielddescr> + <fieldname>port</fieldname> + <description><![CDATA[Listening port of this peer.<br> + example: 80]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Peer Protocol</fielddescr> + <fieldname>protocol</fieldname> + <description><![CDATA[Protocol listening on this peer port.]]></description> + <type>select</type> + <options> + <option> <name>HTTP</name> <value>HTTP</value> </option> + <option> <name>HTTPS</name> <value>HTTPS</value> </option> + </options> + </field> + <field> + <fielddescr>Peer Description</fielddescr> + <fieldname>description</fieldname> + <description><![CDATA[Peer Description (optional)]]></description> + <type>input</type> + <size>60</size> + </field> + </fields> + <custom_php_command_before_form> + squid_before_form_general(&$pkg); + </custom_php_command_before_form> + <custom_php_validation_command> + squid_validate_reverse($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/squid3/33/squid_reverse_redir.xml b/config/squid3/33/squid_reverse_redir.xml new file mode 100755 index 00000000..de25f56a --- /dev/null +++ b/config/squid3/33/squid_reverse_redir.xml @@ -0,0 +1,182 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ============================================================================ */ +/* + squid_reverse_redir.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2013 Gekkenhuis + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ============================================================================ */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidreverseredir</name> + <version>none</version> + <title>Reverse Proxy server: Redirects</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + </tab> + <tab> + <text>Web Servers</text> + <url>/pkg.php?xml=squid_reverse_peer.xml</url> + </tab> + <tab> + <text>Mappings</text> + <url>/pkg.php?xml=squid_reverse_uri.xml</url> + </tab> + <tab> + <text>Redirects</text> + <url>/pkg.php?xml=squid_reverse_redir.xml</url> + <active/> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Redirect Name</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Redirect to</fielddescr> + <fieldname>redirurl</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Squid Redirect Mappings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable this redirect</fielddescr> + <fieldname>enable</fieldname> + <description><![CDATA[If this field is checked, then this redirect will be available for reverse config.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Redirect name</fielddescr> + <fieldname>name</fieldname> + <description><![CDATA[Name to identify this redirect on squid reverse conf<br/> + example: REDIR1]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Redirect Description</fielddescr> + <fieldname>description</fieldname> + <description><![CDATA[Redirect Description (optional)]]></description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Redirect Protocol</fielddescr> + <fieldname>protocol</fieldname> + <description><![CDATA[Protocol to redirect on.<br/> + Use CTRL + click to select multiple]]></description> + <type>select</type> + <multiple/> + <size>03</size> + <options> + <option> + <name>HTTP</name> + <value>HTTP</value> + </option> + <option> + <name>HTTPS</name> + <value>HTTPS</value> + </option> + </options> + </field> + <field> + <fielddescr>Blocked domains</fielddescr> + <fieldname>none</fieldname> + <description>Domains to redirect for</description> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr><![CDATA[<strong>Domains to match</strong><br/><br/> + Samples: mydomain.com sub.mydomain.com www.mydomain.com<br/><br/> + Do not enter http:// or https:// here! only the hostname is required.]]></fielddescr> + <fieldname>uri</fieldname> + <type>input</type> + <size>60</size> + </rowhelperfield> + </rowhelper> + </field> + <field> + <fielddescr>Path regex</fielddescr> + <fieldname>pathregex</fieldname> + <description><![CDATA[Path regex to match<br/><br/>]]> + Enter ^/$ to match the domain only.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>URL to redirect to</fielddescr> + <fieldname>redirurl</fieldname> + <description><![CDATA[URL to redirect to]]></description> + <type>input</type> + <size>60</size> + </field> + </fields> + + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/squid3/33/squid_reverse_sync.xml b/config/squid3/33/squid_reverse_sync.xml new file mode 100755 index 00000000..041576b8 --- /dev/null +++ b/config/squid3/33/squid_reverse_sync.xml @@ -0,0 +1,135 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_sync.xml + part of the sarg package for pfSense + Copyright (C) 2012-2013 Marcello Coutinho + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidsync</name> + <version>1.0</version> + <title>Reverse Proxy server: XMLRPC Sync</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + </tab> + <tab> + <text>Web Servers</text> + <url>/pkg.php?xml=squid_reverse_peer.xml</url> + </tab> + <tab> + <text>Mappings</text> + <url>/pkg.php?xml=squid_reverse_uri.xml</url> + </tab> + <tab> + <text>Redirects</text> + <url>/pkg.php?xml=squid_reverse_redir.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync squid configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Select a sync method for squid.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_reverse_uri.xml b/config/squid3/33/squid_reverse_uri.xml new file mode 100755 index 00000000..1232cfe3 --- /dev/null +++ b/config/squid3/33/squid_reverse_uri.xml @@ -0,0 +1,159 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_reverse_general.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidreverseuri</name> + <version>none</version> + <title>Reverse Proxy server: Mappings</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_reverse_general.xml&id=0</url> + </tab> + <tab> + <text>Web Servers</text> + <url>/pkg.php?xml=squid_reverse_peer.xml</url> + </tab> + <tab> + <text>Mappings</text> + <url>/pkg.php?xml=squid_reverse_uri.xml</url> + <active/> + </tab> + <tab> + <text>Redirects</text> + <url>/pkg.php?xml=squid_reverse_redir.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Group Name</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Peers</fielddescr> + <fieldname>peers</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Squid Reverse Peer Mappings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable this URI</fielddescr> + <fieldname>enable</fieldname> + <description><![CDATA[If this field is checked, then this URI(Uniform Resource Name) will be available for reverse config.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Group name</fielddescr> + <fieldname>name</fieldname> + <description><![CDATA[Name to identify this URI on squid reverse conf<br> + example: URI1]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Group Description</fielddescr> + <fieldname>description</fieldname> + <description><![CDATA[URI Group Description (optional)]]></description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Peers</fielddescr> + <fieldname>peers</fieldname> + <description><![CDATA[Apply this Group Mappings to selected Peers<br> + Use CTRL + click to select.]]></description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['squidreversepeer']['config']]]></source> + <source_name>name</source_name> + <source_value>name</source_value> + <multiple/> + <size>05</size> + </field> + <field> + <fielddescr><![CDATA[URIs]]></fielddescr> + <fieldname>none</fieldname> + <description><![CDATA[URI to publish]]></description> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr><![CDATA[<strong>Url regex to match</strong><br><br> + Samples: .mydomain.com .mydomain.com/test<br> + www.mydomain.com http://www.mydomain.com/ ^http://www.mydomain.com/.*$]]></fielddescr> + <fieldname>uri</fieldname> + <type>input</type> + <size>70</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/squid3/33/squid_sync.xml b/config/squid3/33/squid_sync.xml new file mode 100755 index 00000000..e67defc7 --- /dev/null +++ b/config/squid3/33/squid_sync.xml @@ -0,0 +1,151 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_sync.xml + part of the sarg package for pfSense + Copyright (C) 2012-2013 Marcello Coutinho + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidsync</name> + <version>1.0</version> + <title>Proxy server: XMLRPC Sync</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync squid configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Select a sync method for squid.</description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> + </field> + <field> + <fielddescr>Sync timeout</fielddescr> + <fieldname>synctimeout</fieldname> + <description>Select sync max wait time</description> + <type>select</type> + <required/> + <default_value>250</default_value> + <options> + <option><name>250 seconds(Default)</name><value>250</value></option> + <option><name>120 seconds</name><value>120</value></option> + <option><name>90 seconds</name><value>90</value></option> + <option><name>60 seconds</name><value>60</value></option> + <option><name>30 seconds</name><value>30</value></option> + </options> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_traffic.xml b/config/squid3/33/squid_traffic.xml new file mode 100755 index 00000000..82e849c1 --- /dev/null +++ b/config/squid3/33/squid_traffic.xml @@ -0,0 +1,208 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidtraffic</name> + <version>none</version> + <title>Proxy server: Traffic management</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <fields> + <field> + <name>Squid Traffic Managment Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Maximum download size</fielddescr> + <fieldname>max_download_size</fieldname> + <description>Limit the maximum total download size to the size specified here (in kilobytes). Set to 0 to disable.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Maximum upload size</fielddescr> + <fieldname>max_upload_size</fieldname> + <description>Limit the maximum total upload size to the size specified here (in kilobytes). Set to 0 to disable.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Overall bandwidth throttling</fielddescr> + <fieldname>overall_throttling</fieldname> + <description>This value specifies (in kilobytes per second) the bandwidth throttle for downloads. Users will gradually have their download speed increased according to this value. Set to 0 to disable bandwidth throttling.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Per-host throttling</fielddescr> + <fieldname>perhost_throttling</fieldname> + <description>This value specifies the download throttling per host. Set to 0 to disable this.</description> + <type>input</type> + <size>10</size> + <required/> + <default_value>0</default_value> + </field> + <field> + <name>Squid Transfer Extension Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Throttle only specific extensions</fielddescr> + <fieldname>throttle_specific</fieldname> + <description>Leave this checked to be able to choose the extensions that throttling will be applied to. Otherwise, all files will be throttled.</description> + <type>checkbox</type> + <enablefields>throttle_binaries,throttle_cdimages,throttle_multimedia,throttle_others</enablefields> + <default_value>on</default_value> + </field> + <field> + <fielddescr>Throttle binary files</fielddescr> + <fieldname>throttle_binaries</fieldname> + <description>Check this to apply bandwidth throttle to binary files. This includes compressed archives and executables.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Throttle CD images</fielddescr> + <fieldname>throttle_cdimages</fieldname> + <description>Check this to apply bandwidth throttle to CD image files.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Throttle multimedia files</fielddescr> + <fieldname>throttle_multimedia</fieldname> + <description>Check this to apply bandwidth throttle to multimedia files, such as movies or songs.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Throttle other extensions</fielddescr> + <fieldname>throttle_others</fieldname> + <description>Comma-separated list of extensions to apply bandwidth throttle to.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <name>Squid Transfer Quick Abort Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Finish transfer if less than x KB remaining</fielddescr> + <fieldname>quick_abort_min</fieldname> + <description>If the transfer has less than x KB remaining, it will finish the retrieval. Set to 0 to abort the transfer immediately.</description> + <type>input</type> + <size>10</size> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Abort transfer if more than x KB remaining</fielddescr> + <fieldname>quick_abort_max</fieldname> + <description>If the transfer has more than x KB remaining, it will abort the retrieval. Set to 0 to abort the transfer immediately.</description> + <type>input</type> + <default_value>0</default_value> + </field> + <field> + <fielddescr>Finish transfer if more than x % finished</fielddescr> + <fieldname>quick_abort_pct</fieldname> + <description>If more than x % of the transfer has completed, it will finish the retrieval.</description> + <type>input</type> + <size>10</size> + <default_value>0</default_value> + </field> + </fields> + <custom_php_validation_command> + squid_validate_traffic($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_upstream.xml b/config/squid3/33/squid_upstream.xml new file mode 100755 index 00000000..407cedd8 --- /dev/null +++ b/config/squid3/33/squid_upstream.xml @@ -0,0 +1,361 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + squid_upstream.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidremote</name> + <version>none</version> + <title>Proxy server: Remote proxy settings</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <tabs> +<tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + <active/> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>name</fielddescr> + <fieldname>proxyaddr</fieldname> + </columnitem> + <columnitem> + <fielddescr>Port</fielddescr> + <fieldname>proxyport</fieldname> + </columnitem> + <columnitem> + <fielddescr>ICP</fielddescr> + <fieldname>icpport</fieldname> + </columnitem> + <columnitem> + <fielddescr>Peer type</fielddescr> + <fieldname>hierarchy</fieldname> + </columnitem> + <columnitem> + <fielddescr>Method</fielddescr> + <fieldname>peermethod</fieldname> + </columnitem> + </adddeleteeditpagefields> + + <fields> + <field> + <name>General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <description>This option enables the proxy server to forward requests to an upstream/neighbor server.</description> + <type>checkbox</type> + <required/> + </field> + <field> + <fielddescr>Hostname</fielddescr> + <fieldname>proxyaddr</fieldname> + <description>Enter here the IP address or host name of the upstream proxy.</description> + <type>input</type> + <size>35</size> + <required/> + </field> + <field> + <fielddescr>Name</fielddescr> + <fieldname>proxyname</fieldname> + <description>Unique name for the peer.Required if you have multiple peers on the same host but different ports.</description> + <type>input</type> + <size>35</size> + <required/> + </field> + <field> + <fielddescr>TCP port</fielddescr> + <fieldname>proxyport</fieldname> + <description>Enter the port to use to connect to the upstream proxy.</description> + <type>input</type> + <size>5</size> + <default_value>3128</default_value> + <required/> + </field> + <field> + <fielddescr>Timeout</fielddescr> + <fieldname>connecttimeout</fieldname> + <description>A peer-specific connect timeout. Also see the peer_connect_timeout directive.</description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Fail Limit</fielddescr> + <fieldname>connectfailLimit</fieldname> + <description>How many times connecting to a peer must fail before it is marked as down. Default is 10.</description> + <type>input</type> + <size>5</size> + <default_value>10</default_value> + </field> + <field> + <fielddescr>Max</fielddescr> + <fieldname>maxconn</fieldname> + <description>Limit the amount of connections Squid may open to this peer.</description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Allow Miss</fielddescr> + <fieldname>allowmiss</fieldname> + <description><![CDATA[<strong>allow-miss</strong> - Disable Squid's use of only-if-cached when forwarding requests to siblings. This is primarily useful when icp_hit_stale is used by the sibling.<br><br> + <strong>no-tproxy</strong> - Do not use the client-spoof TPROXY support when forwarding requests to this peer. Use normal address selection instead.<br><br> + <strong>proxy-only</strong> - Objects fetched from the peer will not be stored locally.]]></description> + <type>select</type> + <default_value>allow-miss</default_value> + <options> + <option><name>Allow Miss</name><value>allow-miss</value></option> + <option><name>No Tproxy</name><value>no-tproxy</value></option> + <option><name>Proxy Only</name><value>proxy-only</value></option> + </options> + <multiple/> + <size>4</size> + </field> + <field> + <name>Peer settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Hierarchy</fielddescr> + <fieldname>hierarchy</fieldname> + <description>Specify remote caches hierarchy.</description> + <type>select</type> + <default_value>parent</default_value> + <options> + <option><name>parent</name><value>parent</value></option> + <option><name>sibling</name><value>sibling</value></option> + <option><name>multicast</name><value>multicast</value></option> + </options> + </field> + <field> + <fielddescr>Select method</fielddescr> + <fieldname>peermethod</fieldname> + <description><![CDATA[The default peer selection method is ICP, with the first responding peer being used as source. These options can be used for better load balancing.<br><br> + <strong>default</strong> - This is a parent cache which can be used as a "last-resort" if a peer cannot be located by any of the peer-selection methods.<br> + If specified more than once, only the first is used.<br><br> + <strong>round-robin</strong> - Load-Balance parents which should be used in a round-robin fashion in the absence of any ICP queries.<br>weight=N can be used to add bias.<br><br> + <strong>weighted-round-robin</strong> - Load-Balance parents which should be used in a round-robin fashion with the frequency of each parent being based on the round trip time.<br> + Closer parents are used more often. Usually used for background-ping parents. weight=N can be used to add bias.<br><br> + <strong>carp</strong> - Load-Balance parents which should be used as a CARP array. The requests will be distributed among the parents based on the CARP load balancing hash function based on their weight.<br><br> + <strong>userhash</strong> - Load-balance parents based on the client proxy_auth or ident username.<br><br> + <strong>sourcehash</strong> - Load-balance parents based on the client source IP.<br><br> + <strong>multicast-siblings</strong> - To be used only for cache peers of type "multicast".<br> + ALL members of this multicast group have "sibling" relationship with it, not "parent". This is to a multicast group when the requested object would be fetched only from a "parent" cache, anyway.<br> + It's useful, e.g., when configuring a pool of redundant Squid proxies, being members of the same multicast group.]]></description> + <type>select</type> + <default_value>round-robin</default_value> + <options> + <option><name>round-robin</name><value>round-robin</value></option> + <option><name>default</name><value>default</value></option> + <option><name>weighted-round-robin</name><value>weighted-round-robin</value></option> + <option><name>carp</name><value>carp</value></option> + <option><name>userhash</name><value>userhash</value></option> + <option><name>sourcehash</name><value>sourcehash</value></option> + <option><name>multicast-sibling</name><value>multicast-sibling</value></option> + </options> + </field> + <field> + <fielddescr>weight</fielddescr> + <fieldname>weight</fieldname> + <description>Use to affect the selection of a peer during any weighted peer-selection mechanisms. The weight must be an integer; default is 1,larger weights are favored more.</description> + <type>input</type> + <size>5</size> + <default>1</default> + </field> + <field> + <fielddescr>basetime</fielddescr> + <fieldname>basetime</fieldname> + <description><![CDATA[Specify a base amount to be subtracted from round trip times of parents.<br> + It is subtracted before division by weight in calculating which parent to fectch from. If the rtt is less than the base time the rtt is set to a minimal value.]]></description> + <type>input</type> + <size>5</size> + <default>1</default> + </field> + <field> + <fielddescr>ttl</fielddescr> + <fieldname>ttl</fieldname> + <description><![CDATA[Specify a TTL to use when sending multicast ICP queries to this address<br> + Only useful when sending to a multicast group. Because we don't accept ICP replies from random hosts, you must configure other group members as peers with the 'multicast-responder' option.]]></description> + <type>input</type> + <size>5</size> + <default>1</default> + </field> + <field> + <fielddescr>no-delay</fielddescr> + <fieldname>nodelay</fieldname> + <description><![CDATA[To prevent access to this neighbor from influencing the delay pools.]]></description> + <type>checkbox</type> + </field> + <field> + <name>ICP settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>ICP port</fielddescr> + <fieldname>icpport</fieldname> + <description>Enter the port to connect to the upstream proxy for the ICP protocol. Use port number 7 to disable ICP communication between the proxies.</description> + <type>input</type> + <size>5</size> + <default_value>7</default_value> + </field> + <field> + <fielddescr>ICP Options</fielddescr> + <fieldname>icpoptions</fieldname> + <description><![CDATA[You MUST also set icp_port and icp_access explicitly when using these options.<br> + The defaults will prevent peer traffic using ICP<br><br> + <strong>no-query</strong> - Disable ICP queries to this neighbor.<br><br> + <strong>multicast-responder</strong> -Indicates the named peer is a member of a multicast group.<br> + ICP queries will not be sent directly to the peer, but ICP replies will be accepted from it.<br><br> + <strong>closest-only</strong> - Indicates that, for ICP_OP_MISS replies, we'll only forward CLOSEST_PARENT_MISSes and never FIRST_PARENT_MISSes.<br><br> + <strong>background-ping</strong> - To only send ICP queries to this neighbor infrequently.<br> + This is used to keep the neighbor round trip time updated and is usually used in conjunction with weighted-round-robin.]]></description> + <type>select</type> + <default_value>no-query</default_value> + <options> + <option><name>no-query</name><value>no-query</value></option> + <option><name>multicast-responder</name><value>multicast-responder</value></option> + <option><name>closest-only</name><value>closest-only</value></option> + <option><name>background-ping</name><value>background-ping</value></option> + </options> + </field> + <field> + <name>Auth settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Username</fielddescr> + <fieldname>username</fieldname> + <description>If the upstream proxy requires a username, specify it here.</description> + <type>input</type> + </field> + <field> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>If the upstream proxy requires a password, specify it here.</description> + <type>password</type> + </field> + <field> + <fielddescr>Authentication options</fielddescr> + <fieldname>authoption</fieldname> + <description><![CDATA[<br><strong>login=user:password</strong> - If this is a personal/workgroup proxy and your parent requires proxy authentication.<br><br> + <strong>login=PASSTHRU</strong> - Send login details received from client to this peer. Authentication is not required by Squid for this to work.<br> + This will pass any form of authentication but only Basic auth will work through a proxy unless the connection-auth options are also used.<br><br> + <strong>login=PASS</strong> - Send login details received from client to this peer.Authentication is not required by this option.<br> + To combine this with proxy_auth both proxies must share the same user database as HTTP only allows for a single login (one for proxy, one for origin server).<br> + Also be warned this will expose your users proxy password to the peer. USE WITH CAUTION<br><br> + <strong>login=*:password</strong> - Send the username to the upstream cache, but with a fixed password. This is meant to be used when the peer is in another administrative domain, but it is still needed to identify each user.<br><br> + <strong>login=NEGOTIATE</strong> - If this is a personal/workgroup proxy and your parent requires a secure proxy authentication.<br> + The first principal from the default keytab or defined by the environment variable KRB5_KTNAME will be used.<br> + WARNING: The connection may transmit requests from multiple clients. Negotiate often assumes end-to-end authentication and a single-client. Which is not strictly true here.<br><br> + <strong>login=NEGOTIATE:principal_name</strong>If this is a personal/workgroup proxy and your parent requires a secure proxy authentication.<br> + The principal principal_name from the default keytab or defined by the environment variable KRB5_KTNAME will be used. + WARNING: The connection may transmit requests from multiple clients. Negotiate often assumes end-to-end authentication and a single-client. Which is not strictly true here.<br><br> + <strong>connection-auth=on</strong> - Tell Squid that this peer does support Microsoft connection oriented authentication, and any such challenges received from there should be ignored.<br> + Default is auto to automatically determine the status of the peer.<br><br> + <strong>connection-auth=off</strong> - Tell Squid that this peer does not support Microsoft connection oriented authentication, and any such challenges received from there should be ignored.<br> + Default is auto to automatically determine the status of the peer.]]></description> + <type>select</type> + <default_value>login=*:password</default_value> + <options> + <option><name>login=*:password</name><value>login=*:password</value></option> + <option><name>login=user:password</name><value>login=user:password</value></option> + <option><name>login=PASSTHRU</name><value>login=PASSTHRU</value></option> + <option><name>login=PASS</name><value>login=PASS</value></option> + <option><name>login=NEGOTIATE</name><value>login=NEGOTIATE</value></option> + <option><name>login=NEGOTIATE:principal_name</name><value>login=NEGOTIATE:principal_name</value></option> + <option><name>connection-auth=on</name><value>connection-auth=on</value></option> + <option><name>connection-auth=off</name><value>connection-auth=off</value></option> + </options> + </field> + </fields> + <custom_php_validation_command> + squid_validate_upstream($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + squid_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/squid_users.xml b/config/squid3/33/squid_users.xml new file mode 100755 index 00000000..4acf9dd6 --- /dev/null +++ b/config/squid3/33/squid_users.xml @@ -0,0 +1,137 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + Copyright (C) 2012-2013 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidusers</name> + <version>none</version> + <title>Proxy server: Local users</title> + <include_file>/usr/local/pkg/squid.inc</include_file> + <delete_string>A proxy server user has been deleted.</delete_string> + <addedit_string>A proxy server user has been created/modified.</addedit_string> + <tabs> +<tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid.xml&id=0</url> + </tab> + <tab> + <text>Remote Cache</text> + <url>/pkg.php?xml=squid_upstream.xml</url> + </tab> + <tab> + <text>Local Cache</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + <tab> + <text>Antivirus</text> + <url>/pkg_edit.php?xml=squid_antivirus.xml&id=0</url> + </tab> + <tab> + <text>ACLs</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + <tab> + <text>Authentication</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + <tab> + <text>Users</text> + <url>/pkg.php?xml=squid_users.xml</url> + <active/> + </tab> + <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=squid_sync.xml</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Username</fielddescr> + <fieldname>username</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Squid Local Users</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Username</fielddescr> + <fieldname>username</fieldname> + <description>Enter the username here.</description> + <type>input</type> + <required/> + </field> + <field> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Enter the password here.</description> + <type>password</type> + <required/> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>You may enter a description here for your reference (not parsed).</description> + <type>input</type> + </field> + </fields> + <custom_php_resync_config_command> + squid_resync_users(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/squid3/33/swapstate_check.php b/config/squid3/33/swapstate_check.php new file mode 100644 index 00000000..6ecfff3c --- /dev/null +++ b/config/squid3/33/swapstate_check.php @@ -0,0 +1,58 @@ +#!/usr/local/bin/php -q +<?php +/* + swapstate_check.php + Copyright (C) 2011 Jim Pingle + 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('util.inc'); + +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('SQUID_LOCALBASE', '/usr/pbi/squid-' . php_uname("m")); +else + define('SQUID_LOCALBASE','/usr/local'); + + $settings = $config['installedpackages']['squidcache']['config'][0]; +// Only check the cache if Squid is actually caching. +// If there is no cache then quietly do nothing. +if ($settings['harddisk_cache_system'] != "null"){ + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + $swapstate = $cachedir . '/swap.state'; + $disktotal = disk_total_space(dirname($cachedir)); + $diskfree = disk_free_space(dirname($cachedir)); + $diskusedpct = round((($disktotal - $diskfree) / $disktotal) * 100); + $swapstate_size = filesize($swapstate); + $swapstate_pct = round(($swapstate_size / $disktotal) * 100); + + // If the swap.state file is taking up more than 75% disk space, + // or the drive is 90% full and swap.state is larger than 1GB, + // kill it and initiate a rotate to write a fresh copy. + if (($swapstate_pct > 75) || (($diskusedpct > 90) && ($swapstate_size > 1024*1024*1024))) { + mwexec_bg("/bin/rm $swapstate; ". SQUID_LOCALBASE . "/sbin/squid -k rotate"); + log_error(gettext(sprintf("Squid swap.state file exceeded size limits. Removing and rotating. File was %d bytes, %d%% of total disk space.", $swapstate_size, $swapstate_pct))); + } +} +?>
\ No newline at end of file diff --git a/config/squid3/proxy_monitor.sh b/config/squid3/old/proxy_monitor.sh index 00430018..00430018 100644 --- a/config/squid3/proxy_monitor.sh +++ b/config/squid3/old/proxy_monitor.sh diff --git a/config/squid3/squid.inc b/config/squid3/old/squid.inc index 784fea8f..784fea8f 100644 --- a/config/squid3/squid.inc +++ b/config/squid3/old/squid.inc diff --git a/config/squid3/squid.xml b/config/squid3/old/squid.xml index ea13625e..ea13625e 100644 --- a/config/squid3/squid.xml +++ b/config/squid3/old/squid.xml diff --git a/config/squid3/old/squid_auth.inc b/config/squid3/old/squid_auth.inc new file mode 100644 index 00000000..7c99a01b --- /dev/null +++ b/config/squid3/old/squid_auth.inc @@ -0,0 +1,446 @@ +<?php +/* $Id$ */ + +/* + squid_auth.inc + part of pfSense (www.pfSense.com) + + Copyright (C) 2005 Michael Capp <michael.capp@gmail.com> + 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. + +*/ + +function global_eval_auth_options() +{ + global $config; + conf_mount_rw(); + config_lock(); + + switch ($config['installedpackages']['squidauth']['config'][0]['auth_method']) { + case "none": + dynamic_auth_content("pkg_edit"); + dynamic_no_auth(); + break; + case "local_auth": + dynamic_auth_content("pkg"); + /* create empty passwd file to prevent stat error with squid reload */ + touch ("/usr/local/etc/squid/advanced/ncsa/passwd"); + dynamic_local_auth(); + break; + case "ldap_bind": + dynamic_auth_content("pkg_edit"); + dynamic_ldap_auth(); + break; + case "domain_auth": + $filecontents = file("/usr/local/pkg/squid_auth.xml"); + dynamic_auth_content("pkg_edit"); + dynamic_domain_auth(); + break; + case "radius_auth": + $filecontents = file("/usr/local/pkg/squid_auth.xml"); + dynamic_auth_content("pkg_edit"); + dynamic_radius_auth(); + break; + default: + $filecontents = file("/usr/local/pkg/squid_auth.xml"); + dynamic_auth_content("pkg_edit"); + dynamic_no_auth(); + break; + } + + config_unlock(); + conf_mount_ro(); + +} /* end function global_eval_auth_options */ + +function dynamic_no_auth() { + global $config; + conf_mount_rw(); + $fout = fopen("/usr/local/pkg/squid_extauth.xml", "w"); + fwrite($fout, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); + fwrite($fout, "<packagegui>\n"); + fwrite($fout, " <name>squidextnoauth</name>\n"); + fwrite($fout, " <title>Services: Proxy Server -> Extended Authentication Settings</title>\n"); + fwrite($fout, " <configpath>installedpackages->package->squidextnoauth->configuration->settings</configpath>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <aftersaveredirect>/pkg_edit.php?xml=squid_extauth.xml&id=0</aftersaveredirect>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tabs>\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>General Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_ng.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Upstream Proxy</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Cache Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Network Access Control</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Traffic Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Extended Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url>\n"); + fwrite($fout, " <active/>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " </tabs>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <fields>\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>No Authentication Defined</fielddescr>\n"); + fwrite($fout, " <fieldname>no_auth</fieldname>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, " </fields>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <custom_add_php_command_late>\n"); + fwrite($fout, " require_once(\"/usr/local/pkg/squid_ng.inc\");"); + fwrite($fout, "\n"); + fwrite($fout, " global_write_squid_config();\n"); + fwrite($fout, " mwexec(\"/usr/local/sbin/squid -k reconfigure\");\n"); + fwrite($fout, " </custom_add_php_command_late>\n"); + fwrite($fout, "\n"); + fwrite($fout, "</packagegui>\n"); + fclose($fout); + + /* mount filesystem read-only */ + conf_mount_ro(); +} + +function dynamic_local_auth() { + global $config; + conf_mount_rw(); + + $fout = fopen("/usr/local/pkg/squid_extauth.xml", "w"); + + fwrite($fout, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); + fwrite($fout, "\n"); + fwrite($fout, "<packagegui>\n"); + fwrite($fout, " <name>squidextlocalauth</name>\n"); + fwrite($fout, " <title>Services: Proxy Server -> Extended Auth Settings</title>\n"); + fwrite($fout, " <version>2.5.10_4</version>\n"); + fwrite($fout, " <configpath>installedpackages->package->squidextlocalauth->configuration->settings</configpath>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <files></files>\n"); + fwrite($fout, " <menu></menu>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <aftersaveredirect>/pkg.php?xml=squid_extauth.xml&id=0</aftersaveredirect>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tabs>\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>General Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_ng.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Upstream Proxy</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Cache Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Network Access Control</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Traffic Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Extended Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg.php?xml=squid_extauth.xml&id=0</url>\n"); + fwrite($fout, " <active/>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " </tabs>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <adddeleteeditpagefields>\n"); + fwrite($fout, " <columnitem>\n"); + fwrite($fout, " <fielddescr>Username</fielddescr>\n"); + fwrite($fout, " <fieldname>username</fieldname>\n"); + fwrite($fout, " </columnitem>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <columnitem>\n"); + fwrite($fout, " <fielddescr>Description</fielddescr>\n"); + fwrite($fout, " <fieldname>description</fieldname>\n"); + fwrite($fout, " </columnitem>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <columnitem>\n"); + fwrite($fout, " <fielddescr>Restriction Group</fielddescr>\n"); + fwrite($fout, " <fieldname>group</fieldname>\n"); + fwrite($fout, " </columnitem>\n"); + fwrite($fout, " </adddeleteeditpagefields>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <fields>\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Username</fielddescr>\n"); + fwrite($fout, " <fieldname>username</fieldname>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>15</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Password</fielddescr>\n"); + fwrite($fout, " <fieldname>password</fieldname>\n"); + fwrite($fout, " <type>password</type>\n"); + fwrite($fout, " <size>8</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Description (Optional)</fielddescr>\n"); + fwrite($fout, " <fieldname>description</fieldname>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>30</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Restriction Group</fielddescr>\n"); + fwrite($fout, " <fieldname>group</fieldname>\n"); + fwrite($fout, " <type>select</type>\n"); + fwrite($fout, " <options>\n"); + fwrite($fout, " <option><name>Standard</name><value>Standard</value></option>\n"); + fwrite($fout, " <option><name>Extended</name><value>Extended</value></option>\n"); + fwrite($fout, " </options>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " </fields>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <custom_add_php_command_late>\n"); + fwrite($fout, " require_once(\"/usr/local/pkg/squid_ng.inc\");\n"); + fwrite($fout, "\n"); + fwrite($fout, " mod_htpasswd();\n"); + fwrite($fout, " global_write_squid_config();\n"); + fwrite($fout, " mwexec(\"/usr/local/sbin/squid -k reconfigure\");\n"); + fwrite($fout, " </custom_add_php_command_late>\n"); + fwrite($fout, "\n"); + fwrite($fout, "</packagegui>\n"); + + fclose($fout); + + /* mount filesystem read-only */ + conf_mount_ro(); +} + +function dynamic_ldap_auth() { + global $config; + conf_mount_rw(); + + $fout = fopen("/usr/local/pkg/squid_extauth.xml", "w"); + + fwrite($fout, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); + fwrite($fout, "\n"); + fwrite($fout, "<packagegui>\n"); + fwrite($fout, " <name>squidextldapauth</name>\n"); + fwrite($fout, " <title>Services: Proxy Server -> Extended Auth Settings</title>\n"); + fwrite($fout, " <version>2.5.11</version>\n"); + fwrite($fout, " <configpath>installedpackages->package->squidextldapauth->configuration->settings</configpath>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <files></files>\n"); + fwrite($fout, " <menu></menu>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <aftersaveredirect>/pkg_edit.php?xml=squid_extauth.xml&id=0</aftersaveredirect>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tabs>\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>General Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_ng.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Upstream Proxy</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Cache Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Network Access Control</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Traffic Mgmt</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <tab>\n"); + fwrite($fout, " <text>Extended Auth Settings</text>\n"); + fwrite($fout, " <url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url>\n"); + fwrite($fout, " <active/>\n"); + fwrite($fout, " </tab>\n"); + fwrite($fout, "\n"); + fwrite($fout, " </tabs>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <fields>\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Base DN</fielddescr>\n"); + fwrite($fout, " <fieldname>ldap_basedn</fieldname>\n"); + fwrite($fout, " <description>This is the base where the LDAP search starts. All subsequent organizational units (OUs)will be included. Example: \"ou=users,o=company\" will search for users in and under the specified company.</description>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>50</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>LDAP Server</fielddescr>\n"); + fwrite($fout, " <fieldname>ldap_server</fieldname>\n"); + fwrite($fout, " <description>This is the LDAP server that the bind will be attempted against.</description>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>20</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>LDAP Type</fielddescr>\n"); + fwrite($fout, " <fieldname>ldap_type</fieldname>\n"); + fwrite($fout, " <description>This specifies the supported LDAP types.</description>\n"); + fwrite($fout, " <type>select</type>\n"); + fwrite($fout, " <options>\n"); + fwrite($fout, " <option><name>Active Directory</name><value>active_directory</value></option>\n"); + fwrite($fout, " <option><name>Novell eDirectory</name><value>novell_edirectory</value></option>\n"); + fwrite($fout, " <option><name>LDAP v2</name><value>ldap_v2</value></option>\n"); + fwrite($fout, " <option><name>LDAP v3</name><value>ldap_v3</value></option>\n"); + fwrite($fout, " </options>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>LDAP Port</fielddescr>\n"); + fwrite($fout, " <fieldname>ldap_port</fieldname>\n"); + fwrite($fout, " <description>This is the port that LDAP bind will attempt on. The default is \"389\".</description>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>5</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Bind DN Username</fielddescr>\n"); + fwrite($fout, " <fieldname>bind_dn_username</fieldname>\n"); + fwrite($fout, " <description>If \"anonymous bind\" is not supported, please specify the bind username that can access the Base DN hierarchy.</description>\n"); + fwrite($fout, " <type>input</type>\n"); + fwrite($fout, " <size>30</size>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <field>\n"); + fwrite($fout, " <fielddescr>Bind DN Password</fielddescr>\n"); + fwrite($fout, " <fieldname>bind_dn_password</fieldname>\n"); + fwrite($fout, " <description>This is the associated password with the Bind DN Username previously specified.</description>\n"); + fwrite($fout, " <type>password</type>\n"); + fwrite($fout, " </field>\n"); + fwrite($fout, "\n"); + fwrite($fout, " </fields>\n"); + fwrite($fout, "\n"); + fwrite($fout, " <custom_add_php_command_late>\n"); + fwrite($fout, " require_once(\"/usr/local/pkg/squid_ng.inc\");\n"); + fwrite($fout, "\n"); + fwrite($fout, " mod_htpasswd();\n"); + fwrite($fout, "\n"); + fwrite($fout, " global_write_squid_config();\n"); + fwrite($fout, " mwexec(\"/usr/local/sbin/squid -k reconfigure\");\n"); + fwrite($fout, " </custom_add_php_command_late>\n"); + fwrite($fout, "\n"); + fwrite($fout, "</packagegui>\n"); + + fclose($fout); + + /* mount filesystem read-only */ + conf_mount_ro(); +} + +/* dynamically re-writes all squid xml files to handle adddeletecolumnitems properly */ +function dynamic_auth_content($pkgvar) { + + switch ($pkgvar) { + case "pkg": + if ($handle = opendir("/usr/local/pkg")) { + while (($file = readdir($handle)) != false) { + if (stristr($file, "squid_") && stristr($file, ".xml")) { + $filecontents = file("/usr/local/pkg/" . $file); + $fout = fopen("/usr/local/pkg/" . $file, "w"); + foreach($filecontents as $line) { + if (stristr($line, "<url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url>")) { + fwrite($fout, " <url>/pkg.php?xml=squid_extauth.xml&id=0</url>\n"); + } else { + fwrite($fout, $line); + } + } + } + } + } + break; + + case "pkg_edit": + if ($handle = opendir("/usr/local/pkg")) { + while (($file = readdir($handle)) != false) { + if (stristr($file, "squid_") && stristr($file, ".xml")) { + $filecontents = file("/usr/local/pkg/" . $file); + $fout = fopen("/usr/local/pkg/" . $file,"w"); + foreach($filecontents as $line) { + if (stristr($line, "<url>/pkg.php?xml=squid_extauth.xml&id=0</url>")) { + fwrite($fout, " <url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url>\n"); + } else { + fwrite($fout, $line); + } + } + } + } + } + break; + } + +} /* end function dynamic_auth_content */ +?>
\ No newline at end of file diff --git a/config/squid3/squid_auth.xml b/config/squid3/old/squid_auth.xml index c8e34553..c8e34553 100644 --- a/config/squid3/squid_auth.xml +++ b/config/squid3/old/squid_auth.xml diff --git a/config/squid3/squid_cache.xml b/config/squid3/old/squid_cache.xml index 881f15b3..881f15b3 100644 --- a/config/squid3/squid_cache.xml +++ b/config/squid3/old/squid_cache.xml diff --git a/config/squid3/old/squid_extauth.xml b/config/squid3/old/squid_extauth.xml new file mode 100644 index 00000000..41d9f633 --- /dev/null +++ b/config/squid3/old/squid_extauth.xml @@ -0,0 +1,106 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + 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. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>squidextnoauth</name> + <version>none</version> + <title>Services: Proxy Server -> Extended Authentication Settings</title> + <aftersaveredirect>/pkg_edit.php?xml=squid_extauth.xml&id=0</aftersaveredirect> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=squid_ng.xml&id=0</url> + </tab> + + <tab> + <text>Upstream Proxy</text> + <url>/pkg_edit.php?xml=squid_upstream.xml&id=0</url> + </tab> + + <tab> + <text>Cache Mgmt</text> + <url>/pkg_edit.php?xml=squid_cache.xml&id=0</url> + </tab> + + <tab> + <text>Access Control</text> + <url>/pkg_edit.php?xml=squid_nac.xml&id=0</url> + </tab> + + <tab> + <text>Traffic Mgmt</text> + <url>/pkg_edit.php?xml=squid_traffic.xml&id=0</url> + </tab> + + <tab> + <text>Auth</text> + <url>/pkg_edit.php?xml=squid_auth.xml&id=0</url> + </tab> + + <tab> + <text>Extended Auth</text> + <url>/pkg_edit.php?xml=squid_extauth.xml&id=0</url> + <active/> + </tab> + + </tabs> + <configpath>installedpackages->package->squidextnoauth->configuration->settings</configpath> + <fields> + <field> + <fielddescr>No Authentication Defined</fielddescr> + <fieldname>no_auth</fieldname> + <type>text</type> + </field> + </fields> + + <custom_add_php_command_late> + require_once("/usr/local/pkg/squid_ng.inc"); + + global_write_squid_config(); + mwexec("/usr/local/sbin/squid -k reconfigure"); + </custom_add_php_command_late> + +</packagegui> diff --git a/config/squid3/squid_nac.xml b/config/squid3/old/squid_nac.xml index 193a89c6..193a89c6 100644 --- a/config/squid3/squid_nac.xml +++ b/config/squid3/old/squid_nac.xml diff --git a/config/squid3/squid_ng.inc b/config/squid3/old/squid_ng.inc index 03f6d48c..03f6d48c 100644 --- a/config/squid3/squid_ng.inc +++ b/config/squid3/old/squid_ng.inc diff --git a/config/squid3/squid_ng.xml b/config/squid3/old/squid_ng.xml index cb535cd3..cb535cd3 100644 --- a/config/squid3/squid_ng.xml +++ b/config/squid3/old/squid_ng.xml diff --git a/config/squid3/squid_traffic.xml b/config/squid3/old/squid_traffic.xml index d560a7ad..d560a7ad 100644 --- a/config/squid3/squid_traffic.xml +++ b/config/squid3/old/squid_traffic.xml diff --git a/config/squid3/squid_upstream.xml b/config/squid3/old/squid_upstream.xml index ad494524..ad494524 100644 --- a/config/squid3/squid_upstream.xml +++ b/config/squid3/old/squid_upstream.xml diff --git a/config/squid3/squid_users.xml b/config/squid3/old/squid_users.xml index eef6389f..eef6389f 100644 --- a/config/squid3/squid_users.xml +++ b/config/squid3/old/squid_users.xml diff --git a/config/squidGuard/squidguard.inc b/config/squidGuard/squidguard.inc index fb7fad28..1ea1b5a5 100644 --- a/config/squidGuard/squidguard.inc +++ b/config/squidGuard/squidguard.inc @@ -1,17 +1,20 @@ <?php # ------------------------------------------------------------------------------ /* squidguard.inc - 2006-2011 Serg Dvoriancev + + Copyright (C) 2006-2011 Serg Dvoriancev + Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> + Copyright (C) 2013 Marcello Coutinho part of pfSense (www.pfSense.com) 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, + 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 + 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. @@ -302,13 +305,9 @@ function squidguard_validate_rewrite($post, $input_errors) { # ----------------------------------------------------------------------------- function squidguard_resync() { $upload_file = ''; - $submit = ''; - $url = ''; - $proxy = ''; - - $submit = isset($_POST['submit']) ? $_POST['submit'] : $_GET['submit']; - $url = isset($_POST[F_BLACKLISTURL]) ? $_POST[F_BLACKLISTURL] : $_GET[F_BLACKLISTURL]; - $proxy = isset($_POST['blacklist_proxy']) ? $_POST['blacklist_proxy'] : $_GET['blacklist_proxy']; + $submit = isset($_REQUEST['submit']) ? $_REQUEST['submit'] : ''; + $url = isset($_REQUEST[F_BLACKLISTURL]) ? $_REQUEST[F_BLACKLISTURL] : ''; + $proxy = isset($_REQUEST['blacklist_proxy'])? $_REQUEST['blacklist_proxy'] : ''; sg_init(convert_pfxml_to_sgxml()); @@ -332,7 +331,10 @@ function squidguard_resync() { //} squidguard_cron_install(); - squidguard_sync_on_changes(); + + //Sync only with apply button to avoid multiples reloads on backup server while editing master config + if ($submit == APPLY_BTN) + squidguard_sync_on_changes(); } # ----------------------------------------------------------------------------- @@ -373,6 +375,44 @@ function squidguard_resync_acl() { } } +# ----------------------------------------------------------------------------- +# squidguard_resync_dest +# ----------------------------------------------------------------------------- + +function squidguard_resync_dest() { + global $config; # !!! ORDER !!! + + $conf = $config['installedpackages'][MODULE_DESTINATION]['config']; + $id = isset($_POST['id']) ? $_POST['id'] : $_GET['id']; + + # --- sources part --- + # move current id by order + if (($id !== '') and is_array($conf)) { + $src_new = array(); + + foreach ($conf as $key => $src) { + $order = $src[F_ORDER]; + # n_key: no_move=$key+$order or move=$order+$key + $n_key = is_numeric($order) ? sprintf("%04d%04d", $order, $key) : sprintf("%04d%04d", $key, 9999); + unset($src[F_ORDER]); # ! must be unset for display correct default position in 'select'! + $src_new[$n_key] = $src; + } + # sort by key + ksort($src_new); + reset($src_new); + + $src_new = array_values($src_new); # make keys '0, 1, 2, ...' + + # renew config + unset ($config['installedpackages'][MODULE_DESTINATION]['config']); + $config['installedpackages'][MODULE_DESTINATION]['config'] = $src_new; + write_config('Update squidguarddest config'); + + # renew global $squidguard_config + sg_init(convert_pfxml_to_sgxml()); + } +} + # ============================================================================= # common functions # ============================================================================= @@ -596,6 +636,28 @@ function squidguard_before_form_acl($pkg, $is_acl=true) { } # ----------------------------------------------------------------------------- +# squidguard_before_form_dest +# ----------------------------------------------------------------------------- +function squidguard_before_form_dest($pkg) { + global $g, $squidguard_config; + $destination_items = get_sgconf_items_list(F_DESTINATIONS, 'name'); +//var_dump($squidguard_config); + $i=0; + foreach($pkg['fields']['field'] as $field) { + # order + if ($field['fieldname'] == 'order') { + $fld = &$pkg['fields']['field'][$i]; + if (is_array($destination_items)) + foreach($destination_items as $nmkey => $nm) + $fld['options']['option'][] = array('name'=>$nm, 'value'=>$nmkey); + $fld['options']['option'][] = array('name'=>'--- Last ---', 'value'=>'9999'); + $fld['options']['option'][] = array('name'=>'-----', 'value'=>''); # ! this is must be last ! + } + $i++; + } +} + +# ----------------------------------------------------------------------------- # make_grid_general_items # ----------------------------------------------------------------------------- function make_grid_general_items($id = '') @@ -1406,52 +1468,75 @@ function squidguard_blacklist_list() /* Uses XMLRPC to synchronize the changes to a remote node */ function squidguard_sync_on_changes() { global $config, $g; - $varsyncenablexmlrpc = $config['installedpackages']['squidguardsync']['config'][0]['varsyncenablexmlrpc']; - $varsynctimeout = $config['installedpackages']['squidguardsync']['config'][0]['varsynctimeout']; - - // if checkbox is NOT checked do nothing - if(!$varsyncenablexmlrpc) { + if (is_array($config['installedpackages']['squidguardsync'])){ + $synconchanges = $config['installedpackages']['squidguardsync']['config'][0]['varsyncenablexmlrpc']; + $varsynctimeout = $config['installedpackages']['squidguardsync']['config'][0]['varsynctimeout']; + } + else + { return; } - - log_error("SquidGuard: Starting XMLRPC process (squidguard_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); - - // if checkbox is checked get IP and password of the destination hosts - foreach ($config['installedpackages']['squidguardsync']['config'] as $rs ){ - foreach($rs['row'] as $sh){ - // if checkbox is NOT checked do nothing - if($sh['varsyncdestinenable']) { - $varsyncprotocol = $sh['varsyncprotocol']; - $sync_to_ip = $sh['varsyncipaddress']; - $password = $sh['varsyncpassword']; - $varsyncport = $sh['varsyncport']; - // check if all credentials are complete for this host - if($password && $sync_to_ip && $varsyncport && $varsyncprotocol) { - squidguard_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol); + + // if checkbox is NOT checked do nothing + switch ($synconchanges){ + case "manual": + if (is_array($config['installedpackages']['squidguardsync']['config'][0]['row'])){ + $rs=$config['installedpackages']['squidguardsync']['config'][0]['row']; + } + else{ + log_error("[Squidguard] xmlrpc sync is enabled but there is no hosts to push on Squidguard config."); + return; + } + break; + case "auto": + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + $system_carp=$config['installedpackages']['carpsettings']['config'][0]; + $rs[0]['varsyncdestinenable']="on"; + $rs[0]['varsyncprotocol']=($config['system']['webgui']['protocol']!=""?$config['system']['webgui']['protocol']:"https"); + $rs[0]['varsyncipaddress']=$system_carp['synchronizetoip']; + $rs[0]['varsyncpassword']=$system_carp['password']; + $rs[0]['varsyncport']=($config['system']['webgui']['port']!=""?$config['system']['webgui']['port']:"443"); + if (! is_ipaddr($system_carp['synchronizetoip'])){ + log_error("[Squidguard] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + } + else{ + log_error("[Squidguard] xmlrpc sync is enabled but there is no system backup hosts to push squid config."); + return; + } + break; + default: + return; + break; + } + if (is_array($rs)){ + log_error("[SquidGuard] xmlrpc sync is starting with timeout {$varsynctimeout} seconds."); + foreach($rs as $sh){ + if($sh['varsyncdestinenable']){ + $varsyncprotocol = $sh['varsyncprotocol']; + $sync_to_ip = $sh['varsyncipaddress']; + $password = $sh['varsyncpassword']; + $varsyncport = $sh['varsyncport']; + if($password && $sync_to_ip) + squidguard_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol,$varsynctimeout); + else + log_error("SquidGuard: XMLRPC Sync with {$sh['varsyncipaddress']} has incomplete credentials. No XMLRPC Sync done!"); } else { - log_error("SquidGuard: XMLRPC Sync with {$sh['varsyncipaddress']} has incomplete credentials. No XMLRPC Sync done!"); + log_error("SquidGuard: XMLRPC Sync with {$sh['varsyncipaddress']} is disabled"); } } - else { - log_error("SquidGuard: XMLRPC Sync with {$sh['varsyncipaddress']} is disabled"); + log_error("[SquidGuard] xmlrpc sync is ending."); } - } - } - log_error("SquidGuard: Finished XMLRPC process (squidguard_do_xmlrpc_sync)."); } /* Do the actual XMLRPC sync */ -function squidguard_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol) { +function squidguard_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol,$varsynctimeout) { global $config, $g; - $varsynctimeout = $config['installedpackages']['squidguardsync']['config'][0]['varsynctimeout']; - - if($varsynctimeout == '' || $varsynctimeout == 0) { + if($varsynctimeout == '' || $varsynctimeout == 0) $varsynctimeout = 150; - } - - // log_error("SquidGuard: Starting XMLRPC process (squidguard_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); if(!$password) return; @@ -1551,6 +1636,7 @@ function squidguard_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn function squidguard_all_after_XMLRPC_resync() { squidguard_resync_acl(); + squidguard_resync_dest(); squidguard_resync(); log_error("SquidGuard: Finished XMLRPC process. It should be OK. For more information look at the host which started sync."); diff --git a/config/squidGuard/squidguard.xml b/config/squidGuard/squidguard.xml index c9df88ca..21356e1c 100644 --- a/config/squidGuard/squidguard.xml +++ b/config/squidGuard/squidguard.xml @@ -6,7 +6,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>squidguardgeneral</name> - <version>1.3_1 pkg v.1.9</version> + <version>1.4_4 pkg v.1.9.3</version> <title>Proxy filter SquidGuard: General settings</title> <include_file>/usr/local/pkg/squidguard.inc</include_file> <!-- Installation --> diff --git a/config/squidGuard/squidguard_configurator.inc b/config/squidGuard/squidguard_configurator.inc index 81f9cd96..b900a477 100644 --- a/config/squidGuard/squidguard_configurator.inc +++ b/config/squidGuard/squidguard_configurator.inc @@ -112,9 +112,12 @@ define('REDIRECT_URL_ARGS', '&a=%a&n=%n&i=%i&s=%s&t=%t&u=%u'); # ------------------------------------------------------------------------------ $pf_version=substr(trim(file_get_contents("/etc/version")),0,3); -if ($pf_version > 2.0) - define('SQUIDGUARD_LOCALBASE', '/usr/pbi/squidguard-' . php_uname("m")); -else +if ($pf_version > 2.0) { + if (file_exists('/usr/pbi/squidguard-squid3-' . php_uname("m"))) + define('SQUIDGUARD_LOCALBASE', '/usr/pbi/squidguard-squid3-' . php_uname("m")); + else + define('SQUIDGUARD_LOCALBASE', '/usr/pbi/squidguard-' . php_uname("m")); +} else define('SQUIDGUARD_LOCALBASE','/usr/local'); if (!defined('SQUID_LOCALBASE') && ($pf_version > 2.0)) @@ -414,7 +417,6 @@ function squid_reconfigure($remove_only = '') global $squidguard_config; $conf = ''; $cust_opt = $config['installedpackages']['squid']['config'][0]['custom_options']; - # remove old options if (!empty($cust_opt)) { $conf = explode(";", $cust_opt); @@ -444,7 +446,7 @@ function squid_reconfigure($remove_only = '') if (is_array($conf)) $conf = implode(";", $conf); /* Only update squid options if we have something to do, otherwise this can interfere with squid's default options in a new install. */ - if (!empty($conf)) { + if ($conf != $cust_opt) { $config['installedpackages']['squid']['config'][0]['custom_options'] = $conf; write_config('Update redirector options to squid config.'); } diff --git a/config/squidGuard/squidguard_dest.xml b/config/squidGuard/squidguard_dest.xml index 5ffc0aa6..3525098e 100644 --- a/config/squidGuard/squidguard_dest.xml +++ b/config/squidGuard/squidguard_dest.xml @@ -77,6 +77,14 @@ <required/> </field> <field> + <fielddescr>Order</fielddescr> + <fieldname>order</fieldname> + <description><![CDATA[ + Select the new position for this target category. Target categories are listed in this order on ALCs and are matched from the top down in sequence.<br> + ]]></description> + <type>select</type> + </field> + <field> <fielddescr>Domain List</fielddescr> <fieldname>domains</fieldname> <description><![CDATA[ @@ -163,12 +171,18 @@ <description><![CDATA[Check this option to enable logging for this ACL.]]></description> </field> </fields> - <custom_delete_php_command/> + <custom_php_command_before_form> + squidguard_before_form_dest(&$pkg); + </custom_php_command_before_form> <custom_php_validation_command> squidguard_validate_destination($_POST, &$input_errors); </custom_php_validation_command> <custom_php_resync_config_command> + squidguard_resync_dest(); </custom_php_resync_config_command> + <custom_delete_php_command> + squidguard_resync_dest(); + </custom_delete_php_command> <custom_php_after_form_command> squidGuard_print_javascript(); </custom_php_after_form_command> diff --git a/config/squidGuard/squidguard_sync.xml b/config/squidGuard/squidguard_sync.xml index cf21c1bf..f0537faf 100644 --- a/config/squidGuard/squidguard_sync.xml +++ b/config/squidGuard/squidguard_sync.xml @@ -10,6 +10,7 @@ squidguardsync.xml part of pfSense (http://www.pfSense.com) Copyright (C) 2013 Alexander Wilke <nachtfalkeaw@web.de> +Copyright (C) 2013 Marcello Coutinho based on pfblocker_sync.xml All rights reserved. @@ -94,11 +95,18 @@ POSSIBILITY OF SUCH DAMAGE. <type>listtopic</type> </field> <field> - <fielddescr>Automatically sync SquidGuard configuration changes?</fielddescr> + <fielddescr>Enable Sync</fielddescr> <fieldname>varsyncenablexmlrpc</fieldname> <description><![CDATA[All changes will be synced immediately to the IPs listed below if this option is checked.<br> - <b>Important:</b> Only sync from host A to B, A to C but <b>do not</B> enable XMLRPC sync <b>to</b> A. This will result in a loop!]]></description> - <type>checkbox</type> + <b>Important:</b> While using "Sync to hosts defined below", only sync from host A to B, A to C but <b>do not</B> enable XMLRPC sync <b>to</b> A. This will result in a loop!]]></description> + <type>select</type> + <required/> + <default_value>auto</default_value> + <options> + <option><name>Sync to configured system backup server</name><value>auto</value></option> + <option><name>Sync to host(s) defined below</name><value>manual</value></option> + <option><name>Do not sync this package configuration</name><value>disabled</value></option> + </options> </field> <field> <fielddescr>XMLRPC timeout</fielddescr> diff --git a/config/systempatches/apply_patches.php b/config/systempatches/apply_patches.php new file mode 100644 index 00000000..3ac0d671 --- /dev/null +++ b/config/systempatches/apply_patches.php @@ -0,0 +1,11 @@ +#!/usr/local/bin/php +<?php +require_once("config.inc"); +require_once("patches.inc"); + +global $g, $config; + +echo "Applying patches..."; +bootup_apply_patches(); +echo "Done.\n"; +?>
\ No newline at end of file diff --git a/config/systempatches/patches.inc b/config/systempatches/patches.inc index 89610565..0547f2cf 100644 --- a/config/systempatches/patches.inc +++ b/config/systempatches/patches.inc @@ -29,11 +29,19 @@ require_once("globals.inc"); require_once("util.inc"); -$git_root_url = "http://github.com/bsdperimeter/pfsense/commit/"; +$git_root_url = "http://github.com/pfsense/pfsense/commit/"; $patch_suffix = ".patch"; $patch_dir = "/var/patches"; $patch_cmd = "/usr/bin/patch"; +function patch_package_install() { + patch_add_shellcmd(); +} + +function patch_package_deinstall() { + patch_remove_shellcmd(); +} + function patch_commit($patch, $action, $test=false, $fulldetail=false) { global $patch_dir, $patch_cmd, $patch_suffix; $directory = empty($patch['basedir']) ? "/" : $patch['basedir']; @@ -44,12 +52,14 @@ function patch_commit($patch, $action, $test=false, $fulldetail=false) { $whitespace = isset($patch['ignorewhitespace']) ? "--ignore-whitespace" : ""; $pathstrip = '-p' . $patch['pathstrip']; $full_patch_command = "{$patch_cmd} --directory={$directory} {$force} {$pathstrip} {$filename} {$check} {$direction} {$whitespace}"; + conf_mount_rw(); patch_write($patch); if (!$fulldetail) $output = (mwexec($full_patch_command, true) == 0); else $output = $full_patch_command . "\n\n" . shell_exec($full_patch_command . ' 2>&1'); patch_erase($patch); + conf_mount_ro(); return $output; } @@ -139,4 +149,55 @@ function is_github_url($url) { $urlbits = explode("/", $url); return (substr($urlbits[2], -10) == "github.com"); } -?>
\ No newline at end of file + +function bootup_apply_patches() { + global $config; + + $a_patches = &$config['installedpackages']['patches']['item']; + + foreach ($a_patches as $patch) { + /* Skip the patch if it should not be automatically applied. */ + if (!isset($patch['autoapply'])) + continue; + /* If the patch can be reverted it is already applied, so skip it. */ + if (!patch_test_revert($patch)) { + /* Only attempt to apply if it can be applied. */ + if (patch_test_apply($patch)) { + patch_apply($patch); + } + } + } +} + +function patch_add_shellcmd() { + global $config; + $a_earlyshellcmd = &$config['system']['earlyshellcmd']; + if (!is_array($a_earlyshellcmd)) + $a_earlyshellcmd = array(); + $found = false; + foreach ($a_earlyshellcmd as $idx => $cmd) + if (stristr($cmd, "apply_patches.php")) + $found = true; + if (!$found) { + $a_earlyshellcmd[] = "/usr/local/bin/php -f /usr/local/bin/apply_patches.php"; + write_config("System Patches package added a shellcmd"); + } +} + +function patch_remove_shellcmd() { + global $config; + $a_earlyshellcmd = &$config['system']['earlyshellcmd']; + if (!is_array($a_earlyshellcmd)) + $a_earlyshellcmd = array(); + $removed = false; + foreach ($a_earlyshellcmd as $idx => $cmd) { + if (stristr($cmd, "apply_patches.php")) { + unset($a_earlyshellcmd[$idx]); + $removed = true; + } + } + if ($removed) + write_config("System Patches package removed a shellcmd"); +} + +?> diff --git a/config/systempatches/system_patches.php b/config/systempatches/system_patches.php index 1dd6470b..7fe860bd 100644 --- a/config/systempatches/system_patches.php +++ b/config/systempatches/system_patches.php @@ -179,11 +179,12 @@ include("head.inc"); <tr id="frheader"> <td width="5%" class="list"> </td> <td width="5%" class="listhdrr"><?=gettext("Description");?></td> -<td width="65%" class="listhdrr"><?=gettext("URL/ID");?></td> +<td width="60%" class="listhdrr"><?=gettext("URL/ID");?></td> <td width="5%" class="listhdrr"><?=gettext("Fetch");?></td> <td width="5%" class="listhdrr"><?=gettext("Test");?></td> <td width="5%" class="listhdrr"><?=gettext("Apply");?></td> <td width="5%" class="listhdr"><?=gettext("Revert");?></td> +<td width="5%" class="listhdr"><?=gettext("Auto Apply");?></td> <td width="5%" class="list"> <table border="0" cellspacing="0" cellpadding="1" summary="buttons"> <tr><td width="17"> @@ -242,6 +243,9 @@ foreach ($a_patches as $thispatch): <a href="system_patches.php?id=<?=$i;?>&act=revert"><?php echo gettext("Revert"); ?></a> <?php endif; ?> </td> + <td class="listr" onclick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?= isset($thispatch['autoapply']) ? "Yes" : "No" ?> + </td> <td valign="middle" class="list" nowrap> <table border="0" cellspacing="0" cellpadding="1" summary="edit"> <tr> @@ -256,7 +260,7 @@ foreach ($a_patches as $thispatch): </td></tr> <?php $i++; $npatches++; endforeach; ?> <tr> - <td class="list" colspan="7"></td> + <td class="list" colspan="8"></td> <td class="list" valign="middle" nowrap> <table border="0" cellspacing="0" cellpadding="1" summary="edit"> <tr> diff --git a/config/systempatches/system_patches_edit.php b/config/systempatches/system_patches_edit.php index 260a7300..5b30c9c5 100644 --- a/config/systempatches/system_patches_edit.php +++ b/config/systempatches/system_patches_edit.php @@ -127,6 +127,8 @@ if ($_POST) { } write_config(); + if ($thispatch['autoapply']) + patch_add_shellcmd(); header("Location: system_patches.php"); return; } @@ -165,7 +167,7 @@ include("head.inc"); <tr> <td width="22%" valign="top" class="vncell"><?=gettext("Patch Contents"); ?></td> <td width="78%" class="vtable"> - <textarea name="patch" class="" id="patch" rows="15" cols="70" wrap="off"><?=base64_decode($pconfig['patch']);?></textarea> + <textarea name="patch" class="" id="patch" rows="15" cols="70" wrap="off"><?=htmlspecialchars(base64_decode($pconfig['patch']));?></textarea> <br /> <span class="vexpl"><?=gettext("The contents of the patch. You can paste a patch here, or enter a URL/commit ID above, it can then be fetched into here automatically."); ?></span></td> </tr> <tr> @@ -192,7 +194,6 @@ include("head.inc"); <span class="vexpl"><?=gettext("Set this option to ignore whitespace in the patch."); ?></span> </td> </tr> -<!-- This isn't ready yet <tr> <td width="22%" valign="top" class="vncell"><?=gettext("Auto Apply"); ?></td> <td width="78%" class="vtable"> @@ -201,7 +202,6 @@ include("head.inc"); <span class="vexpl"><?=gettext("Set this option to apply the patch automatically when possible, useful for patches to survive after firmware updates."); ?></span> </td> </tr> ---> <tr> <td width="22%" valign="top"> </td> <td width="78%">Patch id: <?php echo $pconfig['uniqid']; ?></td> diff --git a/config/systempatches/systempatches.xml b/config/systempatches/systempatches.xml index 3802ba58..c5e0a784 100644 --- a/config/systempatches/systempatches.xml +++ b/config/systempatches/systempatches.xml @@ -40,8 +40,9 @@ <requirements>None</requirements> <faq>Applies patches supplied by the user to the firewall.</faq> <name>System Patches</name> - <version>0.5.1</version> + <version>0.9</version> <title>System: Patches</title> + <include_file>/usr/local/pkg/patches.inc</include_file> <menu> <name>Patches</name> <tooltiptext></tooltiptext> @@ -59,8 +60,19 @@ <item>http://www.pfsense.com/packages/config/systempatches/system_patches_edit.php</item> </additional_files_needed> <additional_files_needed> + <prefix>/usr/local/bin/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/systempatches/apply_patches.php</item> + </additional_files_needed> + <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>644</chmod> <item>http://www.pfsense.com/packages/config/systempatches/patches.inc</item> </additional_files_needed> + <custom_php_install_command> + patch_package_install(); + </custom_php_install_command> + <custom_php_deinstall_command> + patch_package_deinstall(); + </custom_php_deinstall_command> </packagegui>
\ No newline at end of file diff --git a/config/unbound/unbound.inc b/config/unbound/unbound.inc index 6588c5c2..2dd33bcd 100644 --- a/config/unbound/unbound.inc +++ b/config/unbound/unbound.inc @@ -23,6 +23,12 @@ POSSIBILITY OF SUCH DAMAGE. */ +// Define basedir constant for unbound according to FreeBSD version (PBI support or no PBI) +if (floatval(php_uname("r")) >= 8.3) + define("UNBOUND_BASE", "/usr/pbi/unbound-" . php_uname("m")); +else + define("UNBOUND_BASE", "/usr/local"); + if(!function_exists("is_service_running")) require_once("service-utils.inc"); @@ -40,34 +46,35 @@ function unbound_initial_setup() { // Make sure read-write conf_mount_rw(); - + if (!is_array($config['installedpackages']['unbound']['config'])) $config['installedpackages']['unbound']['config'] = array(); $unbound_config = &$config['installedpackages']['unbound']['config'][0]; // Ensure Unbound user exists - exec("/usr/sbin/pw useradd unbound"); + mwexec("/usr/sbin/pw useradd unbound", true); // Setup unbound // Create and chown dirs - mwexec("/bin/mkdir -p /usr/local/etc/unbound /usr/local/etc/unbound/dev"); - @chown("/usr/local/etc/unbound/.", "unbound"); - @chown("/usr/local/etc/unbound/dev.", "unbound"); + mwexec("/bin/mkdir -p " . UNBOUND_BASE . "/etc/unbound/dev"); + @chown(UNBOUND_BASE . "/etc/unbound/.", "unbound"); + @chown(UNBOUND_BASE . "/etc/unbound/dev.", "unbound"); // Touch needed files - @touch("/usr/local/etc/unbound/root.hints"); - @touch("/usr/local/etc/unbound/root-trust-anchor"); + @touch(UNBOUND_BASE . "/etc/unbound/root.hints"); + @touch(UNBOUND_BASE . "/etc/unbound/root-trust-anchor"); // Ensure files and folders belong to unbound - @chown("/usr/local/etc/unbound/root-trust-anchor", "unbound"); - @chgrp("/usr/local/etc/unbound/root-trust-anchor", "wheel"); - @chmod("/usr/local/etc/unbound/root-trust-anchor", 0600); + @chown(UNBOUND_BASE . "/etc/unbound/root-trust-anchor", "unbound"); + @chgrp(UNBOUND_BASE . "/etc/unbound/root-trust-anchor", "wheel"); + @chmod(UNBOUND_BASE . "/etc/unbound/root-trust-anchor", 0600); // We do not need the sample conf or the default rc.d startup file - @unlink_if_exists("/usr/local/etc/unbound/unbound.conf.sample"); + @unlink_if_exists(UNBOUND_BASE . "/etc/unbound/unbound.conf.sample"); + @unlink_if_exists(UNBOUND_BASE . "/etc/rc.d/unbound"); @unlink_if_exists("/usr/local/etc/rc.d/unbound"); - + // Setup rc file for startup and shutdown. unbound_rc_setup(); - + /* Check to see if Set initial interfaces that are allowed to query to lan, if that does not exist set it to the wan * */ @@ -77,34 +84,34 @@ function unbound_initial_setup() { else $unbound_config['active_interface'] = "wan"; } - + unbound_anchor_setup(); unbound_resync_config(); unbound_keys_setup(); - exec("/usr/sbin/chown -R unbound:wheel /usr/local/etc/unbound/*"); + exec("/usr/sbin/chown -R unbound:wheel " . UNBOUND_BASE . "/etc/unbound/*"); // Write out the XML config write_config(); - + // Back to read-only conf_mount_ro(); } function unbound_anchor_setup() { - + $conf = <<<EOD . IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5 EOD; - file_put_contents("/usr/local/etc/unbound/root-trust-anchor", $conf); - + file_put_contents(UNBOUND_BASE . "/etc/unbound/root-trust-anchor", $conf); + } function unbound_keys_setup() { - + // Generate SSL Keys for controlling the unbound server - mwexec("/usr/local/sbin/unbound-control-setup"); + mwexec(UNBOUND_BASE . "/sbin/unbound-control-setup"); } @@ -148,25 +155,21 @@ ENDPHP\n"; } function unbound_install() { - - conf_mount_rw(); unbound_initial_setup(); - conf_mount_ro(); - } function unbound_control($action) { global $config, $g; - + $unbound_config = $config['installedpackages']['unbound']['config'][0]; $cache_dumpfile = "/var/tmp/unbound_cache"; - + switch ($action) { case "forward": /* Dont utilize forward cmd if Unbound is doing DNS queries directly * XXX: We could make this an option to then make pfSense use Unbound * as the recursive nameserver instead of upstream ones(?) - */ + */ if ($unbound_config['forwarding_mode'] == "on") { // Get configured DNS servers and add them as forwarders if (!isset($config['system']['dnsallowoverride'])) { @@ -182,7 +185,7 @@ function unbound_control($action) { $dns_servers .= " $nameserver"; } } - + if(is_service_running("unbound")) { unbound_ctl_exec("forward $dns_servers"); } else { @@ -192,7 +195,7 @@ function unbound_control($action) { } } break; - + case "start": //Start unbound if($unbound_config['unbound_status'] == "on") { @@ -203,28 +206,31 @@ function unbound_control($action) { @unlink("/var/run/dnsmasq.pid"); mwexec("/bin/ln -s /var/run/unbound.pid /var/run/dnsmasq.pid"); } + mwexec_bg("/usr/local/bin/unbound_monitor.sh"); fetch_root_hints(); } break; - + case "stop": //Stop unbound and unmount the file system if($unbound_config['unbound_status'] == "on") { - unbound_ctl_exec("stop"); + mwexec_bg("/usr/local/bin/unbound_monitor.sh stop"); + unbound_ctl_exec("stop"); } break; - + case "termstop": //Stop Unbound by sigkillbypid(); + mwexec_bg("/usr/local/bin/unbound_monitor.sh stop"); sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM"); break; - + case "dump_cache": //Dump Unbound's Cache if($unbound_config['dumpcache'] == "on") unbound_ctl_exec("dump_cache > $cache_dumpfile"); break; - + case "restore_cache": //Restore Unbound's Cache if ((is_service_running("unbound")) && ($unbound_config['dumpcache'] == "on")) { @@ -234,13 +240,13 @@ function unbound_control($action) { break; case "anchor_update": //Update the Root Trust Anchor - mwexec("/usr/local/sbin/unbound-anchor -a /usr/local/etc/unbound/root-trust-anchor", true); + mwexec(UNBOUND_BASE . "/sbin/unbound-anchor -a " . UNBOUND_BASE . "/etc/unbound/root-trust-anchor", true); break; default: break; - + } - + } function unbound_get_network_interface_addresses() { @@ -251,7 +257,7 @@ function unbound_get_network_interface_addresses() { $unboundint = explode(",", $unbound_config['active_interface']); $unbound_interfaces = array(); $i = 0; - + foreach ($unboundint as $unboundidx => $unboundif) { /* Configure IPv4 addresses */ if (is_ipaddr($interfaces[$unboundif]['ipaddr'])) { @@ -283,7 +289,7 @@ function unbound_get_network_interface_addresses() { $unbound_interfaces[$i]['ipv4']['subnet'] = find_interface_subnet($unboundrealif); $unbound_interfaces[$i]['ipv4']['network'] = gen_subnet($unbound_interfaces[$i]['ipv4']['ipaddr'],$unbound_interfaces[$i]['ipv4']['subnet']); } - + /* Configure IPv6 addresses */ if(function_exists("is_ipaddrv6")) { if(is_ipaddrv6($interfaces[$unboundif]['ipaddrv6'])) { @@ -370,7 +376,7 @@ function unbound_get_query_interface_addresses() { function unbound_acls_config() { global $config; - + /* Configure the ACLs */ if(is_array($config['installedpackages']['unboundacls']['config'])) { $unbound_acls = $config['installedpackages']['unboundacls']['config']; @@ -381,7 +387,7 @@ function unbound_acls_config() { if ($unbound_acl['aclaction'] == "allow snoop") $unbound_acl['aclaction'] = "allow_snoop"; $unboundcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n"; - } + } } return $unboundcfg; } else @@ -390,21 +396,20 @@ function unbound_acls_config() { function unbound_resync_config() { global $config, $g, $input_errors; - + + $unbound_base = UNBOUND_BASE; + if (!is_array($config['installedpackages']['unbound']['config'])) $config['installedpackages']['unbound']['config'] = array(); $unbound_config = &$config['installedpackages']['unbound']['config'][0]; - + // Interfaces to bind to and setup acls for nics $unbound_bind_interfaces = ""; $unbound_allowed_networks = ""; $unboundnetcfg = unbound_get_network_interface_addresses(); foreach($unboundnetcfg as $netent) { foreach($netent as $entry) { - # If virtual interface then skip - if (!$entry['network'] && !$entry['subnet'] && ($entry['ipaddr'] != "127.0.0.1" && $entry['ipaddr'] != "::1")) - continue; $unbound_bind_interfaces .="interface: {$entry['ipaddr']}\n"; if($entry['ipaddr'] != "127.0.0.1" && $entry['ipaddr'] != "::1") $unbound_allowed_networks .= "access-control: {$entry['network']}/{$entry['subnet']} allow\n"; @@ -420,19 +425,19 @@ function unbound_resync_config() { /* Configure user configured ACLs */ $unbound_allowed_networks .= unbound_acls_config(); - + if($unbound_config['dnssec_status'] == "on") { $module_config = "validator iterator"; - $anchor_file = "auto-trust-anchor-file: /usr/local/etc/unbound/root-trust-anchor"; + $anchor_file = "auto-trust-anchor-file: " . UNBOUND_BASE . "/etc/unbound/root-trust-anchor"; } else $module_config = "iterator"; - + // Host entries $host_entries = unbound_add_host_entries(); - + // Domain Overrides $domain_overrides = unbound_add_domain_overrides(); - + // Unbound Statistics if($unbound_config['stats'] == "on") { $stats_interval = $unbound_config['stats_interval']; @@ -440,13 +445,13 @@ function unbound_resync_config() { if ($unbound_config['extended_stats'] == "on") $extended_stats = "yes"; else - $extended_stats = "no"; + $extended_stats = "no"; } else { $stats_interval = "0"; $cumulative_stats = "no"; $extended_stats = "no"; } - + // Private-address support for DNS Rebinding if($unbound_config['private_address'] == "on") { $pvt_addr = <<<EOF @@ -467,7 +472,7 @@ EOF; //Setup optimization $optimization = unbound_optimization(); - + $unbound_config = &$config['installedpackages']['unboundadvanced']['config'][0]; // Setup Advanced options $log_verbosity = (isset($unbound_config['unbound_verbosity'])) ? $unbound_config['unbound_verbosity'] : "1"; @@ -488,8 +493,7 @@ EOF; $infra_lame_ttl = (!empty($unbound_config['infra_lame_ttl'])) ? $unbound_config['infra_lame_ttl'] : "900"; $infra_cache_numhosts = (!empty($unbound_config['infra_cache_numhosts'])) ? $unbound_config['infra_cache_numhosts'] : "10000"; $unwanted_reply_threshold = (!empty($unbound_config['unwanted_reply_threshold'])) ? $unbound_config['unwanted_reply_threshold'] : "0"; - - + $unbound_conf = <<<EOD ######################### @@ -502,7 +506,7 @@ EOF; server: chroot: "" username: "unbound" -directory: "/usr/local/etc/unbound" +directory: "{$unbound_base}/etc/unbound" pidfile: "{$g['varrun_path']}/unbound.pid" root-hints: "root.hints" harden-referral-path: no @@ -564,14 +568,14 @@ access-control: ::1 allow EOD; -# Handle custom options -if(!empty($unbound_config['custom_options'])) { - $custom_options = explode(";", ($unbound_config['custom_options'])); - $unbound_conf .= "# Unbound Custom options\n"; - foreach ($custom_options as $ent) { - $unbound_conf .= $ent."\n"; + # Handle custom options + if(!empty($unbound_config['custom_options'])) { + $custom_options = explode(";", ($unbound_config['custom_options'])); + $unbound_conf .= "# Unbound Custom options\n"; + foreach ($custom_options as $ent) { + $unbound_conf .= $ent."\n"; + } } -} $unbound_conf .= <<<EOD @@ -582,22 +586,24 @@ remote-control: control-enable: yes control-interface: 127.0.0.1 control-port: 953 -server-key-file: "/usr/local/etc/unbound/unbound_server.key" -server-cert-file: "/usr/local/etc/unbound/unbound_server.pem" -control-key-file: "/usr/local/etc/unbound/unbound_control.key" -control-cert-file: "/usr/local/etc/unbound/unbound_control.pem" +server-key-file: "{$unbound_base}/etc/unbound/unbound_server.key" +server-cert-file: "{$unbound_base}/etc/unbound/unbound_server.pem" +control-key-file: "{$unbound_base}/etc/unbound/unbound_control.key" +control-cert-file: "{$unbound_base}/etc/unbound/unbound_control.pem" EOD; - file_put_contents("/usr/local/etc/unbound/unbound.conf", $unbound_conf); - + conf_mount_rw(); + file_put_contents("{$unbound_base}/etc/unbound/unbound.conf", $unbound_conf); + conf_mount_ro(); + } function unbound_ctl_exec($cmd) { - - mwexec("/usr/local/sbin/unbound-control $cmd"); - + + mwexec(UNBOUND_BASE . "/sbin/unbound-control $cmd"); + } @@ -609,7 +615,7 @@ function unbound_optimization() { $unbound_config = $config['installedpackages']['unboundadvanced']['config'][0]; $optimization_settings = array(); - + // Set the number of threads equal to number of CPUs. // Use 1 (disable threading) if for some reason this sysctl fails. $numprocs = intval(trim(`/sbin/sysctl kern.smp.cpus | /usr/bin/cut -d" " -f2`)); @@ -617,7 +623,7 @@ function unbound_optimization() { $optimization['number_threads'] = "num-threads: {$numprocs}"; else $optimization['number_threads'] = "num-threads: 1"; - + // Slabs to help reduce lock contention. if ($numprocs > 4) { $optimization['msg_cache_slabs'] = "msg-cache-slabs: {$numprocs}"; @@ -630,7 +636,7 @@ function unbound_optimization() { $optimization['infra_cache_slabs'] = "infra-cache-slabs: 4"; $optimization['key_cache_slabs'] = "key-cache-slabs: 4"; } - + // Memory usage - default is 4Mb if nothing has been selected if(isset($unbound_config['msg_cache_size'])) { $rr = $unbound_config['msg_cache_size']*2; @@ -640,7 +646,7 @@ function unbound_optimization() { $optimization['msg_cache_size'] = "msg-cache-size: 4m"; $optimization['rrset_cache_size'] = "rrset-cache-size: 8m"; } - + // More outgoing connections per thread otherwise assign a default of 4096 for a single thread if($numprocs > 0) { $or = (1024/$numprocs) - 50; @@ -659,7 +665,7 @@ function unbound_optimization() { $optimization['so_rcvbuf'] = "so-rcvbuf: {$so}m"; else unset($optimization['so_rcvbuf']); - + } } // Safety check in case kern.ipc.maxsockbuf is deleted. @@ -671,12 +677,12 @@ function unbound_optimization() { function fetch_root_hints() { - $destination_file = "/usr/local/etc/unbound/root.hints"; + $destination_file = UNBOUND_BASE . "/etc/unbound/root.hints"; if (filesize($destination_file) == 0 ) { conf_mount_rw(); $fout = fopen($destination_file, "w"); $url = "ftp://ftp.internic.net/domain/named.cache"; - + $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); @@ -688,7 +694,7 @@ function fetch_root_hints() { fwrite($fout, $data); fclose($fout); conf_mount_ro(); - + return ($http_code == 200) ? true : $http_code; } else { return false; @@ -700,18 +706,18 @@ function unbound_validate($post, $type=null) { if($post['unbound_status'] == "on" && isset($config['dnsmasq']['enable'])) $input_errors[] = "The system dns-forwarder is still active. Disable it before enabling the Unbound service."; - + /* Validate the access lists */ if($type == "acl") { $acls = $post; // Check to ensure values entered is an action that is in the list if ($acls['aclaction'] != 'refuse' && $acls['aclaction'] != 'allow' && $acls['aclaction'] != 'allow_snoop' && $acls['aclaction'] != 'deny') $input_errors[] = "{$acls['aclaction']} is not a valid ACL Action. Please select one of the four actions defined in the list."; - + // Make sure there is at least 1 network defined. - if (!isset($acls['acl_network0'])) + if (!isset($acls['acl_network0'])) $input_errors[] = "You need to specify at least one network to create a valid ACL."; - + $count = 0; // Get number of rows added, should be passed by the form - will look into that later for($i=0; $i<99; $i++) { @@ -719,7 +725,7 @@ function unbound_validate($post, $type=null) { // Check to ensure values entered are networks if(!is_ipaddr($acls['acl_network'.$i]) && !is_subnet($acls['mask'.$i])) $input_errors[] = "{$acls['acl_network'.$i]}/{$acls['mask'.$i]} is not a valid network."; - } + } } } else if($type == "advanced") { if(!is_numeric($post['cache_max_ttl'])) @@ -732,7 +738,7 @@ function unbound_validate($post, $type=null) { $input_errors[] = "You must enter a valid number in 'TTL for lame delegation'."; if(!is_numeric($post['infra_cache_numhosts'])) $input_errors[] = "You must enter a valid number in 'Number of Hosts to cache'."; - + } else if($type == "basic") { /* Validate settings */ if($post['active_interface'] == "") @@ -742,9 +748,9 @@ function unbound_validate($post, $type=null) { function unbound_reconfigure() { global $config; - + $unbound_config = $config['installedpackages']['unbound']['config'][0]; - + if ($unbound_config['unbound_status'] != "on") { if(is_service_running("unbound")) unbound_control("termstop"); @@ -759,7 +765,7 @@ function unbound_reconfigure() { unbound_control("forward"); unbound_control("restore_cache"); } - } + } } function unbound_uninstall() { @@ -769,20 +775,20 @@ function unbound_uninstall() { unbound_control("termstop"); // Remove pkg config directory and startup file - mwexec("rm -rf /usr/local/etc/unbound"); + mwexec("rm -rf " . UNBOUND_BASE . "/etc/unbound"); @unlink("/usr/local/etc/rc.d/unbound.sh"); @unlink("{$g['varlog_path']}/unbound.log"); @unlink("/var/tmp/unbound_cache"); - conf_mount_ro(); + conf_mount_ro(); } function read_hosts() { - + // Open /etc/hosts and extract the only dhcpleases info $etc_hosts = array(); - foreach (file('/etc/hosts') as $line) { + foreach (file('/etc/hosts') as $line) { $d = preg_split('/\s/', $line, -1, PREG_SPLIT_NO_EMPTY); if (empty($d) || substr(reset($d), 0, 1) == "#") continue; @@ -806,12 +812,12 @@ function read_hosts() { */ function unbound_add_host_entries() { global $config; - + /* XXX: break this out into a separate config file and make use of include */ $unboundcfg = $config['installedpackages']['unbound']['config'][0]; $syscfg = $config['system']; $dnsmasqcfg = $config['dnsmasq']; - + $unbound_entries = "local-zone: \"{$syscfg['domain']}\" transparent\n"; // IPv4 entries $unbound_entries .= "local-data-ptr: \"127.0.0.1 localhost\"\n"; @@ -823,7 +829,7 @@ function unbound_add_host_entries() { $unbound_entries .= "local-data: \"localhost AAAA ::1\"\n"; $unbound_entries .= "local-data: \"localhost.{$syscfg['domain']} AAAA ::1\"\n"; } - + if ($config['interfaces']['lan']) { $cfgip = get_interface_ip("lan"); if (is_ipaddr($cfgip)) { @@ -866,12 +872,12 @@ function unbound_add_host_entries() { $host_entries .= "local-data: \"{$host['host']}{$host['domain']} IN A {$host['ip']}\"\n"; if (!empty($host['descr']) && $unboundcfg['txtsupport'] == 'on') $host_entries .= "local-data: '{$host['host']}{$host['domain']} TXT \"".addslashes($host['descr'])."\"'\n"; - + // Do not add duplicate entries $added_item[$current_host] = true; } } - $unbound_entries .= $host_entries; + $unbound_entries .= $host_entries; } // Static DHCP entries $host_entries = ""; @@ -886,7 +892,7 @@ function unbound_add_host_entries() { $host_entries .= "local-data: '{$host['hostname']}.{$syscfg['domain']} TXT \"".addslashes($host['descr'])."\"'\n"; } $unbound_entries .= $host_entries; - } + } // Handle DHCPLeases added host entries $dhcplcfg = read_hosts(); @@ -915,7 +921,7 @@ function unbound_add_domain_overrides($pvt=false) { // Domain overrides that have multiple entries need multiple stub-addr: added $sorted_domains = msort($domains, "domain"); - $result = array(); + $result = array(); foreach($sorted_domains as $domain) { $domain_key = current($domain); if(!isset($result[$domain_key])) { @@ -923,7 +929,7 @@ function unbound_add_domain_overrides($pvt=false) { } $result[$domain_key][] = $domain['ip']; } - + $domain_entries = ""; foreach($result as $domain=>$ips) { if($pvt == true) { @@ -939,7 +945,7 @@ function unbound_add_domain_overrides($pvt=false) { } } return $domain_entries; - } + } } function unbound_acl_id_used($id) { @@ -962,4 +968,4 @@ function unbound_get_next_id() { return $aclid; } -?>
\ No newline at end of file +?> diff --git a/config/unbound/unbound.xml b/config/unbound/unbound.xml index 202e8451..10de1f97 100644 --- a/config/unbound/unbound.xml +++ b/config/unbound/unbound.xml @@ -9,7 +9,7 @@ part of the Unbound package for pfSense (http://www.pfSense.com) Copyright (C) 2011 Warren Baker All rights reserved. - */ + */ /* ========================================================================== */ /* Redistribution and use in source and binary forms, with or without @@ -34,13 +34,13 @@ POSSIBILITY OF SUCH DAMAGE. */ /* ========================================================================== */ - ]]> + ]]> </copyright> <description>Unbound is a validating, recursive, and caching DNS resolver.</description> <requirements/> <faq/> <name>unbound</name> - <version>1.4.14</version> + <version>1.4.20_5</version> <title>Services: Unbound DNS Forwarder: Basic Settings</title> <include_file>/usr/local/pkg/unbound.inc</include_file> <menu> @@ -76,7 +76,7 @@ <item>http://www.pfsense.org/packages/config/unbound/unbound_advanced.xml</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/etc/rc.d/</prefix> + <prefix>/usr/local/bin/</prefix> <chmod>0755</chmod> <item>http://www.pfsense.org/packages/config/unbound/unbound_monitor.sh</item> </additional_files_needed> @@ -142,7 +142,7 @@ <fieldname>forwarding_mode</fieldname> <fielddescr>Enable forwarding mode</fielddescr> <description>Configure the server to make use of the DNS servers configured in <a href="system.php">System: General setup</a>. <br/> - <b>Note:</b> Disabling this will cause Unbound to perform DNS queries without + <b>Note:</b> Disabling this will cause Unbound to perform DNS queries without using the upstream configured DNS servers.</description> <type>checkbox</type> <default_value>on</default_value> diff --git a/config/unbound/unbound_acls.php b/config/unbound/unbound_acls.php index a7c3ea9e..721d3adb 100644 --- a/config/unbound/unbound_acls.php +++ b/config/unbound/unbound_acls.php @@ -95,7 +95,7 @@ if ($_POST) { $input_errors[] = gettext("You must enter a valid IPv4 address for {$networkacl[$x]['acl_network']}."); } } - + if (!$input_errors) { if ($pconfig['Submit'] == gettext("Save")) { @@ -173,7 +173,7 @@ if (is_subsystem_dirty("unbound")) print_info_box_np(gettext("The settings for Unbound DNS has changed. You must apply the configuration to take affect.")); ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> + <tr> <td class="tabnavtbl"> <ul id="tabnav"> <?php @@ -186,7 +186,7 @@ if (is_subsystem_dirty("unbound")) ?> </ul> </td> - </tr> + </tr> <tr> <td class="tabcont"> @@ -221,10 +221,10 @@ if (is_subsystem_dirty("unbound")) <br/> <span class="vexpl"> <?=gettext("Choose what to do with DNS requests that match the criteria specified below.");?> <br/> - <?=gettext("<b>Deny:</b> This actions stops queries from hosts within the netblock defined below.");?> <br/> - <?=gettext("<b>Refuse:</b> This actions also stops queries from hosts within the netblock defined below, but sends back DNS rcode REFUSED error message back tot eh client.");?> <br/> - <?=gettext("<b>Allow:</b> This actions allows queries from hosts within the netblock defined below.");?> <br/> - <?=gettext("<b>Allow Snoop:</b> This actions allows recursive and nonrecursive access from hosts within the netblock defined below. Used for cache snooping and ideally should only be configured for your administrative host.");?> <br/> + <?=gettext("<b>Deny:</b> This action stops queries from hosts within the netblock defined below.");?> <br/> + <?=gettext("<b>Refuse:</b> This action also stops queries from hosts within the netblock defined below, but sends a DNS rcode REFUSED error message back to the client.");?> <br/> + <?=gettext("<b>Allow:</b> This action allows queries from hosts within the netblock defined below.");?> <br/> + <?=gettext("<b>Allow Snoop:</b> This action allows recursive and nonrecursive access from hosts within the netblock defined below. Used for cache snooping and ideally should only be configured for your administrative host.");?> <br/> </span> </td> </tr> @@ -375,4 +375,4 @@ if (is_subsystem_dirty("unbound")) </tr> </table> </body> -<?php include("fend.inc"); ?>
\ No newline at end of file +<?php include("fend.inc"); ?> diff --git a/config/unbound/unbound_acls.xml b/config/unbound/unbound_acls.xml index 7c6840ce..04319169 100644 --- a/config/unbound/unbound_acls.xml +++ b/config/unbound/unbound_acls.xml @@ -99,10 +99,10 @@ <fieldname>aclaction</fieldname> <fielddescr>Action</fielddescr> <description><br/>Choose an action:<br/><br/> - <b>Allow:</b> This actions allows queries from hosts within the netblock(s) defined below.<br/> - <b>Allow Snoop:</b> This actions allows recursive and nonrecursive access from hosts within the netblock(s) defined below. Used for cache snooping and ideally should only be configured for your administrative host.<br/> - <b>Deny:</b> This actions stops queries from hosts within the netblock(s) defined below.<br/> - <b>Refuse:</b> This actions also stops queries from hosts within the netblock(s) defined below, but sends back DNS rcode REFUSED error message back to the client.</description> + <b>Allow:</b> This action allows queries from hosts within the netblock(s) defined below.<br/> + <b>Allow Snoop:</b> This action allows recursive and nonrecursive access from hosts within the netblock(s) defined below. Used for cache snooping and ideally should only be configured for your administrative host.<br/> + <b>Deny:</b> This action stops queries from hosts within the netblock(s) defined below.<br/> + <b>Refuse:</b> This action also stops queries from hosts within the netblock(s) defined below, but sends a DNS rcode REFUSED error message back to the client.</description> <type>select</type> <options> <option><name>Allow</name><value>allow</value></option> diff --git a/config/unbound/unbound_advanced.xml b/config/unbound/unbound_advanced.xml index 30fca482..7603d0aa 100644 --- a/config/unbound/unbound_advanced.xml +++ b/config/unbound/unbound_advanced.xml @@ -99,7 +99,7 @@ <field> <fieldname>prefetch</fieldname> <fielddescr>Prefetch Support</fielddescr> - <description>If enabled, the message cache elements are prefetched before they expire to keep the cache up to date. Enabling this option causes an increase of about 10 percent more traffic and load on the server, but popular items do not expire form the cache. Default is disabled.</description> + <description>If enabled, the message cache elements are prefetched before they expire to keep the cache up to date. Enabling this option causes an increase of about 10 percent more traffic and load on the server, but popular items do not expire from the cache. Default is disabled.</description> <type>checkbox</type> <default_value>off</default_value> <advancedfield/> @@ -123,7 +123,7 @@ <field> <fieldname>harden_dnssec_stripped</fieldname> <fielddescr>Harden DNSSEC data</fielddescr> - <description>If enabled, DNSSEC data is required for trust-anchored zones. If such data is absent, the zone is becomes bogus. If disabled then and no DNSSEC data is received, then the zone is made insecure. The default is enabled.</description> + <description>If enabled, DNSSEC data is required for trust-anchored zones. If such data is absent, the zone is considered bogus. If disabled and no DNSSEC data is received, then the zone is made insecure. The default is enabled.</description> <type>checkbox</type> <default_value>on</default_value> <advancedfield/> @@ -305,7 +305,7 @@ <field> <fielddescr>Custom Options</fielddescr> <fieldname>custom_options</fieldname> - <description>You can put your own custom options here, separated by semi-colons (;). These configurations options will then be added to the configuration file. <br/> <b>Note:</b> They need to be Unbound native configuration options, otherwise Unbound will <b>not</b> work.</description> + <description>You can put your own custom options here, separated by semi-colons (;). These configuration options will then be added to the configuration file. <br/> <b>Note:</b> They need to be Unbound native configuration options, otherwise Unbound will <b>not</b> work.</description> <type>textarea</type> <cols>65</cols> <rows>5</rows> diff --git a/config/unbound/unbound_monitor.sh b/config/unbound/unbound_monitor.sh index 152a308e..91e5a2ed 100755 --- a/config/unbound/unbound_monitor.sh +++ b/config/unbound/unbound_monitor.sh @@ -27,37 +27,65 @@ # POSSIBILITY OF SUCH DAMAGE. # +export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin + set -e LOOP_SLEEP=5 +PIDFILE=/var/run/unbound_monitor.pid if [ -f /var/run/unbound_alarm ]; then rm /var/run/unbound_alarm fi +PID="" +if [ -f "${PIDFILE}" ]; then + PID=`head -n 1 ${PIDFILE}` +fi + +if [ "$1" = "stop" ]; then + if [ -n "${PID}" ] && ps -p ${PID} | grep -q unbound_monitor.sh; then + kill ${PID} + else + pkill -f unbound_monitor.sh + fi + exit 0 +fi + +if [ -n "${PID}" ] && ps -p ${PID} | grep -q unbound_monitor.sh; then + echo "There is another unbound monitor process running" + exit 0 +fi + +echo $$ > ${PIDFILE} + # Sleep 5 seconds on startup not to mangle with existing boot scripts. sleep 5 -while [ /bin/true ]; do - if [ ! -f /var/run/unbound_alarm ]; then - NUM_PROCS=`/bin/pgrep unbound | wc -l | awk '{print $1}'` - if [ $NUM_PROCS -lt 1 ]; then - # Unbound is not running - echo "Unbound has exited." | logger -p daemon.info -i -t Unbound_Alarm - echo "Attempting restart..." | logger -p daemon.info -i -t Unbound_Alarm - /usr/local/etc/rc.d/unbound.sh start - sleep 3 - touch /var/run/unbound_alarm - fi - fi - NUM_PROCS=`/bin/pgrep unbound | wc -l | awk '{print $1}'` - if [ $NUM_PROCS -gt 0 ]; then - if [ -f /var/run/unbound_alarm ]; then - echo "Unbound has resumed." | logger -p daemon.info -i -t Unbound_Alarm - rm /var/run/unbound_alarm - fi - fi - sleep $LOOP_SLEEP +while true; do + if [ ! -f "${PIDFILE}" ]; then + echo $$ > ${PIDFILE} + fi + + if [ ! -f /var/run/unbound_alarm ]; then + NUM_PROCS=`pgrep unbound | wc -l | awk '{print $1}'` + if [ $NUM_PROCS -lt 1 ]; then + # Unbound is not running + echo "Unbound has exited." | logger -p daemon.info -i -t Unbound_Alarm + echo "Attempting restart..." | logger -p daemon.info -i -t Unbound_Alarm + /usr/local/etc/rc.d/unbound.sh start + sleep 3 + touch /var/run/unbound_alarm + fi + fi + NUM_PROCS=`pgrep unbound | wc -l | awk '{print $1}'` + if [ $NUM_PROCS -gt 0 ]; then + if [ -f /var/run/unbound_alarm ]; then + echo "Unbound has resumed." | logger -p daemon.info -i -t Unbound_Alarm + rm /var/run/unbound_alarm + fi + fi + sleep $LOOP_SLEEP done if [ -f /var/run/unbound_alarm ]; then diff --git a/config/unbound/unbound_status.php b/config/unbound/unbound_status.php index d011b109..d7371f29 100644 --- a/config/unbound/unbound_status.php +++ b/config/unbound/unbound_status.php @@ -31,6 +31,12 @@ require("guiconfig.inc"); +// Define basedir constant for unbound according to FreeBSD version (PBI support or no PBI) +if (floatval(php_uname("r")) >= 8.3) + define("UNBOUND_BASE", "/usr/pbi/unbound-" . php_uname("m")); +else + define("UNBOUND_BASE", "/usr/local"); + if(!is_process_running("unbound")) { Header("Location: /pkg_edit.php?xml=unbound.xml&id=0"); exit; @@ -40,11 +46,11 @@ $pgtitle = "Services: Unbound DNS Forwarder: Status"; include("head.inc"); function doCmdT($title, $command, $rows) { - echo "<p>\n"; - echo "<a name=\"" . $title . "\">\n"; - echo "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"; - echo "<tr><td class=\"listtopic\">" . $title . "</td></tr>\n"; - echo "<tr><td class=\"listlr\"><textarea style=\"font-family:courier\"cols=\"101\" rows=\"$rows\">"; /* no newline after pre */ + echo "<p>\n"; + echo "<a name=\"" . $title . "\">\n"; + echo "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"; + echo "<tr><td class=\"listtopic\">" . $title . "</td></tr>\n"; + echo "<tr><td class=\"listlr\"><textarea style=\"font-family:courier\"cols=\"101\" rows=\"$rows\">"; /* no newline after pre */ if ($command == "dumpconfigxml") { $fd = @fopen("/conf/config.xml", "r"); @@ -71,46 +77,46 @@ function doCmdT($title, $command, $rows) { echo htmlspecialchars($execOutput[$i],ENT_NOQUOTES); } } - echo "</textarea></tr>\n"; - echo "</table>\n"; + echo "</textarea></tr>\n"; + echo "</table>\n"; } /* Execute a command, giving it a title which is the same as the command. */ function doCmd($command) { - doCmdT($command,$command); + doCmdT($command,$command); } /* Define a command, with a title, to be executed later. */ function defCmdT($title, $command, $rows = "20") { - global $commands; - $title = htmlspecialchars($title,ENT_NOQUOTES); - $commands[] = array($title, $command, $rows); + global $commands; + $title = htmlspecialchars($title,ENT_NOQUOTES); + $commands[] = array($title, $command, $rows); } /* Define a command, with a title which is the same as the command, * to be executed later. */ function defCmd($command) { - defCmdT($command,$command); + defCmdT($command,$command); } /* List all of the commands as an index. */ function listCmds() { - global $commands; - echo "<p>" . gettext("This status page includes the following information") . ":\n"; - echo "<ul width=\"100%\">\n"; - for ($i = 0; isset($commands[$i]); $i++ ) { - echo "<li><strong><a href=\"#" . $commands[$i][0] . "\">" . $commands[$i][0] . "</a></strong>\n"; - } - echo "</ul>\n"; + global $commands; + echo "<p>" . gettext("This status page includes the following information") . ":\n"; + echo "<ul width=\"100%\">\n"; + for ($i = 0; isset($commands[$i]); $i++ ) { + echo "<li><strong><a href=\"#" . $commands[$i][0] . "\">" . $commands[$i][0] . "</a></strong>\n"; + } + echo "</ul>\n"; } /* Execute all of the commands which were defined by a call to defCmd. */ function execCmds() { - global $commands; - for ($i = 0; isset($commands[$i]); $i++ ) { - doCmdT($commands[$i][0], $commands[$i][1], $commands[$i][2]); - } + global $commands; + for ($i = 0; isset($commands[$i]); $i++ ) { + doCmdT($commands[$i][0], $commands[$i][1], $commands[$i][2]); + } } ?> @@ -135,10 +141,10 @@ function execCmds() { </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td class="tabcont" width="100%"> + <tr> + <td class="tabcont" width="100%"> <?php - $entries = trim(exec("/usr/local/sbin/unbound-control dump_cache | wc -l")); + $entries = trim(exec(UNBOUND_BASE . "/sbin/unbound-control dump_cache | wc -l")); defCmdT("Unbound status", "unbound-control status", "6"); defCmdT("Unbound stats", "unbound-control stats_noreset"); defCmdT("Unbound stubs", "unbound-control list_stubs", "8"); @@ -146,12 +152,12 @@ function execCmds() { defCmdT("Unbound local zones", "unbound-control list_local_zones"); defCmdT("Unbound local data", "unbound-control list_local_data"); defCmdT("Unbound cache ($entries entries)", "unbound-control dump_cache", "60"); - defCmdT("Unbound configuration", "/bin/cat /usr/local/etc/unbound/unbound.conf", "60"); + defCmdT("Unbound configuration", "/bin/cat " . UNBOUND_BASE . "/etc/unbound/unbound.conf", "60"); listCmds(); execCmds(); ?> - </td> - </tr> + </td> + </tr> </table> </div> <?php include("fend.inc"); ?> diff --git a/config/vhosts/vhosts.inc b/config/vhosts/vhosts.inc index a5b8c4e2..651b79b2 100644 --- a/config/vhosts/vhosts.inc +++ b/config/vhosts/vhosts.inc @@ -736,31 +736,31 @@ function vhosts_install_command() { if(stristr(php_uname('r'), '7.2') == TRUE) { if (!file_exists('/usr/local/php5')) { chdir('/usr/local/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd7.2/php5.tar.gz"); + exec ("fetch http://files.pfsense.org/packages/7/vhosts/php5.tar.gz"); exec("tar zxvf /usr/local/php5.tar.gz -C /usr/local/"); exec("rm /usr/local/php5.tar.gz"); } if (!file_exists('/usr/local/lib/libxml2.so.5')) { chdir('/usr/local/lib/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd7.2/usr.local.lib/libxml2.so.5"); + exec ("fetch http://files.pfsense.org/packages/7/vhosts/usr.local.lib/libxml2.so.5"); } if (!file_exists('/usr/local/lib/libxml2.so')) { chdir('/usr/local/lib/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd7.2/usr.local.lib/libxml2.so"); + exec ("fetch http://files.pfsense.org/packages/7/vhosts/usr.local.lib/libxml2.so"); } if (!file_exists('/usr/local/lib/libxml2.la')) { chdir('/usr/local/lib/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd7.2/usr.local.lib/libxml2.la"); + exec ("fetch http://files.pfsense.org/packages/7/vhosts/usr.local.lib/libxml2.la"); } if (!file_exists('/usr/local/lib/libxml2.a')) { chdir('/usr/local/lib/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd7.2/usr.local.lib/lib/libxml2.a"); + exec ("fetch http://files.pfsense.org/packages/7/vhosts/usr.local.lib/lib/libxml2.a"); } } if(stristr(php_uname('r'), '8.1') == TRUE) { if (!file_exists('/usr/local/php5')) { chdir('/usr/local/'); - exec ("fetch http://www.pfsense.com/packages/config/vhosts/freebsd8.0/php5.tar.gz"); + exec ("fetch http://files.pfsense.org/packages/8/vhosts/php5.tar.gz"); exec("tar zxvf /usr/local/php5.tar.gz -C /usr/local/"); exec("rm /usr/local/php5.tar.gz"); } diff --git a/config/vnstat/vnstat.xml b/config/vnstat/vnstat.xml index 2a0c06f5..63a121a0 100644 --- a/config/vnstat/vnstat.xml +++ b/config/vnstat/vnstat.xml @@ -25,7 +25,7 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat/bin/vnstat_php_frontend-1.4.1.tar.gz</item> + <item>http://files.pfsense.org/packages/7/vnstat/vnstat_php_frontend-1.4.1.tar.gz</item> </additional_files_needed> <custom_php_resync_config_command></custom_php_resync_config_command> <custom_php_install_command>vnstat_install_config();</custom_php_install_command> diff --git a/config/vnstat2/vnstat2.xml b/config/vnstat2/vnstat2.xml index 08bfc91d..25cd0bcb 100644 --- a/config/vnstat2/vnstat2.xml +++ b/config/vnstat2/vnstat2.xml @@ -48,7 +48,7 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat2/bin/vnstat_php_frontend-1.4.1.tar.gz</item> + <item>http://files.pfsense.org/packages/8/vnstat/vnstat_php_frontend-1.4.1.tar.gz</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> @@ -68,22 +68,22 @@ <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat2/bin/diag_vnstat.abc</item> + <item>http://files.pfsense.org/packages/8/vnstat/diag_vnstat.abc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat2/bin/diag_vnstat2.abc</item> + <item>http://files.pfsense.org/packages/8/vnstat/diag_vnstat2.abc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat2/bin/vnstat2_img.abc</item> + <item>http://files.pfsense.org/packages/8/vnstat/vnstat2_img.abc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/vnstat2/bin/vnstati.abc</item> + <item>http://files.pfsense.org/packages/8/vnstat/vnstati.abc</item> </additional_files_needed> <fields> <field> diff --git a/config/widget-snort/snort_alerts.widget.php b/config/widget-snort/snort_alerts.widget.php index bb51a387..e488bc49 100644 --- a/config/widget-snort/snort_alerts.widget.php +++ b/config/widget-snort/snort_alerts.widget.php @@ -60,55 +60,61 @@ function sksort(&$array, $subkey="id", $sort_ascending=false) { /* check if firewall widget variable is set */ if (!isset($nentries)) $nentries = 5; -/* retrieve snort variables */ -require_once("/usr/local/pkg/snort/snort.inc"); -if (!is_array($config['installedpackages']['snortglobal']['rule'])) - $config['installedpackages']['snortglobal']['rule'] = array(); -$a_instance = &$config['installedpackages']['snortglobal']['rule']; +/* check if Snort include file exists before we use it */ +if (file_exists("/usr/local/pkg/snort/snort.inc")) { + require_once("/usr/local/pkg/snort/snort.inc"); -/* read log file(s) */ -$counter=0; -foreach ($a_instance as $instanceid => $instance) { - $snort_uuid = $a_instance[$instanceid]['uuid']; - $if_real = snort_get_real_interface($a_instance[$instanceid]['interface']); + /* retrieve snort variables */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); + $a_instance = &$config['installedpackages']['snortglobal']['rule']; + + /* read log file(s) */ + $counter=0; + foreach ($a_instance as $instanceid => $instance) { + $snort_uuid = $a_instance[$instanceid]['uuid']; + $if_real = snort_get_real_interface($a_instance[$instanceid]['interface']); - /* make sure alert file exists */ - if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { - exec("tail -n{$nentries} /var/log/snort/snort_{$if_real}{$snort_uuid}/alert > /tmp/alert_{$snort_uuid}"); - if (file_exists("/tmp/alert_{$snort_uuid}")) { - $tmpblocked = array_flip(snort_get_blocked_ips()); + /* make sure alert file exists */ + if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { + exec("tail -n{$nentries} /var/log/snort/snort_{$if_real}{$snort_uuid}/alert > /tmp/alert_{$snort_uuid}"); + if (file_exists("/tmp/alert_{$snort_uuid}")) { + $tmpblocked = array_flip(snort_get_blocked_ips()); - /* 0 1 2 3 4 5 6 7 8 9 10 11 12 */ - /* File format timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority */ - $fd = fopen("/tmp/alert_{$snort_uuid}", "r"); - while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { - if(count($fields) < 11) - continue; + /* 0 1 2 3 4 5 6 7 8 9 10 11 12 */ + /* File format timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority */ + $fd = fopen("/tmp/alert_{$snort_uuid}", "r"); + while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { + if(count($fields) < 11) + continue; - $snort_alerts[$counter]['instanceid'] = $a_instance[$instanceid]['interface']; - $snort_alerts[$counter]['timestamp'] = $fields[0]; - $snort_alerts[$counter]['timeonly'] = substr($fields[0], 6, -8); - $snort_alerts[$counter]['dateonly'] = substr($fields[0], 0, -17); - $snort_alerts[$counter]['src'] = $fields[6]; - $snort_alerts[$counter]['srcport'] = $fields[7]; - $snort_alerts[$counter]['dst'] = $fields[8]; - $snort_alerts[$counter]['dstport'] = $fields[9]; - $snort_alerts[$counter]['priority'] = $fields[12]; - $snort_alerts[$counter]['category'] = $fields[11]; - $counter++; + $snort_alerts[$counter]['instanceid'] = $a_instance[$instanceid]['interface']; + $snort_alerts[$counter]['timestamp'] = $fields[0]; + $snort_alerts[$counter]['timeonly'] = substr($fields[0], strpos($fields[0], '-')+1, -8); + $snort_alerts[$counter]['dateonly'] = substr($fields[0], 0, strpos($fields[0], '-')); + $snort_alerts[$counter]['src'] = $fields[6]; + $snort_alerts[$counter]['srcport'] = $fields[7]; + $snort_alerts[$counter]['dst'] = $fields[8]; + $snort_alerts[$counter]['dstport'] = $fields[9]; + $snort_alerts[$counter]['priority'] = $fields[12]; + $snort_alerts[$counter]['category'] = $fields[11]; + $counter++; + }; + fclose($fd); + @unlink("/tmp/alert_{$snort_uuid}"); }; - fclose($fd); - @unlink("/tmp/alert_{$snort_uuid}"); }; }; -}; -/* sort the array */ -if (isset($config['syslog']['reverse'])) { - sksort($snort_alerts, 'timestamp', false); + /* sort the array */ + if (isset($config['syslog']['reverse'])) { + sksort($snort_alerts, 'timestamp', false); + } else { + sksort($snort_alerts, 'timestamp', true); + }; } else { - sksort($snort_alerts, 'timestamp', true); -}; + $msg = gettext("The Snort package is not installed."); +} /* display the result */ ?> @@ -131,7 +137,13 @@ if (is_array($snort_alerts)) { $counter++; if($counter >= $nentries) break; } -}; +} else { + if (!empty($msg)) { + echo (" <tr class=\"snort-alert-entry\"> + <td colspan=\"3\" align=\"center\"><br>{$msg}</br></td> + </tr>"); + } +} ?> </tbody> </table> diff --git a/config/widget-snort/widget-snort.inc b/config/widget-snort/widget-snort.inc new file mode 100644 index 00000000..105dd1e7 --- /dev/null +++ b/config/widget-snort/widget-snort.inc @@ -0,0 +1,24 @@ +<?php +require_once("config.inc"); +function widget_snort_uninstall() { + + global $config; + + /* Remove the Snort widget from the Dashboard display list */ + $widgets = $config['widgets']['sequence']; + if (!empty($widgets)) { + $widgetlist = explode(",", $widgets); + foreach ($widgetlist as $key => $widget) { + if (strstr($widget, "snort_alerts-container")) + unset($widgetlist[$key]); + } + $config['widgets']['sequence'] = implode(",", $widgetlist); + write_config(); + } + + /* Remove our associated files */ + unlink("/usr/local/www/widgets/include/widget-snort.inc"); + unlink("/usr/local/www/widgets/widgets/snort_alerts.widget.php"); + unlink("/usr/local/www/widgets/javascript/snort_alerts.js"); +} +?> diff --git a/config/widget-snort/widget-snort.xml b/config/widget-snort/widget-snort.xml index 785ac5b1..b415bd12 100644 --- a/config/widget-snort/widget-snort.xml +++ b/config/widget-snort/widget-snort.xml @@ -46,8 +46,15 @@ <requirements>Dashboard package and Snort</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>widget-snort</name> - <version>0.5</version> + <version>0.3.4</version> <title>Widget - Snort</title> + <include_file>/usr/local/www/widgets/include/widget-snort.inc</include_file> + <menu> + </menu> + <service> + </service> + <tabs> + </tabs> <additional_files_needed> <prefix>/usr/local/www/widgets/javascript/</prefix> <chmod>0644</chmod> @@ -58,4 +65,20 @@ <chmod>0644</chmod> <item>http://www.pfsense.com/packages/config/widget-snort/snort_alerts.widget.php</item> </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/widgets/include/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/widget-snort/widget-snort.inc</item> + </additional_files_needed> + <fields> + </fields> + <custom_add_php_command> + </custom_add_php_command> + <custom_php_resync_config_command> + </custom_php_resync_config_command> + <custom_php_install_command> + </custom_php_install_command> + <custom_php_deinstall_command> + widget_snort_uninstall(); + </custom_php_deinstall_command> </packagegui> |