diff options
Diffstat (limited to 'config/snort')
43 files changed, 7057 insertions, 3533 deletions
diff --git a/config/snort/disablesid-sample.conf b/config/snort/disablesid-sample.conf new file mode 100644 index 00000000..026f4d94 --- /dev/null +++ b/config/snort/disablesid-sample.conf @@ -0,0 +1,43 @@ +# example disablesid.conf + +# Example of modifying state for individual rules +# 1:1034,1:9837,1:1270,1:3390,1:710,1:1249,3:13010 + +# Example of modifying state for rule ranges +# 1:220-1:3264,3:13010-3:13013 + +# Comments are allowed in this file, and can also be on the same line +# As the modify state syntax, as long as it is a trailing comment +# 1:1011 # I Disabled this rule because I could! + +# Example of modifying state for MS and cve rules, note the use of the : +# in cve. This will modify MS09-008, cve 2009-0233, bugtraq 21301, +# and all MS00 and all cve 2000 related sids! These support regular expression +# matching only after you have specified what you are looking for, i.e. +# MS00-<regex> or cve:<regex>, the first section CANNOT contain a regular +# expression (MS\d{2}-\d+) will NOT work, use the pcre: keyword (below) +# for this. +# MS09-008,cve:2009-0233,bugtraq:21301,MS00-\d+,cve:2000-\d+ + +# Example of using the pcre: keyword to modify rulestate. the pcre keyword +# allows for full use of regular expression syntax, you do not need to designate +# with / and all pcre searches are treated as case insensitive. For more information +# about regular expression syntax: http://www.regular-expressions.info/ +# The following example modifies state for all MS07 through MS10 +# pcre:MS(0[7-9]|10)-\d+ +# pcre:"Joomla" + +# Example of modifying state for specific categories entirely. +# "snort_" limits to Snort VRT rules, "emerging-" limits to +# Emerging Threats Open rules, "etpro-" limits to ET-PRO rules. +# "shellcode" with no prefix would match in any vendor set. +# snort_web-iis,emerging-shellcode,etpro-imap,shellcode + +# Any of the above values can be on a single line or multiple lines, when +# on a single line they simply need to be separated by a , +# 1:9837,1:220-1:3264,3:13010-3:13013,pcre:MS(0[0-7])-\d+,MS09-008,cve:2009-0233 + +# The modifications in this file are for sample/example purposes only and +# should not actively be used, you need to modify this file to fit your +# environment. + diff --git a/config/snort/enablesid-sample.conf b/config/snort/enablesid-sample.conf new file mode 100644 index 00000000..4cccc5dd --- /dev/null +++ b/config/snort/enablesid-sample.conf @@ -0,0 +1,39 @@ +# example enablesid.conf + +# Example of modifying state for individual rules +# 1:1034,1:9837,1:1270,1:3390,1:710,1:1249,3:13010 + +# Example of modifying state for rule ranges +# 1:220-1:3264,3:13010-3:13013 + +# Comments are allowed in this file, and can also be on the same line +# As the modify state syntax, as long as it is a trailing comment +# 1:1011 # I Disabled this rule because I could! + +# Example of modifying state for MS and cve rules, note the use of the : +# in cve. This will modify MS09-008, cve 2009-0233, bugtraq 21301, +# and all MS00 and all cve 2000 related sids! These support regular expression +# matching only after you have specified what you are looking for, i.e. +# MS00-<regex> or cve:<regex>, the first section CANNOT contain a regular +# expression (MS\d{2}-\d+) will NOT work, use the pcre: keyword (below) +# for this. +# MS09-008,cve:2009-0233,bugtraq:21301,MS00-\d+,cve:2000-\d+ + +# Example of using the pcre: keyword to modify rulestate. the pcre keyword +# allows for full use of regular expression syntax, you do not need to designate +# with / and all pcre searches are treated as case insensitive. For more information +# about regular expression syntax: http://www.regular-expressions.info/ +# The following example modifies state for all MS07 through MS10 +# pcre:MS(0[7-9]|10)-\d+ +# pcre:"Joomla" + +# Example of modifying state for specific categories entirely. +# "snort_" limits to Snort VRT rules, "emerging-" limits to +# Emerging Threats Open rules, "etpro-" limits to ET-PRO rules. +# "shellcode" with no prefix would match in any vendor set. +# snort_web-iis,emerging-shellcode,etpro-imap,shellcode + +# Any of the above values can be on a single line or multiple lines, when +# on a single line they simply need to be separated by a , +# 1:9837,1:220-1:3264,3:13010-3:13013,pcre:MS(0[0-7])-\d+,MS09-008,cve:2009-0233 + diff --git a/config/snort/modifysid-sample.conf b/config/snort/modifysid-sample.conf new file mode 100644 index 00000000..d59f84ba --- /dev/null +++ b/config/snort/modifysid-sample.conf @@ -0,0 +1,23 @@ +# example modifysid.conf +# +# formatting is simple +# <sid or sid list> "what I'm replacing" "what I'm replacing it with" +# +# Note that this will only work with GID:1 rules, simply because modifying +# GID:3 SO stub rules would not actually affect the rule. +# +# If you are attempting to change rulestate (enable,disable) from here +# then you are doing it wrong. Do this from within the respective +# rulestate modification configuration files. + +# the following applies to sid 10010 only and represents what would normally +# be s/to_client/from_server/ +# 10010 "to_client" "from_server" + +# the following would replace HTTP_PORTS with HTTPS_PORTS for ALL GID:1 +# rules +# "HTTP_PORTS" "HTTPS_PORTS" + +# multiple sids can be specified as noted below: +# 302,429,1821 "\$EXTERNAL_NET" "\$HOME_NET" + diff --git a/config/snort/snort.inc b/config/snort/snort.inc index c0c5756c..bec163d7 100755 --- a/config/snort/snort.inc +++ b/config/snort/snort.inc @@ -36,55 +36,23 @@ 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"); +require("/usr/local/pkg/snort/snort_defs.inc"); // Snort GUI needs some extra PHP memory space to manipulate large rules arrays -ini_set("memory_limit", "192M"); +ini_set("memory_limit", "256M"); // Explicitly declare this as global so it works through function call includes -global $rebuild_rules, $pfSense_snort_version; +global $g, $config, $rebuild_rules, $pfSense_snort_version; // Grab the Snort binary version programmatically, but if that fails use a safe default $snortver = array(); -exec("/usr/local/bin/snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); -$snort_version = $snortver[0]; -if (empty($snort_version)) - $snort_version = "2.9.6.0"; - -/* Used to indicate latest version of this include file has been loaded */ -$pfSense_snort_version = "3.0.8"; +$snortbindir = SNORT_PBI_BINDIR; +exec("{$snortbindir}snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); /* get installed package version for display */ $snort_package_version = "Snort {$config['installedpackages']['package'][get_pkg_id("snort")]['version']}"; -// Define SNORTDIR and SNORTLIBDIR constants according to pfSense version -$pfs_version=substr(trim(file_get_contents("/etc/version")),0,3); -if ($pfs_version > 2.0) { - define("SNORTDIR", "/usr/pbi/snort-" . php_uname("m") . "/etc/snort"); - define("SNORTLIBDIR", "/usr/pbi/snort-" . php_uname("m") . "/lib/snort"); -} -else { - define("SNORTDIR", "/usr/local/etc/snort"); - define("SNORTLIBDIR", "/usr/local/lib/snort"); -} - -/* Define some useful constants for Snort */ -/* Be sure to include trailing slash on the URL defines */ -define("SNORTLOGDIR", "/var/log/snort"); -define("ET_DNLD_FILENAME", "emerging.rules.tar.gz"); -define("ETPRO_DNLD_FILENAME", "etpro.rules.tar.gz"); -define("GPLV2_DNLD_FILENAME", "community-rules.tar.gz"); -define("FLOWBITS_FILENAME", "flowbit-required.rules"); -define("ENFORCING_RULES_FILENAME", "snort.rules"); -define("RULES_UPD_LOGFILE", SNORTLOGDIR . "/snort_rules_update.log"); -define("VRT_FILE_PREFIX", "snort_"); -define("GPL_FILE_PREFIX", "GPLv2_"); -define("ET_OPEN_FILE_PREFIX", "emerging-"); -define("ET_PRO_FILE_PREFIX", "etpro-"); -define("IPREP_PATH", "/var/db/snort/iprep/"); - /* Rebuild Rules Flag -- if "true", rebuild enforcing rules and flowbit-rules files */ $rebuild_rules = false; @@ -309,7 +277,7 @@ function snort_find_list($find_name, $type = 'whitelist') { } /* func builds custom whitelists and the HOME_NET variable */ -function snort_build_list($snortcfg, $listname = "", $whitelist = false) { +function snort_build_list($snortcfg, $listname = "", $whitelist = false, $externallist = false) { /***********************************************************/ /* The default is to build a HOME_NET variable unless */ @@ -319,9 +287,10 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { global $config, $g, $aliastable, $filterdns; $home_net = array(); - if ($listname == 'default' || empty($listname)) { + if (!$externallist && ($listname == 'default' || empty($listname))) { $localnet = 'yes'; $wanip = 'yes'; $wangw = 'yes'; $wandns = 'yes'; $vips = 'yes'; $vpns = 'yes'; - } else { + } + else { $list = snort_find_list($listname); if (empty($list)) return $list; @@ -335,9 +304,13 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { $home_net = explode(" ", trim(filter_expand_alias($list['address']))); } - /* 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 add loopback addresses to HOME_NET and whitelist */ + if (!$externallist) { + if (!in_array("127.0.0.1", $home_net)) + $home_net[] = "127.0.0.1"; + if (!in_array("::1", $home_net)) + $home_net[] = "::1"; + } /********************************************************************/ /* Always put the interface running Snort in HOME_NET and whitelist */ @@ -348,7 +321,7 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { /* though, to prevent locking out the firewall itself. */ /********************************************************************/ $snortip = get_interface_ip($snortcfg['interface']); - if (!$whitelist || $localnet == 'yes' || empty($localnet)) { + if (($externallist && $localnet == 'yes') || (!$externallist && (!$whitelist || $localnet == 'yes' || empty($localnet)))) { if (is_ipaddr($snortip)) { if ($snortcfg['interface'] <> "wan") { $sn = get_interface_subnet($snortcfg['interface']); @@ -358,35 +331,46 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { } } } - else { - if (is_ipaddr($snortip)) { + elseif (!$externallist && $localnet != 'yes') { + if (is_ipaddrv4($snortip)) { if (!in_array($snortip, $home_net)) $home_net[] = $snortip; } } - /* Handle IPv6 if available (2.1 and higher) */ - if (function_exists('get_interface_ipv6')) { - $snortip = get_interface_ipv6($snortcfg['interface']); - if (!$whitelist || $localnet == 'yes' || empty($localnet)) { - if (is_ipaddrv6($snortip)) { - if ($snortcfg['interface'] <> "wan") { - $sn = get_interface_subnetv6($snortcfg['interface']); - $ip = gen_subnetv6($snortip, $sn). "/{$sn}"; - if (!in_array($ip, $home_net)) - $home_net[] = $ip; - } + // Grab the IPv6 address if we have one assigned + $snortip = get_interface_ipv6($snortcfg['interface']); + // Trim off the interface designation (e.g., %em1) if present + if (strpos($snortip, "%") !== FALSE) + $snortip = substr($snortip, 0, strpos($snortip, "%")); + if (($externallist && $localnet == 'yes') || (!$externallist && (!$whitelist || $localnet == 'yes' || empty($localnet)))) { + if (is_ipaddrv6($snortip)) { + if ($snortcfg['interface'] <> "wan") { + $sn = get_interface_subnetv6($snortcfg['interface']); + $ip = gen_subnetv6($snortip, $sn). "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; } } - else { - if (is_ipaddrv6($snortip)) { - if (!in_array($snortip, $home_net)) - $home_net[] = $snortip; - } + } + elseif (!$externallist && $localnet != 'yes') { + if (is_ipaddrv6($snortip)) { + if (!in_array($snortip, $home_net)) + $home_net[] = $snortip; } } - if (!$whitelist || $localnet == 'yes' || empty($localnet)) { + // Add link-local address if user included locally-attached networks + $snortip = get_interface_linklocal($snortcfg['interface']); + if (!empty($snortip) && $localnet == 'yes') { + // Trim off the interface designation (e.g., %em1) if present + if (strpos($snortip, "%") !== FALSE) + $snortip = substr($snortip, 0, strpos($snortip, "%")); + if (!in_array($snortip, $home_net)) + $home_net[] = $snortip; + } + + if (($externallist && $localnet == 'yes') || (!$externallist && (!$whitelist || $localnet == 'yes' || empty($localnet)))) { /*************************************************************************/ /* Iterate through the interface list and write out whitelist items and */ /* also compile a HOME_NET list of all the local interfaces for snort. */ @@ -398,56 +382,79 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { if ($int == "wan") continue; $subnet = get_interface_ip($int); - if (is_ipaddr($subnet)) { + if (is_ipaddrv4($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_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; - } + + $subnet = get_interface_ipv6($int); + // Trim off the interface designation (e.g., %em1) if present + if (strpos($subnet, "%") !== FALSE) + $subnet = substr($subnet, 0, strpos($subnet, "%")); + if (is_ipaddrv6($subnet)) { + $sn = get_interface_subnetv6($int); + $ip = gen_subnetv6($subnet, $sn). "/{$sn}"; + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + + // Add link-local address + $snortip = get_interface_linklocal($int); + if (!empty($snortip)) { + // Trim off the interface designation (e.g., %em1) if present + if (strpos($snortip, "%") !== FALSE) + $snortip = substr($snortip, 0, strpos($snortip, "%")); + if (!in_array($snortip, $home_net)) + $home_net[] = $snortip; } } } if ($wanip == 'yes') { $ip = get_interface_ip("wan"); - if (is_ipaddr($ip)) { + if (is_ipaddrv4($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; - } + $ip = get_interface_ipv6("wan"); + // Trim off the interface designation (e.g., %em1) if present + if (strpos($ip, "%") !== FALSE) + $ip = substr($ip, 0, strpos($ip, "%")); + if (is_ipaddrv6($ip)) { + if (!in_array($ip, $home_net)) + $home_net[] = $ip; + } + // Explicitly grab the WAN Link-Local address + $snortip = get_interface_linklocal("wan"); + if (!empty($snortip)) { + // Trim off the interface designation (e.g., %em1) if present + if (strpos($snortip, "%") !== FALSE) + $snortip = substr($snortip, 0, strpos($snortip, "%")); + if (!in_array($snortip, $home_net)) + $home_net[] = $snortip; } } if ($wangw == 'yes') { /* Grab the default gateway if set */ $default_gw = exec("/sbin/route -n get default |grep 'gateway:' | /usr/bin/awk '{ print $2 }'"); - if (is_ipaddr($default_gw) && !in_array($default_gw, $home_net)) + if (is_ipaddrv4($default_gw) && !in_array($default_gw, $home_net)) + $home_net[] = $default_gw; + if (is_ipaddrv6($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) && !in_array($gw, $home_net)) + if (is_ipaddrv4($gw) && !in_array($gw, $home_net)) + $home_net[] = $gw; + $gw = get_interface_gateway_v6($snortcfg['interface']); + // Trim off the interface designation (e.g., %em1) if present + if (strpos($gw, "%") !== FALSE) + $gw = substr($gw, 0, strpos($gw, "%")); + if (is_ipaddrv6($gw) && !in_array($gw, $home_net)) $home_net[] = $gw; - if (function_exists("get_interface_gateway_v6")) { - $gw = get_interface_gateway_v6($snortcfg['interface']); - if (is_ipaddrv6($gw) && !in_array($gw, $home_net)) - $home_net[] = $gw; - } } if ($wandns == 'yes') { @@ -471,7 +478,7 @@ function snort_build_list($snortcfg, $listname = "", $whitelist = false) { } } - /* grab a list of vpns and whitelist if user desires added by nestorfish 954 */ + // Grab a list of vpns enabled - these come back as CIDR mask networks if ($vpns == 'yes') { $vpns_list = filter_get_vpns_list(); if (!empty($vpns_list)) { @@ -513,9 +520,19 @@ function snort_barnyard_stop($snortcfg, $if_real) { $snort_uuid = $snortcfg['uuid']; if (isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) { - log_error("[Snort] Barnyard2 STOP for {$snortcfg['descr']}({$if_real})..."); + log_error("[Snort] Barnyard2 STOP for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); killbypid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); + + // Now wait up to 5 seconds for Barnyard2 to actually stop and clear its PID file + $count = 0; + do { + if (!isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) + break; + sleep(1); + $count++; + } while ($count < 5); } + unlink_if_exists("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); } function snort_stop($snortcfg, $if_real) { @@ -523,56 +540,131 @@ function snort_stop($snortcfg, $if_real) { $snort_uuid = $snortcfg['uuid']; if (isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { - log_error("[Snort] Snort STOP for {$snortcfg['descr']}({$if_real})..."); + log_error("[Snort] Snort STOP for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); killbypid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); + + // Now wait up to 10 seconds for Snort to actually stop and clear its PID file + $count = 0; + do { + if (!isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) + break; + sleep(1); + $count++; + } while ($count < 10); } + unlink_if_exists("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); snort_barnyard_stop($snortcfg, $if_real); } -function snort_barnyard_start($snortcfg, $if_real) { +function snort_barnyard_start($snortcfg, $if_real, $background=FALSE) { global $config, $g; $snortdir = SNORTDIR; $snortlogdir = SNORTLOGDIR; $snort_uuid = $snortcfg['uuid']; + $snortbindir = SNORT_PBI_BINDIR; - /* define snortbarnyardlog_chk */ - if ($snortcfg['barnyard_enable'] == 'on') { - log_error("[Snort] Barnyard2 START for {$snortcfg['descr']}({$if_real})..."); - mwexec("/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 {$snortlogdir}/snort_{$if_real}{$snort_uuid} -D -q"); + if ($snortcfg['barnyard_enable'] == 'on' && !isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) { + log_error("[Snort] Barnyard2 START for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); + if ($background) + mwexec_bg("{$snortbindir}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 {$snortlogdir}/snort_{$if_real}{$snort_uuid} -D -q"); + else + mwexec("{$snortbindir}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 {$snortlogdir}/snort_{$if_real}{$snort_uuid} -D -q"); } } -function snort_start($snortcfg, $if_real) { +function snort_start($snortcfg, $if_real, $background=FALSE) { global $config, $g; $snortdir = SNORTDIR; $snortlogdir = SNORTLOGDIR; $snort_uuid = $snortcfg['uuid']; + $snortbindir = SNORT_PBI_BINDIR; - if ($snortcfg['enable'] == 'on') { - log_error("[Snort] Snort START for {$snortcfg['descr']}({$if_real})..."); - mwexec("/usr/local/bin/snort -R {$snort_uuid} -D -q -l {$snortlogdir}/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 ($config['installedpackages']['snortglobal']['verbose_logging'] == "on") + $quiet = ""; else + $quiet = "-q --suppress-config-log"; + + if ($snortcfg['enable'] == 'on' && !isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { + log_error("[Snort] Snort START for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); + if ($background) + mwexec_bg("{$snortbindir}snort -R {$snort_uuid} -D {$quiet} -l {$snortlogdir}/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 + mwexec("{$snortbindir}snort -R {$snort_uuid} -D {$quiet} -l {$snortlogdir}/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}"); + snort_barnyard_start($snortcfg, $if_real, $background); + } +} + +function snort_start_all_interfaces($background=FALSE) { + + /*************************************************************/ + /* This function starts all configured and enabled Snort */ + /* interfaces. */ + /*************************************************************/ + + global $g, $config; + + /* do nothing if no Snort interfaces active */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; - snort_barnyard_start($snortcfg, $if_real); + foreach ($config['installedpackages']['snortglobal']['rule'] as $snortcfg) { + if ($snortcfg['enable'] != 'on') + continue; + snort_start($snortcfg, get_real_interface($snortcfg['interface']), $background); + } +} + +function snort_stop_all_interfaces() { + + /*************************************************************/ + /* This function stops all configured Snort interfaces. */ + /*************************************************************/ + + global $g, $config; + + /* do nothing if no Snort interfaces active */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; + + foreach ($config['installedpackages']['snortglobal']['rule'] as $snortcfg) { + snort_stop($snortcfg, get_real_interface($snortcfg['interface'])); + } +} + +function snort_restart_all_interfaces() { + + /*************************************************************/ + /* This function stops all configured Snort interfaces and */ + /* restarts enabled Snort interfaces. */ + /*************************************************************/ + + global $g, $config; + + /* do nothing if no Snort interfaces active */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; + + snort_stop_all_interfaces(); + sleep(2); + snort_start_all_interfaces(TRUE); } -/**************************************************************/ -/* This function sends the passed SIGNAL 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. */ -/* */ -/* $signal = SIGHUP (default) parses and reloads config. */ -/* SIGURG updates Host Attribute Table. */ -/**************************************************************/ function snort_reload_config($snortcfg, $signal="SIGHUP") { + + /*************************************************************/ + /* This function sends the passed SIGNAL 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 */ + /* the reload as a background process and returns control */ + /* immediately to the caller. */ + /* */ + /* $signal = SIGHUP (default) parses and reloads config. */ + /* SIGURG updates Host Attribute Table. */ + /*************************************************************/ global $config, $g; $snortdir = SNORTDIR; @@ -584,23 +676,23 @@ function snort_reload_config($snortcfg, $signal="SIGHUP") { /* can find a valid PID for the process. */ /******************************************************/ if (isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { - log_error("[Snort] Snort RELOAD CONFIG for {$snortcfg['descr']} ({$if_real})..."); + log_error("[Snort] Snort RELOAD CONFIG for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); mwexec_bg("/bin/pkill -{$signal} -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); } } function snort_barnyard_reload_config($snortcfg, $signal="HUP") { - /**************************************************************/ - /* This function sends the passed SIGNAL to the Barnyard2 */ - /* instance on the passed interface to cause Barnyard to */ - /* reload and parse the running configuration without */ - /* impacting packet processing. It also executes the reload */ - /* as a background process and returns control immediately */ - /* to the caller. */ - /* */ - /* $signal = HUP (default) parses and reloads config. */ - /**************************************************************/ + /*************************************************************/ + /* This function sends the passed SIGNAL to the Barnyard2 */ + /* instance on the passed interface to cause Barnyard to */ + /* reload and parse the running configuration without */ + /* impacting packet processing. It also executes the reload */ + /* as a background process and returns control immediately */ + /* to the caller. */ + /* */ + /* $signal = HUP (default) parses and reloads config. */ + /*************************************************************/ global $g; $snortdir = SNORTDIR; @@ -612,7 +704,7 @@ function snort_barnyard_reload_config($snortcfg, $signal="HUP") { /* we can find a valid PID for the process. */ /******************************************************/ if (isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) { - log_error("[Snort] Barnyard2 CONFIG RELOAD initiated for {$snortcfg['descr']} ({$if_real})..."); + log_error("[Snort] Barnyard2 CONFIG RELOAD initiated for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})..."); mwexec_bg("/bin/pkill -{$signal} -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); } } @@ -664,14 +756,79 @@ function snort_Getdirsize($node) { return substr( $blah, 0, strpos($blah, 9) ); } +function snort_cron_job_exists($crontask, $match_time=FALSE, $minute="0", $hour="*", $monthday="*", $month="*", $weekday="*", $who="root") { + + /************************************************************ + * This function iterates the cron[] array in the config * + * to determine if the passed $crontask entry exists. It * + * returns TRUE if the $crontask already exists, or FALSE * + * if there is no match. * + * * + * The $match_time flag, when set, causes a test of the * + * configured task execution times along with the task * + * when checking for a match. * + * * + * We use this to prevent unneccessary config writes if * + * the $crontask already exists. * + ************************************************************/ + + global $config, $g; + + if (!is_array($config['cron'])) + $config['cron'] = array(); + if (!is_array($config['cron']['item'])) + $config['cron']['item'] = array(); + + foreach($config['cron']['item'] as $item) { + if(strpos($item['command'], $crontask) !== FALSE) { + if ($match_time) { + if ($item['minute'] != $minute) + return FALSE; + if ($item['hour'] != $hour) + return FALSE; + if ($item['mday'] != $monthday) + return FALSE; + if ($item['month'] != $month) + return FALSE; + if ($item['wday'] != $weekday) + return FALSE; + if ($item['who'] != $who) + return FALSE; + } + return TRUE; + } + } + return FALSE; +} + function snort_snortloglimit_install_cron($should_install=TRUE) { + // See if simply removing existing "loglimit" job for Snort + if ($should_install == FALSE) { + if (snort_cron_job_exists("snort/snort_check_cron_misc.inc", FALSE)) + install_cron_job("snort_check_cron_misc.inc", false); + return; + } + + // If there are no changes in the cron job command string from the existing job, then exit. + if ($should_install && snort_cron_job_exists("/usr/local/pkg/snort/snort_check_cron_misc.inc", TRUE, "*/5")) + return; + + // Else install the new or updated cron job install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_cron_misc.inc", $should_install, "*/5"); } function snort_rm_blocked_install_cron($should_install) { global $config, $g; + // See if simply removing existing "expiretable" job for Snort + if ($should_install == FALSE) { + if (snort_cron_job_exists("snort2c", FALSE)) + install_cron_job("snort2c", false); + return; + } + + // Grab the configured interval from our configuration $snort_rm_blocked_info_ck = $config['installedpackages']['snortglobal']['rm_blocked']; if ($snort_rm_blocked_info_ck == "15m_b") { @@ -755,13 +912,15 @@ function snort_rm_blocked_install_cron($should_install) { $snort_rm_blocked_expire = "2419200"; } - // First remove any existing "expiretable" jobs for Snort. - install_cron_job("snort2c", false); + // Construct the basic cron command task + $command = "/usr/bin/nice -n20 /sbin/pfctl -q -t snort2c -T expire {$snort_rm_blocked_expire}"; + + // If there are no changes in the cron job command string from the existing job, then exit. + if (snort_cron_job_exists($command, TRUE, $snort_rm_blocked_min, $snort_rm_blocked_hr, $snort_rm_blocked_mday, $snort_rm_blocked_month, $snort_rm_blocked_wday, "root")) + return; - // Now either install the new or updated cron job, - // or return if "rm_blocked" is disabled + // Else install the new or updated cron job if ($should_install) { - $command = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t $snort_rm_blocked_expire snort2c"; install_cron_job($command, $should_install, $snort_rm_blocked_min, $snort_rm_blocked_hr, $snort_rm_blocked_mday, $snort_rm_blocked_month, $snort_rm_blocked_wday, "root"); } } @@ -770,6 +929,15 @@ function snort_rm_blocked_install_cron($should_install) { function snort_rules_up_install_cron($should_install) { global $config, $g; + // If called with FALSE as argument, then we're removing + // the existing job. + if ($should_install == FALSE) { + if (snort_cron_job_exists("snort_check_for_rule_updates.php", FALSE)) + install_cron_job("snort_check_for_rule_updates.php", false); + return; + } + + // Grab the configured update interval from our configuration $snort_rules_up_info_ck = $config['installedpackages']['snortglobal']['autorulesupdate7']; /* See if a customized start time has been set for rule file updates */ @@ -833,8 +1001,16 @@ function snort_rules_up_install_cron($should_install) { $snort_rules_up_wday = "*"; } - $command = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/www/snort/snort_check_for_rule_updates.php"; - install_cron_job($command, $should_install, $snort_rules_up_min, $snort_rules_up_hr, $snort_rules_up_mday, $snort_rules_up_month, $snort_rules_up_wday, "root"); + // Construct the basic cron command task + $command = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_for_rule_updates.php"; + + // If there are no changes in the cron job command string from the existing job, then exit + if (snort_cron_job_exists($command, TRUE, $snort_rules_up_min, $snort_rules_up_hr, $snort_rules_up_mday, $snort_rules_up_month, $snort_rules_up_wday, "root")) + return; + + // Else install the new or updated cron job + if ($should_install) + install_cron_job($command, $should_install, $snort_rules_up_min, $snort_rules_up_hr, $snort_rules_up_mday, $snort_rules_up_month, $snort_rules_up_wday, "root"); } /* Only run when all ifaces needed to sync. Expects filesystem rw */ @@ -845,32 +1021,30 @@ function sync_snort_package_config() { $snortdir = SNORTDIR; $rcdir = RCFILEPREFIX; - conf_mount_rw(); - /* 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'])) { - @unlink("{$rcdir}/snort.sh"); - conf_mount_ro(); return; } $snortconf = $config['installedpackages']['snortglobal']['rule']; foreach ($snortconf as $value) { - $if_real = get_real_interface($value['interface']); + /* Skip configuration of any disabled interface */ + if ($value['enable'] != 'on') + continue; - /* create a snort.conf file for interface */ + /* create a snort.conf file for interface */ snort_generate_conf($value); - /* create barnyard2.conf file for interface */ + /* create barnyard2.conf file for interface */ if ($value['barnyard_enable'] == 'on') - snort_generate_barnyard2_conf($value, $if_real); + snort_generate_barnyard2_conf($value, get_real_interface($value['interface'])); } - /* create snort bootup file snort.sh only create once */ - snort_create_rc(); - $snortglob = $config['installedpackages']['snortglobal']; + /* create snort bootup file snort.sh */ + snort_create_rc(); + snort_snortloglimit_install_cron(true); /* set the snort block hosts time IMPORTANT */ @@ -879,13 +1053,9 @@ function sync_snort_package_config() { /* set the snort rules update time */ snort_rules_up_install_cron($snortglob['autorulesupdate7'] != "never_up" ? true : false); - configure_cron(); - /* Do not attempt package sync if reinstalling package or booting */ if (!$g['snort_postinstall'] && !$g['booting']) snort_sync_on_changes(); - - conf_mount_ro(); } function snort_build_sid_msg_map($rules_path, $sid_file) { @@ -1121,11 +1291,11 @@ function snort_load_rules_map($rules_path) { if (empty($rules_path)) return $map_ref; - /*************************************************************** + /************************************************************************************ * Read all the rules into the map array. * The structure of the map array is: * - * map[gid][sid]['rule']['category']['disabled']['action']['flowbits'] + * map[gid][sid]['rule']['category']['action']['disabled']['managed']['flowbits'] * * where: * gid = Generator ID from rule, or 1 if general text @@ -1133,12 +1303,14 @@ function snort_load_rules_map($rules_path) { * sid = Signature ID from rule * rule = Complete rule text * category = File name of file containing the rule + * action = alert, drop, reject or pass * disabled = 1 if rule is disabled (commented out), 0 if * rule is enabled - * action = alert|log|pass|drop|reject|sdrop + * managed = 1 if rule is auto-managed by SID MGMT process, + * 0 if not auto-managed * flowbits = Array of applicable flowbits if rule contains * flowbits options - ***************************************************************/ + ************************************************************************************/ /* First check if we were passed a directory, a single file */ /* or an array of filenames to read. Set our $rule_files */ @@ -1625,7 +1797,7 @@ function snort_write_enforcing_rules_file($rule_map, $rule_path) { /* rules file will be written. */ /************************************************/ - $rule_file = "/" . ENFORCING_RULES_FILENAME; + $rule_file = "/" . SNORT_ENFORCING_RULES_FILENAME; /* See if we were passed a directory or full */ /* filename to write the rules to, and adjust */ @@ -1661,6 +1833,854 @@ function snort_write_enforcing_rules_file($rule_map, $rule_path) { } } +function snort_parse_sidconf_file($sidconf_file) { + + /**********************************************/ + /* This function loads and processes the file */ + /* specified by '$sidconf_file'. The file is */ + /* assumed to contain valid instructions for */ + /* matching rule SIDs as supported by the */ + /* Oinkmaster and PulledPork utilities. */ + /* */ + /* $sidconf_file ==> full path and name of */ + /* file to process */ + /* */ + /* Returns ==> an array containing */ + /* SID modifier tokens */ + /**********************************************/ + + $buf = ""; + $sid_mods = array(); + + $fd = fopen("{$sidconf_file}", "r"); + if ($fd == FALSE) { + log_error("[Snort] Failed to open SID MGMT file '{$sidconf_file}' for processing."); + return $sid_mods; + } + + // Read and parse the conf file line-by-line + while (($buf = fgets($fd)) !== FALSE) { + $line = array(); + + // Skip any lines that may be just spaces. + if (trim($buf, " \r\n") == "") + continue; + + // Skip line with leading "#" since it's a comment + if (preg_match('/^\s*#/', $buf)) + continue; + + // Trim off any trailing comment + $line = explode("#", $buf); + + // Trim leading and trailing spaces plus newline and any carriage returns + $buf = trim($line[0], ' \r\n'); + + // Now split the SID mod arguments at the commas, if more than one + // per line, and add to our $sid_mods array. + $line = explode(",", $buf); + foreach ($line as $ent) + $sid_mods[] = trim($ent); + } + + // Close the file, release unneeded memory and return + // the array of SID mod tokens parsed from the file. + fclose($fd); + unset($line, $buf); + return $sid_mods; +} + +function snort_sid_mgmt_auto_categories($snortcfg, $log_results = FALSE) { + + /****************************************************/ + /* This function parses any auto-SID conf files */ + /* configured for the interface and returns an */ + /* array of rule categories adjusted from the */ + /* ['enabled_rulesets'] element in the config for */ + /* the interface in accordance with the contents */ + /* of the SID Mgmt conf files. */ + /* */ + /* The returned array shows which files should be */ + /* removed and which should be added to the list */ + /* used when building the enforcing ruleset. */ + /* */ + /* $snortcfg ==> pointer to interface */ + /* configuration info */ + /* $log_results ==> [optional] log results to */ + /* 'sid_changes.log' in the */ + /* interface directory in */ + /* /var/log/snort when TRUE */ + /* */ + /* Returns ==> array of category file names */ + /* for the interface. The keys */ + /* are category file names and */ + /* the corresponding values show */ + /* if the file should be added */ + /* or removed from the enabled */ + /* rulesets list. */ + /* */ + /* Example - */ + /* $changes[file] = 'enabled' */ + /* */ + /****************************************************/ + + global $config; + $snort_sidmods_dir = SNORT_SID_MODS_PATH; + $sid_mods = array(); + $enables = array(); + $disables = array(); + + // Check if auto-mgmt of SIDs is enabled, exit if not + if ($config['installedpackages']['snortglobal']['auto_manage_sids'] != 'on') + return array(); + if (empty($snortcfg['disable_sid_file']) && empty($snortcfg['enable_sid_file'])) + return array(); + + // Configure the interface's logging subdirectory if log results is enabled + if ($log_results == TRUE) + $log_file = SNORTLOGDIR . "/snort_" . get_real_interface($snortcfg['interface']) . "{$snortcfg['uuid']}/sid_changes.log"; + else + $log_file = NULL; + + // Get the list of currently enabled categories for the interface + if (!empty($snortcfg['rulesets'])) + $enabled_cats = explode("||", $snortcfg['rulesets']); + + if ($log_results == TRUE) { + error_log(gettext("********************************************************\n"), 3, $log_file); + error_log(gettext("Starting auto RULE CATEGORY management for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) ."\n"), 3, $log_file); + error_log(gettext("Start Time: " . date("Y-m-d H:i:s") . "\n"), 3, $log_file); + } + + switch ($snortcfg['sid_state_order']) { + case "disable_enable": + if (!empty($snortcfg['disable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing disable_sid file: {$snortcfg['disable_sid_file']}\n"), 3, $log_file); + + // Attempt to open the 'disable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'disable_sid_file' \"{$snortcfg['disable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) + error_log(gettext("Unable to open disable_sid file \"{$snortcfg['disable_sid_file']}\".\n"), 3, $log_file); + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}"); + + if (!empty($sid_mods)) + $disables = snort_get_auto_category_mods($enabled_cats, $sid_mods, "disable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['disable_sid_file']}\".\n"), 3, $log_file); + } + } + if (!empty($snortcfg['enable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing enable_sid file: {$snortcfg['enable_sid_file']}\n"), 3, $log_file); + + // Attempt to open the 'enable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'enable_sid_file' \"{$snortcfg['enable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) + error_log(gettext("Unable to open enable_sid file \"{$snortcfg['enable_sid_file']}\".\n"), 3, $log_file); + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}"); + + if (!empty($sid_mods)) + $enables = snort_get_auto_category_mods($enabled_cats, $sid_mods, "enable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['enable_sid_file']}\".\n"), 3, $log_file); + } + } + break; + + case "enable_disable": + if (!empty($snortcfg['enable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing enable_sid file: {$snortcfg['enable_sid_file']}\n"), 3, $log_file); + + // Attempt to open the 'enable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'enable_sid_file' \"{$snortcfg['enable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) + error_log(gettext("Unable to open enable_sid file \"{$snortcfg['enable_sid_file']}\".\n"), 3, $log_file); + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}"); + + if (!empty($sid_mods)) + $enables = snort_get_auto_category_mods($enabled_cats, $sid_mods, "enable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['enable_sid_file']}\".\n"), 3, $log_file); + } + } + if (!empty($snortcfg['disable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing disable_sid file: {$snortcfg['disable_sid_file']}\n"), 3, $log_file); + + // Attempt to open the 'disable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'disable_sid_file' \"{$snortcfg['disable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) + error_log(gettext("Unable to open disable_sid file \"{$snortcfg['disable_sid_file']}\".\n"), 3, $log_file); + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}"); + + if (!empty($sid_mods)) + $disables = snort_get_auto_category_mods($enabled_cats, $sid_mods, "disable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['disable_sid_file']}\".\n"), 3, $log_file); + } + } + break; + + default: + log_error(gettext("[Snort] Unrecognized 'sid_state_order' value. Skipping auto CATEGORY mgmt step for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) { + error_log(gettext("ERROR: unrecognized 'sid_state_order' value. Skipping auto CATEGORY mgmt step for ") . convert_friendly_interface_to_friendly_descr($snortcfg['interface']). ".\n", 3, $log_file); + } + } + + if ($log_results == TRUE) { + error_log(gettext("End Time: " . date("Y-m-d H:i:s") . "\n"), 3, $log_file); + error_log(gettext("********************************************************\n\n"), 3, $log_file); + } + + // Return the required rule category modifications as an array; + return array_merge($enables, $disables); +} + +function snort_get_auto_category_mods($categories, $sid_mods, $action, $log_results = FALSE, $log_file = NULL) { + + /****************************************************/ + /* This function parses the provided SID mod tokens */ + /* in $sid_mods and returns an array of category */ + /* files that must be added ('enabled') or removed */ + /* ('disabled') from the provided $categories list */ + /* of enabled rule categories as determined by the */ + /* content of the SID Mgmt tokens in $sid_mods. */ + /* */ + /* The returned array shows which files should be */ + /* removed and which should be added to the list */ + /* used when building the enforcing ruleset. */ + /* */ + /* $categories ==> array of currently enabled */ + /* ruleset categories */ + /* $sid_mods ==> array of SID modification */ + /* tokens */ + /* $action ==> modification action for */ + /* matching category targets: */ + /* 'enable' or 'disable' */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename of log */ + /* file to write to */ + /* */ + /* Returns ==> array of category file names */ + /* for the interface. The keys */ + /* are category file names and */ + /* the corresponding values show */ + /* if the file should be added */ + /* or removed from the enabled */ + /* rulesets list. */ + /* */ + /* Example - */ + /* $changes[file] = 'enabled' */ + /* */ + /****************************************************/ + + $snortdir = SNORTDIR; + $all_cats = array(); + $changes = array(); + $counter = 0; + $matchcount = 0; + + // Get a list of all possible categories by loading all rules files + foreach (array( VRT_FILE_PREFIX, ET_OPEN_FILE_PREFIX, ET_PRO_FILE_PREFIX, GPL_FILE_PREFIX ) as $prefix) { + $files = glob("{$snortdir}/rules/{$prefix}*.rules"); + foreach ($files as $file) + $all_cats[] = basename($file); + } + + // Walk the SID mod tokens and decode looking for rule + // category enable/disable changes. + foreach ($sid_mods as $tok) { + $matches = array(); + // Test the SID token for a GID:SID range and skip if true + if (preg_match('/^(\d+):(\d+)-\1:(\d+)/', $tok)) + continue; + // Test the token for a single GID:SID and skip if true + elseif (preg_match('/^(\d+):(\d+)$/', $tok)) + continue; + // Test the token for the PCRE: keyword and skip if true + elseif (preg_match('/(^pcre\:)(.+)/i', $tok)) + continue; + // Test the token for the MS reference keyword and skip if true + elseif (preg_match('/^MS\d+-.+/i', $tok)) + continue; + // Test the token for other keywords delimited with a colon and skip if true + elseif (preg_match('/^[a-xA-X]+\:.+/', $tok)) + continue; + // Test the SID token for a rule category name. Anything that + // failed to match above is considered a potential category name. + elseif (preg_match('/[a-xA-X]+(-|\w).*/', $tok, $matches)) { + $counter++; + $regex = "/" . preg_quote(trim($matches[0]), '/') . "/i"; + // Search through the $all_cats array for any matches to the regex + $matches = preg_grep($regex, $all_cats); + + // See if any matches are in the $categories array + foreach ($matches as $cat) { + switch ($action) { + case 'enable': + if (!isset($changes[$cat])) { + $changes[$cat] = 'enabled'; + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext(" Enabled rule category: {$cat}\n"), 3, $log_file); + $matchcount++; + } + break; + + case 'disable': + if (!isset($changes[$cat])) { + $changes[$cat] = 'disabled'; + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext(" Disabled rule category: {$cat}\n"), 3, $log_file); + $matchcount++; + } + break; + + default: + break; + } + } + } + else { + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext("WARNING: unrecognized token '{$tok}' encountered while processing an automatic SID MGMT file.\n"), 3, $log_file); + } + } + + if ($log_results == TRUE && !empty($log_file)) { + error_log(gettext(" Parsed {$counter} potential Rule Categories to match from the list of tokens.\n"), 3, $log_file); + error_log(gettext(" " . ucfirst($action) . "d {$matchcount} matching Rule Categories.\n"), 3, $log_file); + } + + // Release memory no longer needed + unset($all_cats, $matches); + + // Return array of rule category file changes + return $changes; +} + +function snort_modify_sid_state(&$rule_map, $sid_mods, $action, $log_results = FALSE, $log_file = NULL) { + + /**********************************************/ + /* This function walks the provided array of */ + /* SID modification tokens and locates the */ + /* target SID or SIDs in the $rule_map array. */ + /* It then performs the change specified by */ + /* $action on the target SID or SIDs. */ + /* */ + /* $rule_map ==> reference to array of */ + /* current rules */ + /* $sid_mods ==> array of SID modification */ + /* tokens */ + /* $action ==> modification action for */ + /* matching SID targets: */ + /* 'enable' or 'disable' */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename */ + /* of log file to write to */ + /* */ + /* On Return ==> $rule_map array modified */ + /* by changing state for */ + /* matching SIDs. */ + /* */ + /* Returns a two-dimension */ + /* array of matching GID:SID */ + /* pairs. */ + /**********************************************/ + + $sids = array(); + + // If no rules in $rule_map or mods in $sid_mods, + // then nothing to do. + if (empty($rule_map) || empty($sid_mods)) + return $sids; + + // Validate the action keyword as we only accept + // 'enable' and 'disable' as valid. + switch ($action) { + + case "enable": + break; + + case "disable": + break; + + default: + log_error(gettext("[Snort] Error - unknown action '{$action}' supplied to snort_modify_sid_state() function...no SIDs modified.")); + return $sids; + } + + // Walk the SID mod tokens and decode each one + foreach ($sid_mods as $tok) { + $matches = array(); + // Test the SID token for a GID:SID range + if (preg_match('/^(\d+):(\d+)-\1:(\d+)/', $tok, $matches)) { + // It was a range, so find all the intervening SIDs + $gid = trim($matches[1]); + $lsid = trim($matches[2]); + $usid = trim($matches[3]); + $sids[$gid][$lsid] = $action; + while ($lsid < $usid) { + $lsid++; + $sids[$gid][$lsid] = $action; + } + } + // Test the SID token for a single GID:SID + elseif (preg_match('/^(\d+):(\d+)$/', $tok, $matches)) { + // It's a single GID:SID, so grab it + $sids[$matches[1]][$matches[2]] = $action; + } + // Test the SID token for the PCRE: keyword + elseif (preg_match('/(^pcre\:)(.+)/i', $tok, $matches)) { + $regex = '/' . preg_quote($matches[2], '/') . '/i'; + + // Now search through the $rule_map in the 'rule' + // element for any matches to the regex and get + // the GID:SID. + foreach ($rule_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + if (preg_match($regex, $v['rule'])) { + $sids[$k1][$k2] = $action; + } + } + } + } + // Test the SID token for the MS reference keyword + elseif (preg_match('/^MS\d+-.+/i', $tok, $matches)) { + $regex = "/" . preg_quote($matches[0], '/') . "/i"; + + // Now search through the $rule_map in the 'rule' + // element for any matches to the regex and get + // the GID:SID. + foreach ($rule_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + if (preg_match($regex, $v['rule'])) { + $sids[$k1][$k2] = $action; + } + } + } + } + // Test the SID token for other keywords delimited with a colon + elseif (preg_match('/^[a-xA-X]+\:.+/', $tok, $matches)) { + $regex = "/" . str_replace(':', ",", preg_quote($matches[0], '/')) . "/i"; + + // Now search through the $rule_map in the 'rule' + // element for any matches to the regex and get + // the GID:SID. + foreach ($rule_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + if (preg_match($regex, $v['rule'])) { + $sids[$k1][$k2] = $action; + } + } + } + } + // Test the SID token for a rule category name. Anything that + // failed to match above is considered a potential category name. + elseif (preg_match('/[a-xA-X]+(-|\w).*/', $tok, $matches)) { + $regex = "/" . preg_quote(trim($matches[0]), '/') . "/i"; + // Now search through the $rule_map in the 'category' + // element for any matches to the regex and get + // the GID:SID. + foreach ($rule_map as $k1 => $rulem) { + foreach ($rulem as $k2 => $v) { + if (preg_match($regex, $v['category'] . ".rules")) { + $sids[$k1][$k2] = $action; + } + } + } + } + else { + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext("WARNING: unrecognized token '{$tok}' encountered while processing an automatic SID MGMT file.\n"), 3, $log_file); + } + } + + // Change state of all the matching GID:SID pairs we found + // above in the $rule_map array passed to us. + $modcount = $changecount = 0; + $counter = count($sids, COUNT_RECURSIVE) - count($sids); + + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext(" Parsed {$counter} potential SIDs to match from the provided list of tokens.\n"), 3, $log_file); + + foreach (array_keys($sids) as $k1) { + foreach (array_keys($sids[$k1]) as $k2) { + if (isset($rule_map[$k1][$k2])) { + if ($action == 'enable' && $rule_map[$k1][$k2]['disabled'] == 1) { + $rule_map[$k1][$k2]['rule'] = ltrim($rule_map[$k1][$k2]['rule'], " \t#"); + $rule_map[$k1][$k2]['disabled'] = 0; + $rule_map[$k1][$k2]['managed'] = 1; + $changecount++; + $modcount++; + } + elseif ($action == 'disable' && $rule_map[$k1][$k2]['disabled'] == 0) { + $rule_map[$k1][$k2]['rule'] = "# " . $rule_map[$k1][$k2]['rule']; + $rule_map[$k1][$k2]['disabled'] = 1; + $rule_map[$k1][$k2]['managed'] = 1; + $changecount++; + $modcount++; + } + } + } + } + + if ($log_results == TRUE && !empty($log_file)) { + error_log(gettext(" Found {$modcount} matching SIDs in the active rules.\n"), 3, $log_file); + error_log(gettext(" Changed state for {$changecount} SIDs to '{$action}d'.\n"), 3, $log_file); + } + + // Return the array of matching SIDs + return $sids; +} + +function snort_modify_sid_content(&$rule_map, $sid_mods, $log_results = FALSE, $log_file = NULL) { + + /************************************************/ + /* This function walks the provided array of */ + /* SID modification tokens and locates the */ + /* target SID or SIDs in the $rule_map array. */ + /* It then modifies the content of the target */ + /* SID or SIDs. Modifications are only valid */ + /* for normal GID=1 text rules. */ + /* */ + /* $rule_map ==> reference to array of */ + /* current rules */ + /* $sid_mods ==> array of SID modification */ + /* tokens */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename */ + /* of log file to write to */ + /* */ + /* On Return ==> $rule_map array modified */ + /* by changing content for */ + /* matching SIDs. */ + /* */ + /* Returns a two-dimension */ + /* array of matching */ + /* GID:SID pairs. */ + /************************************************/ + + $sids = array(); + $tokencounter = $modcount = $modifiedcount = 0; + + // If no rules in $rule_map or mods in $sid_mods, + // then nothing to do. + if (empty($rule_map) || empty($sid_mods)) + return $sids; + + // Walk the SID mod tokens and decode each one + foreach ($sid_mods as $tok) { + $matches = array(); + if (preg_match('/([\d+|,|\*]*)\s+"(.+)"\s+"(.*)"/', $tok, $matches)) { + $tokencounter++; + $sidlist = explode(",", $matches[1]); + $from = '/' . preg_quote($matches[2], '/') . '/'; + $to = $matches[3]; + $count = 0; + + // Now walk the provided rule map and make the modifications + if ($matches[1] == "*") { + // If wildcard '*' provided for SID, then check them all + foreach ($rule_map[1] as $rulem) { + foreach ($rulem as $k2 => $v) { + $modcount++; + $rule_map[1][$k2]['rule'] = preg_replace($from, $to, $v['rule'], -1, $count); + if ($count > 0) { + $rule_map[1][$k2]['managed'] = 1; + $sids[1][$k2] = 'modify'; + $modifiedcount++; + } + } + } + } + else { + // Otherwise just check the provided SIDs + foreach ($sidlist as $sid) { + if (isset($rule_map[1][$sid])) { + $modcount++; + $rule_map[1][$sid]['rule'] = preg_replace($from, $to, $rule_map[1][$sid]['rule'], -1, $count); + if ($count > 0) { + $rule_map[1][$sid]['managed'] = 1; + $sids[1][$sid] = 'modify'; + $modifiedcount++; + } + } + } + } + } + else { + if ($log_results == TRUE && !empty($log_file)) + error_log(gettext("WARNING: unrecognized token '{$tok}' encountered while processing an automatic SID MGMT file.\n"), 3, $log_file); + } + } + + if ($log_results == TRUE && !empty($log_file)) { + error_log(gettext(" Parsed {$tokencounter} potential SIDs to match from the provided list of tokens.\n"), 3, $log_file); + error_log(gettext(" Found {$modcount} matching SIDs in the active rules.\n"), 3, $log_file); + error_log(gettext(" Modified rule text for {$modifiedcount} SIDs.\n"), 3, $log_file); + } + + // Return the array of matching SIDs + return $sids; +} + +function snort_process_enablesid(&$rule_map, $snortcfg, $log_results = FALSE, $log_file = NULL) { + + /**********************************************/ + /* This function loads and processes the file */ + /* specified by 'enable_sid_file' for the */ + /* interface. The file is assumed to be a */ + /* valid enablesid.conf file containing */ + /* instructions for enabling matching rule */ + /* SIDs. */ + /* */ + /* $rule_map ==> reference to array of */ + /* current rules */ + /* $snortcfg ==> interface config params */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename */ + /* of log file to write to */ + /* */ + /* On Return ==> suitably modified */ + /* $rule_map array */ + /**********************************************/ + + $snort_sidmods_dir = SNORT_SID_MODS_PATH; + $snortlogdir = SNORTLOGDIR; + $sid_mods = array(); + + // If no rules in $rule_map, then nothing to do + if (empty($rule_map)) + return; + + // Attempt to open the 'enable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'enable_sid_file' \"{$snortcfg['enable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + return; + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['enable_sid_file']}"); + + if (!empty($sid_mods)) + snort_modify_sid_state($rule_map, $sid_mods, "enable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['enable_sid_file']}\".\n"), 3, $log_file); + } + + unset($sid_mods); +} + +function snort_process_disablesid(&$rule_map, $snortcfg, $log_results = FALSE, $log_file = NULL) { + + /**********************************************/ + /* This function loads and processes the file */ + /* specified by 'disable_sid_file' for the */ + /* interface. The file is assumed to be a */ + /* valid disablesid.conf file containing */ + /* instructions for disabling matching rule */ + /* SIDs. */ + /* */ + /* $rule_map ==> reference to array of */ + /* current rules */ + /* $snortcfg ==> interface config params */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename */ + /* of log file to write to */ + /* */ + /* On Return ==> suitably modified */ + /* $rule_map array */ + /**********************************************/ + + $snort_sidmods_dir = SNORT_SID_MODS_PATH; + $snortlogdir = SNORTLOGDIR; + $sid_mods = array(); + + // If no rules in $rule_map, then nothing to do + if (empty($rule_map)) + return; + + // Attempt to open the 'disable_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'disable_sid_file' \"{$snortcfg['disable_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + return; + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['disable_sid_file']}"); + + if (!empty($sid_mods)) + snort_modify_sid_state($rule_map, $sid_mods, "disable", $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['disable_sid_file']}\".\n"), 3, $log_file); + } + + unset($sid_mods); +} + +function snort_process_modifysid(&$rule_map, $snortcfg, $log_results = FALSE, $log_file = NULL) { + + /**********************************************/ + /* This function loads and processes the file */ + /* specified by 'modify_sid_file' for the */ + /* interface. The file is assumed to be a */ + /* valid modifysid.conf file containing */ + /* instructions for modifying matching rule */ + /* SIDs. */ + /* */ + /* $rule_map ==> reference to array of */ + /* current rules */ + /* $snortcfg ==> interface config params */ + /* $log_results ==> [optional] 'yes' to log */ + /* results to $log_file */ + /* $log_file ==> full path and filename */ + /* of log file to write to */ + /* */ + /* On Return ==> suitably modified */ + /* $rule_map array */ + /**********************************************/ + + $snort_sidmods_dir = SNORT_SID_MODS_PATH; + $snortlogdir = SNORTLOGDIR; + $sid_mods = array(); + + // If no rules in $rule_map, then nothing to do + if (empty($rule_map)) + return; + + // Attempt to open the 'modify_sid_file' for the interface + if (!file_exists("{$snort_sidmods_dir}{$snortcfg['modify_sid_file']}")) { + log_error(gettext("[Snort] Error - unable to open 'modify_sid_file' \"{$snortcfg['modify_sid_file']}\" specified for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + return; + } + else + $sid_mods = snort_parse_sidconf_file("{$snort_sidmods_dir}{$snortcfg['modify_sid_file']}"); + + if (!empty($sid_mods)) + snort_modify_sid_content($rule_map, $sid_mods, $log_results, $log_file); + elseif ($log_results == TRUE && !empty($log_file)) { + error_log(gettext("WARNING: no valid SID match tokens found in file \"{$snortcfg['modify_sid_file']}\".\n"), 3, $log_file); + } + + unset($sid_mods); +} + +function snort_auto_sid_mgmt(&$rule_map, $snortcfg, $log_results = FALSE) { + + /**************************************************/ + /* This function modifies the rules in the */ + /* passed rule_map array based on values in the */ + /* files 'enable_sid_file', 'disable_sid_file' */ + /* and 'modify_sid_file' for the interface. */ + /* */ + /* If auto-mgmt of SIDs is enabled via the */ + /* settings on the UPDATE RULES tab, then the */ + /* rules are processed against these settings. */ + /* */ + /* $rule_map ==> array of current rules */ + /* $snortcfg ==> interface config settings */ + /* $log_results ==> [optional] log results to */ + /* 'sid_changes.log' in the */ + /* interface directory in */ + /* /var/log/snort when TRUE */ + /* */ + /* Returns ==> TRUE if rules were changed; */ + /* otherwise FALSE */ + /**************************************************/ + + global $config; + $result = FALSE; + + // Configure the interface's logging subdirectory if log results is enabled + if ($log_results == TRUE) + $log_file = SNORTLOGDIR . "/snort_" . get_real_interface($snortcfg['interface']) . "{$snortcfg['uuid']}/sid_changes.log"; + else + $log_file = NULL; + + // Check if auto-mgmt of SIDs is enabled and files are specified + // for the interface. + if ($config['installedpackages']['snortglobal']['auto_manage_sids'] == 'on' && + (!empty($snortcfg['disable_sid_file']) || !empty($snortcfg['enable_sid_file']) || + !empty($snortcfg['modify_sid_file']))) { + if ($log_results == TRUE) { + error_log(gettext("********************************************************\n"), 3, $log_file); + error_log(gettext("Starting auto SID management for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) ."\n"), 3, $log_file); + error_log(gettext("Start Time: " . date("Y-m-d H:i:s") . "\n"), 3, $log_file); + } + + switch ($snortcfg['sid_state_order']) { + case "disable_enable": + if (!empty($snortcfg['disable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing disable_sid file: {$snortcfg['disable_sid_file']}\n"), 3, $log_file); + snort_process_disablesid($rule_map, $snortcfg, $log_results, $log_file); + } + if (!empty($snortcfg['enable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing enable_sid file: {$snortcfg['enable_sid_file']}\n"), 3, $log_file); + snort_process_enablesid($rule_map, $snortcfg, $log_results, $log_file); + } + if (!empty($snortcfg['modify_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing modify_sid file: {$snortcfg['modify_sid_file']}\n"), 3, $log_file); + snort_process_modifysid($rule_map, $snortcfg, $log_results, $log_file); + } + $result = TRUE; + break; + + case "enable_disable": + if (!empty($snortcfg['enable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing enable_sid file: {$snortcfg['enable_sid_file']}\n"), 3, $log_file); + snort_process_enablesid($rule_map, $snortcfg, $log_results, $log_file); + } + if (!empty($snortcfg['disable_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing disable_sid file: {$snortcfg['disable_sid_file']}\n"), 3, $log_file); + snort_process_disablesid($rule_map, $snortcfg, $log_results, $log_file); + } + if (!empty($snortcfg['modify_sid_file'])) { + if ($log_results == TRUE) + error_log(gettext("Processing modify_sid file: {$snortcfg['modify_sid_file']}\n"), 3, $log_file); + snort_process_modifysid($rule_map, $snortcfg, $log_results, $log_file); + } + $result = TRUE; + break; + + default: + log_error(gettext("[Snort] Unrecognized 'sid_state_order' value. Skipping auto SID mgmt step for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']))); + if ($log_results == TRUE) { + error_log(gettext("ERROR: unrecognized 'sid_state_order' value. Skipping auto SID mgmt step for ") . convert_friendly_interface_to_friendly_descr($snortcfg['interface']). ".\n", 3, $log_file); + } + $result = FALSE; + } + + if ($log_results == TRUE) { + error_log(gettext("End Time: " . date("Y-m-d H:i:s") . "\n"), 3, $log_file); + error_log(gettext("********************************************************\n\n"), 3, $log_file); + } + } + return $result; +} + function snort_load_sid_mods($sids) { /*****************************************/ @@ -1686,11 +2706,12 @@ function snort_load_sid_mods($sids) { if (preg_match('/(\d+)\s*:\s*(\d+)/', $v, $match)) { if (!is_array($result[$match[1]])) $result[$match[1]] = array(); + if (!is_array($result[$match[1]][$match[2]])) + $result[$match[1]][$match[2]] = array(); $result[$match[1]][$match[2]] = "{$match[1]}:{$match[2]}"; } } unset($tmp); - return $result; } @@ -1751,31 +2772,31 @@ function snort_create_rc() { /* after any changes to snort.conf saved in the GUI. */ /*********************************************************/ - global $config, $g, $pfs_version; + global $config, $g; $snortdir = SNORTDIR; $snortlogdir = SNORTLOGDIR; + $snortbindir = SNORT_PBI_BINDIR; $rcdir = RCFILEPREFIX; - // If no interfaces are configured for Snort, exit - if (!is_array($config['installedpackages']['snortglobal']['rule'])) - return; $snortconf = $config['installedpackages']['snortglobal']['rule']; - if (empty($snortconf)) + + // If no interfaces are configured for Snort, exit + if (!is_array($snortconf) || count($snortconf) < 1) { + unlink_if_exists("{$rcdir}snort.sh"); return; + } + + // See whether or not to enable detailed startup logging + if ($config['installedpackages']['snortglobal']['verbose_logging'] == "on") + $quiet = ""; + else + $quiet = "-q --suppress-config-log"; // At least one interface is configured, so OK $start_snort_iface_start = array(); $start_snort_iface_stop = array(); - // If not using PBI package, then make sure Barnyard2 can - // find the latest MySQL shared libs in /usr/local/lib/mysql - if ($pfs_version < 2.1) { - $sql_lib_path = "\n# Ensure MySQL shared libs are in ldconfig search path\n"; - $sql_lib_path .= "/sbin/ldconfig -m /usr/local/lib/mysql"; - $start_snort_iface_start[] = $sql_lib_path; - } - // Loop thru each configured interface and build // the shell script. foreach ($snortconf as $value) { @@ -1787,19 +2808,16 @@ function snort_create_rc() { $start_barnyard = <<<EOE + sleep 2 if [ ! -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then pid=`/bin/pgrep -fn "barnyard2 -r {$snort_uuid} "` else 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 SOFT RESTART for {$value['descr']}({$snort_uuid}_{$if_real})..." - /bin/pkill -HUP \$pid - else + if [ -z \$pid ]; then /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 {$snortlogdir}/snort_{$if_real}{$snort_uuid} -D -q + {$snortbindir}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 {$snortlogdir}/snort_{$if_real}{$snort_uuid} -D -q > /dev/null 2>&1 fi - EOE; $stop_barnyard2 = <<<EOE @@ -1815,8 +2833,8 @@ EOE; break fi done - if [ -f /var/run/barnyard2_{$if_real}{$snort_uuid}.pid ]; then - /bin/rm /var/run/barnyard2_{$if_real}{$snort_uuid}.pid + if [ -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /bin/rm {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid fi else pid=`/bin/pgrep -fn "barnyard2 -r {$snort_uuid} "` @@ -1832,7 +2850,6 @@ EOE; done fi fi - EOE; if ($value['barnyard_enable'] == 'on') $start_barnyard2 = $start_barnyard; @@ -1841,29 +2858,24 @@ EOE; $start_snort_iface_start[] = <<<EOE -###### For Each Iface - # Start snort and barnyard2 + # Start snort and barnyard2 for {$value['descr']} if [ ! -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then pid=`/bin/pgrep -fn "snort -R {$snort_uuid} "` else pid=`/bin/pgrep -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid` fi - 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 + if [ -z \$pid ]; then /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 {$snortlogdir}/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} + {$snortbindir}snort -R {$snort_uuid} -D {$quiet} -l {$snortlogdir}/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} > /dev/null 2>&1 fi - sleep 2 {$start_barnyard2} - EOE; $start_snort_iface_stop[] = <<<EOE + # Stop snort and barnyard2 for {$value['descr']} 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})..." @@ -1876,8 +2888,8 @@ EOE; break fi done - if [ -f /var/run/snort_{$if_real}{$snort_uuid}.pid ]; then - /bin/rm /var/run/snort_{$if_real}{$snort_uuid}.pid + if [ -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then + /bin/rm {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid fi else pid=`/bin/pgrep -fn "snort -R {$snort_uuid} "` @@ -1895,9 +2907,8 @@ EOE; fi fi - sleep 2 + sleep 1 {$stop_barnyard2} - EOE; } @@ -1909,11 +2920,18 @@ EOE; ######## # This file was automatically generated # by the pfSense service handler. -# Code added to protect from double starts on pfSense bootup ######## Start of main snort.sh rc_start() { + + ### Lock out other start signals until we are done + /usr/bin/touch {$g['varrun_path']}/snort_pkg_starting.lck {$rc_start} + + ### Remove the lock since we have started all interfaces + if [ -f {$g['varrun_path']}/snort_pkg_starting.lck ]; then + /bin/rm {$g['varrun_path']}/snort_pkg_starting.lck + fi } rc_stop() { @@ -1922,7 +2940,11 @@ rc_stop() { case $1 in start) - rc_start + if [ ! -f {$g['varrun_path']}/snort_pkg_starting.lck ]; then + rc_start + else + /usr/bin/logger -p daemon.info -i -t SnortStartup "Ignoring additional START command since Snort is already starting..." + fi ;; stop) rc_stop @@ -1936,11 +2958,8 @@ esac EOD; /* write out snort.sh */ - if (!@file_put_contents("{$rcdir}/snort.sh", $snort_sh_text)) { - log_error("Could not open {$rcdir}/snort.sh for writing."); - return; - } - @chmod("{$rcdir}/snort.sh", 0755); + @file_put_contents("{$rcdir}snort.sh", $snort_sh_text); + @chmod("{$rcdir}snort.sh", 0755); } function snort_generate_barnyard2_conf($snortcfg, $if_real) { @@ -2008,7 +3027,7 @@ function snort_generate_barnyard2_conf($snortcfg, $if_real) { else $snortbarnyardlog_output_plugins .= "sensor_name {$snortbarnyard_hostname_info}, "; if ($snortcfg['barnyard_syslog_local'] == 'on') - $snortbarnyardlog_output_plugins .= "local, log_facility LOG_AUTH, log_priority LOG_INFO\n\n"; + $snortbarnyardlog_output_plugins .= "local, log_facility {$snortcfg['barnyard_syslog_facility']}, log_priority {$snortcfg['barnyard_syslog_priority']}\n\n"; else { $snortbarnyardlog_output_plugins .= "server {$snortcfg['barnyard_syslog_rhost']}, protocol {$snortcfg['barnyard_syslog_proto']}, "; $snortbarnyardlog_output_plugins .= "port {$snortcfg['barnyard_syslog_dport']}, operation_mode {$snortcfg['barnyard_syslog_opmode']}, "; @@ -2066,44 +3085,49 @@ function snort_deinstall() { global $config, $g; $snortdir = SNORTDIR; - $snortlibdir = SNORTLIBDIR; + $snortlibdir = "/usr/pbi/snort-" . php_uname("m") . "/lib"; $snortlogdir = SNORTLOGDIR; $rcdir = RCFILEPREFIX; - $snort_rules_upd_log = RULES_UPD_LOGFILE; - $iprep_path = IPREP_PATH; + $snort_rules_upd_log = SNORT_RULES_UPD_LOGFILE; + $mounted_rw = FALSE; log_error(gettext("[Snort] Snort package uninstall in progress...")); + /* Remove our rc.d startup shell script */ + unlink_if_exists("{$rcdir}snort.sh"); + /* Make sure all active Snort processes are terminated */ /* Log a message only if a running process is detected */ - if (is_service_running("snort")) + if (is_process_running("snort")) { log_error(gettext("[Snort] Snort STOP for all interfaces...")); + snort_stop_all_interfaces(); + } + sleep(2); mwexec('/usr/bin/killall -z snort', true); sleep(2); mwexec('/usr/bin/killall -9 snort', true); sleep(2); // Delete any leftover snort PID files in /var/run - unlink_if_exists("/var/run/snort_*.pid"); + unlink_if_exists("{$g['varrun_path']}/snort_*.pid"); /* Make sure all active Barnyard2 processes are terminated */ /* Log a message only if a running process is detected */ - if (is_service_running("barnyard2")) + if (is_process_running("barnyard2")) log_error(gettext("[Snort] Barnyard2 STOP for all interfaces...")); mwexec('/usr/bin/killall -z barnyard2', true); sleep(2); mwexec('/usr/bin/killall -9 barnyard2', true); sleep(2); // Delete any leftover barnyard2 PID files in /var/run - unlink_if_exists("/var/run/barnyard2_*.pid"); - - /* Remove the snort user and group */ - mwexec('/usr/sbin/pw userdel snort; /usr/sbin/pw groupdel snort', true); + unlink_if_exists("{$g['varrun_path']}/barnyard2_*.pid"); - /* Remove all the Snort cron jobs. */ - install_cron_job("snort2c", false); - install_cron_job("snort_check_for_rule_updates.php", false); - install_cron_job("snort_check_cron_misc.inc", false); - configure_cron(); + /* Remove all the existing Snort cron jobs. */ + if (snort_cron_job_exists("snort2c", FALSE)) + install_cron_job("snort2c", false); + if (snort_cron_job_exists("snort_check_for_rule_updates.php", FALSE)) + install_cron_job("snort_check_for_rule_updates.php", false); + if (snort_cron_job_exists("snort_check_cron_misc.inc", FALSE)) + install_cron_job("snort_check_cron_misc.inc", false); /* Remove our associated Dashboard widget config. If */ /* "save settings" is enabled, then save old widget */ @@ -2121,7 +3145,6 @@ function snort_deinstall() { } } $config['widgets']['sequence'] = implode(",", $widgetlist); - write_config("Snort pkg: remove Snort Dashboard Widget on package deinstall."); } /* See if we are to clear blocked hosts on uninstall */ @@ -2134,29 +3157,35 @@ function snort_deinstall() { if ($config['installedpackages']['snortglobal']['clearlogs'] == 'on') { log_error(gettext("[Snort] Clearing all Snort-related log files...")); unlink_if_exists("{$snort_rules_upd_log}"); - mwexec("/bin/rm -rf {$snortlogdir}"); + rmdir_recursive($snortlogdir); } /**********************************************************/ - /* Test for existence of library backup tarballs in /tmp. */ - /* If these are present, then a package "delete" */ + /* If not already, set Snort conf partition to read-write */ + /* so we can make changes there */ + /**********************************************************/ + if (!is_subsystem_dirty('mount')) { + conf_mount_rw(); + $mounted_rw = TRUE; + } + + /**********************************************************/ + /* Test for existence of the snort directory in the PBI */ + /* path. If not 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")) { + if (!is_dir("{$snortdir}")) { 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"); - mwexec("/bin/rm -rf /usr/local/lib/snort"); + unlink_if_exists("{$rcdir}snort.sh"); + rmdir_recursive("/usr/local/pkg/snort"); + rmdir_recursive("/usr/local/www/snort"); + rmdir_recursive("/usr/local/etc/snort"); + rmdir_recursive("/usr/local/lib/snort"); + rmdir_recursive("/usr/local/lib/snort_dynamicengine"); + rmdir_recursive("/usr/local/lib/snort_dynamicpreprocessor"); } /* Keep this as a last step */ @@ -2167,10 +3196,17 @@ function snort_deinstall() { unlink_if_exists("{$snort_rules_upd_log}"); log_error(gettext("[Snort] Flushing <snort2c> firewall table to remove addresses blocked by Snort...")); mwexec("/sbin/pfctl -t snort2c -T flush"); - mwexec("/bin/rm -rf {$snortlogdir}"); - mwexec("/bin/rm -rf {$iprep_path}"); + rmdir_recursive("{$snortlogdir}"); + rmdir_recursive("{$g['vardb_path']}/snort"); log_error(gettext("[Snort] The package has been removed from this system...")); } + + /**********************************************************/ + /* We're finished with conf partition mods, return to */ + /* read-only if we changed it */ + /**********************************************************/ + if ($mounted_rw == TRUE) + conf_mount_ro(); } function snort_prepare_rule_files($snortcfg, $snortcfgdir) { @@ -2188,11 +3224,14 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { /* to be written. */ /***********************************************************/ - global $g, $rebuild_rules; + global $g, $config, $rebuild_rules; $snortdir = SNORTDIR; $flowbit_rules_file = FLOWBITS_FILENAME; - $snort_enforcing_rules_file = ENFORCING_RULES_FILENAME; + $snort_enforcing_rules_file = SNORT_ENFORCING_RULES_FILENAME; + $enabled_files = array(); + $all_rules = array(); + $cat_mods = array(); $no_rules_defined = true; $enabled_rules = array(); @@ -2203,6 +3242,10 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { /* Log a message for rules rebuild in progress */ log_error(gettext("[Snort] Updating rules configuration for: " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) . " ...")); + // Get any automatic rule category enable/disable modifications + // if auto-SID Mgmt is enabled and conf files exist for the interface. + $cat_mods = snort_sid_mgmt_auto_categories($snortcfg, TRUE); + /* Enable all, some or none of the SDF rules depending on setting. */ if ($snortcfg['sensitive_data'] == 'on' && $snortcfg['protect_preproc_rules'] != 'on') { if (file_exists(SNORTDIR."/preproc_rules/sensitive-data.rules")) { @@ -2229,8 +3272,6 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { /* Only rebuild rules if some are selected or an IPS Policy is enabled */ if (!empty($snortcfg['rulesets']) || $snortcfg['ips_policy_enable'] == 'on') { - $enabled_files = array(); - $all_rules = array(); $no_rules_defined = false; /* Load up all the text rules into a Rules Map array. */ @@ -2246,6 +3287,28 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { $enabled_files[$category] = $file; } + // Now adjust the list using any required changes as + // determined by auto-SID Mgmt policy files. + if (!empty($cat_mods)) { + foreach ($cat_mods as $k => $action) { + $key = basename($k, ".rules"); + switch ($action) { + case 'enabled': + if (!isset($enabled_files[$key])) + $enabled_files[$key] = $k; + break; + + case 'disabled': + if (isset($enabled_files[$key])) + unset($enabled_files[$key]); + break; + + default: + break; + } + } + } + /****************************************************/ /* Walk the ALL_RULES map array and copy the rules */ /* matching our selected file categories to the */ @@ -2268,7 +3331,7 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { } /* Release memory we no longer need. */ - unset($enabled_files, $rulem, $v); + unset($enabled_files, $cat_mods, $rulem, $v); } /* Check if a pre-defined Snort VRT policy is selected. If so, */ @@ -2291,7 +3354,9 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { unset($policy_rules, $policy, $p); } - /* Process any enablesid or disablesid modifications for the selected rules. */ + // Process any enablesid or disablesid modifications for the selected rules. + // Do the auto-SID managment first, if enabled, then do any manual SID state changes. + snort_auto_sid_mgmt($enabled_rules, $snortcfg, TRUE); snort_modify_sids($enabled_rules, $snortcfg); /* Check for and disable any rules dependent upon disabled preprocessors if */ @@ -2324,7 +3389,45 @@ function snort_prepare_rule_files($snortcfg, $snortcfgdir) { } else /* Just put an empty file to always have the file present */ snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); - } else { + unset($all_rules); + } + // If no rule categories were enabled, then use auto-SID management if enabled, since it may enable some rules + elseif ($config['installedpackages']['snortglobal']['auto_manage_sids'] == 'on' && + (!empty($snortcfg['disable_sid_file']) || !empty($snortcfg['enable_sid_file']) || + !empty($snortcfg['modify_sid_file']))) { + + snort_auto_sid_mgmt($enabled_rules, $snortcfg, TRUE); + if (!empty($enabled_rules)) { + // Auto-SID management generated some rules, so use them + $no_rules_defined = false; + snort_modify_sids($enabled_rules, $snortcfg); + + // 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}"); + + // If auto-flowbit resolution is enabled, generate the dependent flowbits rules file. + if ($snortcfg['autoflowbitrules'] == 'on') { + log_error('[Snort] Enabling any flowbit-required rules for: ' . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) . '...'); + + // Load up all rules into a Rules Map array for flowbits assessment + $all_rules = snort_load_rules_map("{$snortdir}/rules/"); + $fbits = snort_resolve_flowbits($all_rules, $enabled_rules); + + // Check for and disable any flowbit-required rules the + // user has manually forced to a disabled state. + snort_modify_sids($fbits, $snortcfg); + snort_write_flowbit_rules_file($fbits, "{$snortcfgdir}/rules/{$flowbit_rules_file}"); + unset($all_rules, $fbits); + } else + // Just put an empty file to always have the file present + snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); + } + else { + snort_write_enforcing_rules_file(array(), "{$snortcfgdir}/rules/{$snort_enforcing_rules_file}"); + snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); + } + } + else { /* No regular rules or policy were selected, so just use the decoder and preproc rules */ snort_write_enforcing_rules_file($enabled_rules, "{$snortcfgdir}/rules/{$snort_enforcing_rules_file}"); snort_write_flowbit_rules_file(array(), "{$snortcfgdir}/rules/{$flowbit_rules_file}"); @@ -2396,10 +3499,9 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules, $persist_log = fa * Format of array is: * * "rule_option" => "dependent_preprocessor" * * * - * Last Update: 04/05/2013 * + * Last Update: 10/30/2014 * * * - * Added: http_inspect content modifiers and * - * various "service" metadata values. * + * Added: appid: detection option * * * ***************************************************/ $rule_opts_preprocs = array("ssl_version:" => "ssl_preproc","ssl_state:" => "ssl_preproc", @@ -2422,7 +3524,8 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules, $persist_log = fa "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"); + "service pop3" => "pop_preproc", "service smtp" => "smtp_preprocessor", + "appid:" => "appid_preproc" ); /*************************************************** * Iterate the enabled rules, and check for rule * @@ -2515,1283 +3618,44 @@ function snort_filter_preproc_rules($snortcfg, &$active_rules, $persist_log = fa function snort_generate_conf($snortcfg) { - global $config, $g, $rebuild_rules; + /********************************************************/ + /* This function generates the snort.conf file for the */ + /* passed interface using stored values from the Snort */ + /* package configuration. */ + /********************************************************/ - $snortdir = SNORTDIR; - $snortlibdir = SNORTLIBDIR; - $snortlogdir = SNORTLOGDIR; - $flowbit_rules_file = FLOWBITS_FILENAME; - $snort_enforcing_rules_file = ENFORCING_RULES_FILENAME; + global $config, $g, $rebuild_rules; + // Exit if there are no configured Snort interfaces if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; - conf_mount_rw(); - - /* 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"; + $snortdir = SNORTDIR; + $snortlibdir = SNORT_PBI_BASEDIR . "lib"; + $snortlogdir = SNORTLOGDIR; + $flowbit_rules_file = FLOWBITS_FILENAME; + $snort_enforcing_rules_file = SNORT_ENFORCING_RULES_FILENAME; $if_real = get_real_interface($snortcfg['interface']); $snort_uuid = $snortcfg['uuid']; $snortcfgdir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}"; - /* custom home nets */ - $home_net_list = snort_build_list($snortcfg, $snortcfg['homelistname']); - $home_net = implode(",", $home_net_list); - - $external_net = '!$HOME_NET'; - if (!empty($snortcfg['externallistname']) && $snortcfg['externallistname'] != 'default') { - $external_net_list = snort_build_list($snortcfg, $snortcfg['externallistname']); - $external_net = implode(",", $external_net_list); - } - - /* user added arguments */ - $snort_config_pass_thru = str_replace("\r", "", base64_decode($snortcfg['configpassthru'])); - // Remove the trailing newline - $snort_config_pass_thru = rtrim($snort_config_pass_thru); - - /* create a few directories and ensure the sample files are in place */ - $snort_dirs = array( $snortdir, $snortcfgdir, "{$snortcfgdir}/rules", - "{$snortlogdir}/snort_{$if_real}{$snort_uuid}", - "{$snortlogdir}/snort_{$if_real}{$snort_uuid}/barnyard2", - "{$snortcfgdir}/preproc_rules", - "dynamicrules" => "{$snortlibdir}/dynamicrules", - "dynamicengine" => "{$snortlibdir}/dynamicengine", - "dynamicpreprocessor" => "{$snortcfgdir}/dynamicpreprocessor" - ); - foreach ($snort_dirs as $dir) { - if (!is_dir($dir)) - 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", "attribute_table.dtd", - "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}")) { - $ftime = filemtime("{$snortdir}/{$file}"); - if (!file_exists("{$snortcfgdir}/{$file}") || ($ftime > filemtime("{$snortcfgdir}/{$file}"))) - @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); - } - } - - /* define alertsystemlog */ - $alertsystemlog_type = ""; - if ($snortcfg['alertsystemlog'] == "on") - $alertsystemlog_type = "output alert_syslog: log_alert"; - - /* define snortunifiedlog */ - $snortunifiedlog_type = ""; - if ($snortcfg['barnyard_enable'] == "on") { - if (isset($snortcfg['unified2_log_limit'])) - $u2_log_limit = "limit {$snortcfg['unified2_log_limit']}"; - else - $u2_log_limit = "limit 128"; - - $snortunifiedlog_type = "output unified2: filename snort_{$snort_uuid}_{$if_real}.u2, {$u2_log_limit}"; - if ($snortcfg['barnyard_log_vlan_events'] == 'on') - $snortunifiedlog_type .= ", vlan_event_types"; - if ($snortcfg['barnyard_log_mpls_events'] == 'on') - $snortunifiedlog_type .= ", mpls_event_types"; - } - - /* define spoink */ - $spoink_type = ""; - if ($snortcfg['blockoffenders7'] == "on") { - $pfkill = ""; - if ($snortcfg['blockoffenderskill'] == "on") - $pfkill = "kill"; - $spoink_wlist = snort_build_list($snortcfg, $snortcfg['whitelistname'], true); - /* write Pass List */ - @file_put_contents("{$snortcfgdir}/{$snortcfg['whitelistname']}", implode("\n", $spoink_wlist)); - $spoink_type = "output alert_pf: {$snortcfgdir}/{$snortcfg['whitelistname']},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; - } - - /* define selected suppress file */ - $suppress_file_name = ""; - $suppress = snort_find_list($snortcfg['suppresslistname'], 'suppress'); - if (!empty($suppress)) { - $suppress_data = str_replace("\r", "", base64_decode($suppress['suppresspassthru'])); - @file_put_contents("{$snortcfgdir}/supp{$snortcfg['suppresslistname']}", $suppress_data); - $suppress_file_name = "include {$snortcfgdir}/supp{$snortcfg['suppresslistname']}"; - } - - /* set the snort performance model */ - $snort_performance = "ac-bnfa"; - if(!empty($snortcfg['performance'])) - $snort_performance = $snortcfg['performance']; - - /* if user has defined a custom ssh port, use it */ - if(is_array($config['system']['ssh']) && isset($config['system']['ssh']['port'])) - $ssh_port = $config['system']['ssh']['port']; - else - $ssh_port = "22"; - - /* Define an array of default values for the various preprocessor ports */ - $snort_ports = array( - "dns_ports" => "53", "smtp_ports" => "25", "mail_ports" => "25,465,587,691", - "http_ports" => "36,80,81,82,83,84,85,86,87,88,89,90,311,383,591,593,631,901,1220,1414,1533,1741,1830,2301,2381,2809,3037,3057,3128,3443,3702,4343,4848,5250,6080,6988,7000,7001,7144,7145,7510,7777,7779,8000,8008,8014,8028,8080,8081,8082,8085,8088,8090,8118,8123,8180,8181,8222,8243,8280,8300,8500,8800,8888,8899,9000,9060,9080,9090,9091,9443,9999,10000,11371,15489,29991,33300,34412,34443,34444,41080,44440,50000,50002,51423,55555,56712", - "oracle_ports" => "1024:", "mssql_ports" => "1433", "telnet_ports" => "23", - "snmp_ports" => "161", "ftp_ports" => "21,2100,3535", "ssh_ports" => $ssh_port, - "pop2_ports" => "109", "pop3_ports" => "110", "imap_ports" => "143", - "sip_ports" => "5060,5061,5600", "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,992,993,994,995,7801,7802,7900,7901,7902,7903,7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920", - "file_data_ports" => "\$HTTP_PORTS,110,143", "shellcode_ports" => "!80", - "sun_rpc_ports" => "111,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779", - "DCERPC_NCACN_IP_TCP" => "139,445", "DCERPC_NCADG_IP_UDP" => "138,1024:", - "DCERPC_NCACN_IP_LONG" => "135,139,445,593,1024:", "DCERPC_NCACN_UDP_LONG" => "135,1024:", - "DCERPC_NCACN_UDP_SHORT" => "135,593,1024:", "DCERPC_NCACN_TCP" => "2103,2105,2107", - "DCERPC_BRIGHTSTORE" => "6503,6504", "DNP3_PORTS" => "20000", "MODBUS_PORTS" => "502", - "GTP_PORTS" => "2123,2152,3386" - ); - - /* Check for defined Aliases that may override default port settings as we build the portvars array */ - $portvardef = ""; - foreach ($snort_ports as $alias => $avalue) { - if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) - $snort_ports[$alias] = trim(filter_expand_alias($snortcfg["def_{$alias}"])); - $snort_ports[$alias] = preg_replace('/\s+/', ',', trim($snort_ports[$alias])); - $portvardef .= "portvar " . strtoupper($alias) . " [" . $snort_ports[$alias] . "]\n"; - } - - /* Define the default ports for the Stream5 preprocessor (formatted for easier reading in the snort.conf file) */ - $stream5_ports_client = "21 22 23 25 42 53 70 79 109 110 111 113 119 135 136 137 \\\n"; - $stream5_ports_client .= "\t 139 143 161 445 513 514 587 593 691 1433 1521 1741 \\\n"; - $stream5_ports_client .= "\t 2100 3306 6070 6665 6666 6667 6668 6669 7000 8181 \\\n"; - $stream5_ports_client .= "\t 32770 32771 32772 32773 32774 32775 32776 32777 \\\n"; - $stream5_ports_client .= "\t 32778 32779"; - $stream5_ports_both = "80 81 82 83 84 85 86 87 88 89 90 110 311 383 443 465 563 \\\n"; - $stream5_ports_both .= "\t 591 593 631 636 901 989 992 993 994 995 1220 1414 1533 \\\n"; - $stream5_ports_both .= "\t 1830 2301 2381 2809 3037 3057 3128 3443 3702 4343 4848 \\\n"; - $stream5_ports_both .= "\t 5250 6080 6988 7907 7000 7001 7144 7145 7510 7802 7777 \\\n"; - $stream5_ports_both .= "\t 7779 7801 7900 7901 7902 7903 7904 7905 7906 7908 7909 \\\n"; - $stream5_ports_both .= "\t 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 \\\n"; - $stream5_ports_both .= "\t 8000 8008 8014 8028 8080 8081 8082 8085 8088 8090 8118 \\\n"; - $stream5_ports_both .= "\t 8123 8180 8222 8243 8280 8300 8500 8800 8888 8899 9000 \\\n"; - $stream5_ports_both .= "\t 9060 9080 9090 9091 9443 9999 10000 11371 15489 29991 \\\n"; - $stream5_ports_both .= "\t 33300 34412 34443 34444 41080 44440 50000 50002 51423 \\\n"; - $stream5_ports_both .= "\t 55555 56712"; - - ///////////////////////////// - /* preprocessor code */ - /* def perform_stat */ - $perform_stat = <<<EOD -# Performance Statistics # -preprocessor perfmonitor: time 300 file {$snortlogdir}/snort_{$if_real}{$snort_uuid}/{$if_real}.stats pktcnt 10000 - -EOD; - - /* def ftp_preprocessor */ - $telnet_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['telnet_ports'])); - $ftp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ftp_ports'])); - - // Configure FTP_Telnet global options - $ftp_telnet_globals = "inspection_type "; - if ($snortcfg['ftp_telnet_inspection_type'] != "") { $ftp_telnet_globals .= $snortcfg['ftp_telnet_inspection_type']; }else{ $ftp_telnet_globals .= "stateful"; } - if ($snortcfg['ftp_telnet_alert_encrypted'] == "on") - $ftp_telnet_globals .= " \\\n\tencrypted_traffic yes"; - else - $ftp_telnet_globals .= " \\\n\tencrypted_traffic no"; - if ($snortcfg['ftp_telnet_check_encrypted'] == "on") - $ftp_telnet_globals .= " \\\n\tcheck_encrypted"; - - // Configure FTP_Telnet Telnet protocol options - $ftp_telnet_protocol = "ports { {$telnet_ports} }"; - if ($snortcfg['ftp_telnet_normalize'] == "on") - $ftp_telnet_protocol .= " \\\n\tnormalize"; - if ($snortcfg['ftp_telnet_detect_anomalies'] == "on") - $ftp_telnet_protocol .= " \\\n\tdetect_anomalies"; - if ($snortcfg['ftp_telnet_ayt_attack_threshold'] <> '0') { - $ftp_telnet_protocol .= " \\\n\tayt_attack_thresh "; - if ($snortcfg['ftp_telnet_ayt_attack_threshold'] != "") - $ftp_telnet_protocol .= $snortcfg['ftp_telnet_ayt_attack_threshold']; - else - $ftp_telnet_protocol .= "20"; - } - - // Setup the standard FTP commands used for all FTP Server engines - $ftp_cmds = <<<EOD - ftp_cmds { ABOR ACCT ADAT ALLO APPE AUTH CCC CDUP } \ - ftp_cmds { CEL CLNT CMD CONF CWD DELE ENC EPRT } \ - ftp_cmds { EPSV ESTA ESTP FEAT HELP LANG LIST LPRT } \ - ftp_cmds { LPSV MACB MAIL MDTM MFMT MIC MKD MLSD MLST } \ - ftp_cmds { MODE NLST NOOP OPTS PASS PASV PBSZ PORT } \ - ftp_cmds { PROT PWD QUIT REIN REST RETR RMD RNFR } \ - ftp_cmds { RNTO SDUP SITE SIZE SMNT STAT STOR STOU } \ - ftp_cmds { STRU SYST TEST TYPE USER XCUP XCRC XCWD } \ - ftp_cmds { XMAS XMD5 XMKD XPWD XRCP XRMD XRSQ XSEM } \ - ftp_cmds { XSEN XSHA1 XSHA256 } \ - alt_max_param_len 0 { ABOR CCC CDUP ESTA FEAT LPSV NOOP PASV PWD QUIT REIN STOU SYST XCUP XPWD } \ - alt_max_param_len 200 { ALLO APPE CMD HELP NLST RETR RNFR STOR STOU XMKD } \ - alt_max_param_len 256 { CWD RNTO } \ - alt_max_param_len 400 { PORT } \ - alt_max_param_len 512 { MFMT SIZE } \ - chk_str_fmt { ACCT ADAT ALLO APPE AUTH CEL CLNT CMD } \ - chk_str_fmt { CONF CWD DELE ENC EPRT EPSV ESTP HELP } \ - chk_str_fmt { LANG LIST LPRT MACB MAIL MDTM MIC MKD } \ - chk_str_fmt { MLSD MLST MODE NLST OPTS PASS PBSZ PORT } \ - chk_str_fmt { PROT REST RETR RMD RNFR RNTO SDUP SITE } \ - chk_str_fmt { SIZE SMNT STAT STOR STRU TEST TYPE USER } \ - chk_str_fmt { XCRC XCWD XMAS XMD5 XMKD XRCP XRMD XRSQ } \ - chk_str_fmt { XSEM XSEN XSHA1 XSHA256 } \ - cmd_validity ALLO < int [ char R int ] > \ - cmd_validity EPSV < [ { char 12 | char A char L char L } ] > \ - cmd_validity MACB < string > \ - cmd_validity MDTM < [ date nnnnnnnnnnnnnn[.n[n[n]]] ] string > \ - cmd_validity MODE < char ASBCZ > \ - cmd_validity PORT < host_port > \ - cmd_validity PROT < char CSEP > \ - cmd_validity STRU < char FRPO [ string ] > \ - cmd_validity TYPE < { char AE [ char NTC ] | char I | char L [ number ] } > - -EOD; + // Pull in the PHP code that generates required string variables + include("/usr/local/pkg/snort/snort_generate_conf.php"); - // Configure all the FTP_Telnet FTP protocol options - // Iterate and configure the FTP Client engines - $ftp_default_client_engine = array( "name" => "default", "bind_to" => "all", "max_resp_len" => 256, - "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", - "bounce" => "yes", "bounce_to_net" => "", "bounce_to_port" => "" ); - - if (!is_array($snortcfg['ftp_client_engine']['item'])) - $snortcfg['ftp_client_engine']['item'] = array(); - - // If no FTP client engine is configured, use the default - // to keep from breaking Snort. - if (empty($snortcfg['ftp_client_engine']['item'])) - $snortcfg['ftp_client_engine']['item'][] = $ftp_default_client_engine; - $ftp_client_engine = ""; - - foreach ($snortcfg['ftp_client_engine']['item'] as $f => $v) { - $buffer = "preprocessor ftp_telnet_protocol: ftp client "; - if ($v['name'] == "default" && $v['bind_to'] == "all") - $buffer .= "default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "{$tmp} \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); - continue; - } - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); - continue; - } - - if ($v['max_resp_len'] == "") - $buffer .= "\tmax_resp_len 256 \\\n"; - else - $buffer .= "\tmax_resp_len {$v['max_resp_len']} \\\n"; - - $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; - $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; - - if ($v['bounce'] == "yes") { - if (is_alias($v['bounce_to_net']) && is_alias($v['bounce_to_port'])) { - $net = trim(filter_expand_alias($v['bounce_to_net'])); - $port = trim(filter_expand_alias($v['bounce_to_port'])); - if (!empty($net) && !empty($port) && - snort_is_single_addr_alias($v['bounce_to_net']) && - (is_port($port) || is_portrange($port))) { - $port = preg_replace('/\s+/', ',', $port); - // Change port range delimiter to comma for ftp_telnet client preprocessor - if (is_portrange($port)) - $port = str_replace(":", ",", $port); - $buffer .= "\tbounce yes \\\n"; - $buffer .= "\tbounce_to { {$net},{$port} }\n"; - } - else { - // One or both of the BOUNCE_TO alias values is not right, - // so figure out which and log an appropriate error. - if (empty($net) || !snort_is_single_addr_alias($v['bounce_to_net'])) - log_error("[snort] ERROR: illegal value for bounce_to Address Alias [{$v['bounce_to_net']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); - if (empty($port) || !(is_port($port) || is_portrange($port))) - log_error("[snort] ERROR: illegal value for bounce_to Port Alias [{$v['bounce_to_port']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); - $buffer .= "\tbounce yes\n"; - } - } - else - $buffer .= "\tbounce yes\n"; - } - else - $buffer .= "\tbounce no\n"; - - // Add this FTP client engine to the master string - $ftp_client_engine .= "{$buffer}\n"; - } - // Trim final trailing newline - rtrim($ftp_client_engine); - - // Iterate and configure the FTP Server engines - $ftp_default_server_engine = array( "name" => "default", "bind_to" => "all", "ports" => "default", - "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", - "ignore_data_chan" => "no", "def_max_param_len" => 100 ); - - if (!is_array($snortcfg['ftp_server_engine']['item'])) - $snortcfg['ftp_server_engine']['item'] = array(); - - // If no FTP server engine is configured, use the default - // to keep from breaking Snort. - if (empty($snortcfg['ftp_server_engine']['item'])) - $snortcfg['ftp_server_engine']['item'][] = $ftp_default_server_engine; - $ftp_server_engine = ""; - - foreach ($snortcfg['ftp_server_engine']['item'] as $f => $v) { - $buffer = "preprocessor ftp_telnet_protocol: ftp server "; - if ($v['name'] == "default" && $v['bind_to'] == "all") - $buffer .= "default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "{$tmp} \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); - continue; - } - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); - continue; - } - - if ($v['def_max_param_len'] == "") - $buffer .= "\tdef_max_param_len 100 \\\n"; - elseif ($v['def_max_param_len'] <> '0') - $buffer .= "\tdef_max_param_len {$v['def_max_param_len']} \\\n"; - - if ($v['ports'] == "default" || !is_alias($v['ports']) || empty($v['ports'])) - $buffer .= "\tports { {$ftp_ports} } \\\n"; - elseif (is_alias($v['ports'])) { - $tmp = trim(filter_expand_alias($v['ports'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $tmp = snort_expand_port_range($tmp, ' '); - $buffer .= "\tports { {$tmp} } \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve Port Alias '{$v['ports']}' for FTP server '{$v['name']}' ... reverting to defaults."); - $buffer .= "\tports { {$ftp_ports} } \\\n"; - } - } - - $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; - $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; - if ($v['ignore_data_chan'] == "yes") - $buffer .= "\tignore_data_chan yes \\\n"; - $buffer .= "{$ftp_cmds}\n"; - - // Add this FTP server engine to the master string - $ftp_server_engine .= $buffer; - } - // Remove trailing newlines - rtrim($ftp_server_engine); - - $ftp_preprocessor = <<<EOD -# ftp_telnet preprocessor # -preprocessor ftp_telnet: global \ - {$ftp_telnet_globals} - -preprocessor ftp_telnet_protocol: telnet \ - {$ftp_telnet_protocol} - -{$ftp_server_engine} -{$ftp_client_engine} -EOD; - - $pop_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['pop3_ports'])); - $pop_preproc = <<<EOD -# POP preprocessor # -preprocessor pop: \ - ports { {$pop_ports} } \ - memcap 1310700 \ - qp_decode_depth 0 \ - b64_decode_depth 0 \ - bitenc_decode_depth 0 - -EOD; - - $imap_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['imap_ports'])); - $imap_preproc = <<<EOD -# IMAP preprocessor # -preprocessor imap: \ - ports { {$imap_ports} } \ - memcap 1310700 \ - qp_decode_depth 0 \ - b64_decode_depth 0 \ - bitenc_decode_depth 0 - -EOD; - - $smtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['mail_ports'])); - /* def smtp_preprocessor */ - $smtp_preprocessor = <<<EOD -# SMTP preprocessor # -preprocessor SMTP: \ - ports { {$smtp_ports} } \ - inspection_type stateful \ - normalize cmds \ - ignore_tls_data \ - valid_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT \ - NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX QUEU \ - STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE \ - XQUEU XSTA XTRN XUSR } \ - normalize_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY \ - IDENT NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT \ - ONEX QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 \ - XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ - max_header_line_len 1000 \ - max_response_line_len 512 \ - alt_max_command_line_len 260 { MAIL } \ - alt_max_command_line_len 300 { RCPT } \ - alt_max_command_line_len 500 { HELP HELO ETRN EHLO } \ - alt_max_command_line_len 255 { EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT NOOP RSET } \ - alt_max_command_line_len 246 { SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX } \ - alt_max_command_line_len 246 { QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR } \ - alt_max_command_line_len 246 { XAUTH XCIR XEXCH50 XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ - xlink2state { enable } \ - log_mailfrom \ - log_rcptto \ - log_email_hdrs \ - email_hdrs_log_depth 1464 \ - log_filename \ - qp_decode_depth 0 \ - b64_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']; - $sf_pscan_ignore_scanners = "\$HOME_NET"; - if (!empty($snortcfg['pscan_ignore_scanners']) && is_alias($snortcfg['pscan_ignore_scanners'])) { - $sf_pscan_ignore_scanners = trim(filter_expand_alias($snortcfg['pscan_ignore_scanners'])); - $sf_pscan_ignore_scanners = preg_replace('/\s+/', ',', trim($sf_pscan_ignore_scanners)); - } - - $sf_portscan = <<<EOD -# sf Portscan # -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} } - -EOD; - - /* def ssh_preproc */ - $ssh_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssh_ports'])); - $ssh_preproc = <<<EOD -# SSH preprocessor # -preprocessor ssh: \ - server_ports { {$ssh_ports} } \ - autodetect \ - max_client_bytes 19600 \ - max_encrypted_packets 20 \ - max_server_version_len 100 \ - enable_respoverflow enable_ssh1crc32 \ - enable_srvoverflow enable_protomismatch - -EOD; - - /* def other_preprocs */ - $sun_rpc_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sun_rpc_ports'])); - $other_preprocs = <<<EOD -# Other preprocs # -preprocessor rpc_decode: \ - {$sun_rpc_ports} \ - no_alert_multiple_requests \ - no_alert_large_fragments \ - no_alert_incomplete - -# Back Orifice preprocessor # -preprocessor bo - -EOD; + // Pull in the boilerplate template for the snort.conf + // configuration file. The contents of the template along + // with substituted variables is stored in $snort_conf_text + // (which is defined in the included file). + include("/usr/local/pkg/snort/snort_conf_template.inc"); - /* def dce_rpc_2 */ - $dce_rpc_2 = <<<EOD -# DCE/RPC 2 # -preprocessor dcerpc2: \ - memcap 102400, \ - events [co] - -preprocessor dcerpc2_server: default, \ - policy WinXP, \ - detect [smb [{$snort_ports['smb_ports']}], \ - tcp 135, \ - udp 135, \ - rpc-over-http-server 593], \ - autodetect [tcp 1025:, \ - udp 1025:, \ - rpc-over-http-server 1025:], \ - smb_max_chain 3, smb_invalid_shares ["C$", "D$", "ADMIN$"] - -EOD; - - $sip_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sip_ports'])); - $sip_preproc = <<<EOD -# SIP preprocessor # -preprocessor sip: \ - max_sessions 40000, \ - ports { {$sip_ports} }, \ - methods { invite \ - cancel \ - ack \ - bye \ - register \ - options \ - refer \ - subscribe \ - update \ - join \ - info \ - message \ - notify \ - benotify \ - do \ - qauth \ - sprack \ - publish \ - service \ - unsubscribe \ - prack }, \ - max_call_id_len 80, \ - max_from_len 256, \ - max_to_len 256, \ - max_via_len 1024, \ - max_requestName_len 50, \ - max_uri_len 512, \ - ignore_call_channel, \ - max_content_len 2048, \ - max_contact_len 512 - -EOD; - - $dns_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['dns_ports'])); - /* def dns_preprocessor */ - $dns_preprocessor = <<<EOD -# DNS preprocessor # -preprocessor dns: \ - ports { {$dns_ports} } \ - enable_rdata_overflow - -EOD; - - /* def dnp3_preprocessor */ - $dnp3_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['DNP3_PORTS'])); - $dnp3_preproc = <<<EOD -# DNP3 preprocessor # -preprocessor dnp3: \ - ports { {$dnp3_ports} } \ - memcap 262144 \ - check_crc - -EOD; - - /* def modbus_preprocessor */ - $modbus_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['MODBUS_PORTS'])); - $modbus_preproc = <<<EOD -# Modbus preprocessor # -preprocessor modbus: \ - ports { {$modbus_ports} } - -EOD; - - /* def gtp_preprocessor */ - $gtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['GTP_PORTS'])); - $gtp_preproc = <<<EOD -# GTP preprocessor # -preprocessor gtp: \ - ports { {$gtp_ports} } - -EOD; - - /* def ssl_preprocessor */ - $ssl_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssl_ports'])); - $ssl_preproc = <<<EOD -# SSL preprocessor # -preprocessor ssl: \ - ports { {$ssl_ports} }, \ - trustservers, \ - noinspect_encrypted - -EOD; - - /* def sensitive_data_preprocessor */ - if ($snortcfg['sdf_mask_output'] == "on") - $sdf_mask_output = "\\\n\tmask_output"; - else - $sdf_mask_output = ""; - if (empty($snortcfg['sdf_alert_threshold'])) - $snortcfg['sdf_alert_threshold'] = 25; - $sensitive_data = <<<EOD -# SDF preprocessor # -preprocessor sensitive_data: \ - alert_threshold {$snortcfg['sdf_alert_threshold']} {$sdf_mask_output} - -EOD; - - /* define IP Reputation preprocessor */ - if (is_array($snortcfg['blist_files']['item'])) { - $blist_files = ""; - $bIsFirst = TRUE; - foreach ($snortcfg['blist_files']['item'] as $blist) { - if ($bIsFirst) { - $blist_files .= "blacklist " . IPREP_PATH . $blist; - $bIsFirst = FALSE; - } - else - $blist_files .= ", \\ \n\tblacklist " . IPREP_PATH . $blist; - } - } - if (is_array($snortcfg['wlist_files']['item'])) { - $wlist_files = ""; - $bIsFirst = TRUE; - foreach ($snortcfg['wlist_files']['item'] as $wlist) { - if ($bIsFirst) { - $wlist_files .= "whitelist " . IPREP_PATH . $wlist; - $bIsFirst = FALSE; - } - else - $wlist_files .= ", \\ \n\twhitelist " . IPREP_PATH . $wlist; - } - } - if (!empty($blist_files)) - $ip_lists = $blist_files; - if (!empty($wlist_files)) - $ip_lists .= ", \\ \n" . $wlist_files; - if ($snortcfg['iprep_scan_local'] == 'on') - $ip_lists .= ", \\ \n\tscan_local"; - - $reputation_preproc = <<<EOD -# IP Reputation preprocessor # -preprocessor reputation: \ - memcap {$snortcfg['iprep_memcap']}, \ - priority {$snortcfg['iprep_priority']}, \ - nested_ip {$snortcfg['iprep_nested_ip']}, \ - white {$snortcfg['iprep_white']}, \ - {$ip_lists} - -EOD; - - /* define servers as IP variables */ - $snort_servers = array ( - "dns_servers" => "\$HOME_NET", "smtp_servers" => "\$HOME_NET", "http_servers" => "\$HOME_NET", - "www_servers" => "\$HOME_NET", "sql_servers" => "\$HOME_NET", "telnet_servers" => "\$HOME_NET", - "snmp_servers" => "\$HOME_NET", "ftp_servers" => "\$HOME_NET", "ssh_servers" => "\$HOME_NET", - "pop_servers" => "\$HOME_NET", "imap_servers" => "\$HOME_NET", "sip_proxy_ip" => "\$HOME_NET", - "sip_servers" => "\$HOME_NET", "rpc_servers" => "\$HOME_NET", "dnp3_server" => "\$HOME_NET", - "dnp3_client" => "\$HOME_NET", "modbus_server" => "\$HOME_NET", "modbus_client" => "\$HOME_NET", - "enip_server" => "\$HOME_NET", "enip_client" => "\$HOME_NET", - "aim_servers" => "64.12.24.0/23,64.12.28.0/23,64.12.161.0/24,64.12.163.0/24,64.12.200.0/24,205.188.3.0/24,205.188.5.0/24,205.188.7.0/24,205.188.9.0/24,205.188.153.0/24,205.188.179.0/24,205.188.248.0/24" - ); - - // Change old name from "var" to new name of "ipvar" for IP variables because - // Snort is deprecating the old "var" name in newer versions. - $ipvardef = ""; - foreach ($snort_servers as $alias => $avalue) { - if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) { - $avalue = trim(filter_expand_alias($snortcfg["def_{$alias}"])); - $avalue = preg_replace('/\s+/', ',', trim($avalue)); - } - $ipvardef .= "ipvar " . strtoupper($alias) . " [{$avalue}]\n"; - } - - $snort_preproc_libs = array( - "dce_rpc_2" => "dce2_preproc", "dns_preprocessor" => "dns_preproc", "ftp_preprocessor" => "ftptelnet_preproc", "imap_preproc" => "imap_preproc", - "pop_preproc" => "pop_preproc", "reputation_preproc" => "reputation_preproc", "sensitive_data" => "sdf_preproc", - "sip_preproc" => "sip_preproc", "gtp_preproc" => "gtp_preproc", "smtp_preprocessor" => "smtp_preproc", "ssh_preproc" => "ssh_preproc", - "ssl_preproc" => "ssl_preproc", "dnp3_preproc" => "dnp3_preproc", "modbus_preproc" => "modbus_preproc" - ); - $snort_preproc = array ( - "perform_stat", "other_preprocs", "ftp_preprocessor", "smtp_preprocessor", "ssl_preproc", "sip_preproc", "gtp_preproc", "ssh_preproc", "sf_portscan", - "dce_rpc_2", "dns_preprocessor", "sensitive_data", "pop_preproc", "imap_preproc", "dnp3_preproc", "modbus_preproc", "reputation_preproc" - ); - $default_disabled_preprocs = array( - "sf_portscan", "gtp_preproc", "sensitive_data", "dnp3_preproc", "modbus_preproc", "reputation_preproc", "perform_stat" - ); - $snort_preprocessors = ""; - foreach ($snort_preproc as $preproc) { - 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("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so")) { - @copy("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } else - log_error("Could not find the {$preproclib} file. Snort might error out!"); - } else { - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } - } else { - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } - } - } - // Remove final trailing newline - $snort_preprocessors = rtrim($snort_preprocessors); - - $snort_misc_include_rules = ""; - if (file_exists("{$snortcfgdir}/reference.config")) - $snort_misc_include_rules .= "include {$snortcfgdir}/reference.config\n"; - if (file_exists("{$snortcfgdir}/classification.config")) - $snort_misc_include_rules .= "include {$snortcfgdir}/classification.config\n"; - if (!file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") || !file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules")) { - $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; - log_error("[Snort] Seems preprocessor and/or decoder rules are missing, enabling autogeneration of them in conf file."); - } - - /* generate rule sections to load */ - /* The files are always configured so the update process is easier */ - $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"; - - // Remove trailing newlines - $snort_misc_include_rules = rtrim($snort_misc_include_rules); - $selected_rules_sections = rtrim($selected_rules_sections); + // Write out snort.conf file using contents of $snort_conf_text + @file_put_contents("{$snortcfgdir}/snort.conf", $snort_conf_text); - /* Create the actual rules files and save in the interface directory */ + // Create the actual rules files and save them in the interface directory snort_prepare_rule_files($snortcfg, $snortcfgdir); - $cksumcheck = "all"; - if ($snortcfg['cksumcheck'] == 'on') - $cksumcheck = "none"; - - /* Pull in user-configurable detection config options */ - $cfg_detect_settings = "search-method {$snort_performance} max-pattern-len 20 max_queue_events 5"; - if ($snortcfg['fpm_split_any_any'] == "on") - $cfg_detect_settings .= " split-any-any"; - if ($snortcfg['fpm_search_optimize'] == "on") - $cfg_detect_settings .= " search-optimize"; - if ($snortcfg['fpm_no_stream_inserts'] == "on") - $cfg_detect_settings .= " no_stream_inserts"; - - /* Pull in user-configurable options for Frag3 preprocessor settings */ - /* Get global Frag3 options first and put into a string */ - $frag3_global = "preprocessor frag3_global: "; - if (!empty($snortcfg['frag3_memcap']) || $snortcfg['frag3_memcap'] == "0") - $frag3_global .= "memcap {$snortcfg['frag3_memcap']}, "; - else - $frag3_global .= "memcap 4194304, "; - if (!empty($snortcfg['frag3_max_frags'])) - $frag3_global .= "max_frags {$snortcfg['frag3_max_frags']}"; - else - $frag3_global .= "max_frags 8192"; - if ($snortcfg['frag3_detection'] == "off") - $frag3_global .= ", disabled"; - - $frag3_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", - "timeout" => 60, "min_ttl" => 1, "detect_anomalies" => "on", - "overlap_limit" => 0, "min_frag_len" => 0 ); - $frag3_engine = ""; - - // Now iterate configured Frag3 engines and write them to a string if enabled - if ($snortcfg['frag3_detection'] == "on") { - if (!is_array($snortcfg['frag3_engine']['item'])) - $snortcfg['frag3_engine']['item'] = array(); - - // If no frag3 tcp engine is configured, use the default - if (empty($snortcfg['frag3_engine']['item'])) - $snortcfg['frag3_engine']['item'][] = $frag3_default_tcp_engine; - - foreach ($snortcfg['frag3_engine']['item'] as $f => $v) { - $frag3_engine .= "preprocessor frag3_engine: "; - $frag3_engine .= "policy {$v['policy']}"; - if ($v['bind_to'] <> "all") { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ',', $tmp); - if (strpos($tmp, ",") !== false) - $frag3_engine .= " \\\n\tbind_to [{$tmp}]"; - else - $frag3_engine .= " \\\n\tbind_to {$tmp}"; - } - else - log_error("[snort] WARNING: unable to resolve IP List Alias '{$v['bind_to']}' for Frag3 engine '{$v['name']}' ... using 0.0.0.0 failsafe."); - } - $frag3_engine .= " \\\n\ttimeout {$v['timeout']}"; - $frag3_engine .= " \\\n\tmin_ttl {$v['min_ttl']}"; - if ($v['detect_anomalies'] == "on") { - $frag3_engine .= " \\\n\tdetect_anomalies"; - $frag3_engine .= " \\\n\toverlap_limit {$v['overlap_limit']}"; - $frag3_engine .= " \\\n\tmin_fragment_length {$v['min_frag_len']}"; - } - // Add newlines to terminate this engine - $frag3_engine .= "\n\n"; - } - // Remove trailing newline - $frag3_engine = rtrim($frag3_engine); - } - - // Grab any user-customized value for Protocol Aware Flushing (PAF) max PDUs - $paf_max_pdu_config = "config paf_max: "; - if (empty($snortcfg['max_paf']) || $snortcfg['max_paf'] == '0') - $paf_max_pdu_config .= "0"; - else - $paf_max_pdu_config .= $snortcfg['max_paf']; - - // Pull in user-configurable options for Stream5 preprocessor settings - // Get global options first and put into a string - $stream5_global = "preprocessor stream5_global: \\\n"; - if ($snortcfg['stream5_reassembly'] == "off") - $stream5_global .= "\tdisabled, \\\n"; - if ($snortcfg['stream5_track_tcp'] == "off") - $stream5_global .= "\ttrack_tcp no,"; - else { - $stream5_global .= "\ttrack_tcp yes,"; - if (!empty($snortcfg['stream5_max_tcp'])) - $stream5_global .= " \\\n\tmax_tcp {$snortcfg['stream5_max_tcp']},"; - else - $stream5_global .= " \\\n\tmax_tcp 262144,"; - } - if ($snortcfg['stream5_track_udp'] == "off") - $stream5_global .= " \\\n\ttrack_udp no,"; - else { - $stream5_global .= " \\\n\ttrack_udp yes,"; - if (!empty($snortcfg['stream5_max_udp'])) - $stream5_global .= " \\\n\tmax_udp {$snortcfg['stream5_max_udp']},"; - else - $stream5_global .= " \\\n\tmax_udp 131072,"; - } - if ($snortcfg['stream5_track_icmp'] == "on") { - $stream5_global .= " \\\n\ttrack_icmp yes,"; - if (!empty($snortcfg['stream5_max_icmp'])) - $stream5_global .= " \\\n\tmax_icmp {$snortcfg['stream5_max_icmp']},"; - else - $stream5_global .= " \\\n\tmax_icmp 65536,"; - } - else - $stream5_global .= " \\\n\ttrack_icmp no,"; - if (!empty($snortcfg['stream5_mem_cap'])) - $stream5_global .= " \\\n\tmemcap {$snortcfg['stream5_mem_cap']},"; - else - $stream5_global .= " \\\n\tmemcap 8388608,"; - - if (!empty($snortcfg['stream5_prune_log_max']) || $snortcfg['stream5_prune_log_max'] == '0') - $stream5_global .= " \\\n\tprune_log_max {$snortcfg['stream5_prune_log_max']}"; - else - $stream5_global .= " \\\n\tprune_log_max 1048576"; - if ($snortcfg['stream5_flush_on_alert'] == "on") - $stream5_global .= ", \\\n\tflush_on_alert"; - - $stream5_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", "timeout" => 30, - "max_queued_bytes" => 1048576, "detect_anomalies" => "off", "overlap_limit" => 0, - "max_queued_segs" => 2621, "require_3whs" => "off", "startup_3whs_timeout" => 0, - "no_reassemble_async" => "off", "dont_store_lg_pkts" => "off", "max_window" => 0, - "use_static_footprint_sizes" => "off", "check_session_hijacking" => "off", "ports_client" => "default", - "ports_both" => "default", "ports_server" => "none" ); - $stream5_tcp_engine = ""; - - // Now iterate configured Stream5 TCP engines and write them to a string if enabled - if ($snortcfg['stream5_reassembly'] == "on") { - if (!is_array($snortcfg['stream5_tcp_engine']['item'])) - $snortcfg['stream5_tcp_engine']['item'] = array(); - - // If no stream5 tcp engine is configured, use the default - if (empty($snortcfg['stream5_tcp_engine']['item'])) - $snortcfg['stream5_tcp_engine']['item'][] = $stream5_default_tcp_engine; - - foreach ($snortcfg['stream5_tcp_engine']['item'] as $f => $v) { - $buffer = "preprocessor stream5_tcp: "; - $buffer .= "policy {$v['policy']},"; - if ($v['bind_to'] <> "all") { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ',', $tmp); - if (strpos($tmp, ",") !== false) - $buffer .= " \\\n\tbind_to [{$tmp}],"; - else - $buffer .= " \\\n\tbind_to {$tmp},"; - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for Stream5 TCP engine '{$v['name']}' ... skipping this engine."); - continue; - } - } - $stream5_tcp_engine .= $buffer; - $stream5_tcp_engine .= " \\\n\ttimeout {$v['timeout']},"; - $stream5_tcp_engine .= " \\\n\toverlap_limit {$v['overlap_limit']},"; - $stream5_tcp_engine .= " \\\n\tmax_window {$v['max_window']},"; - $stream5_tcp_engine .= " \\\n\tmax_queued_bytes {$v['max_queued_bytes']},"; - $stream5_tcp_engine .= " \\\n\tmax_queued_segs {$v['max_queued_segs']}"; - if ($v['use_static_footprint_sizes'] == "on") - $stream5_tcp_engine .= ", \\\n\tuse_static_footprint_sizes"; - if ($v['check_session_hijacking'] == "on") - $stream5_tcp_engine .= ", \\\n\tcheck_session_hijacking"; - if ($v['dont_store_lg_pkts'] == "on") - $stream5_tcp_engine .= ", \\\n\tdont_store_large_packets"; - if ($v['no_reassemble_async'] == "on") - $stream5_tcp_engine .= ", \\\n\tdont_reassemble_async"; - if ($v['detect_anomalies'] == "on") - $stream5_tcp_engine .= ", \\\n\tdetect_anomalies"; - if ($v['require_3whs'] == "on") - $stream5_tcp_engine .= ", \\\n\trequire_3whs {$v['startup_3whs_timeout']}"; - if (!empty($v['ports_client'])) { - $stream5_tcp_engine .= ", \\\n\tports client"; - if ($v['ports_client'] == " all") - $stream5_tcp_engine .= " all"; - elseif ($v['ports_client'] == "default") - $stream5_tcp_engine .= " {$stream5_ports_client}"; - else { - $tmp = trim(filter_expand_alias($v['ports_client'])); - if (!empty($tmp)) - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - else { - $stream5_tcp_engine .= " {$stream5_ports_client}"; - log_error("[snort] WARNING: unable to resolve Ports Client Alias [{$v['ports_client']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); - } - } - } - if (!empty($v['ports_both'])) { - $stream5_tcp_engine .= ", \\\n\tports both"; - if ($v['ports_both'] == " all") - $stream5_tcp_engine .= " all"; - elseif ($v['ports_both'] == "default") - $stream5_tcp_engine .= " {$stream5_ports_both}"; - else { - $tmp = trim(filter_expand_alias($v['ports_both'])); - if (!empty($tmp)) - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - else { - $stream5_tcp_engine .= " {$stream5_ports_both}"; - log_error("[snort] WARNING: unable to resolve Ports Both Alias [{$v['ports_both']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); - } - } - } - if (!empty($v['ports_server']) && $v['ports_server'] <> "none" && $v['ports_server'] <> "default") { - if ($v['ports_server'] == " all") { - $stream5_tcp_engine .= ", \\\n\tports server"; - $stream5_tcp_engine .= " all"; - } - else { - $tmp = trim(filter_expand_alias($v['ports_server'])); - if (!empty($tmp)) { - $stream5_tcp_engine .= ", \\\n\tports server"; - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - } - else - log_error("[snort] WARNING: unable to resolve Ports Server Alias [{$v['ports_server']}] for Stream5 TCP engine '{$v['name']}' ... defaulting to none."); - } - } - - // Make sure the "ports" parameter is set, or else default to a safe value - if (strpos($stream5_tcp_engine, "ports ") === false) - $stream5_tcp_engine .= ", \\\n\tports both all"; - - // Add a pair of newlines to terminate this engine - $stream5_tcp_engine .= "\n\n"; - } - // Trim off the final trailing newline - $stream5_tcp_engine = rtrim($stream5_tcp_engine); - } - - // Configure the Stream5 UDP engine if it and Stream5 reassembly are enabled - if ($snortcfg['stream5_track_udp'] == "off" || $snortcfg['stream5_reassembly'] == "off") - $stream5_udp_engine = ""; - else { - $stream5_udp_engine = "preprocessor stream5_udp: "; - if (!empty($snortcfg['stream5_udp_timeout'])) - $stream5_udp_engine .= "timeout {$snortcfg['stream5_udp_timeout']}"; - else - $stream5_udp_engine .= "timeout 30"; - } - - // Configure the Stream5 ICMP engine if it and Stream5 reassembly are enabled - if ($snortcfg['stream5_track_icmp'] == "on" && $snortcfg['stream5_reassembly'] == "on") { - $stream5_icmp_engine = "preprocessor stream5_icmp: "; - if (!empty($snortcfg['stream5_icmp_timeout'])) - $stream5_icmp_engine .= "timeout {$snortcfg['stream5_icmp_timeout']}"; - else - $stream5_icmp_engine .= "timeout 30"; - } - else - $stream5_icmp_engine = ""; - - // Check for and configure Host Attribute Table if enabled - $host_attrib_config = ""; - if ($snortcfg['host_attribute_table'] == "on" && !empty($snortcfg['host_attribute_data'])) { - @file_put_contents("{$snortcfgdir}/host_attributes", base64_decode($snortcfg['host_attribute_data'])); - $host_attrib_config = "# Host Attribute Table #\n"; - $host_attrib_config .= "attribute_table filename {$snortcfgdir}/host_attributes\n"; - if (!empty($snortcfg['max_attribute_hosts'])) - $host_attrib_config .= "config max_attribute_hosts: {$snortcfg['max_attribute_hosts']}\n"; - if (!empty($snortcfg['max_attribute_services_per_host'])) - $host_attrib_config .= "config max_attribute_services_per_host: {$snortcfg['max_attribute_services_per_host']}"; - } - - // Configure the HTTP_INSPECT preprocessor - // Get global options first and put into a string - $http_inspect_global = "preprocessor http_inspect: global "; - if ($snortcfg['http_inspect'] == "off") - $http_inspect_global .= "disabled "; - $http_inspect_global .= "\\\n\tiis_unicode_map unicode.map 1252 \\\n"; - $http_inspect_global .= "\tcompress_depth 65535 \\\n"; - $http_inspect_global .= "\tdecompress_depth 65535 \\\n"; - if (!empty($snortcfg['http_inspect_memcap'])) - $http_inspect_global .= "\tmemcap {$snortcfg['http_inspect_memcap']} \\\n"; - else - $http_inspect_global .= "\tmemcap 150994944 \\\n"; - if (!empty($snortcfg['http_inspect_max_gzip_mem'])) - $http_inspect_global .= "\tmax_gzip_mem {$snortcfg['http_inspect_max_gzip_mem']}"; - else - $http_inspect_global .= "\tmax_gzip_mem 838860"; - if ($snortcfg['http_inspect_proxy_alert'] == "on") - $http_inspect_global .= " \\\n\tproxy_alert"; - - $http_inspect_default_engine = array( "name" => "default", "bind_to" => "all", "server_profile" => "all", "enable_xff" => "off", - "log_uri" => "off", "log_hostname" => "off", "server_flow_depth" => 65535, "enable_cookie" => "on", - "client_flow_depth" => 1460, "extended_response_inspection" => "on", "no_alerts" => "off", - "unlimited_decompress" => "on", "inspect_gzip" => "on", "normalize_cookies" =>"on", "normalize_headers" => "on", - "normalize_utf" => "on", "normalize_javascript" => "on", "allow_proxy_use" => "off", "inspect_uri_only" => "off", - "max_javascript_whitespaces" => 200, "post_depth" => -1, "max_headers" => 0, "max_spaces" => 0, - "max_header_length" => 0, "ports" => "default" ); - $http_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['http_ports'])); - $http_inspect_servers = ""; - - // Iterate configured HTTP_INSPECT servers and write them to string if HTTP_INSPECT enabled - if ($snortcfg['http_inspect'] <> "off") { - if (!is_array($snortcfg['http_inspect_engine']['item'])) - $snortcfg['http_inspect_engine']['item'] = array(); - - // If no http_inspect_engine is configured, use the default - if (empty($snortcfg['http_inspect_engine']['item'])) - $snortcfg['http_inspect_engine']['item'][] = $http_inspect_default_engine; - - foreach ($snortcfg['http_inspect_engine']['item'] as $f => $v) { - $buffer = "preprocessor http_inspect_server: \\\n"; - if ($v['name'] == "default") - $buffer .= "\tserver default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "\tserver { {$tmp} } \\\n"; - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); - continue; - } - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); - continue; - } - $http_inspect_servers .= $buffer; - $http_inspect_servers .= "\tprofile {$v['server_profile']} \\\n"; - - if ($v['no_alerts'] == "on") - $http_inspect_servers .= "\tno_alerts \\\n"; - - if ($v['ports'] == "default" || empty($v['ports'])) - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - elseif (is_alias($v['ports'])) { - $tmp = trim(filter_expand_alias($v['ports'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $tmp = snort_expand_port_range($tmp, ' '); - $http_inspect_servers .= "\tports { {$tmp} } \\\n"; - } - else { - log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - } - } - else { - log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - } - - $http_inspect_servers .= "\tserver_flow_depth {$v['server_flow_depth']} \\\n"; - $http_inspect_servers .= "\tclient_flow_depth {$v['client_flow_depth']} \\\n"; - $http_inspect_servers .= "\thttp_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 } \\\n"; - $http_inspect_servers .= "\tpost_depth {$v['post_depth']} \\\n"; - $http_inspect_servers .= "\tmax_headers {$v['max_headers']} \\\n"; - $http_inspect_servers .= "\tmax_header_length {$v['max_header_length']} \\\n"; - $http_inspect_servers .= "\tmax_spaces {$v['max_spaces']}"; - if ($v['enable_xff'] == "on") - $http_inspect_servers .= " \\\n\tenable_xff"; - if ($v['enable_cookie'] == "on") - $http_inspect_servers .= " \\\n\tenable_cookie"; - if ($v['normalize_cookies'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_cookies"; - if ($v['normalize_headers'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_headers"; - if ($v['normalize_utf'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_utf"; - if ($v['allow_proxy_use'] == "on") - $http_inspect_servers .= " \\\n\tallow_proxy_use"; - if ($v['inspect_uri_only'] == "on") - $http_inspect_servers .= " \\\n\tinspect_uri_only"; - if ($v['extended_response_inspection'] == "on") { - $http_inspect_servers .= " \\\n\textended_response_inspection"; - if ($v['inspect_gzip'] == "on") { - $http_inspect_servers .= " \\\n\tinspect_gzip"; - if ($v['unlimited_decompress'] == "on") - $http_inspect_servers .= " \\\n\tunlimited_decompress"; - } - if ($v['normalize_javascript'] == "on") { - $http_inspect_servers .= " \\\n\tnormalize_javascript"; - $http_inspect_servers .= " \\\n\tmax_javascript_whitespaces {$v['max_javascript_whitespaces']}"; - } - } - if ($v['log_uri'] == "on") - $http_inspect_servers .= " \\\n\tlog_uri"; - if ($v['log_hostname'] == "on") - $http_inspect_servers .= " \\\n\tlog_hostname"; - - // Add a pair of trailing newlines to terminate this server config - $http_inspect_servers .= "\n\n"; - } - /* Trim off the final trailing newline */ - $http_inspect_server = rtrim($http_inspect_server); - } - - // Finally, build the Snort configuration file - $snort_conf_text = <<<EOD -# snort configuration file -# generated automatically by the pfSense subsystems do not modify manually - -# Define Local Network # -ipvar HOME_NET [{$home_net}] -ipvar EXTERNAL_NET [{$external_net}] - -# Define Rule Path # -var RULE_PATH {$snortcfgdir}/rules - -# Define Servers # -{$ipvardef} - -# Define Server Ports # -{$portvardef} - -# Configure quiet startup mode # -config quiet - -# Configure the snort decoder # -config checksum_mode: {$cksumcheck} -config disable_decode_alerts -config disable_tcpopt_experimental_alerts -config disable_tcpopt_obsolete_alerts -config disable_ttcp_alerts -config disable_tcpopt_alerts -config disable_ipopt_alerts -config disable_decode_drops - -# Enable the GTP decoder # -config enable_gtp - -# Configure PCRE match limitations -config pcre_match_limit: 3500 -config pcre_match_limit_recursion: 1500 - -# Configure the detection engine # -config detection: {$cfg_detect_settings} -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 # -{$paf_max_pdu_config} - -# Configure dynamically loaded libraries -dynamicpreprocessor directory {$snort_dirs['dynamicpreprocessor']} -dynamicengine directory {$snort_dirs['dynamicengine']} -dynamicdetection directory {$snort_dirs['dynamicrules']} - -# Inline packet normalization. For more information, see README.normalize -# Disabled since we do not use "inline" mode with pfSense -# preprocessor normalize_ip4 -# preprocessor normalize_tcp: ips ecn stream -# preprocessor normalize_icmp4 -# preprocessor normalize_ip6 -# preprocessor normalize_icmp6 - -# Flow and stream # -{$frag3_global} - -{$frag3_engine} - -{$stream5_global} - -{$stream5_tcp_engine} - -{$stream5_udp_engine} - -{$stream5_icmp_engine} - -# HTTP Inspect # -{$http_inspect_global} - -{$http_inspect_servers} -{$snort_preprocessors} -{$host_attrib_config} - -# Snort Output Logs # -output alert_csv: alert timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority -{$alertsystemlog_type} -{$snortunifiedlog_type} -{$spoink_type} - -# Misc Includes # -{$snort_misc_include_rules} - -{$suppress_file_name} - -# Snort user pass through configuration -{$snort_config_pass_thru} - -# Rules Selection # -{$selected_rules_sections} -EOD; - - // Write out snort.conf file - @file_put_contents("{$snortcfgdir}/snort.conf", $snort_conf_text); - conf_mount_ro(); + // Clean up variables we no longer need and free memory unset($snort_conf_text, $selected_rules_sections, $suppress_file_name, $snort_misc_include_rules, $spoink_type, $snortunifiedlog_type, $alertsystemlog_type); unset($home_net, $external_net, $ipvardef, $portvardef); } @@ -3801,8 +3665,10 @@ function snort_sync_on_changes() { global $config, $g; /* Do not attempt a package sync while booting up or installing package */ - if ($g['booting'] || $g['snort_postinstall']) + if ($g['booting'] || $g['snort_postinstall']) { + log_error("[snort] No xmlrpc sync to CARP targets when booting up or during package reinstallation."); return; + } if (is_array($config['installedpackages']['snortsync']['config'])){ $snort_sync=$config['installedpackages']['snortsync']['config'][0]; @@ -3848,13 +3714,14 @@ function snort_sync_on_changes() { else $syncstartsnort = "OFF"; $sync_to_ip = $sh['varsyncipaddress']; + $port = $sh['varsyncport']; $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); + snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $port, $username, $password, $synctimeout, $syncstartsnort); } log_error("[snort] Snort pkg xmlrpc sync completed."); } @@ -3862,12 +3729,14 @@ function snort_sync_on_changes() { } /* Do the actual XMLRPC sync */ -function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $password, $synctimeout, $syncstartsnort) { +function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $port, $username, $password, $synctimeout, $syncstartsnort) { global $config, $g; /* Do not attempt a package sync while booting up or installing package */ - if ($g['booting'] || $g['snort_postinstall']) + if ($g['booting'] || $g['snort_postinstall']) { + log_error("[snort] No xmlrpc sync to CARP targets when booting up or during package reinstallation."); 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"); @@ -3883,8 +3752,9 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw $synchronizetoip = $config['system']['webgui']['protocol']; $synchronizetoip .= "://"; } - $port = $config['system']['webgui']['port']; - /* if port is empty lets rely on the protocol selection */ + if ($port == "") + $port = $config['system']['webgui']['port']; + /* if port is empty let's rely on the protocol selection */ if($port == "") { if($config['system']['webgui']['protocol'] == "http") $port = "80"; @@ -3892,8 +3762,44 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw $port = "443"; } $synchronizetoip .= $sync_to_ip; + $url = $synchronizetoip; - /* xml will hold the sections to sync */ + /*************************************************/ + /* Send over any auto-SID management files */ + /*************************************************/ + $sid_files = glob(SNORT_SID_MODS_PATH . '*'); + foreach ($sid_files as $file) { + $content = base64_encode(file_get_contents($file)); + $payload = "@file_put_contents('{$file}', base64_decode('{$content}'));"; + + /* assemble xmlrpc payload */ + $method = 'pfsense.exec_php'; + $params = array( XML_RPC_encode($password), XML_RPC_encode($payload) ); + + log_error("[snort] Snort XMLRPC CARP sync sending auto-SID conf files 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); + $error = ""; + if(!$resp) { + $error = "A communications error occurred while attempting Snort XMLRPC CARP sync with {$url}:{$port}. Failed to transfer file: " . basename($file); + log_error($error); + file_notice("sync_settings", $error, "Snort Settings Sync", ""); + } elseif($resp->faultCode()) { + $error = "An error code was received while attempting Snort XMLRPC CARP sync with {$url}:{$port}. Failed to transfer file: " . basename($file) . " - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "Snort Settings Sync", ""); + } + } + + if (!empty($sid_files) && $error == "") + log_error("[snort] Snort pkg XMLRPC CARP sync auto-SID conf files success with {$url}:{$port} (pfsense.exec_php)."); + + /**************************************************/ + /* Send over the <snortglobal> portion of the */ + /* config.xml. $xml will hold section to sync. */ + /**************************************************/ $xml = array(); $xml['snortglobal'] = $config['installedpackages']['snortglobal']; /* assemble xmlrpc payload */ @@ -3902,8 +3808,6 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw 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); @@ -3927,18 +3831,19 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw $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"; + $downloadrulescmd .= "\tinclude_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"; + $snortstart = "log_error(gettext(\"[snort] XMLRPC pkg sync: Starting Snort if not running...\"));\n"; + $snortstart .= "\tsnort_start_all_interfaces(TRUE);\n"; } - /* Build a series of commands as a PHP file for the secondary host to execute to load the new settings. */ + /*************************************************/ + /* Build a series of commands as a PHP file for */ + /* the secondary host to execute to load the new */ + /* settings. */ + /*************************************************/ $snort_sync_cmd = <<<EOD <?php require_once("/usr/local/pkg/snort/snort.inc"); @@ -3953,7 +3858,9 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw unset(\$g["snort_postinstall"]); log_error(gettext("[snort] XMLRPC pkg sync: Generating snort.conf file using Master Host settings...")); \$rebuild_rules = true; + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); \$rebuild_rules = false; {$snortstart} log_error(gettext("[snort] XMLRPC pkg sync process on this host is complete...")); @@ -3964,7 +3871,10 @@ function snort_do_xmlrpc_sync($syncdownloadrules, $sync_to_ip, $username, $passw EOD; - /* First, have the target host write the commands to a PHP file in the /tmp directory */ + /*************************************************/ + /* First, have target host write the commands */ + /* to a PHP file in the /tmp directory. */ + /*************************************************/ $execcmd = "file_put_contents('/tmp/snort_sync_cmds.php', '{$snort_sync_cmd}');"; /* assemble xmlrpc payload */ @@ -3991,7 +3901,10 @@ EOD; log_error("[snort] Snort pkg XMLRPC reload configuration success with {$url}:{$port} (pfsense.exec_php)."); } - /* Now assemble a command to execute the previously sent PHP file in the background */ + /*************************************************/ + /* Now assemble a command to execute the */ + /* previously sent PHP file in the background. */ + /*************************************************/ $execcmd = "exec(\"/usr/local/bin/php -f '/tmp/snort_sync_cmds.php' > /dev/null 2>&1 &\");"; $params2 = array( XML_RPC_encode($password), diff --git a/config/snort/snort.priv.inc b/config/snort/snort.priv.inc index 8db5408d..928ecb52 100644 --- a/config/snort/snort.priv.inc +++ b/config/snort/snort.priv.inc @@ -11,6 +11,7 @@ $priv_list['page-services-snort']['match'][] = "snort/snort_barnyard.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_blocked.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_check_for_rule_updates.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_define_servers.php*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_defs.inc*"; $priv_list['page-services-snort']['match'][] = "snort/snort_download_rules.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_download_updates.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_edit_hat_data.php*"; @@ -37,13 +38,18 @@ $priv_list['page-services-snort']['match'][] = "snort/snort_rulesets.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_select_alias.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_stream5_engine.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_ip_list_mgmt.php*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_sid_mgmt.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_ip_reputation.php*"; $priv_list['page-services-snort']['match'][] = "snort/snort_iprep_list_browser.php*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_generate_conf.php*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_interface_logs.php*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_log_mgmt.php*"; $priv_list['page-services-snort']['match'][] = "widgets/javascript/snort_alerts.js*"; $priv_list['page-services-snort']['match'][] = "widgets/include/widget-snort.inc*"; $priv_list['page-services-snort']['match'][] = "widgets/widgets/snort_alerts.widget.php*"; $priv_list['page-services-snort']['match'][] = "pkg_edit.php?xml=snort_sync.xml*"; $priv_list['page-services-snort']['match'][] = "pkg_edit.php?xml=snort/snort.xml*"; $priv_list['page-services-snort']['match'][] = "snort/snort_check_cron_misc.inc*"; +$priv_list['page-services-snort']['match'][] = "snort/snort_conf_template.inc*"; $priv_list['page-services-snort']['match'][] = "snort/snort.inc*"; ?>
\ No newline at end of file diff --git a/config/snort/snort.xml b/config/snort/snort.xml index ca99accf..fb23997c 100755 --- a/config/snort/snort.xml +++ b/config/snort/snort.xml @@ -46,8 +46,8 @@ <requirements>None</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>Snort</name> - <version>2.9.6.0</version> - <title>Services:2.9.6.0 pkg v3.0.8</title> + <version>2.9.7.0</version> + <title>Services:2.9.7.0 pkg v3.2.2</title> <include_file>/usr/local/pkg/snort/snort.inc</include_file> <menu> <name>Snort</name> @@ -74,12 +74,17 @@ <item>https://packages.pfsense.org/packages/config/snort/snort_check_cron_misc.inc</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_conf_template.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> <item>https://packages.pfsense.org/packages/config/snort/snort_migrate_config.php</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> + <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> <item>https://packages.pfsense.org/packages/config/snort/snort_post_install.php</item> </additional_files_needed> @@ -119,11 +124,16 @@ <item>https://packages.pfsense.org/packages/config/snort/snort_download_updates.php</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> + <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> <item>https://packages.pfsense.org/packages/config/snort/snort_check_for_rule_updates.php</item> </additional_files_needed> <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_defs.inc</item> + </additional_files_needed> + <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> <item>https://packages.pfsense.org/packages/config/snort/snort_interfaces.php</item> @@ -249,6 +259,26 @@ <item>https://packages.pfsense.org/packages/config/snort/snort_iprep_list_browser.php</item> </additional_files_needed> <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_interface_logs.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_log_mgmt.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_sid_mgmt.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>https://packages.pfsense.org/packages/config/snort/snort_generate_conf.php</item> + </additional_files_needed> + <additional_files_needed> <prefix>/usr/local/www/widgets/javascript/</prefix> <chmod>0644</chmod> <item>https://packages.pfsense.org/packages/config/snort/snort_alerts.js</item> @@ -263,19 +293,33 @@ <chmod>0644</chmod> <item>https://packages.pfsense.org/packages/config/snort/widget-snort.inc</item> </additional_files_needed> + <additional_files_needed> + <prefix>/var/db/snort/sidmods/</prefix> + <chmod>0644</chmod> + <item>https://packages.pfsense.org/packages/config/snort/disablesid-sample.conf</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/var/db/snort/sidmods/</prefix> + <chmod>0644</chmod> + <item>https://packages.pfsense.org/packages/config/snort/enablesid-sample.conf</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/var/db/snort/sidmods/</prefix> + <chmod>0644</chmod> + <item>https://packages.pfsense.org/packages/config/snort/modifysid-sample.conf</item> + </additional_files_needed> <fields> </fields> <custom_add_php_command> </custom_add_php_command> <custom_php_resync_config_command> <![CDATA[ - if ($GLOBALS['pfSense_snort_version'] == "3.0.8") sync_snort_package_config(); ]]> </custom_php_resync_config_command> <custom_php_install_command> <![CDATA[ - include_once("/usr/local/www/snort/snort_post_install.php"); + include_once("/usr/local/pkg/snort/snort_post_install.php"); ]]> </custom_php_install_command> <custom_php_deinstall_command> diff --git a/config/snort/snort_alerts.js b/config/snort/snort_alerts.js index 647eb1b1..8133b928 100644 --- a/config/snort/snort_alerts.js +++ b/config/snort/snort_alerts.js @@ -50,11 +50,11 @@ function snort_alerts_fetch_new_events_callback(callback_data) { for(var x=0; x<data_split.length-1; x++) { row_split = data_split[x].split("||"); var line = ''; - line = '<td class="' + snortWidgetColClass + '">' + row_split[0] + '<br/>' + row_split[1] + '</td>'; - line += '<td class="' + snortWidgetColClass + '" style="overflow: hidden; text-overflow: ellipsis;" nowrap>'; + line = '<td class="listMRr">' + row_split[0] + '<br/>' + row_split[1] + '</td>'; + line += '<td class="listMRr" style="overflow: hidden; text-overflow: ellipsis;" nowrap>'; line += '<div style="display:inline;" title="' + row_split[2] + '">' + row_split[2] + '</div><br/>'; line += '<div style="display:inline;" title="' + row_split[3] + '">' + row_split[3] + '</div></td>'; - line += '<td class="' + snortWidgetColClass + '">' + 'Priority: ' + row_split[4] + ' ' + row_split[5] + '</td>'; + line += '<td class="listMRr"><div style="display: fixed; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1.2em; max-height: 2.4em; overflow: hidden; text-overflow: ellipsis;" title="' + row_split[4] + '">' + row_split[4] + '</div></td>'; new_data_to_add[new_data_to_add.length] = line; } snort_alerts_update_div_rows(new_data_to_add); diff --git a/config/snort/snort_alerts.php b/config/snort/snort_alerts.php index 45443ec2..3f3159a6 100755 --- a/config/snort/snort_alerts.php +++ b/config/snort/snort_alerts.php @@ -7,6 +7,7 @@ * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. * Copyright (C) 2006 Scott Ullrich * Copyright (C) 2012 Ermal Luci + * Copyright (C) 2014 Jim Pingle jim@pingle.org * Copyright (C) 2013,2014 Bill Meeks * All rights reserved. * @@ -41,6 +42,7 @@ require_once("/usr/local/pkg/snort/snort.inc"); $snortalertlogt = $config['installedpackages']['snortglobal']['snortalertlogtype']; $supplist = array(); $snortlogdir = SNORTLOGDIR; +$filterlogentries = FALSE; function snort_is_alert_globally_suppressed($list, $gid, $sid) { @@ -124,7 +126,9 @@ function snort_add_supplist_entry($suppress) { /* tell Snort to load it, and return true; otherwise return false. */ if ($found_list) { write_config("Snort pkg: modified Suppress List {$list_name}."); + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); snort_reload_config($a_instance[$instanceid]); return true; } @@ -132,6 +136,32 @@ function snort_add_supplist_entry($suppress) { return false; } +function snort_escape_filter_regex($filtertext) { + /* If the caller (user) has not already put a backslash before a slash, to escape it in the regex, */ + /* then this will do it. Take out any "\/" already there, then turn all ordinary "/" into "\/". */ + return str_replace('/', '\/', str_replace('\/', '/', $filtertext)); +} + +function snort_match_filter_field($flent, $fields) { + foreach ($fields as $key => $field) { + if ($field == null) + continue; + if ((strpos($field, '!') === 0)) { + $field = substr($field, 1); + $field_regex = snort_escape_filter_regex($field); + if (@preg_match("/{$field_regex}/i", $flent[$key])) + return false; + } + else { + $field_regex = snort_escape_filter_regex($field); + if (!@preg_match("/{$field_regex}/i", $flent[$key])) + return false; + } + } + return true; +} + + if (isset($_POST['instance']) && is_numericint($_POST['instance'])) $instanceid = $_POST['instance']; elseif (isset($_GET['instance']) && is_numericint($_GET['instance'])) @@ -164,6 +194,50 @@ if (empty($pconfig['arefresh'])) $pconfig['arefresh'] = 'off'; $anentries = $pconfig['alertnumber']; +# --- AJAX REVERSE DNS RESOLVE Start --- +if (isset($_POST['resolve'])) { + $ip = strtolower($_POST['resolve']); + $res = (is_ipaddr($ip) ? gethostbyaddr($ip) : ''); + + if ($res && $res != $ip) + $response = array('resolve_ip' => $ip, 'resolve_text' => $res); + else + $response = array('resolve_ip' => $ip, 'resolve_text' => gettext("Cannot resolve")); + + echo json_encode(str_replace("\\","\\\\", $response)); // single escape chars can break JSON decode + exit; +} +# --- AJAX REVERSE DNS RESOLVE End --- + +if ($_POST['filterlogentries_submit']) { + // Set flag for filtering alert entries + $filterlogentries = TRUE; + + // -- IMPORTANT -- + // Note the order of these fields must match the order decoded from the alerts log + $filterfieldsarray = array(); + $filterfieldsarray[0] = $_POST['filterlogentries_time'] ? $_POST['filterlogentries_time'] : null; + $filterfieldsarray[1] = $_POST['filterlogentries_gid'] ? $_POST['filterlogentries_gid'] : null; + $filterfieldsarray[2] = $_POST['filterlogentries_sid'] ? $_POST['filterlogentries_sid'] : null; + $filterfieldsarray[3] = null; + $filterfieldsarray[4] = $_POST['filterlogentries_description'] ? $_POST['filterlogentries_description'] : null; + $filterfieldsarray[5] = $_POST['filterlogentries_protocol'] ? $_POST['filterlogentries_protocol'] : null; + // Remove any zero-length spaces added to the IP address that could creep in from a copy-paste operation + $filterfieldsarray[6] = $_POST['filterlogentries_sourceipaddress'] ? str_replace("\xE2\x80\x8B", "", $_POST['filterlogentries_sourceipaddress']) : null; + $filterfieldsarray[7] = $_POST['filterlogentries_sourceport'] ? $_POST['filterlogentries_sourceport'] : null; + // Remove any zero-length spaces added to the IP address that could creep in from a copy-paste operation + $filterfieldsarray[8] = $_POST['filterlogentries_destinationipaddress'] ? str_replace("\xE2\x80\x8B", "", $_POST['filterlogentries_destinationipaddress']) : null; + $filterfieldsarray[9] = $_POST['filterlogentries_destinationport'] ? $_POST['filterlogentries_destinationport'] : null; + $filterfieldsarray[10] = null; + $filterfieldsarray[11] = $_POST['filterlogentries_classification'] ? $_POST['filterlogentries_classification'] : null; + $filterfieldsarray[12] = $_POST['filterlogentries_priority'] ? $_POST['filterlogentries_priority'] : null; +} + +if ($_POST['filterlogentries_clear']) { + $filterlogentries = TRUE; + $filterfieldsarray = array(); +} + if ($_POST['save']) { if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) $config['installedpackages']['snortglobal']['alertsblocks'] = array(); @@ -283,7 +357,9 @@ if ($_POST['togglesid'] && is_numeric($_POST['sidid']) && is_numeric($_POST['gen /* rules for this interface. */ /*************************************************/ $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($a_instance[$instanceid]); + conf_mount_ro(); $rebuild_rules = false; /* Soft-restart Snort to live-load the new rules */ @@ -307,11 +383,11 @@ if ($_POST['delete']) { } if ($_POST['download']) { - $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); + $save_date = date("Y-m-d-H-i-s"); $file_name = "snort_logs_{$save_date}_{$if_real}.tar.gz"; - exec("cd {$snortlogdir}/snort_{$if_real}{$snort_uuid} && /usr/bin/tar -czf /tmp/{$file_name} *"); + exec("cd {$snortlogdir}/snort_{$if_real}{$snort_uuid} && /usr/bin/tar -czf {$g['tmp_path']}/{$file_name} *"); - if (file_exists("/tmp/{$file_name}")) { + if (file_exists("{$g['tmp_path']}/{$file_name}")) { ob_start(); //important or other posts will fail if (isset($_SERVER['HTTPS'])) { header('Pragma: '); @@ -321,13 +397,13 @@ if ($_POST['download']) { header("Cache-Control: private, must-revalidate"); } header("Content-Type: application/octet-stream"); - header("Content-length: " . filesize("/tmp/{$file_name}")); + header("Content-length: " . filesize("{$g['tmp_path']}/{$file_name}")); header("Content-disposition: attachment; filename = {$file_name}"); ob_end_clean(); //important or other post will fail - readfile("/tmp/{$file_name}"); + readfile("{$g['tmp_path']}/{$file_name}"); // Clean up the temp file - @unlink("/tmp/{$file_name}"); + unlink_if_exists("{$g['tmp_path']}/{$file_name}"); } else $savemsg = gettext("An error occurred while creating archive"); @@ -342,7 +418,6 @@ include_once("head.inc"); ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> -<script src="/javascript/filter_log.js" type="text/javascript"></script> <?php include_once("fbegin.inc"); @@ -376,7 +451,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -423,9 +500,97 @@ if ($savemsg) { </td> </tr> <tr> + <td colspan="2" class="listtopic"><?php echo gettext("Alert Log View Filter"); ?></td> + </tr> + <tr id="filter_enable_row" style="display:<?php if (!$filterlogentries) {echo "table-row;";} else {echo "none;";} ?>"> + <td width="22%" class="vncell"><?php echo gettext('Alert Log Filter Options'); ?></td> + <td width="78%" class="vtable"> + <input name="show_filter" id="show_filter" type="button" class="formbtns" value="<?=gettext("Show Filter");?>" onclick="enable_showFilter();" /> + <?=gettext("Click to display advanced filtering options dialog");?> + </td> + </tr> + <tr id="filter_options_row" style="display:<?php if (!$filterlogentries) {echo "none;";} else {echo "table-row;";} ?>"> + <td colspan="2"> + <table width="100%" border="0" cellpadding="0" cellspacing="1" summary="action"> + <tr> + <td valign="top"> + <div align="center"><?=gettext("Date");?></div> + <div align="center"><input id="filterlogentries_time" name="filterlogentries_time" class="formfld search" type="text" size="10" value="<?= $filterfieldsarray[0] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Source IP Address");?></div> + <div align="center"><input id="filterlogentries_sourceipaddress" name="filterlogentries_sourceipaddress" class="formfld search" type="text" size="28" value="<?= $filterfieldsarray[6] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Source Port");?></div> + <div align="center"><input id="filterlogentries_sourceport" name="filterlogentries_sourceport" class="formfld search" type="text" size="5" value="<?= $filterfieldsarray[7] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Description");?></div> + <div align="center"><input id="filterlogentries_description" name="filterlogentries_description" class="formfld search" type="text" size="28" value="<?= $filterfieldsarray[4] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("GID");?></div> + <div align="center"><input id="filterlogentries_gid" name="filterlogentries_gid" class="formfld search" type="text" size="6" value="<?= $filterfieldsarray[1] ?>" /></div> + </td> + </tr> + <tr> + <td valign="top"> + <div align="center"><?=gettext("Priority");?></div> + <div align="center"><input id="filterlogentries_priority" name="filterlogentries_priority" class="formfld search" type="text" size="10" value="<?= $filterfieldsarray[12] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Destination IP Address");?></div> + <div align="center"><input id="filterlogentries_destinationipaddress" name="filterlogentries_destinationipaddress" class="formfld search" type="text" size="28" value="<?= $filterfieldsarray[8] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Destination Port");?></div> + <div align="center"><input id="filterlogentries_destinationport" name="filterlogentries_destinationport" class="formfld search" type="text" size="5" value="<?= $filterfieldsarray[9] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("Classification");?></div> + <div align="center"><input id="filterlogentries_classification" name="filterlogentries_classification" class="formfld search" type="text" size="28" value="<?= $filterfieldsarray[11] ?>" /></div> + </td> + <td valign="top"> + <div align="center"><?=gettext("SID");?></div> + <div align="center"><input id="filterlogentries_sid" name="filterlogentries_sid" class="formfld search" type="text" size="6" value="<?= $filterfieldsarray[2] ?>" /></div> + </td> + </tr> + <tr> + <td valign="top"> + <div align="center"><?=gettext("Protocol");?></div> + <div align="center"><input id="filterlogentries_protocol" name="filterlogentries_protocol" class="formfld search" type="text" size="10" value="<?= $filterfieldsarray[5] ?>" /></div> + </td> + <td valign="top"> + </td> + <td valign="top"> + </td> + <td colspan="2" style="vertical-align:bottom"> + <div align="right"><input id="filterlogentries_submit" name="filterlogentries_submit" type="submit" class="formbtns" value="<?=gettext("Filter");?>" title="<?=gettext("Apply filter"); ?>" /> + <input id="filterlogentries_clear" name="filterlogentries_clear" type="submit" class="formbtns" value="<?=gettext("Clear");?>" title="<?=gettext("Remove filter");?>" /> + <input id="filterlogentries_hide" name="filterlogentries_hide" type="button" class="formbtns" value="<?=gettext("Hide");?>" onclick="enable_hideFilter();" title="<?=gettext("Hide filter options");?>" /></div> + </td> + </tr> + <tr> + <td colspan="5" style="vertical-align:bottom"> + <?printf(gettext('Matches %1$s regular expression%2$s.'), '<a target="_blank" href="http://www.php.net/manual/en/book.pcre.php">', '</a>');?> + <?=gettext("Precede with exclamation (!) as first character to exclude match.");?> + </td> + </tr> + </table> + </td> + </tr> + <?php if ($filterlogentries) : ?> + <tr> + <td colspan="2" class="listtopic"><?php printf(gettext("Last %s Alert Entries"), $anentries); ?> + <?php echo gettext("(Most recent listed first) ** FILTERED VIEW ** clear filter to see all entries"); ?></td> + </tr> + <?php else: ?> + <tr> <td colspan="2" class="listtopic"><?php printf(gettext("Last %s Alert Entries"), $anentries); ?> <?php echo gettext("(Most recent entries are listed first)"); ?></td> </tr> + <?php endif; ?> <tr> <td width="100%" colspan="2"> <table id="myTable" style="table-layout: fixed;" width="100%" class="sortable" border="0" cellpadding="0" cellspacing="0"> @@ -442,7 +607,7 @@ if ($savemsg) { <col axis="string"> </colgroup> <thead> - <tr> + <tr class="sortableHeaderRowIdentifier"> <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> @@ -460,17 +625,21 @@ if ($savemsg) { /* make sure alert file exists */ if (file_exists("{$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert")) { - exec("tail -{$anentries} -r {$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert > /tmp/alert_{$snort_uuid}"); - if (file_exists("/tmp/alert_{$snort_uuid}")) { + exec("tail -{$anentries} -r {$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert > {$g['tmp_path']}/alert_{$snort_uuid}"); + if (file_exists("{$g['tmp_path']}/alert_{$snort_uuid}")) { $tmpblocked = array_flip(snort_get_blocked_ips()); $counter = 0; /* 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"); + $fd = fopen("{$g['tmp_path']}/alert_{$snort_uuid}", "r"); while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { if(count($fields) < 13) continue; + if ($filterlogentries && !snort_match_filter_field($fields, $filterfieldsarray)) { + continue; + } + /* Time */ $alert_time = substr($fields[0], strpos($fields[0], '-')+1, -8); /* Date */ @@ -486,16 +655,12 @@ if (file_exists("{$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert")) { $alert_ip_src = $fields[6]; /* Add zero-width space as soft-break opportunity after each colon if we have an IPv6 address */ $alert_ip_src = str_replace(":", ":​", $alert_ip_src); + /* Add Reverse DNS lookup icons (two different links if pfSense version supports them) */ $alert_ip_src .= "<br/>"; - if ($pfs_version > 2.0) { - $alert_ip_src .= "<a onclick=\"javascript:getURL('/diag_dns.php?host={$fields[6]}&dialog_output=true', outputrule);\">"; - $alert_ip_src .= "<img src='../themes/{$g['theme']}/images/icons/icon_log_d.gif' width='11' height='11' border='0' "; - $alert_ip_src .= "title='" . gettext("Resolve host via reverse DNS lookup (quick pop-up)") . "' style=\"cursor: pointer;\"></a> "; - } - $alert_ip_src .= "<a href='/diag_dns.php?host={$fields[6]}&instance={$instanceid}'>"; - $alert_ip_src .= "<img src='../themes/{$g['theme']}/images/icons/icon_log.gif' width='11' height='11' border='0' "; - $alert_ip_src .= "title='" . gettext("Resolve host via reverse DNS lookup") . "'></a>"; + $alert_ip_src .= "<img onclick=\"javascript:resolve_with_ajax('{$fields[6]}');\" title=\""; + $alert_ip_src .= gettext("Resolve host via reverse DNS lookup") . "\" border=\"0\" src=\"/themes/{$g['theme']}/images/icons/icon_log.gif\" alt=\"Icon Reverse Resolve with DNS\" "; + $alert_ip_src .= " style=\"cursor: pointer;\"/>"; /* Add icons for auto-adding to Suppress List if appropriate */ if (!snort_is_alert_globally_suppressed($supplist, $fields[1], $fields[2]) && @@ -519,16 +684,13 @@ if (file_exists("{$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert")) { $alert_ip_dst = $fields[8]; /* Add zero-width space as soft-break opportunity after each colon if we have an IPv6 address */ $alert_ip_dst = str_replace(":", ":​", $alert_ip_dst); + /* Add Reverse DNS lookup icons (two different links if pfSense version supports them) */ $alert_ip_dst .= "<br/>"; - if ($pfs_version > 2.0) { - $alert_ip_dst .= "<a onclick=\"javascript:getURL('/diag_dns.php?host={$fields[8]}&dialog_output=true', outputrule);\">"; - $alert_ip_dst .= "<img src='../themes/{$g['theme']}/images/icons/icon_log_d.gif' width='11' height='11' border='0' "; - $alert_ip_dst .= "title='" . gettext("Resolve host via reverse DNS lookup (quick pop-up)") . "' style=\"cursor: pointer;\"></a> "; - } - $alert_ip_dst .= "<a href='/diag_dns.php?host={$fields[8]}&instance={$instanceid}'>"; - $alert_ip_dst .= "<img src='../themes/{$g['theme']}/images/icons/icon_log.gif' width='11' height='11' border='0' "; - $alert_ip_dst .= "title='" . gettext("Resolve host via reverse DNS lookup") . "'></a>"; + $alert_ip_dst .= "<img onclick=\"javascript:resolve_with_ajax('{$fields[8]}');\" title=\""; + $alert_ip_dst .= gettext("Resolve host via reverse DNS lookup") . "\" border=\"0\" src=\"/themes/{$g['theme']}/images/icons/icon_log.gif\" alt=\"Icon Reverse Resolve with DNS\" "; + $alert_ip_dst .= " style=\"cursor: pointer;\"/>"; + /* Add icons for auto-adding to Suppress List if appropriate */ if (!snort_is_alert_globally_suppressed($supplist, $fields[1], $fields[2]) && !isset($supplist[$fields[1]][$fields[2]]['by_dst'][$fields[8]])) { @@ -578,17 +740,17 @@ if (file_exists("{$snortlogdir}/snort_{$if_real}{$snort_uuid}/alert")) { <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' sorttable_customkey='{$fields[6]}'>{$alert_ip_src}</td> + <td class='listr' align='center' style=\"sorttable_customkey:{$fields[6]};\" sorttable_customkey=\"{$fields[6]}\">{$alert_ip_src}</td> <td class='listr' align='center'>{$alert_src_p}</td> - <td class='listr' align='center' sorttable_customkey='{$fields[8]}'>{$alert_ip_dst}</td> + <td class='listr' align='center' style=\"sorttable_customkey:{$fields[8]};\" sorttable_customkey=\"{$fields[8]}\">{$alert_ip_dst}</td> <td class='listr' align='center'>{$alert_dst_p}</td> - <td class='listr' align='center' sorttable_customkey='{$fields[2]}'>{$alert_sid_str}<br/>{$sidsupplink} {$sid_dsbl_link}</td> + <td class='listr' align='center' style=\"sorttable_customkey:{$fields[2]};\" sorttable_customkey=\"{$fields[2]}\">{$alert_sid_str}<br/>{$sidsupplink} {$sid_dsbl_link}</td> <td class='listbg' style=\"word-wrap:break-word;\">{$alert_descr}</td> </tr>\n"; $counter++; } fclose($fd); - @unlink("/tmp/alert_{$snort_uuid}"); + unlink_if_exists("{$g['tmp_path']}/alert_{$snort_uuid}"); } } ?> @@ -619,6 +781,50 @@ function encRuleSig(rulegid,rulesid,srcip,ruledescr) { document.getElementById("ip").value = srcip; document.getElementById("descr").value = ruledescr; } + +function enable_showFilter() { + document.getElementById("filter_enable_row").style.display="none"; + document.getElementById("filter_options_row").style.display="table-row"; +} + +function enable_hideFilter() { + document.getElementById("filter_enable_row").style.display="table-row"; + document.getElementById("filter_options_row").style.display="none"; +} + </script> + +<!-- The following AJAX code was borrowed from the diag_logs_filter.php --> +<!-- file in pfSense. See copyright info at top of this page. --> +<script type="text/javascript"> +//<![CDATA[ +function resolve_with_ajax(ip_to_resolve) { + var url = "/snort/snort_alerts.php"; + + jQuery.ajax( + url, + { + type: 'post', + dataType: 'json', + data: { + resolve: ip_to_resolve, + }, + complete: resolve_ip_callback + }); +} + +function resolve_ip_callback(transport) { + var response = jQuery.parseJSON(transport.responseText); + var msg = 'IP address "' + response.resolve_ip + '" resolves to\n'; + alert(msg + 'host "' + htmlspecialchars(response.resolve_text) + '"'); +} + +// From http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities +function htmlspecialchars(str) { + return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); +} +//]]> +</script> + </body> </html> diff --git a/config/snort/snort_alerts.widget.php b/config/snort/snort_alerts.widget.php index 0700ef2a..552dab61 100644 --- a/config/snort/snort_alerts.widget.php +++ b/config/snort/snort_alerts.widget.php @@ -39,19 +39,10 @@ if (!is_array($config['installedpackages']['snortglobal']['rule'])) $config['installedpackages']['snortglobal']['rule'] = array(); $a_instance = &$config['installedpackages']['snortglobal']['rule']; -// Test pfSense version and set different CSS class variables -// depending on version. 2.1 offers enhanced CSS styles. -$pfs_version=substr(trim(file_get_contents("/etc/version")),0,3); -if ($pfs_version > '2.0') { - $alertRowEvenClass = "listMReven"; - $alertRowOddClass = "listMRodd"; - $alertColClass = "listMRr"; -} -else { - $alertRowEvenClass = "listr"; - $alertRowOddClass = "listr"; - $alertColClass = "listr"; -} +// Set some CSS class variables +$alertRowEvenClass = "listMReven"; +$alertRowOddClass = "listMRodd"; +$alertColClass = "listMRr"; /* check if Snort widget alert display lines value is set */ $snort_nentries = $config['widgets']['widget_snort_display_lines']; @@ -93,7 +84,7 @@ if (isset($_GET['getNewAlerts'])) { $counter = 0; foreach ($s_alerts as $a) { $response .= $a['instanceid'] . " " . $a['dateonly'] . "||" . $a['timeonly'] . "||" . $a['src'] . "||"; - $response .= $a['dst'] . "||" . $a['priority'] . "||" . $a['category'] . "\n"; + $response .= $a['dst'] . "||" . $a['msg'] . "\n"; $counter++; if($counter >= $snort_nentries) break; @@ -165,8 +156,7 @@ function snort_widget_get_alerts() { // Add the DST PORT if not null if (!empty($fields[9])) $snort_alerts[$counter]['dst'] .= ":" . trim($fields[9]); - $snort_alerts[$counter]['priority'] = trim($fields[12]); - $snort_alerts[$counter]['category'] = trim($fields[11]); + $snort_alerts[$counter]['msg'] = trim($fields[4]); $counter++; }; fclose($fd); @@ -205,7 +195,7 @@ function snort_widget_get_alerts() { <tr> <th class="widgetsubheader"><?=gettext("IF/Date");?></th> <th class="widgetsubheader"><?=gettext("Src/Dst Address");?></th> - <th class="widgetsubheader"><?=gettext("Classification");?></th> + <th class="widgetsubheader"><?=gettext("Description");?></th> </tr> </thead> <tbody id="snort-alert-entries"> @@ -216,9 +206,9 @@ function snort_widget_get_alerts() { foreach ($snort_alerts as $alert) { $alertRowClass = $counter % 2 ? $alertRowEvenClass : $alertRowOddClass; echo(" <tr class='" . $alertRowClass . "'> - <td class='" . $alertColClass . "'>" . $alert['instanceid'] . " " . $alert['dateonly'] . "<br/>" . $alert['timeonly'] . "</td> - <td class='" . $alertColClass . "' style='overflow: hidden; text-overflow: ellipsis;' nowrap><div style='display:inline;' title='" . $alert['src'] . "'>" . $alert['src'] . "</div><br/><div style='display:inline;' title='" . $alert['dst'] . "'>" . $alert['dst'] . "</div></td> - <td class='" . $alertColClass . "'>Priority: " . $alert['priority'] . " " . $alert['category'] . "</td></tr>"); + <td class='listMRr'>" . $alert['instanceid'] . " " . $alert['dateonly'] . "<br/>" . $alert['timeonly'] . "</td> + <td class='listMRr' style='overflow: hidden; text-overflow: ellipsis;' nowrap><div style='display:inline;' title='" . $alert['src'] . "'>" . $alert['src'] . "</div><br/><div style='display:inline;' title='" . $alert['dst'] . "'>" . $alert['dst'] . "</div></td> + <td class='listMRr'><div style='display: fixed; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1.2em; max-height: 2.4em; overflow: hidden; text-overflow: ellipsis;' title='{$alert['msg']}'>" . $alert['msg'] . "</div></td></tr>"); $counter++; if($counter >= $snort_nentries) break; @@ -233,9 +223,8 @@ function snort_widget_get_alerts() { <!-- needed in the snort_alerts.js file code --> var snortupdateDelay = 10000; // update every 10 seconds var snort_nentries = <?=$snort_nentries;?>; // number of alerts to display (5 is default) - var snortWidgetRowEvenClass = "<?=$alertRowEvenClass;?>"; // allows alternating background on 2.1 and higher - var snortWidgetRowOddClass = "<?=$alertRowOddClass;?>"; // allows alternating background on 2.1 and higher - var snortWidgetColClass = "<?=$alertColClass;?>"; // sets column CSS style (different on 2.1 and higher) + var snortWidgetRowEvenClass = "<?=$alertRowEvenClass;?>"; // allows alternating background + var snortWidgetRowOddClass = "<?=$alertRowOddClass;?>"; // allows alternating background <!-- needed to display the widget settings menu --> selectIntLink = "snort_alerts-configure"; diff --git a/config/snort/snort_barnyard.php b/config/snort/snort_barnyard.php index 902c1637..b3e3723e 100644 --- a/config/snort/snort_barnyard.php +++ b/config/snort/snort_barnyard.php @@ -57,8 +57,8 @@ $retentions = array( '0' => gettext('KEEP ALL'), '24' => gettext('1 DAY'), '168' '720' => gettext('30 DAYS'), '1080' => gettext("45 DAYS"), '2160' => gettext('90 DAYS'), '4320' => gettext('180 DAYS'), '8766' => gettext('1 YEAR'), '26298' => gettext("3 YEARS") ); -$log_sizes = array( '0' => gettext('NO LIMIT'), '8' => gettext('8 MB'), '16' => gettext('16 MB'), '32' => gettext('32 MB'), - '64' => gettext('64 MB'), '128' => gettext('128 MB'), '256' => gettext('256 MB') ); +$log_sizes = array( '0' => gettext('NO LIMIT'), '128K' => '128 KB', '256K' => '256 KB', '512K' => '512 KB', '1M' => '1 MB', '4M' => '4 MB', '8M' => gettext('8 MB'), + '16M' => gettext('16 MB'), '32M' => gettext('32 MB'), '64M' => gettext('64 MB'), '128M' => gettext('128 MB'), '256M' => gettext('256 MB') ); if (isset($id) && $a_nat[$id]) { $pconfig = $a_nat[$id]; @@ -69,7 +69,7 @@ if (isset($id) && $a_nat[$id]) { if (empty($a_nat[$id]['barnyard_show_year'])) $pconfig['barnyard_show_year'] = "on"; if (empty($a_nat[$id]['unified2_log_limit'])) - $pconfig['unified2_log_limit'] = "32"; + $pconfig['unified2_log_limit'] = "128K"; if (empty($a_nat[$id]['barnyard_archive_enable'])) $pconfig['barnyard_archive_enable'] = "on"; if (empty($a_nat[$id]['u2_archived_log_retention'])) @@ -91,6 +91,30 @@ if (isset($id) && $a_nat[$id]) { } if ($_POST['save']) { + + // If disabling Barnyard2 on the interface, stop any + // currently running instance, then save the disabled + // state and exit. + if ($_POST['barnyard_enable'] != 'on') { + $a_nat[$id]['barnyard_enable'] = 'off'; + write_config("Snort pkg: modified Barnyard2 settings."); + touch("{$g['varrun_path']}/barnyard2_{$uuid}.disabled"); + snort_barnyard_stop($a_nat[$id], get_real_interface($a_nat[$id]['interface'])); + + // No need to rebuild rules for Barnyard2 changes + $rebuild_rules = false; + conf_mount_rw(); + sync_snort_package_config(); + conf_mount_ro(); + 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' ); + header( 'Cache-Control: post-check=0, pre-check=0', false ); + header( 'Pragma: no-cache' ); + header("Location: /snort/snort_barnyard.php"); + exit; + } + // Check that at least one output plugin is enabled if ($_POST['barnyard_mysql_enable'] != 'on' && $_POST['barnyard_syslog_enable'] != 'on' && $_POST['barnyard_bro_ids_enable'] != 'on' && $_POST['barnyard_enable'] == "on") @@ -106,6 +130,12 @@ if ($_POST['save']) { $input_errors[] = gettext("You must provide a DB user login name when logging to a MySQL database."); } + // Validate Sensor Name contains no spaces + if ($_POST['barnyard_enable'] == 'on') { + if (!empty($_POST['barnyard_sensor_name']) && strpos($_POST['barnyard_sensor_name'], " ") !== FALSE) + $input_errors[] = gettext("The value for 'Sensor Name' cannot contain spaces."); + } + // Validate inputs if syslog output enabled if ($_POST['barnyard_syslog_enable'] == 'on' && $_POST['barnyard_enable'] == "on") { if ($_POST['barnyard_log_vlan_events'] == 'on' || $_POST['barnyard_log_mpls_events'] == 'on') @@ -161,14 +191,16 @@ if ($_POST['save']) { if ($_POST['barnyard_syslog_priority']) $natent['barnyard_syslog_priority'] = $_POST['barnyard_syslog_priority']; else $natent['barnyard_syslog_priority'] = 'LOG_INFO'; if ($_POST['barnyard_bro_ids_rhost']) $natent['barnyard_bro_ids_rhost'] = $_POST['barnyard_bro_ids_rhost']; else unset($natent['barnyard_bro_ids_rhost']); if ($_POST['barnyard_bro_ids_dport']) $natent['barnyard_bro_ids_dport'] = $_POST['barnyard_bro_ids_dport']; else $natent['barnyard_bro_ids_dport'] = '47760'; - if ($_POST['barnconfigpassthru']) $natent['barnconfigpassthru'] = base64_encode($_POST['barnconfigpassthru']); else unset($natent['barnconfigpassthru']); + if ($_POST['barnconfigpassthru']) $natent['barnconfigpassthru'] = base64_encode(str_replace("\r\n", "\n", $_POST['barnconfigpassthru'])); else unset($natent['barnconfigpassthru']); $a_nat[$id] = $natent; write_config("Snort pkg: modified Barnyard2 settings."); // No need to rebuild rules for Barnyard2 changes $rebuild_rules = false; + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); // If disabling Barnyard2 on the interface, stop any // currently running instance. If an instance is @@ -230,7 +262,9 @@ include_once("head.inc"); $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td>'; @@ -243,6 +277,7 @@ include_once("head.inc"); $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -275,7 +310,7 @@ include_once("head.inc"); <?php if ($k == $pconfig['unified2_log_limit']) echo "selected"; ?>> <?=htmlspecialchars($p);?></option> <?php endforeach; ?> - </select> <?php echo gettext("Choose a Unified2 Log file size limit in megabytes (MB). Default is "); ?><strong><?=gettext("32 MB.");?></strong><br/><br/> + </select> <?php echo gettext("Choose a Unified2 Log file size limit. Default is "); ?><strong><?=gettext("128 KB.");?></strong><br/><br/> <?php echo gettext("This sets the maximum size for a Unified2 Log file before it is rotated and a new one created."); ?> </td> </tr> @@ -418,7 +453,7 @@ include_once("head.inc"); <input name="barnyard_syslog_local" type="checkbox" value="on" <?php if ($pconfig['barnyard_syslog_local'] == "on") echo "checked"; ?> onClick="toggle_local_syslog()"/> <?php echo gettext("Enable logging of alerts to the local system only"); ?><br/> - <?php echo gettext("This will send alert data to the local system only and overrides the host, port, protocol, facility and priority values below."); ?></td> + <?php echo gettext("This will send alert data to the local system only and overrides the host, port, and protocol values below."); ?></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Remote Host"); ?></td> @@ -461,7 +496,7 @@ include_once("head.inc"); echo "<option value='{$facility}'{$selected}>" . $facility . "</option>\n"; } ?></select> - <?php echo gettext("Select Syslog Facility to use for remote reporting. Default is ") . "<strong>" . gettext("LOG_USER") . "</strong>."; ?> + <?php echo gettext("Select Syslog Facility to use for reporting. Default is ") . "<strong>" . gettext("LOG_USER") . "</strong>."; ?> </td> </tr> <tr> @@ -477,7 +512,7 @@ include_once("head.inc"); echo "<option value='{$priority}'{$selected}>" . $priority . "</option>\n"; } ?></select> - <?php echo gettext("Select Syslog Priority (Level) to use for remote reporting. Default is ") . "<strong>" . gettext("LOG_INFO") . "</strong>."; ?> + <?php echo gettext("Select Syslog Priority (Level) to use for reporting. Default is ") . "<strong>" . gettext("LOG_INFO") . "</strong>."; ?> </td> </tr> </tbody> @@ -583,8 +618,6 @@ function toggle_local_syslog() { document.iform.barnyard_syslog_dport.disabled = endis; document.iform.barnyard_syslog_proto_udp.disabled = endis; document.iform.barnyard_syslog_proto_tcp.disabled = endis; - document.iform.barnyard_syslog_facility.disabled = endis; - document.iform.barnyard_syslog_priority.disabled = endis; } } diff --git a/config/snort/snort_blocked.php b/config/snort/snort_blocked.php index 76d5a9df..39119210 100644 --- a/config/snort/snort_blocked.php +++ b/config/snort/snort_blocked.php @@ -7,6 +7,7 @@ * * Modified for the Pfsense snort package v. 1.8+ * Copyright (C) 2009 Robert Zelaya Sr. Developer + * Copyright (C) 2014 Jim Pingle jim@pingle.org * Copyright (C) 2014 Bill Meeks * * Redistribution and use in source and binary forms, with or without @@ -50,6 +51,21 @@ if (empty($pconfig['blertnumber'])) else $bnentries = $pconfig['blertnumber']; +# --- AJAX REVERSE DNS RESOLVE Start --- +if (isset($_POST['resolve'])) { + $ip = strtolower($_POST['resolve']); + $res = (is_ipaddr($ip) ? gethostbyaddr($ip) : ''); + + if ($res && $res != $ip) + $response = array('resolve_ip' => $ip, 'resolve_text' => $res); + else + $response = array('resolve_ip' => $ip, 'resolve_text' => gettext("Cannot resolve")); + + echo json_encode(str_replace("\\","\\\\", $response)); // single escape chars can break JSON decode + exit; +} +# --- AJAX REVERSE DNS RESOLVE End --- + if ($_POST['todelete']) { $ip = ""; if ($_POST['ip']) @@ -73,22 +89,22 @@ if ($_POST['download']) exec('/sbin/pfctl -t snort2c -T show', $blocked_ips_array_save); /* build the list */ if (is_array($blocked_ips_array_save) && count($blocked_ips_array_save) > 0) { - $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); + $save_date = date("Y-m-d-H-i-s"); $file_name = "snort_blocked_{$save_date}.tar.gz"; - exec('/bin/mkdir -p /tmp/snort_blocked'); - file_put_contents("/tmp/snort_blocked/snort_block.pf", ""); + safe_mkdir("{$g['tmp_path']}/snort_blocked"); + file_put_contents("{$g['tmp_path']}/snort_blocked/snort_block.pf", ""); foreach($blocked_ips_array_save as $counter => $fileline) { if (empty($fileline)) continue; $fileline = trim($fileline, " \n\t"); - file_put_contents("/tmp/snort_blocked/snort_block.pf", "{$fileline}\n", FILE_APPEND); + file_put_contents("{$g['tmp_path']}/snort_blocked/snort_block.pf", "{$fileline}\n", FILE_APPEND); } // Create a tar gzip archive of blocked host IP addresses - exec("/usr/bin/tar -czf /tmp/{$file_name} -C/tmp/snort_blocked snort_block.pf"); + exec("/usr/bin/tar -czf {$g['tmp_path']}/{$file_name} -C{$g['tmp_path']}/snort_blocked snort_block.pf"); // If we successfully created the archive, send it to the browser. - if(file_exists("/tmp/{$file_name}")) { + if(file_exists("{$g['tmp_path']}/{$file_name}")) { ob_start(); //important or other posts will fail if (isset($_SERVER['HTTPS'])) { header('Pragma: '); @@ -98,14 +114,14 @@ if ($_POST['download']) header("Cache-Control: private, must-revalidate"); } header("Content-Type: application/octet-stream"); - header("Content-length: " . filesize("/tmp/{$file_name}")); + header("Content-length: " . filesize("{$g['tmp_path']}/{$file_name}")); header("Content-disposition: attachment; filename = {$file_name}"); ob_end_clean(); //important or other post will fail - readfile("/tmp/{$file_name}"); + readfile("{$g['tmp_path']}/{$file_name}"); // Clean up the temp files and directory - @unlink("/tmp/{$file_name}"); - exec("/bin/rm -fr /tmp/snort_blocked"); + unlink_if_exists("{$g['tmp_path']}/{$file_name}"); + rmdir_recursive("{$g['tmp_path']}/snort_blocked"); } else $savemsg = gettext("An error occurred while creating archive"); } else @@ -133,7 +149,6 @@ include_once("head.inc"); ?> <body link="#000000" vlink="#000000" alink="#000000"> -<script src="/javascript/filter_log.js" type="text/javascript"></script> <?php @@ -168,7 +183,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td> @@ -185,7 +202,7 @@ if ($savemsg) { <input name="download" type="submit" class="formbtns" value="Download" title="<?=gettext("Download list of blocked hosts as a gzip archive");?>"/> <?php echo gettext("All blocked hosts will be saved."); ?> <input name="remove" type="submit" class="formbtns" value="Clear" title="<?=gettext("Remove blocks for all listed hosts");?>" - onClick="return confirm('<?=gettext("Are you sure you want to remove all blocked hosts? Click OK to continue or CANCLE to quit.");?>');"/> + onClick="return confirm('<?=gettext("Are you sure you want to remove all blocked hosts? Click OK to continue or CANCEL to quit.");?>');"/> <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> <?php echo gettext("all hosts will be removed."); ?> </td> </tr> @@ -214,11 +231,11 @@ if ($savemsg) { <col width="10%" align="center"> </colgroup> <thead> - <tr> + <tr class="sortableHeaderRowIdentifier"> <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> + <th class="listhdrr sorttable_nosort"><?php echo gettext("Remove"); ?></th> </tr> </thead> <tbody> @@ -278,20 +295,16 @@ if ($savemsg) { $tmp_ip = str_replace(":", ":​", $blocked_ip); /* Add reverse DNS lookup icons (two different links if pfSense version supports them) */ $rdns_link = ""; - if ($pfs_version > 2.0) { - $rdns_link .= "<a onclick=\"javascript:getURL('/diag_dns.php?host={$blocked_ip}&dialog_output=true', outputrule);\">"; - $rdns_link .= "<img src='../themes/{$g['theme']}/images/icons/icon_log_d.gif' width='11' height='11' border='0' "; - $rdns_link .= "title='" . gettext("Resolve host via reverse DNS lookup (quick pop-up)") . "' style=\"cursor: pointer;\"></a> "; - } - $rdns_link .= "<a href='/diag_dns.php?host={$blocked_ip}'>"; - $rdns_link .= "<img src='../themes/{$g['theme']}/images/icons/icon_log.gif' width='11' height='11' border='0' "; - $rdns_link .= "title='" . gettext("Resolve host via reverse DNS lookup") . "'></a>"; + $rdns_link .= "<img onclick=\"javascript:resolve_with_ajax('{$blocked_ip}');\" title=\""; + $rdns_link .= gettext("Resolve host via reverse DNS lookup") . "\" border=\"0\" src=\"/themes/{$g['theme']}/images/icons/icon_log.gif\" alt=\"Icon Reverse Resolve with DNS\" "; + $rdns_link.= " style=\"cursor: pointer;\"/>"; + /* use one echo to do the magic*/ echo "<tr> <td align=\"center\" valign=\"middle\" class=\"listr\">{$counter}</td> <td align=\"center\" valign=\"middle\" class=\"listr\">{$tmp_ip}<br/>{$rdns_link}</td> <td valign=\"middle\" class=\"listr\">{$blocked_desc}</td> - <td align=\"center\" valign=\"middle\" class=\"listr\" sorttable_customkey=\"\"> + <td align=\"center\" valign=\"middle\" class=\"listr\"> <input type=\"image\" name=\"todelete[]\" onClick=\"document.getElementById('ip').value='{$blocked_ip}';\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\" title=\"" . gettext("Delete host from Blocked Table") . "\" border=\"0\" /></td> </tr>\n"; @@ -325,5 +338,38 @@ if ($savemsg) { <?php include("fend.inc"); ?> + +<!-- The following AJAX code was borrowed from the diag_logs_filter.php --> +<!-- file in pfSense. See copyright info at top of this page. --> +<script type="text/javascript"> +//<![CDATA[ +function resolve_with_ajax(ip_to_resolve) { + var url = "/snort/snort_blocked.php"; + + jQuery.ajax( + url, + { + type: 'post', + dataType: 'json', + data: { + resolve: ip_to_resolve, + }, + complete: resolve_ip_callback + }); +} + +function resolve_ip_callback(transport) { + var response = jQuery.parseJSON(transport.responseText); + var msg = 'IP address "' + response.resolve_ip + '" resolves to\n'; + alert(msg + 'host "' + htmlspecialchars(response.resolve_text) + '"'); +} + +// From http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities +function htmlspecialchars(str) { + return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); +} +//]]> +</script> + </body> </html> diff --git a/config/snort/snort_check_cron_misc.inc b/config/snort/snort_check_cron_misc.inc index a5b9e65e..a2688b58 100644 --- a/config/snort/snort_check_cron_misc.inc +++ b/config/snort/snort_check_cron_misc.inc @@ -33,6 +33,7 @@ require_once("/usr/local/pkg/snort/snort.inc"); $snortlogdir = SNORTLOGDIR; +global $g, $config; function snort_check_dir_size_limit($snortloglimitsize) { @@ -56,9 +57,9 @@ function snort_check_dir_size_limit($snortloglimitsize) { conf_mount_rw(); // Truncate the Rules Update Log file if it exists - if (file_exists(RULES_UPD_LOGFILE)) { + if (file_exists(SNORT_RULES_UPD_LOGFILE)) { log_error(gettext("[Snort] Truncating the Rules Update Log file...")); - @file_put_contents(RULES_UPD_LOGFILE, ""); + @file_put_contents(SNORT_RULES_UPD_LOGFILE, ""); } // Clean-up the logs for each configured Snort instance @@ -74,6 +75,21 @@ function snort_check_dir_size_limit($snortloglimitsize) { @file_put_contents("{$snort_log_dir}/alert", ""); } + // Cleanup any perfmon stats logs + $files = array(); + $list = glob("{$snort_log_dir}/*"); + foreach ($list as $file) { + if (preg_match('/(^\d{4}-\d{2}-\d{2}[\.\d+]*)/', basename($file), $matches)) + $files[] = $snort_log_dir . "/" . $matches[1]; + } + foreach ($files as $file) + unlink_if_exists($file); + + // Cleanup any AppID stats logs + $files = glob("{$snort_log_dir}/appid-stats.log.*"); + foreach ($files as $file) + unlink_if_exists($file); + // This is needed if snort is run as snort user mwexec('/bin/chmod 660 {$snort_log_dir}/*', true); @@ -88,6 +104,56 @@ function snort_check_dir_size_limit($snortloglimitsize) { } } +function snort_check_rotate_log($log_file, $log_limit, $retention) { + + /******************************************************** + * This function checks the passed log file against * + * the passed size limit and rotates the log file if * + * necessary. It also checks the age of previously * + * rotated logs and removes those older than the * + * rentention parameter. * + * * + * On Entry: $log_file -> full pathname/filename of * + * log file to check * + * $log_limit -> size of file in bytes to * + * trigger rotation. Zero * + * means no rotation. * + * $retention -> retention period in hours * + * for rotated logs. Zero * + * means never remove. * + ********************************************************/ + + // Check the current log to see if it needs rotating. + // If it does, rotate it and put the current time + // on the end of the filename as UNIX timestamp. + if (!file_exists($log_file)) + return; + if (($log_limit > 0) && (filesize($log_file) >= $log_limit)) { + $newfile = $log_file . "." . strval(time()); + try { + copy($log_file, $newfile); + file_put_contents($log_file, ""); + } catch (Exception $e) { + log_error("[Snort] Failed to rotate file '{$log_file}' -- error was {$e->getMessage()}"); + } + } + + // Check previously rotated logs to see if time to + // delete any older than the retention period. + // Rotated logs have a UNIX timestamp appended to + // filename. + if ($retention > 0) { + $now = time(); + $rotated_files = glob("{$log_file}.*"); + foreach ($rotated_files as $file) { + if (($now - filemtime($file)) > ($retention * 3600)) + unlink_if_exists($file); + } + unset($rotated_files); + } +} + + /************************* * Start of main code * *************************/ @@ -96,27 +162,93 @@ function snort_check_dir_size_limit($snortloglimitsize) { if ($g['booting'] == true) return; +$logs = array (); + +// Build an array of files to check and limits to check them against from our saved configuration +$logs['sid_changes.log']['limit'] = $config['installedpackages']['snortglobal']['sid_changes_log_limit_size']; +$logs['sid_changes.log']['retention'] = $config['installedpackages']['snortglobal']['sid_changes_log_retention']; + // If no interfaces defined, there is nothing to clean up if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; -// Check unified2 archived log retention in the interface logging directories if enabled -foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { - $if_real = get_real_interface($value['interface']); - $snort_log_dir = SNORTLOGDIR . "/snort_{$if_real}{$value['uuid']}"; - if (is_dir("{$snort_log_dir}/barnyard2/archive") && $value['u2_archived_log_retention'] > 0) { - $now = time(); - $files = glob("{$snort_log_dir}/barnyard2/archive/snort_{$value['uuid']}_{$if_real}.u2.*"); - $prune_count = 0; - foreach ($files as $f) { - if (($now - filemtime($f)) > ($value['u2_archived_log_retention'] * 3600)) { - $prune_count++; - unlink_if_exists($f); +// Check log limits and retention in the interface logging directories if enabled +if ($config['installedpackages']['snortglobal']['enable_log_mgmt'] == 'on') { + foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { + $if_real = get_real_interface($value['interface']); + $snort_log_dir = SNORTLOGDIR . "/snort_{$if_real}{$value['uuid']}"; + foreach ($logs as $k => $p) { + snort_check_rotate_log("{$snort_log_dir}/{$k}", $p['limit']*1024, $p['retention']); + } + + // Prune aged-out event packet capture files if any exist + if ($config['installedpackages']['snortglobal']['event_pkts_log_retention'] > 0) { + $now = time(); + $rotated_files = glob("{$snort_log_dir}/snort.log.*"); + $prune_count = 0; + foreach ($rotated_files as $file) { + if (($now - filemtime($file)) > ($config['installedpackages']['snortglobal']['event_pkts_log_retention'] * 3600)) { + $prune_count++; + unlink_if_exists($file); + } + } + unset($rotated_files); + if ($prune_count > 0) + log_error(gettext("[Snort] Alert pcap file cleanup job removed {$prune_count} pcap file(s) from {$snort_log_dir}/...")); + } + + // Prune any aged-out Barnyard2 archived logs if any exist + if (is_dir("{$snort_log_dir}/barnyard2/archive") && $value['u2_archived_log_retention'] > 0) { + $now = time(); + $files = glob("{$snort_log_dir}/barnyard2/archive/snort_{$value['uuid']}_{$if_real}.u2.*"); + $prune_count = 0; + foreach ($files as $f) { + if (($now - filemtime($f)) > ($value['u2_archived_log_retention'] * 3600)) { + $prune_count++; + unlink_if_exists($f); + } + } + unset($files); + if ($prune_count > 0) + log_error(gettext("[Snort] Barnyard2 archived logs cleanup job removed {$prune_count} file(s) from {$snort_log_dir}/barnyard2/archive/...")); + } + + // Prune aged-out perfmon stats logs if any exist + if ($config['installedpackages']['snortglobal']['stats_log_retention'] > 0) { + $now = time(); + $files = array(); + $list = glob("{$snort_log_dir}/*"); + foreach ($list as $file) { + if (preg_match('/(^\d{4}-\d{2}-\d{2}[\.\d+]*)/', basename($file), $matches)) + $files[] = $snort_log_dir . "/" . $matches[1]; + } + $prune_count = 0; + foreach ($files as $f) { + if (($now - filemtime($f)) > ($config['installedpackages']['snortglobal']['stats_log_retention'] * 3600)) { + $prune_count++; + unlink_if_exists($f); + } + } + unset($list, $files); + if ($prune_count > 0) + log_error(gettext("[Snort] perfmon stats logs cleanup job removed {$prune_count} file(s) from {$snort_log_dir}/...")); + } + + // Prune any aged-out AppID stats logs if any exist + if ($value['appid_stats_log_retention'] > 0) { + $now = time(); + $files = glob("{$snort_log_dir}/app-stats.log.*"); + $prune_count = 0; + foreach ($files as $f) { + if (($now - filemtime($f)) > ($value['appid_stats_log_retention'] * 3600)) { + $prune_count++; + unlink_if_exists($f); + } } + unset($files); + if ($prune_count > 0) + log_error(gettext("[Snort] AppID stats logs cleanup job removed {$prune_count} file(s) from {$snort_log_dir}/...")); } - unset($files); - if ($prune_count > 0) - log_error(gettext("[Snort] Barnyard2 archived logs cleanup job removed {$prune_count} file(s)...")); } } diff --git a/config/snort/snort_check_for_rule_updates.php b/config/snort/snort_check_for_rule_updates.php index 667f4044..3106cb7b 100755 --- a/config/snort/snort_check_for_rule_updates.php +++ b/config/snort/snort_check_for_rule_updates.php @@ -32,44 +32,17 @@ 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"); +require("/usr/local/pkg/snort/snort_defs.inc"); global $g, $config, $pkg_interface, $snort_gui_include, $rebuild_rules; -if (!defined("VRT_DNLD_URL")) - define("VRT_DNLD_URL", "https://www.snort.org/reg-rules/"); -if (!defined("ET_VERSION")) - define("ET_VERSION", "2.9.0"); -if (!defined("ET_BASE_DNLD_URL")) - define("ET_BASE_DNLD_URL", "http://rules.emergingthreats.net/"); -if (!defined("ETPRO_BASE_DNLD_URL")) - define("ETPRO_BASE_DNLD_URL", "https://rules.emergingthreatspro.com/"); -if (!defined("ET_DNLD_FILENAME")) - define("ET_DNLD_FILENAME", "emerging.rules.tar.gz"); -if (!defined("ETPRO_DNLD_FILENAME")) - define("ETPRO_DNLD_FILENAME", "etpro.rules.tar.gz"); -if (!defined("GPLV2_DNLD_FILENAME")) - define("GPLV2_DNLD_FILENAME", "community-rules.tar.gz"); -if (!defined("GPLV2_DNLD_URL")) - define("GPLV2_DNLD_URL", "https://s3.amazonaws.com/snort-org/www/rules/community/"); -if (!defined("RULES_UPD_LOGFILE")) - define("RULES_UPD_LOGFILE", SNORTLOGDIR . "/snort_rules_update.log"); -if (!defined("VRT_FILE_PREFIX")) - define("VRT_FILE_PREFIX", "snort_"); -if (!defined("GPL_FILE_PREFIX")) - define("GPL_FILE_PREFIX", "GPLv2_"); -if (!defined("ET_OPEN_FILE_PREFIX")) - define("ET_OPEN_FILE_PREFIX", "emerging-"); -if (!defined("ET_PRO_FILE_PREFIX")) - define("ET_PRO_FILE_PREFIX", "etpro-"); -if (!defined("IPREP_PATH")) - define("IPREP_PATH", "/var/db/snort/iprep/"); - $snortdir = SNORTDIR; -$snortlibdir = SNORTLIBDIR; +$snortlibdir = "/usr/pbi/snort-" . php_uname("m") . "/lib"; $snortlogdir = SNORTLOGDIR; -$snortiprepdir = IPREP_PATH; -$snort_rules_upd_log = RULES_UPD_LOGFILE; +$snortiprepdir = SNORT_IPREP_PATH; +$snortbindir = SNORT_PBI_BINDIR; +$mounted_rw = FALSE; /* Save the state of $pkg_interface so we can restore it */ $pkg_interface_orig = $pkg_interface; @@ -86,19 +59,20 @@ $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats' $etpro = $config['installedpackages']['snortglobal']['emergingthreats_pro'] == 'on' ? 'on' : 'off'; $snortcommunityrules = $config['installedpackages']['snortglobal']['snortcommunityrules'] == 'on' ? 'on' : 'off'; $vrt_enabled = $config['installedpackages']['snortglobal']['snortdownload'] == 'on' ? 'on' : 'off'; +$openappid_detectors = $config['installedpackages']['snortglobal']['openappid_detectors'] == 'on' ? 'on' : 'off'; /* Working directory for downloaded rules tarballs and extraction */ -$tmpfname = "/tmp/snort_rules_up"; +$tmpfname = "{$g['tmp_path']}/snort_rules_up"; /* Grab the Snort binary version programmatically and use it to construct */ /* the proper Snort VRT rules tarball and md5 filenames. Fallback to a */ /* default in the event we fail. */ $snortver = array(); -exec("/usr/local/bin/snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); +exec("{$snortbindir}snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); // Save the version with decimal delimiters for use in extracting the rules $snort_version = $snortver[0]; if (empty($snort_version)) - $snort_version = "2.9.6.0"; + $snort_version = SNORT_BIN_VERSION; // Create a collapsed version string for use in the tarball filename $snortver[0] = str_replace(".", "", $snortver[0]); @@ -106,37 +80,45 @@ $snort_filename = "snortrules-snapshot-{$snortver[0]}.tar.gz"; $snort_filename_md5 = "{$snort_filename}.md5"; $snort_rule_url = VRT_DNLD_URL; -/* Mount the Snort conf directories R/W so we can modify files there */ -conf_mount_rw(); +/* Mount the Snort conf directories R/W, if not already, so we can modify files there */ +if (!is_subsystem_dirty('mount')) { + conf_mount_rw(); + $mounted_rw = TRUE; +} /* Set up Emerging Threats rules filenames and URL */ if ($etpro == "on") { - $emergingthreats_filename = ETPRO_DNLD_FILENAME; - $emergingthreats_filename_md5 = ETPRO_DNLD_FILENAME . ".md5"; + $emergingthreats_filename = SNORT_ETPRO_DNLD_FILENAME; + $emergingthreats_filename_md5 = SNORT_ETPRO_DNLD_FILENAME . ".md5"; $emergingthreats_url = ETPRO_BASE_DNLD_URL; $emergingthreats_url .= "{$etproid}/snort-" . ET_VERSION . "/"; $emergingthreats = "on"; $et_name = "Emerging Threats Pro"; - $et_md5_remove = ET_DNLD_FILENAME . ".md5"; - @unlink("{$snortdir}/{$et_md5_remove}"); + $et_md5_remove = SNORT_ET_DNLD_FILENAME . ".md5"; + unlink_if_exists("{$snortdir}/{$et_md5_remove}"); } else { - $emergingthreats_filename = ET_DNLD_FILENAME; - $emergingthreats_filename_md5 = ET_DNLD_FILENAME . ".md5"; + $emergingthreats_filename = SNORT_ET_DNLD_FILENAME; + $emergingthreats_filename_md5 = SNORT_ET_DNLD_FILENAME . ".md5"; $emergingthreats_url = ET_BASE_DNLD_URL; // If using Sourcefire VRT rules with ET, then we should use the open-nogpl ET rules $emergingthreats_url .= $vrt_enabled == "on" ? "open-nogpl/" : "open/"; $emergingthreats_url .= "snort-" . ET_VERSION . "/"; $et_name = "Emerging Threats Open"; - $et_md5_remove = ETPRO_DNLD_FILENAME . ".md5"; - @unlink("{$snortdir}/{$et_md5_remove}"); + $et_md5_remove = SNORT_ETPRO_DNLD_FILENAME . ".md5"; + unlink_if_exists("{$snortdir}/{$et_md5_remove}"); } /* Snort GPLv2 Community Rules filenames and URL */ -$snort_community_rules_filename = GPLV2_DNLD_FILENAME; -$snort_community_rules_filename_md5 = GPLV2_DNLD_FILENAME . ".md5"; +$snort_community_rules_filename = SNORT_GPLV2_DNLD_FILENAME; +$snort_community_rules_filename_md5 = SNORT_GPLV2_DNLD_FILENAME . ".md5"; $snort_community_rules_url = GPLV2_DNLD_URL; +/* Snort OpenAppID detectors filename and URL */ +$snort_openappid_filename = SNORT_OPENAPPID_DNLD_FILENAME; +$snort_openappid_filename_md5 = SNORT_OPENAPPID_DNLD_FILENAME . ".md5"; +$snort_openappid_url = SNORT_OPENAPPID_DNLD_URL; + function snort_download_file_url($url, $file_out) { /************************************************/ @@ -211,7 +193,9 @@ function snort_download_file_url($url, $file_out) { curl_setopt($ch, CURLOPT_FILE, $fout); // NOTE: required to suppress errors from XMLRPC due to progress bar output - if ($g['snort_sync_in_progress']) + // and to prevent useless spam from rules update cron job execution. This + // prevents progress bar output during package sync and rules update cron task. + if ($g['snort_sync_in_progress'] || $pkg_interface == "console") curl_setopt($ch, CURLOPT_HEADER, false); else { curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header'); @@ -285,21 +269,21 @@ function snort_check_rule_md5($file_url, $file_dst, $desc = "") { /* error occurred. */ /**********************************************************/ - global $pkg_interface, $snort_rules_upd_log, $last_curl_error, $update_errors; + global $pkg_interface, $last_curl_error, $update_errors; $snortdir = SNORTDIR; $filename_md5 = basename($file_dst); if ($pkg_interface <> "console") update_status(gettext("Downloading {$desc} md5 file...")); - error_log(gettext("\tDownloading {$desc} md5 file {$filename_md5}...\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tDownloading {$desc} md5 file {$filename_md5}...\n"), 3, SNORT_RULES_UPD_LOGFILE); $rc = snort_download_file_url($file_url, $file_dst); // See if download from URL was successful if ($rc === true) { if ($pkg_interface <> "console") update_status(gettext("Done downloading {$filename_md5}.")); - error_log("\tChecking {$desc} md5 file...\n", 3, $snort_rules_upd_log); + error_log("\tChecking {$desc} md5 file...\n", 3, SNORT_RULES_UPD_LOGFILE); // check md5 hash in new file against current file to see if new download is posted if (file_exists("{$snortdir}/{$filename_md5}")) { @@ -309,7 +293,7 @@ function snort_check_rule_md5($file_url, $file_dst, $desc = "") { if ($pkg_interface <> "console") update_status(gettext("{$desc} are up to date...")); log_error(gettext("[Snort] {$desc} are up to date...")); - error_log(gettext("\t{$desc} are up to date.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\t{$desc} are up to date.\n"), 3, SNORT_RULES_UPD_LOGFILE); return false; } else @@ -318,7 +302,7 @@ function snort_check_rule_md5($file_url, $file_dst, $desc = "") { return true; } else { - error_log(gettext("\t{$desc} md5 download failed.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\t{$desc} md5 download failed.\n"), 3, SNORT_RULES_UPD_LOGFILE); $snort_err_msg = gettext("Server returned error code {$rc}."); if ($pkg_interface <> "console") { update_status(gettext("{$desc} md5 error ... Server returned error code {$rc} ...")); @@ -326,9 +310,9 @@ function snort_check_rule_md5($file_url, $file_dst, $desc = "") { } log_error(gettext("[Snort] {$desc} 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); - error_log(gettext("\tServer error message was: {$last_curl_error}\n"), 3, $snort_rules_upd_log); - error_log(gettext("\t{$desc} will not be updated.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\t{$snort_err_msg}\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\tServer error message was: {$last_curl_error}\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\t{$desc} will not be updated.\n"), 3, SNORT_RULES_UPD_LOGFILE); $update_errors = true; return false; } @@ -353,7 +337,7 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { /* FALSE if download was not successful. */ /**********************************************************/ - global $pkg_interface, $snort_rules_upd_log, $last_curl_error, $update_errors; + global $pkg_interface, $last_curl_error, $update_errors; $snortdir = SNORTDIR; $filename = basename($file_dst); @@ -361,8 +345,8 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { if ($pkg_interface <> "console") update_status(gettext("There is a new set of {$desc} posted. Downloading...")); log_error(gettext("[Snort] There is a new set of {$desc} posted. Downloading {$filename}...")); - error_log(gettext("\tThere is a new set of {$desc} posted.\n"), 3, $snort_rules_upd_log); - error_log(gettext("\tDownloading file '{$filename}'...\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tThere is a new set of {$desc} posted.\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\tDownloading file '{$filename}'...\n"), 3, SNORT_RULES_UPD_LOGFILE); $rc = snort_download_file_url($file_url, $file_dst); // See if the download from the URL was successful @@ -370,7 +354,7 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { if ($pkg_interface <> "console") update_status(gettext("Done downloading {$desc} file.")); log_error("[Snort] {$desc} file update downloaded successfully"); - error_log(gettext("\tDone downloading rules file.\n"),3, $snort_rules_upd_log); + error_log(gettext("\tDone downloading rules file.\n"),3, SNORT_RULES_UPD_LOGFILE); // Test integrity of the rules file. Turn off update if file has wrong md5 hash if ($file_md5 != trim(md5_file($file_dst))){ @@ -379,10 +363,10 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { log_error(gettext("[Snort] {$desc} file download failed. Bad MD5 checksum...")); log_error(gettext("[Snort] Downloaded File MD5: " . md5_file($file_dst))); log_error(gettext("[Snort] Expected File MD5: {$file_md5}")); - error_log(gettext("\t{$desc} file download failed. Bad MD5 checksum.\n"), 3, $snort_rules_upd_log); - error_log(gettext("\tDownloaded {$desc} file MD5: " . md5_file($file_dst) . "\n"), 3, $snort_rules_upd_log); - error_log(gettext("\tExpected {$desc} file MD5: {$file_md5}\n"), 3, $snort_rules_upd_log); - error_log(gettext("\t{$desc} file download failed. {$desc} will not be updated.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\t{$desc} file download failed. Bad MD5 checksum.\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\tDownloaded {$desc} file MD5: " . md5_file($file_dst) . "\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\tExpected {$desc} file MD5: {$file_md5}\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\t{$desc} file download failed. {$desc} will not be updated.\n"), 3, SNORT_RULES_UPD_LOGFILE); $update_errors = true; return false; } @@ -392,9 +376,9 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { if ($pkg_interface <> "console") update_output_window(gettext("{$desc} file download failed...")); log_error(gettext("[Snort] {$desc} file download failed... server returned error '{$rc}'...")); - error_log(gettext("\t{$desc} file download failed. Server returned error {$rc}.\n"), 3, $snort_rules_upd_log); - error_log(gettext("\tThe error text was: {$last_curl_error}\n"), 3, $snort_rules_upd_log); - error_log(gettext("\t{$desc} will not be updated.\n"), 3, $snort_rules_upd_log); + error_log(gettext("\t{$desc} file download failed. Server returned error {$rc}.\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\tThe error text was: {$last_curl_error}\n"), 3, SNORT_RULES_UPD_LOGFILE); + error_log(gettext("\t{$desc} will not be updated.\n"), 3, SNORT_RULES_UPD_LOGFILE); $update_errors = true; return false; } @@ -407,43 +391,56 @@ function snort_fetch_new_rules($file_url, $file_dst, $file_md5, $desc = "") { /* remove any old $tmpfname files */ if (is_dir("{$tmpfname}")) - exec("/bin/rm -rf {$tmpfname}"); + rmdir_recursive($tmpfname); /* Make sure required snortdirs exsist */ safe_mkdir("{$snortdir}/rules"); safe_mkdir("{$snortdir}/signatures"); safe_mkdir("{$snortdir}/preproc_rules"); safe_mkdir("{$tmpfname}"); -safe_mkdir("{$snortlibdir}/dynamicrules"); +safe_mkdir("{$snortlibdir}/snort_dynamicrules"); safe_mkdir("{$snortlogdir}"); safe_mkdir("{$snortiprepdir}"); /* 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)) - @unlink("{$snort_rules_upd_log}"); +if (file_exists(SNORT_RULES_UPD_LOGFILE)) { + if (1048576 < filesize(SNORT_RULES_UPD_LOGFILE)) + unlink_if_exists("{SNORT_RULES_UPD_LOGFILE}"); } /* 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); +error_log(gettext("Starting rules update... Time: " . date("Y-m-d H:i:s") . "\n"), 3, SNORT_RULES_UPD_LOGFILE); $last_curl_error = ""; $update_errors = false; /* Check for and download any new Snort VRT sigs */ if ($snortdownload == 'on') { - if (snort_check_rule_md5("{$snort_rule_url}{$snort_filename_md5}/{$oinkid}/", "{$tmpfname}/{$snort_filename_md5}", "Snort VRT rules")) { + if (snort_check_rule_md5("{$snort_rule_url}{$snort_filename_md5}?oinkcode={$oinkid}", "{$tmpfname}/{$snort_filename_md5}", "Snort VRT rules")) { /* download snortrules file */ $file_md5 = trim(file_get_contents("{$tmpfname}/{$snort_filename_md5}")); - if (!snort_fetch_new_rules("{$snort_rule_url}{$snort_filename}/{$oinkid}/", "{$tmpfname}/{$snort_filename}", $file_md5, "Snort VRT rules")) + if (!snort_fetch_new_rules("{$snort_rule_url}{$snort_filename}?oinkcode={$oinkid}", "{$tmpfname}/{$snort_filename}", $file_md5, "Snort VRT rules")) $snortdownload = 'off'; } else $snortdownload = 'off'; } +/* Check for and download any new Snort OpenAppID detectors */ +if ($openappid_detectors == 'on') { + if (snort_check_rule_md5("{$snort_openappid_url}{$snort_openappid_filename}/md5", "{$tmpfname}/{$snort_openappid_filename_md5}", "Snort OpenAppID detectors")) { + $file_md5 = trim(file_get_contents("{$tmpfname}/{$snort_openappid_filename_md5}")); + file_put_contents("{$tmpfname}/{$snort_openappid_filename_md5}", $file_md5); + /* download snort-openappid file */ + if (!snort_fetch_new_rules("{$snort_openappid_url}{$snort_openappid_filename}", "{$tmpfname}/{$snort_openappid_filename}", $file_md5, "Snort OpenAppID detectors")) + $openappid_detectors = 'off'; + } + else + $openappid_detectors = 'off'; +} + /* Check for and download any new Snort GPLv2 Community Rules sigs */ if ($snortcommunityrules == 'on') { - if (snort_check_rule_md5("{$snort_community_rules_url}{$snort_community_rules_filename_md5}", "{$tmpfname}/{$snort_community_rules_filename_md5}", "Snort GPLv2 Community Rules")) { + if (snort_check_rule_md5("{$snort_community_rules_url}{$snort_community_rules_filename}/md5", "{$tmpfname}/{$snort_community_rules_filename_md5}", "Snort GPLv2 Community Rules")) { /* download Snort GPLv2 Community Rules file */ $file_md5 = trim(file_get_contents("{$tmpfname}/{$snort_community_rules_filename_md5}")); if (!snort_fetch_new_rules("{$snort_community_rules_url}{$snort_community_rules_filename}", "{$tmpfname}/{$snort_community_rules_filename}", $file_md5, "Snort GPLv2 Community Rules")) @@ -484,7 +481,7 @@ if ($snortdownload == 'on') { 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); + error_log(gettext("\tExtracting and installing Snort VRT rules...\n"), 3, SNORT_RULES_UPD_LOGFILE); /* extract snort.org rules and add VRT_FILE_PREFIX prefix to all snort.org files */ safe_mkdir("{$tmpfname}/snortrules"); exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$tmpfname}/snortrules rules/"); @@ -499,7 +496,7 @@ if ($snortdownload == 'on') { $newfile = basename($file); @copy($file, "{$snortdir}/rules/{$newfile}"); } - exec("rm -r {$tmpfname}/snortrules"); + rmdir_recursive("{$tmpfname}/snortrules"); /* Extract the Snort preprocessor rules */ if ($pkg_interface <> "console") update_output_window(gettext("Extracting preprocessor rules files...")); @@ -509,25 +506,24 @@ if ($snortdownload == 'on') { $newfile = basename($file); @copy($file, "{$snortdir}/preproc_rules/{$newfile}"); } - exec("rm -r {$tmpfname}/preproc_rules"); + rmdir_recursive("{$tmpfname}/preproc_rules"); /* extract so rules */ 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); + error_log(gettext("\tUsing Snort VRT precompiled SO rules for {$freebsd_version_so} ...\n"), 3, SNORT_RULES_UPD_LOGFILE); $snort_arch = php_uname("m"); $nosorules = false; if ($snort_arch == 'i386'){ exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$tmpfname} so_rules/precompiled/{$freebsd_version_so}/i386/{$snort_version}/"); - exec("/bin/cp {$tmpfname}/so_rules/precompiled/{$freebsd_version_so}/i386/{$snort_version}/*.so {$snortlibdir}/dynamicrules/"); + exec("/bin/cp {$tmpfname}/so_rules/precompiled/{$freebsd_version_so}/i386/{$snort_version}/*.so {$snortlibdir}/snort_dynamicrules/"); } elseif ($snort_arch == 'amd64') { exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$tmpfname} so_rules/precompiled/{$freebsd_version_so}/x86-64/{$snort_version}/"); - exec("/bin/cp {$tmpfname}/so_rules/precompiled/{$freebsd_version_so}/x86-64/{$snort_version}/*.so {$snortlibdir}/dynamicrules/"); + exec("/bin/cp {$tmpfname}/so_rules/precompiled/{$freebsd_version_so}/x86-64/{$snort_version}/*.so {$snortlibdir}/snort_dynamicrules/"); } else $nosorules = true; - exec("rm -rf {$tmpfname}/so_rules"); + rmdir_recursive("{$tmpfname}/so_rules/"); if ($nosorules == false) { /* extract Shared Object stub rules, rename and copy to the rules folder. */ if ($pkg_interface <> "console") @@ -538,7 +534,7 @@ if ($snortdownload == 'on') { $newfile = basename($file, ".rules"); @copy($file, "{$snortdir}/rules/" . VRT_FILE_PREFIX . "{$newfile}.so.rules"); } - exec("rm -rf {$tmpfname}/so_rules"); + rmdir_recursive("{$tmpfname}/so_rules/"); } /* extract base etc files */ if ($pkg_interface <> "console") { @@ -550,7 +546,7 @@ if ($snortdownload == 'on') { if (file_exists("{$tmpfname}/etc/{$file}")) @copy("{$tmpfname}/etc/{$file}", "{$tmpfname}/VRT_{$file}"); } - exec("rm -r {$tmpfname}/etc"); + rmdir_recursive("{$tmpfname}/etc"); if (file_exists("{$tmpfname}/{$snort_filename_md5}")) { if ($pkg_interface <> "console") update_status(gettext("Copying md5 signature to snort directory...")); @@ -560,7 +556,30 @@ if ($snortdownload == 'on') { 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); + error_log(gettext("\tInstallation of Snort VRT rules completed.\n"), 3, SNORT_RULES_UPD_LOGFILE); + } +} + +/* Untar Snort OpenAppID detectors file to SNORT_APPID_ODP_PATH */ +if ($openappid_detectors == 'on') { + // If we have a valid downloaded file, then first cleanup the old directory + if (file_exists("{$tmpfname}/{$snort_openappid_filename}")) { + $snort_openappid_path = SNORT_APPID_ODP_PATH; + rmdir_recursive("{$snort_openappid_path}odp"); + error_log(gettext("\tExtracting and installing Snort OpenAppID detectors...\n"), 3, SNORT_RULES_UPD_LOGFILE); + safe_mkdir(SNORT_APPID_ODP_PATH); + exec("/usr/bin/tar oxzf {$tmpfname}/{$snort_openappid_filename} -C {$snort_openappid_path}"); + if (file_exists("{$tmpfname}/{$snort_openappid_filename_md5}")) { + if ($pkg_interface <> "console") + update_status(gettext("Copying md5 signature to snort directory...")); + @copy("{$tmpfname}/{$snort_openappid_filename_md5}", "{$snortdir}/{$snort_openappid_filename_md5}"); + } + if ($pkg_interface <> "console") { + update_status(gettext("Extraction of Snort OpenAppID detectors completed...")); + update_output_window(gettext("Installation of Snort OpenAppID detectors completed...")); + } + unlink_if_exists("{$tmpfname}/{$snort_openappid_filename}"); + error_log(gettext("\tInstallation of Snort OpenAppID detectors completed.\n"), 3, SNORT_RULES_UPD_LOGFILE); } } @@ -572,7 +591,7 @@ if ($snortcommunityrules == 'on') { 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); + error_log(gettext("\tExtracting and installing Snort GPLv2 Community Rules...\n"), 3, SNORT_RULES_UPD_LOGFILE); exec("/usr/bin/tar xzf {$tmpfname}/{$snort_community_rules_filename} -C {$tmpfname}/community/"); $files = glob("{$tmpfname}/community/community-rules/*.rules"); @@ -595,8 +614,8 @@ if ($snortcommunityrules == 'on') { 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 -rf {$tmpfname}/community"); + error_log(gettext("\tInstallation of Snort GPLv2 Community Rules completed.\n"), 3, SNORT_RULES_UPD_LOGFILE); + rmdir_recursive("{$tmpfname}/community/"); } } @@ -608,7 +627,7 @@ if ($emergingthreats == 'on') { update_status(gettext("Extracting {$et_name} rules...")); update_output_window(gettext("Installing {$et_name} rules...")); } - error_log(gettext("\tExtracting and installing {$et_name} rules...\n"), 3, $snort_rules_upd_log); + error_log(gettext("\tExtracting and installing {$et_name} rules...\n"), 3, SNORT_RULES_UPD_LOGFILE); exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$tmpfname}/emerging rules/"); /* Remove the old Emerging Threats rules files */ @@ -632,11 +651,11 @@ if ($emergingthreats == 'on') { foreach ($files as $file) { $newfile = basename($file); if ($etpro == "on") { - @copy($file, IPREP_PATH . ET_PRO_FILE_PREFIX . "{$newfile}"); + @copy($file, SNORT_IPREP_PATH . ET_PRO_FILE_PREFIX . "{$newfile}"); @copy($file, "{$snortdir}/rules/" . ET_PRO_FILE_PREFIX . "{$newfile}"); } else { - @copy($file, IPREP_PATH . ET_OPEN_FILE_PREFIX . "{$newfile}"); + @copy($file, SNORT_IPREP_PATH . ET_OPEN_FILE_PREFIX . "{$newfile}"); @copy($file, "{$snortdir}/rules/" . ET_OPEN_FILE_PREFIX . "{$newfile}"); } } @@ -656,8 +675,8 @@ if ($emergingthreats == 'on') { update_status(gettext("Extraction of {$et_name} rules completed...")); update_output_window(gettext("Installation of {$et_name} rules completed...")); } - error_log(gettext("\tInstallation of {$et_name} rules completed.\n"), 3, $snort_rules_upd_log); - exec("rm -rf {$tmpfname}/emerging"); + error_log(gettext("\tInstallation of {$et_name} rules completed.\n"), 3, SNORT_RULES_UPD_LOGFILE); + rmdir_recursive("{$tmpfname}/emerging/"); } } @@ -668,7 +687,7 @@ function snort_apply_customizations($snortcfg, $if_real) { /* Update the Preprocessor rules from the master configuration for the interface if Snort */ /* VRT rules are in use and the interface's preprocessor rules are not protected. */ - if ($vrt_enabled == 'on' && $snortcfg['protect_preproc_rules'] != 'on') { + if ($vrt_enabled == 'on' && ($snortcfg['protect_preproc_rules'] != 'on' || $g['snort_postinstall'])) { $preproc_files = glob("{$snortdir}/preproc_rules/*.rules"); foreach ($preproc_files as $file) { $newfile = basename($file); @@ -690,7 +709,7 @@ if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules = 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); + error_log(gettext("\tCopying new config and map files...\n"), 3, SNORT_RULES_UPD_LOGFILE); /******************************************************************/ /* Build the classification.config and reference.config files */ @@ -749,8 +768,8 @@ if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules = safe_mkdir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/rules"); if (!is_dir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/preproc_rules")) safe_mkdir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/preproc_rules"); - if (!is_dir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/dynamicpreprocessor")) - safe_mkdir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/dynamicpreprocessor"); + if (!is_dir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/snort_dynamicpreprocessor")) + safe_mkdir("{$snortdir}/snort_{$value['uuid']}_{$if_real}/snort_dynamicpreprocessor"); snort_apply_customizations($value, $if_real); @@ -760,7 +779,7 @@ if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules = $tmp .= gettext("\tPreprocessor text rules flagged as protected and not updated for "); $tmp .= convert_friendly_interface_to_friendly_descr($value['interface']) . "...\n"; } - error_log($tmp, 3, $snort_rules_upd_log); + error_log($tmp, 3, SNORT_RULES_UPD_LOGFILE); } } else { @@ -768,24 +787,52 @@ if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules = 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); + error_log(gettext("\tWarning: No interfaces configured for Snort were found...\n"), 3, SNORT_RULES_UPD_LOGFILE); } /* Clear the rebuild rules flag. */ $rebuild_rules = false; - /* Restart snort if already running and we are not rebooting to pick up the new rules. */ - if (is_process_running("snort") && !$g['booting']) { + /* Restart snort if running, and not in post-install, so as to pick up the new rules. */ + if (!$g['snort_postinstall'] && is_service_running("snort") && count($config['installedpackages']['snortglobal']['rule']) > 0) { 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"); + error_log(gettext("\tRestarting Snort to activate the new set of rules...\n"), 3, SNORT_RULES_UPD_LOGFILE); + touch("{$g['varrun_path']}/snort_pkg_starting.lck"); + snort_restart_all_interfaces(TRUE); + sleep(3); + unlink_if_exists("{$g['varrun_path']}/snort_pkg_starting.lck"); 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); + error_log(gettext("\tSnort has restarted with your new set of rules.\n"), 3, SNORT_RULES_UPD_LOGFILE); + } + else { + if ($pkg_interface <> "console") + update_output_window(gettext("The rules update task is complete...")); + } +} +elseif ($openappid_detectors == 'on') { + /**************************************************************************************/ + /* Only updated OpenAppID detectors, so do not need to rebuild all interface rules. */ + /* Restart snort if running, and not in post-install, so as to pick up the detectors. */ + /**************************************************************************************/ + if (!$g['snort_postinstall'] && is_service_running("snort") && count($config['installedpackages']['snortglobal']['rule']) > 0) { + if ($pkg_interface <> "console") { + update_status(gettext('Restarting Snort to activate the new OpenAppID detectors...')); + update_output_window(gettext("Please wait ... restarting Snort will take some time...")); + } + error_log(gettext("\tRestarting Snort to activate the new OpenAppID detectors...\n"), 3, SNORT_RULES_UPD_LOGFILE); + touch("{$g['varrun_path']}/snort_pkg_starting.lck"); + snort_restart_all_interfaces(TRUE); + sleep(2); + unlink_if_exists("{$g['varrun_path']}/snort_pkg_starting.lck"); + if ($pkg_interface <> "console") + update_output_window(gettext("Snort has restarted with your new set of OpenAppID detectors...")); + log_error(gettext("[Snort] Snort has restarted with your new set of OpenAppID detectors...")); + error_log(gettext("\tSnort has restarted with your new set of OpenAppID detectors.\n"), 3, SNORT_RULES_UPD_LOGFILE); } else { if ($pkg_interface <> "console") @@ -795,14 +842,17 @@ if ($snortdownload == 'on' || $emergingthreats == 'on' || $snortcommunityrules = /* remove $tmpfname files */ if (is_dir("{$tmpfname}")) { - exec("/bin/rm -rf {$tmpfname}"); + rmdir_recursive($tmpfname); } 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(); +error_log(gettext("The Rules update has finished. Time: " . date("Y-m-d H:i:s"). "\n\n"), 3, SNORT_RULES_UPD_LOGFILE); + +/* Remount filesystem read-only if we changed it in this module */ +if ($mounted_rw == TRUE) + conf_mount_ro(); /* Restore the state of $pkg_interface */ $pkg_interface = $pkg_interface_orig; @@ -813,5 +863,5 @@ if ($update_errors) else $config['installedpackages']['snortglobal']['last_rule_upd_status'] = gettext("success"); $config['installedpackages']['snortglobal']['last_rule_upd_time'] = time(); -write_config("Snort pkg: updated status for updated rules package(s) check."); +write_config("Snort pkg: updated status for updated rules package(s) check.", FALSE); ?> diff --git a/config/snort/snort_conf_template.inc b/config/snort/snort_conf_template.inc new file mode 100644 index 00000000..6b362ce5 --- /dev/null +++ b/config/snort/snort_conf_template.inc @@ -0,0 +1,109 @@ +<?php + +// This is the template used to generate the snort.conf +// configuration file for the interface. The contents of +// this file are written to the snort.conf file for +// the interface. Key parameters are provided by the +// included string variables which are populated by the +// snort_generate_conf.php file. + +$snort_conf_text = <<<EOD +# snort configuration file +# generated automatically by the pfSense subsystems do not modify manually + +# Define Local Network # +ipvar HOME_NET [{$home_net}] +ipvar EXTERNAL_NET [{$external_net}] + +# Define Rule Path # +var RULE_PATH {$snortcfgdir}/rules + +# Define Servers # +{$ipvardef} + +# Define Server Ports # +{$portvardef} + +# Configure the snort decoder # +config checksum_mode: {$cksumcheck} +config disable_decode_alerts +config disable_tcpopt_experimental_alerts +config disable_tcpopt_obsolete_alerts +config disable_ttcp_alerts +config disable_tcpopt_alerts +config disable_ipopt_alerts +config disable_decode_drops + +# Enable the GTP decoder # +config enable_gtp + +# Configure PCRE match limitations +config pcre_match_limit: 3500 +config pcre_match_limit_recursion: 1500 + +# Configure the detection engine # +config detection: {$cfg_detect_settings} +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 # +{$paf_max_pdu_config} + +# Configure dynamically loaded libraries +dynamicpreprocessor directory {$snort_dirs['dynamicpreprocessor']} +dynamicengine directory {$snort_dirs['dynamicengine']} +dynamicdetection directory {$snort_dirs['dynamicrules']} + +# Inline packet normalization. For more information, see README.normalize +# Disabled since we do not use "inline" mode with pfSense +# preprocessor normalize_ip4 +# preprocessor normalize_tcp: ips ecn stream +# preprocessor normalize_icmp4 +# preprocessor normalize_ip6 +# preprocessor normalize_icmp6 + +# Flow and stream # +{$frag3_global} + +{$frag3_engine} + +{$stream5_global} + +{$stream5_tcp_engine} + +{$stream5_udp_engine} + +{$stream5_icmp_engine} + +# HTTP Inspect # +{$http_inspect_global} + +{$http_inspect_servers} +{$snort_preprocessors} +{$host_attrib_config} + +# Snort Output Logs # +output alert_csv: alert timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority {$alert_log_limit_size} +{$alertsystemlog_type} +{$snortunifiedlog_type} +{$spoink_type} + +# Misc Includes # +{$snort_misc_include_rules} + +{$suppress_file_name} + +# Snort user pass through configuration +{$snort_config_pass_thru} + +# Rules Selection # +{$selected_rules_sections} +EOD; + +// End of snort.conf template code + +?> + diff --git a/config/snort/snort_define_servers.php b/config/snort/snort_define_servers.php index 4d1b3c2e..ee463ac9 100755 --- a/config/snort/snort_define_servers.php +++ b/config/snort/snort_define_servers.php @@ -100,9 +100,6 @@ $pconfig = $a_nat[$id]; $if_real = get_real_interface($pconfig['interface']); $snort_uuid = $config['installedpackages']['snortglobal']['rule'][$id]['uuid']; -/* alert file */ -$d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; - if ($_POST['save']) { $natent = array(); @@ -138,7 +135,9 @@ if ($_POST['save']) { /* Update the snort conf file for this interface. */ $rebuild_rules = false; + conf_mount_rw(); snort_generate_conf($a_nat[$id]); + conf_mount_ro(); /* Soft-restart Snort to live-load new variables. */ snort_reload_config($a_nat[$id]); @@ -189,7 +188,9 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td class="tabnavtbl">'; @@ -202,6 +203,7 @@ if ($savemsg) $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> diff --git a/config/snort/snort_defs.inc b/config/snort/snort_defs.inc new file mode 100644 index 00000000..43ecada6 --- /dev/null +++ b/config/snort/snort_defs.inc @@ -0,0 +1,101 @@ +<?php +/* + * snort_defs.inc + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009-2010 Robert Zelaya + * Copyright (C) 2011-2012 Ermal Luci + * Copyright (C) 2013,2014 Bill Meeks + * part of pfSense + * 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. + */ + +global $g, $config; + +/* Define some useful constants for Snort */ +if (!defined("SNORT_PBI_BASEDIR")) + define("SNORT_PBI_BASEDIR", "/usr/pbi/snort-" . php_uname("m") . "/"); +if (!defined("SNORT_PBI_BINDIR")) + define("SNORT_PBI_BINDIR", SNORT_PBI_BASEDIR . "bin/"); +if (!defined("SNORTDIR")) + define("SNORTDIR", SNORT_PBI_BASEDIR . "etc/snort"); +if (!defined("SNORTLOGDIR")) + define("SNORTLOGDIR", "{$g['varlog_path']}/snort"); +if (!defined("SNORT_BIN_VERSION")) { + // Grab the Snort binary version programmatically + $snortver = array(); + $snortbindir = SNORT_PBI_BINDIR; + mwexec("{$snortbindir}/snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); + if (!empty($snortver[0])) + define("SNORT_BIN_VERSION", $snortver[0]); + else + define("SNORT_BIN_VERSION", "2.9.7.0"); +} +if (!defined("SNORT_SID_MODS_PATH")) + define('SNORT_SID_MODS_PATH', "{$g['vardb_path']}/snort/sidmods/"); +if (!defined("SNORT_IPREP_PATH")) + define("SNORT_IPREP_PATH", "{$g['vardb_path']}/snort/iprep/"); +if (!defined('SNORT_APPID_ODP_PATH')) + define('SNORT_APPID_ODP_PATH', SNORTDIR . "/appid/"); + +// Rules filenames, download URLs and prefixes. +// Be sure to include the trailing backslash on URLs. +if (!defined("SNORT_ENFORCING_RULES_FILENAME")) + define("SNORT_ENFORCING_RULES_FILENAME", "snort.rules"); +if (!defined("FLOWBITS_FILENAME")) + define("FLOWBITS_FILENAME", "flowbit-required.rules"); +if (!defined("SNORT_RULES_UPD_LOGFILE")) + define("SNORT_RULES_UPD_LOGFILE", SNORTLOGDIR . "/snort_rules_update.log"); +if (!defined("VRT_DNLD_URL")) + define("VRT_DNLD_URL", "https://www.snort.org/rules/"); +if (!defined("ET_VERSION")) + define("ET_VERSION", "2.9.0"); +if (!defined("ET_BASE_DNLD_URL")) + define("ET_BASE_DNLD_URL", "http://rules.emergingthreats.net/"); +if (!defined("ETPRO_BASE_DNLD_URL")) + define("ETPRO_BASE_DNLD_URL", "https://rules.emergingthreatspro.com/"); +if (!defined("SNORT_ET_DNLD_FILENAME")) + define("SNORT_ET_DNLD_FILENAME", "emerging.rules.tar.gz"); +if (!defined("SNORT_ETPRO_DNLD_FILENAME")) + define("SNORT_ETPRO_DNLD_FILENAME", "etpro.rules.tar.gz"); +if (!defined("SNORT_GPLV2_DNLD_FILENAME")) + define("SNORT_GPLV2_DNLD_FILENAME", "community-rules.tar.gz"); +if (!defined("GPLV2_DNLD_URL")) + define("GPLV2_DNLD_URL", "https://www.snort.org/downloads/community/"); +if (!defined("SNORT_OPENAPPID_DNLD_URL")) + define("SNORT_OPENAPPID_DNLD_URL", "https://www.snort.org/downloads/openappid/"); +if (!defined("SNORT_OPENAPPID_DNLD_FILENAME")) + define("SNORT_OPENAPPID_DNLD_FILENAME", "snort-openappid.tar.gz"); +if (!defined("SNORT_RULES_UPD_LOGFILE")) + define("SNORT_RULES_UPD_LOGFILE", SNORTLOGDIR . "/snort_rules_update.log"); +if (!defined("VRT_FILE_PREFIX")) + define("VRT_FILE_PREFIX", "snort_"); +if (!defined("GPL_FILE_PREFIX")) + define("GPL_FILE_PREFIX", "GPLv2_"); +if (!defined("ET_OPEN_FILE_PREFIX")) + define("ET_OPEN_FILE_PREFIX", "emerging-"); +if (!defined("ET_PRO_FILE_PREFIX")) + define("ET_PRO_FILE_PREFIX", "etpro-"); + +?> diff --git a/config/snort/snort_download_rules.php b/config/snort/snort_download_rules.php index f35341f1..0fa20e08 100755 --- a/config/snort/snort_download_rules.php +++ b/config/snort/snort_download_rules.php @@ -43,7 +43,6 @@ include("head.inc"); <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> <?php include("fbegin.inc"); ?> -<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <form action="/snort/snort_download_updates.php" method="GET"> @@ -91,7 +90,7 @@ include("head.inc"); <?php $snort_gui_include = true; -include("/usr/local/www/snort/snort_check_for_rule_updates.php"); +include("/usr/local/pkg/snort/snort_check_for_rule_updates.php"); /* hide progress bar and lets end this party */ echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';\n</script>"; diff --git a/config/snort/snort_download_updates.php b/config/snort/snort_download_updates.php index ecc1e5b5..3f34cb7e 100755 --- a/config/snort/snort_download_updates.php +++ b/config/snort/snort_download_updates.php @@ -38,25 +38,19 @@ require_once("/usr/local/pkg/snort/snort.inc"); /* Define some locally required variables from Snort constants */ $snortdir = SNORTDIR; -$snort_rules_upd_log = RULES_UPD_LOGFILE; +$snort_rules_upd_log = SNORT_RULES_UPD_LOGFILE; +$snortbinver = SNORT_BIN_VERSION; +$snortbinver = str_replace(".", "", $snortbinver); -/* Grab the Snort binary version programmatically and */ -/* use it to construct the proper Snort VRT rules */ -/* tarball filename. Fallback to a safe default if */ -/* we fail. */ -$snortver = array(); -exec("/usr/local/bin/snort -V 2>&1 |/usr/bin/grep Version | /usr/bin/cut -c20-26", $snortver); -if (empty($snortver[0])) - $snortver[0] = "2.9.5.5"; -$snortver[0] = str_replace(".", "", $snortver[0]); - -$snort_rules_file = "snortrules-snapshot-{$snortver[0]}.tar.gz"; -$snort_community_rules_filename = GPLV2_DNLD_FILENAME; +$snort_rules_file = "snortrules-snapshot-{$snortbinver}.tar.gz"; +$snort_community_rules_filename = SNORT_GPLV2_DNLD_FILENAME; +$snort_openappid_filename = SNORT_OPENAPPID_DNLD_FILENAME; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; $etpro = $config['installedpackages']['snortglobal']['emergingthreats_pro']; $snortcommunityrules = $config['installedpackages']['snortglobal']['snortcommunityrules']; +$openappid_detectors = $config['installedpackages']['snortglobal']['openappid_detectors']; /* Get last update information if available */ if (!empty($config['installedpackages']['snortglobal']['last_rule_upd_time'])) @@ -69,22 +63,22 @@ else $last_rule_upd_status = gettext("Unknown"); if ($etpro == "on") { - $emergingthreats_filename = ETPRO_DNLD_FILENAME; - $et_name = "Emerging Threats Pro Rules"; + $emergingthreats_filename = SNORT_ETPRO_DNLD_FILENAME; + $et_name = gettext("Emerging Threats Pro Rules"); } else { - $emergingthreats_filename = ET_DNLD_FILENAME; - $et_name = "Emerging Threats Open Rules"; + $emergingthreats_filename = SNORT_ET_DNLD_FILENAME; + $et_name = gettext("Emerging Threats Open Rules"); } /* quick md5 chk of downloaded rules */ if ($snortdownload == 'on') { - $snort_org_sig_chk_local = 'Not Downloaded'; - $snort_org_sig_date = 'Not Downloaded'; + $snort_org_sig_chk_local = gettext("Not Downloaded"); + $snort_org_sig_date = gettext("Not Downloaded"); } else { - $snort_org_sig_chk_local = 'Not Enabled'; - $snort_org_sig_date = 'Not Enabled'; + $snort_org_sig_chk_local = gettext("Not Enabled"); + $snort_org_sig_date = gettext("Not Enabled"); } if (file_exists("{$snortdir}/{$snort_rules_file}.md5") && $snortdownload == 'on') { $snort_org_sig_chk_local = file_get_contents("{$snortdir}/{$snort_rules_file}.md5"); @@ -92,12 +86,12 @@ if (file_exists("{$snortdir}/{$snort_rules_file}.md5") && $snortdownload == 'on' } if ($etpro == "on" || $emergingthreats == "on") { - $emergingt_net_sig_chk_local = 'Not Downloaded'; - $emergingt_net_sig_date = 'Not Downloaded'; + $emergingt_net_sig_chk_local = gettext("Not Downloaded"); + $emergingt_net_sig_date = gettext("Not Downloaded"); } else { - $emergingt_net_sig_chk_local = 'Not Enabled'; - $emergingt_net_sig_date = 'Not Enabled'; + $emergingt_net_sig_chk_local = gettext("Not Enabled"); + $emergingt_net_sig_date = gettext("Not Enabled"); } if (file_exists("{$snortdir}/{$emergingthreats_filename}.md5") && ($etpro == "on" || $emergingthreats == "on")) { $emergingt_net_sig_chk_local = file_get_contents("{$snortdir}/{$emergingthreats_filename}.md5"); @@ -105,25 +99,37 @@ if (file_exists("{$snortdir}/{$emergingthreats_filename}.md5") && ($etpro == "on } if ($snortcommunityrules == 'on') { - $snort_community_sig_chk_local = 'Not Downloaded'; - $snort_community_sig_sig_date = 'Not Downloaded'; + $snort_community_sig_chk_local = gettext("Not Downloaded"); + $snort_community_sig_date = gettext("Not Downloaded"); } else { - $snort_community_sig_chk_local = 'Not Enabled'; - $snort_community_sig_sig_date = 'Not Enabled'; + $snort_community_sig_chk_local = gettext("Not Enabled"); + $snort_community_sig_date = gettext("Not Enabled"); } if (file_exists("{$snortdir}/{$snort_community_rules_filename}.md5") && $snortcommunityrules == 'on') { $snort_community_sig_chk_local = file_get_contents("{$snortdir}/{$snort_community_rules_filename}.md5"); - $snort_community_sig_sig_date = date(DATE_RFC850, filemtime("{$snortdir}/{$snort_community_rules_filename}.md5")); + $snort_community_sig_date = date(DATE_RFC850, filemtime("{$snortdir}/{$snort_community_rules_filename}.md5")); +} + +if ($openappid_detectors == 'on') { + $openappid_detectors_sig_chk_local = gettext("Not Downloaded"); + $openappid_detectors_sig_date = gettext("Not Downloaded"); +} +else { + $openappid_detectors_sig_chk_local = gettext("Not Enabled"); + $openappid_detectors_sig_date = gettext("Not Enabled"); +} +if (file_exists("{$snortdir}/{$snort_openappid_filename}.md5") && $openappid_detectors == 'on') { + $openappid_detectors_sig_chk_local = file_get_contents("{$snortdir}/{$snort_openappid_filename}.md5"); + $openappid_detectors_sig_date = date(DATE_RFC850, filemtime("{$snortdir}/{$snort_openappid_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}"); + unlink_if_exists($snort_rules_upd_log); } -if (isset($_POST['check'])) { +if (isset($_POST['update'])) { header("Location: /snort/snort_download_rules.php"); exit; } @@ -133,12 +139,10 @@ if ($_POST['force']) { conf_mount_rw(); // Remove the existing MD5 signature files to force a download - if (file_exists("{$snortdir}/{$emergingthreats_filename}.md5")) - @unlink("{$snortdir}/{$emergingthreats_filename}.md5"); - if (file_exists("{$snortdir}/{$snort_community_rules_filename}.md5")) - @unlink("{$snortdir}/{$snort_community_rules_filename}.md5"); - if (file_exists("{$snortdir}/{$snort_rules_file}.md5")) - @unlink("{$snortdir}/{$snort_rules_file}.md5"); + unlink_if_exists("{$snortdir}/{$emergingthreats_filename}.md5"); + unlink_if_exists("{$snortdir}/{$snort_community_rules_filename}.md5"); + unlink_if_exists("{$snortdir}/{$snort_rules_file}.md5"); + unlink_if_exists("{$snortdir}/{$snort_openappid_filename}.md5"); // Revert file system to R/O. conf_mount_ro(); @@ -184,7 +188,9 @@ include_once("head.inc"); $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -206,20 +212,25 @@ include_once("head.inc"); </tr> </thead> <tr> - <td align="center" class="vncell vexpl"><b>Snort VRT Rules</b></td> + <td align="center" class="vncell vexpl"><b><?=gettext("Snort VRT Rules");?></b></td> <td align="center" class="vncell vexpl"><? echo trim($snort_org_sig_chk_local);?></td> <td align="center" class="vncell vexpl"><?php echo gettext($snort_org_sig_date);?></td> </tr> <tr> - <td align="center" class="vncell vexpl"><b>Snort GPLv2 Community Rules</b></td> + <td align="center" class="vncell vexpl"><b><?=gettext("Snort GPLv2 Community Rules");?></b></td> <td align="center" class="vncell vexpl"><? echo trim($snort_community_sig_chk_local);?></td> - <td align="center" class="vncell vexpl"><?php echo gettext($snort_community_sig_sig_date);?></td> + <td align="center" class="vncell vexpl"><?php echo gettext($snort_community_sig_date);?></td> </tr> <tr> <td align="center" class="vncell vexpl"><b><?=$et_name;?></b></td> <td align="center" class="vncell vexpl"><? echo trim($emergingt_net_sig_chk_local);?></td> <td align="center" class="vncell vexpl"><?php echo gettext($emergingt_net_sig_date);?></td> </tr> + <tr> + <td align="center" class="vncell vexpl"><b><?=gettext("Snort OpenAppID Detectors");?></b></td> + <td align="center" class="vncell vexpl"><? echo trim($openappid_detectors_sig_chk_local);?></td> + <td align="center" class="vncell vexpl"><?php echo gettext($openappid_detectors_sig_date);?></td> + </tr> </table><br/> </td> </tr> @@ -251,12 +262,12 @@ include_once("head.inc"); <p style="text-align:center;" class="vexpl"> <font class="red"><b><?php echo gettext("WARNING:");?></b></font> <?php echo gettext('No rule types have been selected for download. ') . - gettext('Visit the ') . '<a href="/snort/snort_global.php">Global Settings Tab</a>' . gettext(' to select rule types.'); ?> + gettext('Visit the ') . '<a href="/snort/snort_interfaces_global.php">Global Settings Tab</a>' . gettext(' to select rule types.'); ?> <br/></p> <?php else: ?> <br/> - <input type="submit" value="<?=gettext("Check");?>" name="check" id="check" class="formbtn" - title="<?php echo gettext("Check for new updates to enabled rule sets"); ?>"/> + <input type="submit" value="<?=gettext("Update");?>" name="update" id="update" class="formbtn" + title="<?php echo gettext("Check for and apply new update to enabled rule sets"); ?>"/> <input type="submit" value="<?=gettext("Force");?>" name="force" id="force" class="formbtn" title="<?=gettext("Force an update of all enabled rule sets");?>" onclick="return confirm('<?=gettext("This will zero-out the MD5 hashes to force a fresh download of enabled rule sets. Click OK to continue or CANCEL to quit");?>');"/> diff --git a/config/snort/snort_edit_hat_data.php b/config/snort/snort_edit_hat_data.php index a5ec0aad..04be18e7 100644 --- a/config/snort/snort_edit_hat_data.php +++ b/config/snort/snort_edit_hat_data.php @@ -68,7 +68,9 @@ if ($_POST['clear']) { $a_nat[$id]['host_attribute_table'] = 'off'; write_config("Snort pkg: cleared Host Attribute Table data for {$a_nat[$id]['interface']}."); $rebuild_rules = false; + conf_mount_rw(); snort_generate_conf($a_nat[$id]); + conf_mount_ro(); $pconfig['host_attribute_data'] = ""; } @@ -80,7 +82,9 @@ if ($_POST['save']) { $a_nat[$id]['host_attribute_table'] = 'off'; write_config("Snort pkg: modified Host Attribute Table data for {$a_nat[$id]['interface']}."); $rebuild_rules = false; + conf_mount_rw(); snort_generate_conf($a_nat[$id]); + conf_mount_ro(); $pconfig['host_attribute_data'] = $_POST['host_attribute_data']; } diff --git a/config/snort/snort_generate_conf.php b/config/snort/snort_generate_conf.php new file mode 100644 index 00000000..1d56fc13 --- /dev/null +++ b/config/snort/snort_generate_conf.php @@ -0,0 +1,1397 @@ +<?php +/* + * snort_generate_conf.php + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009-2010 Robert Zelaya + * Copyright (C) 2011-2012 Ermal Luci + * Copyright (C) 2013,2014 Bill Meeks + * part of pfSense + * 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. + */ + +/**************************************************************************/ +/* This code reads the stored Snort configuration and constructs a series */ +/* of string variables that are used as values for placeholders in the */ +/* snort_conf_template.inc file. These strings along with text in the */ +/* template are used to create the snort.conf file for the interface. */ +/**************************************************************************/ + +/* Custom home nets */ +$home_net_list = snort_build_list($snortcfg, $snortcfg['homelistname']); +$home_net = implode(",", $home_net_list); +$home_net = trim($home_net); +$external_net = ""; +if (!empty($snortcfg['externallistname']) && $snortcfg['externallistname'] != 'default') { + $external_net_list = snort_build_list($snortcfg, $snortcfg['externallistname'], false, true); + $external_net = implode(",", $external_net_list); + $external_net = "[" . trim($external_net) . "]"; +} +else { + foreach ($home_net_list as $ip) + $external_net .= "!{$ip},"; + $external_net = trim($external_net, ', '); +} + +/* User added custom configuration arguments */ +$snort_config_pass_thru = str_replace("\r", "", base64_decode($snortcfg['configpassthru'])); +// Remove the trailing newline +$snort_config_pass_thru = rtrim($snort_config_pass_thru); + +/* create a few directories and ensure the sample files are in place */ +$snort_dirs = array( $snortdir, $snortcfgdir, "{$snortcfgdir}/rules", + "{$snortlogdir}/snort_{$if_real}{$snort_uuid}", + "{$snortlogdir}/snort_{$if_real}{$snort_uuid}/barnyard2", + "{$snortcfgdir}/preproc_rules", + "dynamicrules" => "{$snortlibdir}/snort_dynamicrules", + "dynamicengine" => "{$snortlibdir}/snort_dynamicengine", + "dynamicpreprocessor" => "{$snortcfgdir}/snort_dynamicpreprocessor" +); +foreach ($snort_dirs as $dir) { + if (!is_dir($dir)) + 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", "attribute_table.dtd", + "sid-msg.map", "unicode.map", "file_magic.conf", "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}")) { + $ftime = filemtime("{$snortdir}/{$file}"); + if (!file_exists("{$snortcfgdir}/{$file}") || ($ftime > filemtime("{$snortcfgdir}/{$file}"))) + @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); + } +} + +/* define alert log limit */ +if (!empty($config['installedpackages']['snortglobal']['alert_log_limit_size']) && $config['installedpackages']['snortglobal']['alert_log_limit_size'] != "0") + $alert_log_limit_size = $config['installedpackages']['snortglobal']['alert_log_limit_size'] . "K"; +else + $alert_log_limit_size = ""; + +/* define alertsystemlog */ +$alertsystemlog_type = ""; +if ($snortcfg['alertsystemlog'] == "on") { + $alertsystemlog_type = "output alert_syslog: "; + if (!empty($snortcfg['alertsystemlog_facility'])) + $alertsystemlog_type .= strtoupper($snortcfg['alertsystemlog_facility']) . " "; + else + $alertsystemlog_type .= "LOG_AUTH "; + if (!empty($snortcfg['alertsystemlog_priority'])) + $alertsystemlog_type .= strtoupper($snortcfg['alertsystemlog_priority']) . " "; + else + $alertsystemlog_type .= "LOG_ALERT "; +} + +/* define snortunifiedlog */ +$snortunifiedlog_type = ""; +if ($snortcfg['barnyard_enable'] == "on") { + if (isset($snortcfg['unified2_log_limit'])) + $u2_log_limit = "limit {$snortcfg['unified2_log_limit']}"; + else + $u2_log_limit = "limit 128K"; + + $snortunifiedlog_type = "output unified2: filename snort_{$snort_uuid}_{$if_real}.u2, {$u2_log_limit}"; + if ($snortcfg['barnyard_log_vlan_events'] == 'on') + $snortunifiedlog_type .= ", vlan_event_types"; + if ($snortcfg['barnyard_log_mpls_events'] == 'on') + $snortunifiedlog_type .= ", mpls_event_types"; + + // If AppID detector is enabled, add it to unified2 logging + if ($snortcfg['appid_preproc'] == 'on' ) + $snortunifiedlog_type .= ", appid_event_types"; +} + +/* define spoink */ +$spoink_type = ""; +if ($snortcfg['blockoffenders7'] == "on") { + $pfkill = ""; + if ($snortcfg['blockoffenderskill'] == "on") + $pfkill = "kill"; + $spoink_wlist = snort_build_list($snortcfg, $snortcfg['whitelistname'], true); + /* write Pass List */ + @file_put_contents("{$snortcfgdir}/{$snortcfg['whitelistname']}", implode("\n", $spoink_wlist)); + $spoink_type = "output alert_pf: {$snortcfgdir}/{$snortcfg['whitelistname']},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; +} + +/* define selected suppress file */ +$suppress_file_name = ""; +$suppress = snort_find_list($snortcfg['suppresslistname'], 'suppress'); +if (!empty($suppress)) { + $suppress_data = str_replace("\r", "", base64_decode($suppress['suppresspassthru'])); + @file_put_contents("{$snortcfgdir}/supp{$snortcfg['suppresslistname']}", $suppress_data); + $suppress_file_name = "include {$snortcfgdir}/supp{$snortcfg['suppresslistname']}"; +} + +/* set the snort performance model */ +$snort_performance = "ac-bnfa"; +if(!empty($snortcfg['performance'])) + $snort_performance = $snortcfg['performance']; + +/* if user has defined a custom ssh port, use it */ +if(is_array($config['system']['ssh']) && isset($config['system']['ssh']['port'])) + $ssh_port = $config['system']['ssh']['port']; +else + $ssh_port = "22"; + +/* Define an array of default values for the various preprocessor ports */ +$snort_ports = array( + "dns_ports" => "53", "smtp_ports" => "25", "mail_ports" => "25,465,587,691", + "http_ports" => "36,80,81,82,83,84,85,86,87,88,89,90,311,383,591,593,631,901,1220,1414,1533,1741,1830,2301,2381,2809,3037,3057,3128,3443,3702,4343,4848,5250,6080,6988,7000,7001,7144,7145,7510,7777,7779,8000,8008,8014,8028,8080,8081,8082,8085,8088,8090,8118,8123,8180,8181,8222,8243,8280,8300,8500,8800,8888,8899,9000,9060,9080,9090,9091,9443,9999,10000,11371,15489,29991,33300,34412,34443,34444,41080,44440,50000,50002,51423,55555,56712", + "oracle_ports" => "1024:", "mssql_ports" => "1433", "telnet_ports" => "23", + "snmp_ports" => "161", "ftp_ports" => "21,2100,3535", "ssh_ports" => $ssh_port, + "pop2_ports" => "109", "pop3_ports" => "110", "imap_ports" => "143", + "sip_ports" => "5060,5061,5600", "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,992,993,994,995,7801,7802,7900,7901,7902,7903,7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920", + "file_data_ports" => "\$HTTP_PORTS,110,143", "shellcode_ports" => "!80", + "sun_rpc_ports" => "111,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779", + "DCERPC_NCACN_IP_TCP" => "139,445", "DCERPC_NCADG_IP_UDP" => "138,1024:", + "DCERPC_NCACN_IP_LONG" => "135,139,445,593,1024:", "DCERPC_NCACN_UDP_LONG" => "135,1024:", + "DCERPC_NCACN_UDP_SHORT" => "135,593,1024:", "DCERPC_NCACN_TCP" => "2103,2105,2107", + "DCERPC_BRIGHTSTORE" => "6503,6504", "DNP3_PORTS" => "20000", "MODBUS_PORTS" => "502", + "GTP_PORTS" => "2123,2152,3386" +); + +/* Check for defined Aliases that may override default port settings as we build the portvars array */ +$portvardef = ""; +foreach ($snort_ports as $alias => $avalue) { + if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) + $snort_ports[$alias] = trim(filter_expand_alias($snortcfg["def_{$alias}"])); + $snort_ports[$alias] = preg_replace('/\s+/', ',', trim($snort_ports[$alias])); + $portvardef .= "portvar " . strtoupper($alias) . " [" . $snort_ports[$alias] . "]\n"; +} + +/* Define the default ports for the Stream5 preprocessor (formatted for easier reading in the snort.conf file) */ +$stream5_ports_client = "21 22 23 25 42 53 70 79 109 110 111 113 119 135 136 137 \\\n"; +$stream5_ports_client .= "\t 139 143 161 445 513 514 587 593 691 1433 1521 1741 \\\n"; +$stream5_ports_client .= "\t 2100 3306 6070 6665 6666 6667 6668 6669 7000 8181 \\\n"; +$stream5_ports_client .= "\t 32770 32771 32772 32773 32774 32775 32776 32777 \\\n"; +$stream5_ports_client .= "\t 32778 32779"; +$stream5_ports_both = "80 81 82 83 84 85 86 87 88 89 90 110 311 383 443 465 563 \\\n"; +$stream5_ports_both .= "\t 591 593 631 636 901 989 992 993 994 995 1220 1414 1533 \\\n"; +$stream5_ports_both .= "\t 1830 2301 2381 2809 3037 3057 3128 3443 3702 4343 4848 \\\n"; +$stream5_ports_both .= "\t 5250 6080 6988 7907 7000 7001 7144 7145 7510 7802 7777 \\\n"; +$stream5_ports_both .= "\t 7779 7801 7900 7901 7902 7903 7904 7905 7906 7908 7909 \\\n"; +$stream5_ports_both .= "\t 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 \\\n"; +$stream5_ports_both .= "\t 8000 8008 8014 8028 8080 8081 8082 8085 8088 8090 8118 \\\n"; +$stream5_ports_both .= "\t 8123 8180 8222 8243 8280 8300 8500 8800 8888 8899 9000 \\\n"; +$stream5_ports_both .= "\t 9060 9080 9090 9091 9443 9999 10000 11371 15489 29991 \\\n"; +$stream5_ports_both .= "\t 33300 34412 34443 34444 41080 44440 50000 50002 51423 \\\n"; +$stream5_ports_both .= "\t 55555 56712"; + +/*********************/ +/* preprocessor code */ +/*********************/ + +/* def perform_stat */ + +if (!empty($config['installedpackages']['snortglobal']['stats_log_limit_size']) && $config['installedpackages']['snortglobal']['stats_log_limit_size'] != "0") + $stats_log_limit = "max_file_size " . $config['installedpackages']['snortglobal']['stats_log_limit_size'] * 1000; +else + $stats_log_limit = ""; +$perform_stat = <<<EOD +# Performance Statistics # +preprocessor perfmonitor: time 300 file {$snortlogdir}/snort_{$if_real}{$snort_uuid}/{$if_real}.stats pktcnt 10000 {$stats_log_limit} + +EOD; + +/* def ftp_preprocessor */ + +$telnet_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['telnet_ports'])); +$ftp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ftp_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($telnet_ports) || empty($telnet_ports)) + $telnet_ports = "23"; +if (!isset($ftp_ports) || empty($ftp_ports)) + $ftp_ports = "21 2100 3535"; + +// Configure FTP_Telnet global options +$ftp_telnet_globals = "inspection_type "; +if ($snortcfg['ftp_telnet_inspection_type'] != "") { $ftp_telnet_globals .= $snortcfg['ftp_telnet_inspection_type']; }else{ $ftp_telnet_globals .= "stateful"; } +if ($snortcfg['ftp_telnet_alert_encrypted'] == "on") + $ftp_telnet_globals .= " \\\n\tencrypted_traffic yes"; +else + $ftp_telnet_globals .= " \\\n\tencrypted_traffic no"; +if ($snortcfg['ftp_telnet_check_encrypted'] == "on") + $ftp_telnet_globals .= " \\\n\tcheck_encrypted"; + +// Configure FTP_Telnet Telnet protocol options +$ftp_telnet_protocol = "ports { {$telnet_ports} }"; +if ($snortcfg['ftp_telnet_normalize'] == "on") + $ftp_telnet_protocol .= " \\\n\tnormalize"; +if ($snortcfg['ftp_telnet_detect_anomalies'] == "on") + $ftp_telnet_protocol .= " \\\n\tdetect_anomalies"; +if ($snortcfg['ftp_telnet_ayt_attack_threshold'] <> '0') { + $ftp_telnet_protocol .= " \\\n\tayt_attack_thresh "; + if ($snortcfg['ftp_telnet_ayt_attack_threshold'] != "") + $ftp_telnet_protocol .= $snortcfg['ftp_telnet_ayt_attack_threshold']; + else + $ftp_telnet_protocol .= "20"; +} + +// Setup the standard FTP commands used for all FTP Server engines +$ftp_cmds = <<<EOD + ftp_cmds { ABOR ACCT ADAT ALLO APPE AUTH CCC CDUP } \ + ftp_cmds { CEL CLNT CMD CONF CWD DELE ENC EPRT } \ + ftp_cmds { EPSV ESTA ESTP FEAT HELP LANG LIST LPRT } \ + ftp_cmds { LPSV MACB MAIL MDTM MFMT MIC MKD MLSD MLST } \ + ftp_cmds { MODE NLST NOOP OPTS PASS PASV PBSZ PORT } \ + ftp_cmds { PROT PWD QUIT REIN REST RETR RMD RNFR } \ + ftp_cmds { RNTO SDUP SITE SIZE SMNT STAT STOR STOU } \ + ftp_cmds { STRU SYST TEST TYPE USER XCUP XCRC XCWD } \ + ftp_cmds { XMAS XMD5 XMKD XPWD XRCP XRMD XRSQ XSEM } \ + ftp_cmds { XSEN XSHA1 XSHA256 } \ + alt_max_param_len 0 { ABOR CCC CDUP ESTA FEAT LPSV NOOP PASV PWD QUIT REIN STOU SYST XCUP XPWD } \ + alt_max_param_len 200 { ALLO APPE CMD HELP NLST RETR RNFR STOR STOU XMKD } \ + alt_max_param_len 256 { CWD RNTO } \ + alt_max_param_len 400 { PORT } \ + alt_max_param_len 512 { MFMT SIZE } \ + chk_str_fmt { ACCT ADAT ALLO APPE AUTH CEL CLNT CMD } \ + chk_str_fmt { CONF CWD DELE ENC EPRT EPSV ESTP HELP } \ + chk_str_fmt { LANG LIST LPRT MACB MAIL MDTM MIC MKD } \ + chk_str_fmt { MLSD MLST MODE NLST OPTS PASS PBSZ PORT } \ + chk_str_fmt { PROT REST RETR RMD RNFR RNTO SDUP SITE } \ + chk_str_fmt { SIZE SMNT STAT STOR STRU TEST TYPE USER } \ + chk_str_fmt { XCRC XCWD XMAS XMD5 XMKD XRCP XRMD XRSQ } \ + chk_str_fmt { XSEM XSEN XSHA1 XSHA256 } \ + cmd_validity ALLO < int [ char R int ] > \ + cmd_validity EPSV < [ { char 12 | char A char L char L } ] > \ + cmd_validity MACB < string > \ + cmd_validity MDTM < [ date nnnnnnnnnnnnnn[.n[n[n]]] ] string > \ + cmd_validity MODE < char ASBCZ > \ + cmd_validity PORT < host_port > \ + cmd_validity PROT < char CSEP > \ + cmd_validity STRU < char FRPO [ string ] > \ + cmd_validity TYPE < { char AE [ char NTC ] | char I | char L [ number ] } > + +EOD; + +// Configure all the FTP_Telnet FTP protocol options +// Iterate and configure the FTP Client engines +$ftp_default_client_engine = array( "name" => "default", "bind_to" => "all", "max_resp_len" => 256, + "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", + "bounce" => "yes", "bounce_to_net" => "", "bounce_to_port" => "" ); + +if (!is_array($snortcfg['ftp_client_engine']['item'])) + $snortcfg['ftp_client_engine']['item'] = array(); + +// If no FTP client engine is configured, use the default +// to keep from breaking Snort. +if (empty($snortcfg['ftp_client_engine']['item'])) + $snortcfg['ftp_client_engine']['item'][] = $ftp_default_client_engine; +$ftp_client_engine = ""; + +foreach ($snortcfg['ftp_client_engine']['item'] as $f => $v) { + $buffer = "preprocessor ftp_telnet_protocol: ftp client "; + if ($v['name'] == "default" && $v['bind_to'] == "all") + $buffer .= "default \\\n"; + elseif (is_alias($v['bind_to'])) { + $tmp = trim(filter_expand_alias($v['bind_to'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ' ', $tmp); + $buffer .= "{$tmp} \\\n"; + } + else { + log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); + continue; + } + } + else { + log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); + continue; + } + + if ($v['max_resp_len'] == "") + $buffer .= "\tmax_resp_len 256 \\\n"; + else + $buffer .= "\tmax_resp_len {$v['max_resp_len']} \\\n"; + + $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; + $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; + + if ($v['bounce'] == "yes") { + if (is_alias($v['bounce_to_net']) && is_alias($v['bounce_to_port'])) { + $net = trim(filter_expand_alias($v['bounce_to_net'])); + $port = trim(filter_expand_alias($v['bounce_to_port'])); + if (!empty($net) && !empty($port) && + snort_is_single_addr_alias($v['bounce_to_net']) && + (is_port($port) || is_portrange($port))) { + $port = preg_replace('/\s+/', ',', $port); + // Change port range delimiter to comma for ftp_telnet client preprocessor + if (is_portrange($port)) + $port = str_replace(":", ",", $port); + $buffer .= "\tbounce yes \\\n"; + $buffer .= "\tbounce_to { {$net},{$port} }\n"; + } + else { + // One or both of the BOUNCE_TO alias values is not right, + // so figure out which and log an appropriate error. + if (empty($net) || !snort_is_single_addr_alias($v['bounce_to_net'])) + log_error("[snort] ERROR: illegal value for bounce_to Address Alias [{$v['bounce_to_net']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); + if (empty($port) || !(is_port($port) || is_portrange($port))) + log_error("[snort] ERROR: illegal value for bounce_to Port Alias [{$v['bounce_to_port']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); + $buffer .= "\tbounce yes\n"; + } + } + else + $buffer .= "\tbounce yes\n"; + } + else + $buffer .= "\tbounce no\n"; + + // Add this FTP client engine to the master string + $ftp_client_engine .= "{$buffer}\n"; +} +// Trim final trailing newline +rtrim($ftp_client_engine); + +// Iterate and configure the FTP Server engines +$ftp_default_server_engine = array( "name" => "default", "bind_to" => "all", "ports" => "default", + "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", + "ignore_data_chan" => "no", "def_max_param_len" => 100 ); + +if (!is_array($snortcfg['ftp_server_engine']['item'])) + $snortcfg['ftp_server_engine']['item'] = array(); + +// If no FTP server engine is configured, use the default +// to keep from breaking Snort. +if (empty($snortcfg['ftp_server_engine']['item'])) + $snortcfg['ftp_server_engine']['item'][] = $ftp_default_server_engine; +$ftp_server_engine = ""; + +foreach ($snortcfg['ftp_server_engine']['item'] as $f => $v) { + $buffer = "preprocessor ftp_telnet_protocol: ftp server "; + if ($v['name'] == "default" && $v['bind_to'] == "all") + $buffer .= "default \\\n"; + elseif (is_alias($v['bind_to'])) { + $tmp = trim(filter_expand_alias($v['bind_to'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ' ', $tmp); + $buffer .= "{$tmp} \\\n"; + } + else { + log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); + continue; + } + } + else { + log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); + continue; + } + + if ($v['def_max_param_len'] == "") + $buffer .= "\tdef_max_param_len 100 \\\n"; + elseif ($v['def_max_param_len'] <> '0') + $buffer .= "\tdef_max_param_len {$v['def_max_param_len']} \\\n"; + + if ($v['ports'] == "default" || !is_alias($v['ports']) || empty($v['ports'])) + $buffer .= "\tports { {$ftp_ports} } \\\n"; + elseif (is_alias($v['ports'])) { + $tmp = trim(filter_expand_alias($v['ports'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ' ', $tmp); + $tmp = snort_expand_port_range($tmp, ' '); + $buffer .= "\tports { {$tmp} } \\\n"; + } + else { + log_error("[snort] ERROR: unable to resolve Port Alias '{$v['ports']}' for FTP server '{$v['name']}' ... reverting to defaults."); + $buffer .= "\tports { {$ftp_ports} } \\\n"; + } + } + + $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; + $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; + if ($v['ignore_data_chan'] == "yes") + $buffer .= "\tignore_data_chan yes \\\n"; + $buffer .= "{$ftp_cmds}\n"; + + // Add this FTP server engine to the master string + $ftp_server_engine .= $buffer; +} +// Remove trailing newlines +rtrim($ftp_server_engine); + + $ftp_preprocessor = <<<EOD +# ftp_telnet preprocessor # +preprocessor ftp_telnet: global \ + {$ftp_telnet_globals} + +preprocessor ftp_telnet_protocol: telnet \ + {$ftp_telnet_protocol} + +{$ftp_server_engine} +{$ftp_client_engine} +EOD; + +/* def pop_preprocessor */ + +$pop_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['pop3_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($pop_ports) || empty($pop_ports)) + $pop_ports = "110"; + +if (isset($snortcfg['pop_memcap'])) + $pop_memcap = $snortcfg['pop_memcap']; +else + $pop_memcap = "838860"; +if (isset($snortcfg['pop_qp_decode_depth'])) + $pop_qp_decode_depth = $snortcfg['pop_qp_decode_depth']; +else + $pop_qp_decode_depth = "0"; +if (isset($snortcfg['pop_b64_decode_depth'])) + $pop_b64_decode_depth = $snortcfg['pop_b64_decode_depth']; +else + $pop_b64_decode_depth = "0"; +if (isset($snortcfg['pop_bitenc_decode_depth'])) + $pop_bitenc_decode_depth = $snortcfg['pop_bitenc_decode_depth']; +else + $pop_bitenc_decode_depth = "0"; +if (isset($snortcfg['pop_uu_decode_depth'])) + $pop_uu_decode_depth = $snortcfg['pop_uu_decode_depth']; +else + $pop_uu_decode_depth = "0"; +$pop_preproc = <<<EOD +# POP preprocessor # +preprocessor pop: \ + ports { {$pop_ports} } \ + memcap {$pop_memcap} \ + qp_decode_depth {$pop_qp_decode_depth} \ + b64_decode_depth {$pop_b64_decode_depth} \ + bitenc_decode_depth {$pop_bitenc_decode_depth} \ + uu_decode_depth {$pop_uu_decode_depth} + +EOD; + +/* def imap_preprocessor */ + +$imap_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['imap_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($imap_ports) || empty($imap_ports)) + $imap_ports = "143"; + +if (isset($snortcfg['imap_memcap'])) + $imap_memcap = $snortcfg['imap_memcap']; +else + $imap_memcap = "838860"; +if (isset($snortcfg['imap_qp_decode_depth'])) + $imap_qp_decode_depth = $snortcfg['imap_qp_decode_depth']; +else + $imap_qp_decode_depth = "0"; +if (isset($snortcfg['imap_b64_decode_depth'])) + $imap_b64_decode_depth = $snortcfg['imap_b64_decode_depth']; +else + $imap_b64_decode_depth = "0"; +if (isset($snortcfg['imap_bitenc_decode_depth'])) + $imap_bitenc_decode_depth = $snortcfg['imap_bitenc_decode_depth']; +else + $imap_bitenc_decode_depth = "0"; +if (isset($snortcfg['imap_uu_decode_depth'])) + $imap_uu_decode_depth = $snortcfg['imap_uu_decode_depth']; +else + $imap_uu_decode_depth = "0"; +$imap_preproc = <<<EOD +# IMAP preprocessor # +preprocessor imap: \ + ports { {$imap_ports} } \ + memcap {$imap_memcap} \ + qp_decode_depth {$imap_qp_decode_depth} \ + b64_decode_depth {$imap_b64_decode_depth} \ + bitenc_decode_depth {$imap_bitenc_decode_depth} \ + uu_decode_depth {$imap_uu_decode_depth} + +EOD; + +/* def smtp_preprocessor */ + +$smtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['mail_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($smtp_ports) || empty($smtp_ports)) + $smtp_ports = "25 465 587 691"; + +if (isset($snortcfg['smtp_memcap'])) + $smtp_memcap = $snortcfg['smtp_memcap']; +else + $smtp_memcap = "838860"; +if (isset($snortcfg['smtp_max_mime_mem'])) + $smtp_max_mime_mem = $snortcfg['smtp_max_mime_mem']; +else + $smtp_max_mime_mem = "838860"; +if (isset($snortcfg['smtp_qp_decode_depth'])) + $smtp_qp_decode_depth = $snortcfg['smtp_qp_decode_depth']; +else + $smtp_qp_decode_depth = "0"; +if (isset($snortcfg['smtp_b64_decode_depth'])) + $smtp_b64_decode_depth = $snortcfg['smtp_b64_decode_depth']; +else + $smtp_b64_decode_depth = "0"; +if (isset($snortcfg['smtp_bitenc_decode_depth'])) + $smtp_bitenc_decode_depth = $snortcfg['smtp_bitenc_decode_depth']; +else + $smtp_bitenc_decode_depth = "0"; +if (isset($snortcfg['smtp_uu_decode_depth'])) + $smtp_uu_decode_depth = $snortcfg['smtp_uu_decode_depth']; +else + $smtp_uu_decode_depth = "0"; +if (isset($snortcfg['smtp_email_hdrs_log_depth']) && $snortcfg['smtp_email_hdrs_log_depth'] != '0') + $smtp_email_hdrs_log_depth = $snortcfg['smtp_email_hdrs_log_depth']; +else + $smtp_email_hdrs_log_depth = "0"; +$smtp_boolean_params = ""; +if ($snortcfg['smtp_ignore_data'] == 'on') + $smtp_boolean_params .= "\tignore_data \\\n"; +if ($snortcfg['smtp_ignore_tls_data'] == 'on') + $smtp_boolean_params .= "\tignore_tls_data \\\n"; +if ($snortcfg['smtp_log_mail_from'] == 'on') + $smtp_boolean_params .= "\tlog_mailfrom \\\n"; +if ($snortcfg['smtp_log_rcpt_to'] == 'on') + $smtp_boolean_params .= "\tlog_rcptto \\\n"; +if ($snortcfg['smtp_log_filename'] == 'on') + $smtp_boolean_params .= "\tlog_filename \\\n"; +if ($snortcfg['smtp_log_email_hdrs'] == 'on') + $smtp_boolean_params .= "\tlog_email_hdrs\\\n"; +$smtp_boolean_params = trim($smtp_boolean_params, "\t\n\\"); +$smtp_preprocessor = <<<EOD +# SMTP preprocessor # +preprocessor SMTP: \ + ports { {$smtp_ports} } \ + inspection_type stateful \ + normalize cmds \ + memcap {$smtp_memcap} \ + max_mime_mem {$smtp_max_mime_mem} \ + valid_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT \ + NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX QUEU \ + STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE \ + XQUEU XSTA XTRN XUSR } \ + normalize_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY \ + IDENT NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT \ + ONEX QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 \ + XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ + max_header_line_len 1000 \ + max_response_line_len 512 \ + alt_max_command_line_len 260 { MAIL } \ + alt_max_command_line_len 300 { RCPT } \ + alt_max_command_line_len 500 { HELP HELO ETRN EHLO } \ + alt_max_command_line_len 255 { EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT NOOP RSET } \ + alt_max_command_line_len 246 { SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX } \ + alt_max_command_line_len 246 { QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR } \ + alt_max_command_line_len 246 { XAUTH XCIR XEXCH50 XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ + xlink2state { enable } \ + {$smtp_boolean_params} \ + email_hdrs_log_depth {$smtp_email_hdrs_log_depth} \ + qp_decode_depth {$smtp_qp_decode_depth} \ + b64_decode_depth {$smtp_b64_decode_depth} \ + bitenc_decode_depth {$smtp_bitenc_decode_depth} \ + uu_decode_depth {$smtp_uu_decode_depth} + +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']; +$sf_pscan_ignore_scanners = "\$HOME_NET"; +if (!empty($snortcfg['pscan_ignore_scanners']) && is_alias($snortcfg['pscan_ignore_scanners'])) { + $sf_pscan_ignore_scanners = trim(filter_expand_alias($snortcfg['pscan_ignore_scanners'])); + $sf_pscan_ignore_scanners = preg_replace('/\s+/', ',', trim($sf_pscan_ignore_scanners)); +} + +$sf_portscan = <<<EOD +# sf Portscan # +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} } + +EOD; + +/* def ssh_preproc */ + +$ssh_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssh_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($ssh_ports) || empty($ssh_ports)) + $ssh_ports = "22"; +$ssh_preproc = <<<EOD +# SSH preprocessor # +preprocessor ssh: \ + server_ports { {$ssh_ports} } \ + autodetect \ + max_client_bytes 19600 \ + max_encrypted_packets 20 \ + max_server_version_len 100 \ + enable_respoverflow enable_ssh1crc32 \ + enable_srvoverflow enable_protomismatch + +EOD; + +/* def other_preprocs */ + +$sun_rpc_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sun_rpc_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($sun_rpc_ports) || empty($sun_rpc_ports)) + $sun_rpc_ports = "111 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779"; +$other_preprocs = <<<EOD +# Other preprocs # +preprocessor rpc_decode: \ + {$sun_rpc_ports} \ + no_alert_multiple_requests \ + no_alert_large_fragments \ + no_alert_incomplete + +# Back Orifice preprocessor # +preprocessor bo + +EOD; + +/* def dce_rpc_2 */ + +$dce_rpc_2 = <<<EOD +# DCE/RPC 2 # +preprocessor dcerpc2: \ + memcap 102400, \ + events [co] + +preprocessor dcerpc2_server: default, \ + policy WinXP, \ + detect [smb [{$snort_ports['smb_ports']}], \ + tcp 135, \ + udp 135, \ + rpc-over-http-server 593], \ + autodetect [tcp 1025:, \ + udp 1025:, \ + rpc-over-http-server 1025:], \ + smb_max_chain 3, smb_invalid_shares ["C$", "D$", "ADMIN$"] + +EOD; + + +/* def sip_preprocessor */ + +$sip_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sip_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($sip_ports) || empty($sip_ports)) + $sip_ports = "5060 5061 5600"; +$sip_preproc = <<<EOD +# SIP preprocessor # +preprocessor sip: \ + max_sessions 40000, \ + ports { {$sip_ports} }, \ + methods { invite \ + cancel \ + ack \ + bye \ + register \ + options \ + refer \ + subscribe \ + update \ + join \ + info \ + message \ + notify \ + benotify \ + do \ + qauth \ + sprack \ + publish \ + service \ + unsubscribe \ + prack }, \ + max_call_id_len 80, \ + max_from_len 256, \ + max_to_len 256, \ + max_via_len 1024, \ + max_requestName_len 50, \ + max_uri_len 512, \ + ignore_call_channel, \ + max_content_len 2048, \ + max_contact_len 512 + +EOD; + +/* def dns_preprocessor */ + +$dns_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['dns_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($dns_ports) || empty($dns_ports)) + $dns_ports = "53"; +$dns_preprocessor = <<<EOD +# DNS preprocessor # +preprocessor dns: \ + ports { {$dns_ports} } \ + enable_rdata_overflow + +EOD; + +/* def dnp3_preprocessor */ + +$dnp3_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['DNP3_PORTS'])); + +// Make sure we have port numbers or else use defaults +if (!isset($dnp3_ports) || empty($dnp3_ports)) + $dnp3_ports = "20000"; +$dnp3_preproc = <<<EOD +# DNP3 preprocessor # +preprocessor dnp3: \ + ports { {$dnp3_ports} } \ + memcap 262144 \ + check_crc + +EOD; + +/* def modbus_preprocessor */ + +$modbus_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['MODBUS_PORTS'])); + +// Make sure we have port numbers or else use defaults +if (!isset($modbus_ports) || empty($modbus_ports)) + $modbus_ports = "502"; +$modbus_preproc = <<<EOD +# Modbus preprocessor # +preprocessor modbus: \ + ports { {$modbus_ports} } + +EOD; + +/* def gtp_preprocessor */ + +$gtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['GTP_PORTS'])); + +// Make sure we have port numbers or else use defaults +if (!isset($gtp_ports) || empty($gtp_ports)) + $gtp_ports = "2123 3386 2152"; +$gtp_preproc = <<<EOD +# GTP preprocessor # +preprocessor gtp: \ + ports { {$gtp_ports} } + +EOD; + +/* def ssl_preprocessor */ + +$ssl_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssl_ports'])); + +// Make sure we have port numbers or else use defaults +if (!isset($ssl_ports) || empty($ssl_ports)) + $ssl_ports = "443 465 563 636 989 992 993 994 995 7801 7802 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920"; +$ssl_preproc = <<<EOD +# SSL preprocessor # +preprocessor ssl: \ + ports { {$ssl_ports} }, \ + trustservers, \ + noinspect_encrypted + +EOD; + +/* def sensitive_data_preprocessor */ + +if ($snortcfg['sdf_mask_output'] == "on") + $sdf_mask_output = "\\\n\tmask_output"; +else + $sdf_mask_output = ""; +if (empty($snortcfg['sdf_alert_threshold'])) + $snortcfg['sdf_alert_threshold'] = 25; +$sensitive_data = <<<EOD +# SDF preprocessor # +preprocessor sensitive_data: \ + alert_threshold {$snortcfg['sdf_alert_threshold']} {$sdf_mask_output} + +EOD; + +/* define IP Reputation preprocessor */ + +if (is_array($snortcfg['blist_files']['item'])) { + $blist_files = ""; + $bIsFirst = TRUE; + foreach ($snortcfg['blist_files']['item'] as $blist) { + if ($bIsFirst) { + $blist_files .= "blacklist " . SNORT_IPREP_PATH . $blist; + $bIsFirst = FALSE; + } + else + $blist_files .= ", \\ \n\tblacklist " . SNORT_IPREP_PATH . $blist; + } +} +if (is_array($snortcfg['wlist_files']['item'])) { + $wlist_files = ""; + $bIsFirst = TRUE; + foreach ($snortcfg['wlist_files']['item'] as $wlist) { + if ($bIsFirst) { + $wlist_files .= "whitelist " . SNORT_IPREP_PATH . $wlist; + $bIsFirst = FALSE; + } + else + $wlist_files .= ", \\ \n\twhitelist " . SNORT_IPREP_PATH . $wlist; + } +} +if (!empty($blist_files)) + $ip_lists = $blist_files; +if (!empty($wlist_files)) + $ip_lists .= ", \\ \n" . $wlist_files; +if ($snortcfg['iprep_scan_local'] == 'on') + $ip_lists .= ", \\ \n\tscan_local"; + +$reputation_preproc = <<<EOD +# IP Reputation preprocessor # +preprocessor reputation: \ + memcap {$snortcfg['iprep_memcap']}, \ + priority {$snortcfg['iprep_priority']}, \ + nested_ip {$snortcfg['iprep_nested_ip']}, \ + white {$snortcfg['iprep_white']}, \ + {$ip_lists} + +EOD; + +/* def AppID preprocessor */ +$appid_memcap = $snortcfg['sf_appid_mem_cap'] * 1024 * 1024; +$appid_params = "app_detector_dir " . SNORT_APPID_ODP_PATH . ", \\\n\tmemcap {$appid_memcap}"; +if ($snortcfg['sf_appid_statslog'] == "on") { + $appid_params .= ", \\\n\tapp_stats_filename app-stats.log"; + $appid_params .= ", \\\n\tapp_stats_period {$snortcfg['sf_appid_stats_period']}"; + $appid_params .= ", \\\n\tapp_stats_rollover_size " . strval($config['installedpackages']['snortglobal']['appid_stats_log_limit_size'] * 1024); + $appid_params .= ", \\\n\tapp_stats_rollover_time 86400"; +} + +$appid_preproc = <<<EOD +# AppID preprocessor # +preprocessor appid: \ + {$appid_params} + +EOD; + +/***************************************/ +/* end of preprocessor string var code */ +/***************************************/ + +/* define servers as IP variables */ +$snort_servers = array ( + "dns_servers" => "\$HOME_NET", "smtp_servers" => "\$HOME_NET", "http_servers" => "\$HOME_NET", + "www_servers" => "\$HOME_NET", "sql_servers" => "\$HOME_NET", "telnet_servers" => "\$HOME_NET", + "snmp_servers" => "\$HOME_NET", "ftp_servers" => "\$HOME_NET", "ssh_servers" => "\$HOME_NET", + "pop_servers" => "\$HOME_NET", "imap_servers" => "\$HOME_NET", "sip_proxy_ip" => "\$HOME_NET", + "sip_servers" => "\$HOME_NET", "rpc_servers" => "\$HOME_NET", "dnp3_server" => "\$HOME_NET", + "dnp3_client" => "\$HOME_NET", "modbus_server" => "\$HOME_NET", "modbus_client" => "\$HOME_NET", + "enip_server" => "\$HOME_NET", "enip_client" => "\$HOME_NET", + "aim_servers" => "64.12.24.0/23,64.12.28.0/23,64.12.161.0/24,64.12.163.0/24,64.12.200.0/24,205.188.3.0/24,205.188.5.0/24,205.188.7.0/24,205.188.9.0/24,205.188.153.0/24,205.188.179.0/24,205.188.248.0/24" + ); + +// Change old name from "var" to new name of "ipvar" for IP variables because +// Snort is deprecating the old "var" name in newer versions. +$ipvardef = ""; +foreach ($snort_servers as $alias => $avalue) { + if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) { + $avalue = trim(filter_expand_alias($snortcfg["def_{$alias}"])); + $avalue = preg_replace('/\s+/', ',', trim($avalue)); + } + $ipvardef .= "ipvar " . strtoupper($alias) . " [{$avalue}]\n"; +} + +$snort_preproc_libs = array( + "dce_rpc_2" => "dce2_preproc", "dns_preprocessor" => "dns_preproc", "ftp_preprocessor" => "ftptelnet_preproc", "imap_preproc" => "imap_preproc", + "pop_preproc" => "pop_preproc", "reputation_preproc" => "reputation_preproc", "sensitive_data" => "sdf_preproc", + "sip_preproc" => "sip_preproc", "gtp_preproc" => "gtp_preproc", "smtp_preprocessor" => "smtp_preproc", "ssh_preproc" => "ssh_preproc", + "ssl_preproc" => "ssl_preproc", "dnp3_preproc" => "dnp3_preproc", "modbus_preproc" => "modbus_preproc", "appid_preproc" => "appid_preproc" +); +$snort_preproc = array ( + "perform_stat", "other_preprocs", "ftp_preprocessor", "smtp_preprocessor", "ssl_preproc", "sip_preproc", "gtp_preproc", "ssh_preproc", "sf_portscan", + "dce_rpc_2", "dns_preprocessor", "sensitive_data", "pop_preproc", "imap_preproc", "dnp3_preproc", "modbus_preproc", "reputation_preproc", "appid_preproc" +); +$default_disabled_preprocs = array( + "sf_portscan", "gtp_preproc", "sensitive_data", "dnp3_preproc", "modbus_preproc", "reputation_preproc", "perform_stat", "appid_preproc" +); +$snort_preprocessors = ""; +foreach ($snort_preproc as $preproc) { + 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("{$snortlibdir}/snort_dynamicpreprocessor/{$preproclib}.so")) { + @copy("{$snortlibdir}/snort_dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } else + log_error("Could not find the {$preproclib} file. Snort might error out!"); + } else { + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } + } else { + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } + } +} +// Remove final trailing newline +$snort_preprocessors = rtrim($snort_preprocessors); + +$snort_misc_include_rules = ""; +if (file_exists("{$snortcfgdir}/reference.config")) + $snort_misc_include_rules .= "include {$snortcfgdir}/reference.config\n"; +if (file_exists("{$snortcfgdir}/classification.config")) + $snort_misc_include_rules .= "include {$snortcfgdir}/classification.config\n"; +if (!file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") || !file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules")) { + $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; + log_error("[Snort] Seems preprocessor and/or decoder rules are missing, enabling autogeneration of them in conf file."); +} + +/* generate rule sections to load */ +/* The files are always configured so the update process is easier */ +$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"; + +// Remove trailing newlines +$snort_misc_include_rules = rtrim($snort_misc_include_rules); +$selected_rules_sections = rtrim($selected_rules_sections); + +$cksumcheck = "all"; +if ($snortcfg['cksumcheck'] == 'on') + $cksumcheck = "none"; + +/* Pull in user-configurable detection config options */ +$cfg_detect_settings = "search-method {$snort_performance} max-pattern-len 20 max_queue_events 5"; +if ($snortcfg['fpm_split_any_any'] == "on") + $cfg_detect_settings .= " split-any-any"; +if ($snortcfg['fpm_search_optimize'] == "on") + $cfg_detect_settings .= " search-optimize"; +if ($snortcfg['fpm_no_stream_inserts'] == "on") + $cfg_detect_settings .= " no_stream_inserts"; + +/* Pull in user-configurable options for Frag3 preprocessor settings */ +/* Get global Frag3 options first and put into a string */ +$frag3_global = "preprocessor frag3_global: "; +if (!empty($snortcfg['frag3_memcap']) || $snortcfg['frag3_memcap'] == "0") + $frag3_global .= "memcap {$snortcfg['frag3_memcap']}, "; +else + $frag3_global .= "memcap 4194304, "; +if (!empty($snortcfg['frag3_max_frags'])) + $frag3_global .= "max_frags {$snortcfg['frag3_max_frags']}"; +else + $frag3_global .= "max_frags 8192"; +if ($snortcfg['frag3_detection'] == "off") + $frag3_global .= ", disabled"; + +$frag3_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", + "timeout" => 60, "min_ttl" => 1, "detect_anomalies" => "on", + "overlap_limit" => 0, "min_frag_len" => 0 ); +$frag3_engine = ""; + +// Now iterate configured Frag3 engines and write them to a string if enabled +if ($snortcfg['frag3_detection'] == "on") { + if (!is_array($snortcfg['frag3_engine']['item'])) + $snortcfg['frag3_engine']['item'] = array(); + + // If no frag3 tcp engine is configured, use the default + if (empty($snortcfg['frag3_engine']['item'])) + $snortcfg['frag3_engine']['item'][] = $frag3_default_tcp_engine; + + foreach ($snortcfg['frag3_engine']['item'] as $f => $v) { + $frag3_engine .= "preprocessor frag3_engine: "; + $frag3_engine .= "policy {$v['policy']}"; + if ($v['bind_to'] <> "all") { + $tmp = trim(filter_expand_alias($v['bind_to'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ',', $tmp); + if (strpos($tmp, ",") !== false) + $frag3_engine .= " \\\n\tbind_to [{$tmp}]"; + else + $frag3_engine .= " \\\n\tbind_to {$tmp}"; + } + else + log_error("[snort] WARNING: unable to resolve IP List Alias '{$v['bind_to']}' for Frag3 engine '{$v['name']}' ... using 0.0.0.0 failsafe."); + } + $frag3_engine .= " \\\n\ttimeout {$v['timeout']}"; + $frag3_engine .= " \\\n\tmin_ttl {$v['min_ttl']}"; + if ($v['detect_anomalies'] == "on") { + $frag3_engine .= " \\\n\tdetect_anomalies"; + $frag3_engine .= " \\\n\toverlap_limit {$v['overlap_limit']}"; + $frag3_engine .= " \\\n\tmin_fragment_length {$v['min_frag_len']}"; + } + // Add newlines to terminate this engine + $frag3_engine .= "\n\n"; + } + // Remove trailing newline + $frag3_engine = rtrim($frag3_engine); +} + +// Grab any user-customized value for Protocol Aware Flushing (PAF) max PDUs +$paf_max_pdu_config = "config paf_max: "; +if (empty($snortcfg['max_paf']) || $snortcfg['max_paf'] == '0') + $paf_max_pdu_config .= "0"; +else + $paf_max_pdu_config .= $snortcfg['max_paf']; + +// Pull in user-configurable options for Stream5 preprocessor settings +// Get global options first and put into a string +$stream5_global = "preprocessor stream5_global: \\\n"; +if ($snortcfg['stream5_reassembly'] == "off") + $stream5_global .= "\tdisabled, \\\n"; +if ($snortcfg['stream5_track_tcp'] == "off") + $stream5_global .= "\ttrack_tcp no,"; +else { + $stream5_global .= "\ttrack_tcp yes,"; + if (!empty($snortcfg['stream5_max_tcp'])) + $stream5_global .= " \\\n\tmax_tcp {$snortcfg['stream5_max_tcp']},"; + else + $stream5_global .= " \\\n\tmax_tcp 262144,"; +} +if ($snortcfg['stream5_track_udp'] == "off") + $stream5_global .= " \\\n\ttrack_udp no,"; +else { + $stream5_global .= " \\\n\ttrack_udp yes,"; + if (!empty($snortcfg['stream5_max_udp'])) + $stream5_global .= " \\\n\tmax_udp {$snortcfg['stream5_max_udp']},"; + else + $stream5_global .= " \\\n\tmax_udp 131072,"; +} +if ($snortcfg['stream5_track_icmp'] == "on") { + $stream5_global .= " \\\n\ttrack_icmp yes,"; + if (!empty($snortcfg['stream5_max_icmp'])) + $stream5_global .= " \\\n\tmax_icmp {$snortcfg['stream5_max_icmp']},"; + else + $stream5_global .= " \\\n\tmax_icmp 65536,"; +} +else + $stream5_global .= " \\\n\ttrack_icmp no,"; +if (!empty($snortcfg['stream5_mem_cap'])) + $stream5_global .= " \\\n\tmemcap {$snortcfg['stream5_mem_cap']},"; +else + $stream5_global .= " \\\n\tmemcap 8388608,"; + +if (!empty($snortcfg['stream5_prune_log_max']) || $snortcfg['stream5_prune_log_max'] == '0') + $stream5_global .= " \\\n\tprune_log_max {$snortcfg['stream5_prune_log_max']}"; +else + $stream5_global .= " \\\n\tprune_log_max 1048576"; +if ($snortcfg['stream5_flush_on_alert'] == "on") + $stream5_global .= ", \\\n\tflush_on_alert"; + +$stream5_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", "timeout" => 30, + "max_queued_bytes" => 1048576, "detect_anomalies" => "off", "overlap_limit" => 0, + "max_queued_segs" => 2621, "require_3whs" => "off", "startup_3whs_timeout" => 0, + "no_reassemble_async" => "off", "dont_store_lg_pkts" => "off", "max_window" => 0, + "use_static_footprint_sizes" => "off", "check_session_hijacking" => "off", "ports_client" => "default", + "ports_both" => "default", "ports_server" => "none" ); +$stream5_tcp_engine = ""; + +// Now iterate configured Stream5 TCP engines and write them to a string if enabled +if ($snortcfg['stream5_reassembly'] == "on") { + if (!is_array($snortcfg['stream5_tcp_engine']['item'])) + $snortcfg['stream5_tcp_engine']['item'] = array(); + + // If no stream5 tcp engine is configured, use the default + if (empty($snortcfg['stream5_tcp_engine']['item'])) + $snortcfg['stream5_tcp_engine']['item'][] = $stream5_default_tcp_engine; + + foreach ($snortcfg['stream5_tcp_engine']['item'] as $f => $v) { + $buffer = "preprocessor stream5_tcp: "; + $buffer .= "policy {$v['policy']},"; + if ($v['bind_to'] <> "all") { + $tmp = trim(filter_expand_alias($v['bind_to'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ',', $tmp); + if (strpos($tmp, ",") !== false) + $buffer .= " \\\n\tbind_to [{$tmp}],"; + else + $buffer .= " \\\n\tbind_to {$tmp},"; + } + else { + log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for Stream5 TCP engine '{$v['name']}' ... skipping this engine."); + continue; + } + } + $stream5_tcp_engine .= $buffer; + $stream5_tcp_engine .= " \\\n\ttimeout {$v['timeout']},"; + $stream5_tcp_engine .= " \\\n\toverlap_limit {$v['overlap_limit']},"; + $stream5_tcp_engine .= " \\\n\tmax_window {$v['max_window']},"; + $stream5_tcp_engine .= " \\\n\tmax_queued_bytes {$v['max_queued_bytes']},"; + $stream5_tcp_engine .= " \\\n\tmax_queued_segs {$v['max_queued_segs']}"; + if ($v['use_static_footprint_sizes'] == "on") + $stream5_tcp_engine .= ", \\\n\tuse_static_footprint_sizes"; + if ($v['check_session_hijacking'] == "on") + $stream5_tcp_engine .= ", \\\n\tcheck_session_hijacking"; + if ($v['dont_store_lg_pkts'] == "on") + $stream5_tcp_engine .= ", \\\n\tdont_store_large_packets"; + if ($v['no_reassemble_async'] == "on") + $stream5_tcp_engine .= ", \\\n\tdont_reassemble_async"; + if ($v['detect_anomalies'] == "on") + $stream5_tcp_engine .= ", \\\n\tdetect_anomalies"; + if ($v['require_3whs'] == "on") + $stream5_tcp_engine .= ", \\\n\trequire_3whs {$v['startup_3whs_timeout']}"; + if (!empty($v['ports_client'])) { + $stream5_tcp_engine .= ", \\\n\tports client"; + if ($v['ports_client'] == " all") + $stream5_tcp_engine .= " all"; + elseif ($v['ports_client'] == "default") + $stream5_tcp_engine .= " {$stream5_ports_client}"; + else { + $tmp = trim(filter_expand_alias($v['ports_client'])); + if (!empty($tmp)) + $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); + else { + $stream5_tcp_engine .= " {$stream5_ports_client}"; + log_error("[snort] WARNING: unable to resolve Ports Client Alias [{$v['ports_client']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); + } + } + } + if (!empty($v['ports_both'])) { + $stream5_tcp_engine .= ", \\\n\tports both"; + if ($v['ports_both'] == " all") + $stream5_tcp_engine .= " all"; + elseif ($v['ports_both'] == "default") + $stream5_tcp_engine .= " {$stream5_ports_both}"; + else { + $tmp = trim(filter_expand_alias($v['ports_both'])); + if (!empty($tmp)) + $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); + else { + $stream5_tcp_engine .= " {$stream5_ports_both}"; + log_error("[snort] WARNING: unable to resolve Ports Both Alias [{$v['ports_both']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); + } + } + } + if (!empty($v['ports_server']) && $v['ports_server'] <> "none" && $v['ports_server'] <> "default") { + if ($v['ports_server'] == " all") { + $stream5_tcp_engine .= ", \\\n\tports server"; + $stream5_tcp_engine .= " all"; + } + else { + $tmp = trim(filter_expand_alias($v['ports_server'])); + if (!empty($tmp)) { + $stream5_tcp_engine .= ", \\\n\tports server"; + $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); + } + else + log_error("[snort] WARNING: unable to resolve Ports Server Alias [{$v['ports_server']}] for Stream5 TCP engine '{$v['name']}' ... defaulting to none."); + } + } + + // Make sure the "ports" parameter is set, or else default to a safe value + if (strpos($stream5_tcp_engine, "ports ") === false) + $stream5_tcp_engine .= ", \\\n\tports both all"; + + // Add a pair of newlines to terminate this engine + $stream5_tcp_engine .= "\n\n"; + } + // Trim off the final trailing newline + $stream5_tcp_engine = rtrim($stream5_tcp_engine); +} + +// Configure the Stream5 UDP engine if it and Stream5 reassembly are enabled +if ($snortcfg['stream5_track_udp'] == "off" || $snortcfg['stream5_reassembly'] == "off") + $stream5_udp_engine = ""; +else { + $stream5_udp_engine = "preprocessor stream5_udp: "; + if (!empty($snortcfg['stream5_udp_timeout'])) + $stream5_udp_engine .= "timeout {$snortcfg['stream5_udp_timeout']}"; + else + $stream5_udp_engine .= "timeout 30"; +} + +// Configure the Stream5 ICMP engine if it and Stream5 reassembly are enabled +if ($snortcfg['stream5_track_icmp'] == "on" && $snortcfg['stream5_reassembly'] == "on") { + $stream5_icmp_engine = "preprocessor stream5_icmp: "; + if (!empty($snortcfg['stream5_icmp_timeout'])) + $stream5_icmp_engine .= "timeout {$snortcfg['stream5_icmp_timeout']}"; + else + $stream5_icmp_engine .= "timeout 30"; +} +else + $stream5_icmp_engine = ""; + +// Check for and configure Host Attribute Table if enabled +$host_attrib_config = ""; +if ($snortcfg['host_attribute_table'] == "on" && !empty($snortcfg['host_attribute_data'])) { + @file_put_contents("{$snortcfgdir}/host_attributes", base64_decode($snortcfg['host_attribute_data'])); + $host_attrib_config = "# Host Attribute Table #\n"; + $host_attrib_config .= "attribute_table filename {$snortcfgdir}/host_attributes\n"; + if (!empty($snortcfg['max_attribute_hosts'])) + $host_attrib_config .= "config max_attribute_hosts: {$snortcfg['max_attribute_hosts']}\n"; + if (!empty($snortcfg['max_attribute_services_per_host'])) + $host_attrib_config .= "config max_attribute_services_per_host: {$snortcfg['max_attribute_services_per_host']}"; +} + +// Configure the HTTP_INSPECT preprocessor +// Get global options first and put into a string +$http_inspect_global = "preprocessor http_inspect: global "; +if ($snortcfg['http_inspect'] == "off") + $http_inspect_global .= "disabled "; +$http_inspect_global .= "\\\n\tiis_unicode_map unicode.map 1252 \\\n"; +$http_inspect_global .= "\tcompress_depth 65535 \\\n"; +$http_inspect_global .= "\tdecompress_depth 65535 \\\n"; +if (!empty($snortcfg['http_inspect_memcap'])) + $http_inspect_global .= "\tmemcap {$snortcfg['http_inspect_memcap']} \\\n"; +else + $http_inspect_global .= "\tmemcap 150994944 \\\n"; +if (!empty($snortcfg['http_inspect_max_gzip_mem'])) + $http_inspect_global .= "\tmax_gzip_mem {$snortcfg['http_inspect_max_gzip_mem']}"; +else + $http_inspect_global .= "\tmax_gzip_mem 838860"; +if ($snortcfg['http_inspect_proxy_alert'] == "on") + $http_inspect_global .= " \\\n\tproxy_alert"; + +$http_inspect_default_engine = array( "name" => "default", "bind_to" => "all", "server_profile" => "all", "enable_xff" => "off", + "log_uri" => "off", "log_hostname" => "off", "server_flow_depth" => 65535, "enable_cookie" => "on", + "client_flow_depth" => 1460, "extended_response_inspection" => "on", "no_alerts" => "off", + "unlimited_decompress" => "on", "inspect_gzip" => "on", "normalize_cookies" =>"on", "normalize_headers" => "on", + "normalize_utf" => "on", "normalize_javascript" => "on", "allow_proxy_use" => "off", "inspect_uri_only" => "off", + "max_javascript_whitespaces" => 200, "post_depth" => -1, "max_headers" => 0, "max_spaces" => 0, + "max_header_length" => 0, "ports" => "default" ); +$http_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['http_ports'])); +$http_inspect_servers = ""; + +// Iterate configured HTTP_INSPECT servers and write them to string if HTTP_INSPECT enabled +if ($snortcfg['http_inspect'] <> "off") { + if (!is_array($snortcfg['http_inspect_engine']['item'])) + $snortcfg['http_inspect_engine']['item'] = array(); + + // If no http_inspect_engine is configured, use the default + if (empty($snortcfg['http_inspect_engine']['item'])) + $snortcfg['http_inspect_engine']['item'][] = $http_inspect_default_engine; + + foreach ($snortcfg['http_inspect_engine']['item'] as $f => $v) { + $buffer = "preprocessor http_inspect_server: \\\n"; + if ($v['name'] == "default") + $buffer .= "\tserver default \\\n"; + elseif (is_alias($v['bind_to'])) { + $tmp = trim(filter_expand_alias($v['bind_to'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ' ', $tmp); + $buffer .= "\tserver { {$tmp} } \\\n"; + } + else { + log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); + continue; + } + } + else { + log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); + continue; + } + $http_inspect_servers .= $buffer; + $http_inspect_servers .= "\tprofile {$v['server_profile']} \\\n"; + + if ($v['no_alerts'] == "on") + $http_inspect_servers .= "\tno_alerts \\\n"; + + if ($v['ports'] == "default" || empty($v['ports'])) + $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; + elseif (is_alias($v['ports'])) { + $tmp = trim(filter_expand_alias($v['ports'])); + if (!empty($tmp)) { + $tmp = preg_replace('/\s+/', ' ', $tmp); + $tmp = snort_expand_port_range($tmp, ' '); + $http_inspect_servers .= "\tports { {$tmp} } \\\n"; + } + else { + log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); + $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; + } + } + else { + log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); + $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; + } + + $http_inspect_servers .= "\tserver_flow_depth {$v['server_flow_depth']} \\\n"; + $http_inspect_servers .= "\tclient_flow_depth {$v['client_flow_depth']} \\\n"; + $http_inspect_servers .= "\thttp_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 } \\\n"; + $http_inspect_servers .= "\tpost_depth {$v['post_depth']} \\\n"; + $http_inspect_servers .= "\tmax_headers {$v['max_headers']} \\\n"; + $http_inspect_servers .= "\tmax_header_length {$v['max_header_length']} \\\n"; + $http_inspect_servers .= "\tmax_spaces {$v['max_spaces']}"; + if ($v['enable_xff'] == "on") + $http_inspect_servers .= " \\\n\tenable_xff"; + if ($v['enable_cookie'] == "on") + $http_inspect_servers .= " \\\n\tenable_cookie"; + if ($v['normalize_cookies'] == "on") + $http_inspect_servers .= " \\\n\tnormalize_cookies"; + if ($v['normalize_headers'] == "on") + $http_inspect_servers .= " \\\n\tnormalize_headers"; + if ($v['normalize_utf'] == "on") + $http_inspect_servers .= " \\\n\tnormalize_utf"; + if ($v['allow_proxy_use'] == "on") + $http_inspect_servers .= " \\\n\tallow_proxy_use"; + if ($v['inspect_uri_only'] == "on") + $http_inspect_servers .= " \\\n\tinspect_uri_only"; + if ($v['extended_response_inspection'] == "on") { + $http_inspect_servers .= " \\\n\textended_response_inspection"; + if ($v['inspect_gzip'] == "on") { + $http_inspect_servers .= " \\\n\tinspect_gzip"; + if ($v['unlimited_decompress'] == "on") + $http_inspect_servers .= " \\\n\tunlimited_decompress"; + } + if ($v['normalize_javascript'] == "on") { + $http_inspect_servers .= " \\\n\tnormalize_javascript"; + $http_inspect_servers .= " \\\n\tmax_javascript_whitespaces {$v['max_javascript_whitespaces']}"; + } + } + if ($v['log_uri'] == "on") + $http_inspect_servers .= " \\\n\tlog_uri"; + if ($v['log_hostname'] == "on") + $http_inspect_servers .= " \\\n\tlog_hostname"; + + // Add a pair of trailing newlines to terminate this server config + $http_inspect_servers .= "\n\n"; + } + /* Trim off the final trailing newline */ + $http_inspect_server = rtrim($http_inspect_server); +} + +?> diff --git a/config/snort/snort_import_aliases.php b/config/snort/snort_import_aliases.php index 80b3bb1d..ba71c9bf 100644 --- a/config/snort/snort_import_aliases.php +++ b/config/snort/snort_import_aliases.php @@ -32,13 +32,13 @@ require_once("functions.inc"); require_once("/usr/local/pkg/snort/snort.inc"); // Retrieve any passed QUERY STRING or POST variables -if (isset($_POST['id'])) +if (isset($_POST['id']) && is_numericint($_POST['id'])) $id = $_POST['id']; elseif (isset($_GET['id']) && is_numericint($_GET['id'])) $id = htmlspecialchars($_GET['id']); if (isset($_POST['eng'])) - $eng = $_POST['eng']; + $eng = htmlspecialchars($_POST['eng']); elseif (isset($_GET['eng'])) $eng = htmlspecialchars($_GET['eng']); diff --git a/config/snort/snort_interface_logs.php b/config/snort/snort_interface_logs.php new file mode 100644 index 00000000..c8c4c24c --- /dev/null +++ b/config/snort/snort_interface_logs.php @@ -0,0 +1,267 @@ +<?php +/* + * snort_interface_logs.php + * + * Portions of this code are based on original work done for the + * Snort package for pfSense from the following contributors: + * + * Copyright (C) 2005 Bill Marquette <bill.marquette@gmail.com>. + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya Sr. Developer + * Copyright (C) 2012 Ermal Luci + * Copyright (C) 2014 Bill Meeks + * 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"); + +if (isset($_POST['id']) && is_numericint($_POST['id'])) + $id = $_POST['id']; +elseif (isset($_GET['id']) && is_numericint($_GET['id'])) + $id = htmlspecialchars($_GET['id']); +if (empty($id)) + $id = 0; + +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_instance = $config['installedpackages']['snortglobal']['rule']; +$snort_uuid = $a_instance[$id]['uuid']; +$if_real = get_real_interface($a_instance[$id]['interface']); + +// Construct a pointer to the instance's logging subdirectory +$snortlogdir = SNORTLOGDIR . "/snort_{$if_real}{$snort_uuid}/"; + +// Construct a pointer to the PBI_BIN directory +$snortbindir = SNORT_PBI_BINDIR; + +// Limit all file access to just the currently selected interface's logging subdirectory +$logfile = htmlspecialchars($snortlogdir . basename($_POST['file'])); + +if ($_POST['action'] == 'load') { + // If viewing the app-stats log, then grab only the most recent one + if (strpos(basename($logfile), "app-stats.log") !== FALSE) { + $appid_statlogs = glob("{$snortlogdir}app-stats.log.*"); + $logfile = array_pop($appid_statlogs); + } + + if(!is_file($logfile)) { + echo "|3|" . gettext("Log file does not exist or that logging feature is not enabled") . ".|"; + } + else { + // Test for special unified2 format app-stats file because + // we have to use a Snort binary tool to display its contents. + if (strpos(basename($_POST['file']), "app-stats.log") !== FALSE) + $data = shell_exec("{$snortbindir}u2openappid {$logfile} 2>&1"); + else + $data = file_get_contents($logfile); + if($data === false) { + echo "|1|" . gettext("Failed to read log file") . ".|"; + } else { + $data = base64_encode($data); + echo "|0|{$logfile}|{$data}|"; + } + } + exit; +} + +$if_friendly = convert_friendly_interface_to_friendly_descr($a_instance[$id]['interface']); +$pgtitle = gettext("Snort: {$if_friendly} Logs"); +include_once("head.inc"); + +?> + +<body link="#000000" vlink="#000000" alink="#000000"> + +<?php +include_once("fbegin.inc"); +if ($input_errors) { + print_input_errors($input_errors); +} + +?> +<script type="text/javascript" src="/javascript/base64.js"></script> +<script type="text/javascript"> + function loadFile() { + jQuery("#fileStatus").html("<?=gettext("Loading file"); ?> ..."); + jQuery("#fileStatusBox").show(250); + jQuery("#filePathBox").show(250); + jQuery("#fbTarget").html(""); + + jQuery.ajax( + "<?=$_SERVER['SCRIPT_NAME'];?>", { + type: 'POST', + data: "id=" + jQuery("#id").val() + "&action=load&file=" + jQuery("#logFile").val(), + complete: loadComplete + } + ); + } + + function loadComplete(req) { + jQuery("#fileContent").show(250); + var values = req.responseText.split("|"); + values.shift(); values.pop(); + + if(values.shift() == "0") { + var file = values.shift(); + var fileContent = Base64.decode(values.join("|")); + jQuery("#fileStatus").html("<?=gettext("File successfully loaded"); ?>."); + jQuery("#fbTarget").html(file); + jQuery("#fileRefreshBtn").show(); + jQuery("#fileContent").prop("disabled", false); + jQuery("#fileContent").val(fileContent); + } + else { + jQuery("#fileStatus").html(values[0]); + jQuery("#fbTarget").html(""); + jQuery("#fileRefreshBtn").hide(); + jQuery("#fileContent").val(""); + jQuery("#fileContent").prop("disabled", true); + } + } + +</script> + +<form action="/snort/snort_interface_logs.php" method="post" id="formbrowse"> +<input type="hidden" id="id" value="<?=$id;?>"/> +<?php if ($savemsg) print_info_box($savemsg); ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <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?instance={$id}"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array, true); + echo '</td></tr>'; + echo '<tr><td>'; + $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"), 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("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), true, "/snort/snort_interface_logs.php?id={$id}"); + display_top_tabs($tab_array, true); + ?> + </td> + </tr> + <tr> + <td><div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> + <tbody> + <tr> + <td colspan="2" class="listtopic"><?php echo gettext("Log File Selections"); ?></td> + </tr> + <tr> + <td width="22%" class="vncell"><?php echo gettext('Log File to View'); ?></td> + <td width="78%" class="vtable"> + <select name="logFile" id="logFile" class="formselect" onChange="loadFile();"> + <?php + $logs = array( "alert", "app-stats.log", "{$if_real}.stats" , "sid_changes.log" ); + foreach ($logs as $log) { + $selected = ""; + if ($log == basename($logfile)) + $selected = "selected"; + echo "<option value='{$snortlogdir}{$log}' {$selected}>" . $log . "</option>\n"; + } + ?> + </select> <?php echo gettext('Choose which log you want to view.'); ?> + </td> + </tr> + <tr> + <td colspan="2" class="listtopic"><?php echo gettext("Log File Contents"); ?></td> + </tr> + <tr> + <td colspan="2"> + <table width="100%"> + <tbody> + <tr> + <td width="75%"> + <div style="display:none; " id="fileStatusBox"> + <div class="list" style="padding-left:15px;"> + <strong id="fileStatus"></strong> + </div> + </div> + <div style="padding-left:15px; display:none;" id="filePathBox"> + <strong><?=gettext("Log File Path"); ?>:</strong> + <div class="list" style="display:inline;" id="fbTarget"></div> + </div> + </td> + <td align="right"> + <div style="padding-right:15px; display:none;" id="fileRefreshBtn"> + <input type="button" name="refresh" id="refresh" value="Refresh" class="formbtn" onclick="loadFile();" title="<?=gettext("Refresh current display");?>" /> + </div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + <tr> + <td colspan="2"> + <table width="100%"> + <tbody> + <tr> + <td valign="top" class="label"> + <div style="background:#eeeeee;" id="fileOutput"> + <textarea id="fileContent" name="fileContent" style="width:100%;" rows="30" wrap="off" disabled></textarea> + </div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </div> + </td> + </tr> + </tbody> +</table> +</form> + +<?php if(empty($_POST['file'])): ?> +<script type="text/javascript"> + document.getElementById("logFile").selectedIndex=-1; +</script> +<?php endif; ?> + +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/snort/snort_interfaces.php b/config/snort/snort_interfaces.php index c82ec57e..38471ef0 100755 --- a/config/snort/snort_interfaces.php +++ b/config/snort/snort_interfaces.php @@ -45,6 +45,9 @@ $a_nat = &$config['installedpackages']['snortglobal']['rule']; // Calculate the index of the next added Snort interface $id_gen = count($config['installedpackages']['snortglobal']['rule']); +// Get list of configured firewall interfaces +$ifaces = get_configured_interface_list(); + if (isset($_POST['del_x'])) { /* Delete selected Snort interfaces */ if (is_array($_POST['rule'])) { @@ -53,13 +56,12 @@ if (isset($_POST['del_x'])) { $if_real = get_real_interface($a_nat[$rulei]['interface']); $snort_uuid = $a_nat[$rulei]['uuid']; snort_stop($a_nat[$rulei], $if_real); - exec("/bin/rm -r {$snortlogdir}/snort_{$if_real}{$snort_uuid}"); - exec("/bin/rm -r {$snortdir}/snort_{$snort_uuid}_{$if_real}"); + rmdir_recursive("{$snortlogdir}/snort_{$if_real}{$snort_uuid}"); + rmdir_recursive("{$snortdir}/snort_{$snort_uuid}_{$if_real}"); // 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 interfaces config array. */ if (empty($a_nat)) @@ -67,18 +69,9 @@ if (isset($_POST['del_x'])) { write_config("Snort pkg: deleted one or more Snort interfaces."); sleep(2); - - /* if there are no ifaces remaining do not create snort.sh */ - if (!empty($config['installedpackages']['snortglobal']['rule'])) - snort_create_rc(); - else { - conf_mount_rw(); - @unlink("{$rcdir}/snort.sh"); - conf_mount_ro(); - } - + conf_mount_rw(); sync_snort_package_config(); - + conf_mount_ro(); 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' ); @@ -97,11 +90,13 @@ if ($_POST['bartoggle'] && is_numericint($_POST['id'])) { $if_friendly = convert_friendly_interface_to_friendly_descr($snortcfg['interface']); if (!snort_is_running($snortcfg['uuid'], $if_real, 'barnyard2')) { - log_error("Toggle (barnyard starting) for {$if_friendly}({$snortcfg['descr']})..."); + log_error("Toggle (barnyard starting) for {$if_friendly}({$if_real})..."); + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); 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}({$if_real})..."); snort_barnyard_stop($snortcfg, $if_real); } sleep(3); // So the GUI reports correctly @@ -114,14 +109,16 @@ if ($_POST['toggle'] && is_numericint($_POST['id'])) { $if_friendly = convert_friendly_interface_to_friendly_descr($snortcfg['interface']); if (snort_is_running($snortcfg['uuid'], $if_real)) { - log_error("Toggle (snort stopping) for {$if_friendly}({$snortcfg['descr']})..."); + log_error("Toggle (snort stopping) for {$if_friendly}({$if_real})..."); snort_stop($snortcfg, $if_real); } else { - log_error("Toggle (snort starting) for {$if_friendly}({$snortcfg['descr']})..."); + log_error("Toggle (snort starting) for {$if_friendly}({$if_real})..."); /* set flag to rebuild interface rules before starting Snort */ $rebuild_rules = true; + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); $rebuild_rules = false; snort_start($snortcfg, $if_real); } @@ -161,7 +158,9 @@ include_once("fbegin.inc"); $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td> @@ -173,18 +172,33 @@ include_once("fbegin.inc"); <tr id="frheader"> <td width="3%" class="list"> </td> <td width="10%" class="listhdrr"><?php echo gettext("Interface"); ?></td> - <td width="13%" class="listhdrr"><?php echo gettext("Snort"); ?></td> + <td width="14%" class="listhdrr"><?php echo gettext("Snort"); ?></td> <td width="10%" class="listhdrr"><?php echo gettext("Performance"); ?></td> <td width="10%" class="listhdrr"><?php echo gettext("Block"); ?></td> <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"> + <td width="32%" class="listhdr"><?php echo gettext("Description"); ?></td> + <td class="list"> <table border="0" cellspacing="0" cellpadding="0"> <tr> - <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> + <td class="list" valign="middle"> + <?php if ($id_gen < count($ifaces)): ?> + <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> + <?php else: ?> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus_d.gif" width="17" height="17" border="0" + title="<?php echo gettext('No available interfaces for a new Snort mapping');?>"> + <?php endif; ?> + </td> + <td class="list" valign="middle"> + <?php if ($id_gen == 0): ?> + <img 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> @@ -237,9 +251,11 @@ include_once("fbegin.inc"); $no_rules = true; if (isset($natent['customrules']) && !empty($natent['customrules'])) $no_rules = false; - if (isset($natent['rulesets']) && !empty($natent['rulesets'])) + elseif (isset($natent['rulesets']) && !empty($natent['rulesets'])) $no_rules = false; - if (isset($natent['ips_policy']) && !empty($natent['ips_policy'])) + elseif (isset($natent['ips_policy']) && !empty($natent['ips_policy'])) + $no_rules = false; + elseif ($config['installedpackages']['snortglobal']['auto_manage_sids'] == 'on' && !empty($natent['enable_sid_file'])) $no_rules = false; /* Do not display the "no rules" warning if interface disabled */ if ($natent['enable'] == "off") @@ -317,10 +333,20 @@ include_once("fbegin.inc"); <td valign="middle" class="list" nowrap> <table border="0" cellspacing="0" cellpadding="0"> <tr> - <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img + <td class="list" valign="middle"><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> + <td class="list" valign="middle"> + <?php if ($id_gen < count($ifaces)): ?> + <a href="snort_interfaces_edit.php?id=<?=$i;?>&action=dup"> + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="<?php echo gettext('Add new interface mapping based on this one'); ?>"></a> + <?php else: ?> + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus_d.gif" width="17" height="17" border="0" + title="<?php echo gettext('No available interfaces for a new Snort mapping');?>"> + <?php endif; ?> + </td> </tr> </table> </td> @@ -337,14 +363,25 @@ include_once("fbegin.inc"); <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" " 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> + <td class="list"> + <?php if ($id_gen < count($ifaces)): ?> + <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> + <?php else: ?> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus_d.gif" width="17" height="17" border="0" + title="<?php echo gettext('No available interfaces for a new Snort mapping');?>"> + <?php endif; ?> + </td> + <td class="list"> + <?php if ($id_gen == 0): ?> + <img 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> diff --git a/config/snort/snort_interfaces_edit.php b/config/snort/snort_interfaces_edit.php index 4c868844..0d41c7db 100755 --- a/config/snort/snort_interfaces_edit.php +++ b/config/snort/snort_interfaces_edit.php @@ -32,7 +32,7 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -global $g, $rebuild_rules; +global $g, $config, $rebuild_rules; $snortdir = SNORTDIR; $snortlogdir = SNORTLOGDIR; @@ -55,6 +55,13 @@ if (is_null($id)) { exit; } +if (isset($_POST['action'])) + $action = htmlspecialchars($_POST['action'], ENT_QUOTES | ENT_HTML401); +elseif (isset($_GET['action'])) + $action = htmlspecialchars($_GET['action'], ENT_QUOTES | ENT_HTML401); +else + $action = ""; + $pconfig = array(); if (empty($snortglob['rule'][$id]['uuid'])) { /* Adding new interface, so flag rules to build. */ @@ -89,7 +96,7 @@ elseif (isset($id) && !isset($a_rule[$id])) { foreach ($ifaces as $i) { if (!in_array($i, $ifrules)) { $pconfig['interface'] = $i; - $pconfig['descr'] = strtoupper($i); + $pconfig['descr'] = convert_friendly_interface_to_friendly_descr($i); $pconfig['enable'] = 'on'; break; } @@ -106,8 +113,41 @@ if (empty($pconfig['blockoffendersip'])) $pconfig['blockoffendersip'] = "both"; if (empty($pconfig['performance'])) $pconfig['performance'] = "ac-bnfa"; +if (empty($pconfig['alertsystemlog_facility'])) + $pconfig['alertsystemlog_facility'] = "log_auth"; +if (empty($pconfig['alertsystemlog_priority'])) + $pconfig['alertsystemlog_priority'] = "log_alert"; + +// See if creating a new interface by duplicating an existing one +if (strcasecmp($action, 'dup') == 0) { + + // Try to pick the next available physical interface to use + $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; + $pconfig['enable'] = 'on'; + $pconfig['descr'] = convert_friendly_interface_to_friendly_descr($i); + break; + } + } + if (count($ifrules) == count($ifaces)) { + $input_errors[] = gettext("No more available interfaces to configure for Snort!"); + $interfaces = array(); + $pconfig = array(); + } -if ($_POST["save"]) { + // Set Home Net, External Net, Suppress List and Pass List to defaults + unset($pconfig['suppresslistname']); + unset($pconfig['whitelistname']); + unset($pconfig['homelistname']); + unset($pconfig['externallistname']); +} + +if ($_POST["save"] && !$input_errors) { if (!isset($_POST['interface'])) $input_errors[] = "Interface is mandatory"; @@ -121,8 +161,32 @@ if ($_POST["save"]) { } } + // If Snort is disabled on this interface, stop any running instance, + // save the change, and exit. + if ($_POST['enable'] != 'on') { + $a_rule[$id]['enable'] = $_POST['enable'] ? 'on' : 'off'; + touch("{$g['varrun_path']}/snort_{$a_rule[$id]['uuid']}.disabled"); + touch("{$g['varrun_path']}/barnyard2_{$a_rule[$id]['uuid']}.disabled"); + snort_stop($a_rule[$id], get_real_interface($a_rule[$id]['interface'])); + write_config("Snort pkg: modified interface configuration for {$a_rule[$id]['interface']}."); + $rebuild_rules = false; + conf_mount_rw(); + sync_snort_package_config(); + conf_mount_ro(); + 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' ); + header( 'Cache-Control: post-check=0, pre-check=0', false ); + header( 'Pragma: no-cache' ); + header("Location: /snort/snort_interfaces.php"); + exit; + } + /* if no errors write to conf */ if (!$input_errors) { + /* Most changes don't require a rules rebuild, so default to "off" */ + $rebuild_rules = false; + $natent = $a_rule[$id]; $natent['interface'] = $_POST['interface']; $natent['enable'] = $_POST['enable'] ? 'on' : 'off'; @@ -137,7 +201,7 @@ if ($_POST["save"]) { if ($_POST['suppresslistname'] && ($_POST['suppresslistname'] <> $natent['suppresslistname'])) $snort_reload = true; - if ($_POST['descr']) $natent['descr'] = $_POST['descr']; else $natent['descr'] = strtoupper($natent['interface']); + if ($_POST['descr']) $natent['descr'] = $_POST['descr']; else $natent['descr'] = convert_friendly_interface_to_friendly_descr($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'; @@ -150,14 +214,16 @@ if ($_POST["save"]) { if ($_POST['externallistname']) $natent['externallistname'] = $_POST['externallistname']; else unset($natent['externallistname']); if ($_POST['suppresslistname']) $natent['suppresslistname'] = $_POST['suppresslistname']; else unset($natent['suppresslistname']); if ($_POST['alertsystemlog'] == "on") { $natent['alertsystemlog'] = 'on'; }else{ $natent['alertsystemlog'] = 'off'; } - if ($_POST['configpassthru']) $natent['configpassthru'] = base64_encode($_POST['configpassthru']); else unset($natent['configpassthru']); + if ($_POST['alertsystemlog_facility']) $natent['alertsystemlog_facility'] = $_POST['alertsystemlog_facility']; + if ($_POST['alertsystemlog_priority']) $natent['alertsystemlog_priority'] = $_POST['alertsystemlog_priority']; + if ($_POST['configpassthru']) $natent['configpassthru'] = base64_encode(str_replace("\r\n", "\n", $_POST['configpassthru'])); else unset($natent['configpassthru']); if ($_POST['cksumcheck']) $natent['cksumcheck'] = 'on'; else $natent['cksumcheck'] = 'off'; if ($_POST['fpm_split_any_any'] == "on") { $natent['fpm_split_any_any'] = 'on'; }else{ $natent['fpm_split_any_any'] = 'off'; } if ($_POST['fpm_search_optimize'] == "on") { $natent['fpm_search_optimize'] = 'on'; }else{ $natent['fpm_search_optimize'] = 'off'; } if ($_POST['fpm_no_stream_inserts'] == "on") { $natent['fpm_no_stream_inserts'] = 'on'; }else{ $natent['fpm_no_stream_inserts'] = 'off'; } $if_real = get_real_interface($natent['interface']); - if (isset($id) && $a_rule[$id]) { + if (isset($id) && $a_rule[$id] && $action == '') { // See if moving an existing Snort instance to another physical interface if ($natent['interface'] != $a_rule[$id]['interface']) { $oif_real = get_real_interface($a_rule[$id]['interface']); @@ -167,13 +233,24 @@ if ($_POST["save"]) { } else $snort_start = false; - exec("mv -f {$snortlogdir}/snort_{$oif_real}{$a_rule[$id]['uuid']} {$snortlogdir}/snort_{$if_real}{$a_rule[$id]['uuid']}"); + @rename("{$snortlogdir}/snort_{$oif_real}{$a_rule[$id]['uuid']}", "{$snortlogdir}/snort_{$if_real}{$a_rule[$id]['uuid']}"); conf_mount_rw(); - exec("mv -f {$snortdir}/snort_{$a_rule[$id]['uuid']}_{$oif_real} {$snortdir}/snort_{$a_rule[$id]['uuid']}_{$if_real}"); + @rename("{$snortdir}/snort_{$a_rule[$id]['uuid']}_{$oif_real}", "{$snortdir}/snort_{$a_rule[$id]['uuid']}_{$if_real}"); conf_mount_ro(); } $a_rule[$id] = $natent; - } else { + } + elseif (strcasecmp($action, 'dup') == 0) { + // Duplicating a new interface, so set flag to build new rules + $rebuild_rules = true; + + // Duplicating an interface, so need to generate a new UUID for the cloned interface + $natent['uuid'] = snort_generate_id(); + + // Add the new duplicated interface configuration to the [rule] array in config + $a_rule[] = $natent; + } + else { // Adding new interface, so set required interface configuration defaults $frag3_eng = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", "timeout" => 60, "min_ttl" => 1, "detect_anomalies" => "on", @@ -221,11 +298,35 @@ if ($_POST["save"]) { $natent['ftp_server_engine']['item'][] = $ftp_server_eng; $natent['smtp_preprocessor'] = 'on'; + $natent['smtp_memcap'] = "838860"; + $natent['smtp_max_mime_mem'] = "838860"; + $natent['smtp_b64_decode_depth'] = "0"; + $natent['smtp_qp_decode_depth'] = "0"; + $natent['smtp_bitenc_decode_depth'] = "0"; + $natent['smtp_uu_decode_depth'] = "0"; + $natent['smtp_email_hdrs_log_depth'] = "1464"; + $natent['smtp_ignore_data'] = 'off'; + $natent['smtp_ignore_tls_data'] = 'on'; + $natent['smtp_log_mail_from'] = 'on'; + $natent['smtp_log_rcpt_to'] = 'on'; + $natent['smtp_log_filename'] = 'on'; + $natent['smtp_log_email_hdrs'] = 'on'; + $natent['dce_rpc_2'] = 'on'; $natent['dns_preprocessor'] = 'on'; $natent['ssl_preproc'] = 'on'; $natent['pop_preproc'] = 'on'; + $natent['pop_memcap'] = "838860"; + $natent['pop_b64_decode_depth'] = "0"; + $natent['pop_qp_decode_depth'] = "0"; + $natent['pop_bitenc_decode_depth'] = "0"; + $natent['pop_uu_decode_depth'] = "0"; $natent['imap_preproc'] = 'on'; + $natent['imap_memcap'] = "838860"; + $natent['imap_b64_decode_depth'] = "0"; + $natent['imap_qp_decode_depth'] = "0"; + $natent['imap_bitenc_decode_depth'] = "0"; + $natent['imap_uu_decode_depth'] = "0"; $natent['sip_preproc'] = 'on'; $natent['other_preprocs'] = 'on'; @@ -265,6 +366,14 @@ if ($_POST["save"]) { $natent['stream5_tcp_engine']['item'] = array(); $natent['stream5_tcp_engine']['item'][] = $stream5_eng; + $natent['alertsystemlog_facility'] = "log_auth"; + $natent['alertsystemlog_priority'] = "log_alert"; + + $natent['appid_preproc'] = "off"; + $natent['sf_appid_mem_cap'] = "256"; + $natent['sf_appid_statslog'] = "on"; + $natent['sf_appid_stats_period'] = "300"; + $a_rule[] = $natent; } @@ -275,15 +384,15 @@ if ($_POST["save"]) { /* Save configuration changes */ write_config("Snort pkg: modified interface configuration for {$natent['interface']}."); - /* Most changes don't require a rules rebuild, so default to "off" */ - $rebuild_rules = false; - /* Update snort.conf and snort.sh files for this interface */ + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); /* See if we need to restart Snort after an interface re-assignment */ - if ($snort_start == true) + if ($snort_start == true) { snort_start($natent, $if_real); + } /*******************************************************/ /* Signal Snort to reload configuration if we changed */ @@ -326,6 +435,7 @@ include_once("head.inc"); <form action="snort_interfaces_edit.php" method="post" name="iform" id="iform"> <input name="id" type="hidden" value="<?=$id;?>"/> +<input name="action" type="hidden" value="<?=$action;?>"/> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -338,7 +448,9 @@ include_once("head.inc"); $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td class="tabnavtbl">'; @@ -351,6 +463,7 @@ include_once("head.inc"); $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -397,9 +510,44 @@ include_once("head.inc"); </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Send Alerts to System Logs"); ?></td> - <td width="78%" class="vtable"><input name="alertsystemlog" type="checkbox" value="on" <?php if ($pconfig['alertsystemlog'] == "on") echo "checked"; ?>/> + <td width="78%" class="vtable"><input name="alertsystemlog" type="checkbox" value="on" onclick="toggle_system_log();" <?php if ($pconfig['alertsystemlog'] == "on") echo " checked"; ?>/> <?php echo gettext("Snort will send Alerts to the firewall's system logs."); ?></td> </tr> + <tbody id="alertsystemlog_rows"> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("System Log Facility"); ?></td> + <td width="78%" class="vtable"> + <select name="alertsystemlog_facility" id="alertsystemlog_facility" class="formselect"> + <?php + $log_facility = array( "log_auth", "log_authpriv", "log_daemon", "log_user", "log_local0", "log_local1", + "log_local2", "log_local3", "log_local4", "log_local5", "log_local6", "log_local7" ); + foreach ($log_facility as $facility) { + $selected = ""; + if ($facility == $pconfig['alertsystemlog_facility']) + $selected = " selected"; + echo "<option value='{$facility}'{$selected}>" . $facility . "</option>\n"; + } + ?></select> + <?php echo gettext("Select system log Facility to use for reporting. Default is ") . "<strong>" . gettext("log_auth") . "</strong>."; ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("System Log Priority"); ?></td> + <td width="78%" class="vtable"> + <select name="alertsystemlog_priority" id="alertsystemlog_priority" class="formselect"> + <?php + $log_priority = array( "log_emerg", "log_crit", "log_alert", "log_err", "log_warning", "log_notice", "log_info", "log_debug" ); + foreach ($log_priority as $priority) { + $selected = ""; + if ($priority == $pconfig['alertsystemlog_priority']) + $selected = " selected"; + echo "<option value='{$priority}'{$selected}>" . $priority . "</option>\n"; + } + ?></select> + <?php echo gettext("Select system log Priority (Level) to use for reporting. Default is ") . "<strong>" . gettext("log_alert") . "</strong>."; ?> + </td> + </tr> + </tbody> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Block Offenders"); ?></td> <td width="78%" class="vtable"> @@ -555,13 +703,17 @@ include_once("head.inc"); } } ?> - </select> - <span class="vexpl"><?php echo gettext("Choose the External Net you want this interface " . - "to use."); ?></span> <br/><br/> + </select> + <input type="button" class="formbtns" value="View List" + onclick="viewList('<?=$id;?>','externallistname','externalnet')" id="btnExternalNet" + title="<?php echo gettext("Click to view currently selected External Net contents"); ?>"/> + <br/> + <?php echo gettext("Choose the External Net you want this interface " . + "to use."); ?> <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/> + "External Net is networks that are not Home Net. Most users should leave this setting at default."); ?><br/> + <span class="red"><?php echo gettext("Hint:"); ?></span> + <?php echo gettext("Create a Pass List and add an Alias to it, and then assign the Pass List here for custom External Net settings."); ?><br/> </td> </tr> <tr> @@ -659,6 +811,14 @@ function enable_blockoffenders() { document.iform.btnWhitelist.disabled=endis; } +function toggle_system_log() { + var endis = !(document.iform.alertsystemlog.checked); + if (endis) + document.getElementById("alertsystemlog_rows").style.display="none"; + else + document.getElementById("alertsystemlog_rows").style.display=""; +} + function enable_change(enable_change) { endis = !(document.iform.enable.checked || enable_change); // make sure a default answer is called if this is invoked. @@ -713,6 +873,7 @@ function viewList(id, elemID, elemType) { enable_change(false); enable_blockoffenders(); +toggle_system_log(); //--> </script> diff --git a/config/snort/snort_interfaces_global.php b/config/snort/snort_interfaces_global.php index 69a182bd..6c1d56ac 100644 --- a/config/snort/snort_interfaces_global.php +++ b/config/snort/snort_interfaces_global.php @@ -41,28 +41,42 @@ require_once("/usr/local/pkg/snort/snort.inc"); global $g; $snortdir = SNORTDIR; - -/* make things short */ -$pconfig['snortdownload'] = $config['installedpackages']['snortglobal']['snortdownload'] == "on" ? 'on' : 'off'; -$pconfig['oinkmastercode'] = $config['installedpackages']['snortglobal']['oinkmastercode']; -$pconfig['etpro_code'] = $config['installedpackages']['snortglobal']['etpro_code']; -$pconfig['emergingthreats'] = $config['installedpackages']['snortglobal']['emergingthreats'] == "on" ? 'on' : 'off'; -$pconfig['emergingthreats_pro'] = $config['installedpackages']['snortglobal']['emergingthreats_pro'] == "on" ? 'on' : 'off'; -$pconfig['rm_blocked'] = $config['installedpackages']['snortglobal']['rm_blocked']; -$pconfig['snortloglimit'] = $config['installedpackages']['snortglobal']['snortloglimit']; -$pconfig['snortloglimitsize'] = $config['installedpackages']['snortglobal']['snortloglimitsize']; -$pconfig['autorulesupdate7'] = $config['installedpackages']['snortglobal']['autorulesupdate7']; -$pconfig['rule_update_starttime'] = $config['installedpackages']['snortglobal']['rule_update_starttime']; -$pconfig['forcekeepsettings'] = $config['installedpackages']['snortglobal']['forcekeepsettings'] == "on" ? 'on' : 'off'; -$pconfig['snortcommunityrules'] = $config['installedpackages']['snortglobal']['snortcommunityrules'] == "on" ? 'on' : 'off'; -$pconfig['clearlogs'] = $config['installedpackages']['snortglobal']['clearlogs'] == "on" ? 'on' : 'off'; -$pconfig['clearblocks'] = $config['installedpackages']['snortglobal']['clearblocks'] == "on" ? 'on' : 'off'; +$snort_openappdir = SNORT_APPID_ODP_PATH; + +// Grab any previous input values if doing a SAVE operation +if ($_POST['save']) + $pconfig = $_POST; +else { + $pconfig['snortdownload'] = $config['installedpackages']['snortglobal']['snortdownload'] == "on" ? 'on' : 'off'; + $pconfig['oinkmastercode'] = $config['installedpackages']['snortglobal']['oinkmastercode']; + $pconfig['etpro_code'] = $config['installedpackages']['snortglobal']['etpro_code']; + $pconfig['emergingthreats'] = $config['installedpackages']['snortglobal']['emergingthreats'] == "on" ? 'on' : 'off'; + $pconfig['emergingthreats_pro'] = $config['installedpackages']['snortglobal']['emergingthreats_pro'] == "on" ? 'on' : 'off'; + $pconfig['rm_blocked'] = $config['installedpackages']['snortglobal']['rm_blocked']; + $pconfig['autorulesupdate7'] = $config['installedpackages']['snortglobal']['autorulesupdate7']; + $pconfig['rule_update_starttime'] = $config['installedpackages']['snortglobal']['rule_update_starttime']; + $pconfig['forcekeepsettings'] = $config['installedpackages']['snortglobal']['forcekeepsettings'] == "on" ? 'on' : 'off'; + $pconfig['snortcommunityrules'] = $config['installedpackages']['snortglobal']['snortcommunityrules'] == "on" ? 'on' : 'off'; + $pconfig['clearblocks'] = $config['installedpackages']['snortglobal']['clearblocks'] == "on" ? 'on' : 'off'; + $pconfig['verbose_logging'] = $config['installedpackages']['snortglobal']['verbose_logging'] == "on" ? 'on' : 'off'; + $pconfig['openappid_detectors'] = $config['installedpackages']['snortglobal']['openappid_detectors'] == "on" ? 'on' : 'off'; +} /* Set sensible values for any empty default params */ -if (empty($pconfig['snortloglimit'])) - $pconfig['snortloglimit'] = 'on'; if (!isset($pconfig['rule_update_starttime'])) $pconfig['rule_update_starttime'] = '00:05'; +if (!isset($config['installedpackages']['snortglobal']['forcekeepsettings'])) + $pconfig['forcekeepsettings'] = 'on'; + +/* Grab OpenAppID version info if enabled and downloaded */ +if ($pconfig['openappid_detectors'] == "on") { + if (file_exists("{$snort_openappdir}odp/version.conf")) { + $openappid_ver = gettext("Installed Detection Package "); + $openappid_ver .= gettext(ucfirst(strtolower(file_get_contents("{$snort_openappdir}odp/version.conf")))); + } + else + $openappid_ver = gettext("N/A (Not Downloaded)"); +} if ($_POST['rule_update_starttime']) { if (!preg_match('/^([01]?[0-9]|2[0-3]):?([0-5][0-9])$/', $_POST['rule_update_starttime'])) @@ -83,8 +97,9 @@ if (!$input_errors) { $config['installedpackages']['snortglobal']['snortcommunityrules'] = $_POST['snortcommunityrules'] ? 'on' : 'off'; $config['installedpackages']['snortglobal']['emergingthreats'] = $_POST['emergingthreats'] ? 'on' : 'off'; $config['installedpackages']['snortglobal']['emergingthreats_pro'] = $_POST['emergingthreats_pro'] ? 'on' : 'off'; - $config['installedpackages']['snortglobal']['clearlogs'] = $_POST['clearlogs'] ? 'on' : 'off'; $config['installedpackages']['snortglobal']['clearblocks'] = $_POST['clearblocks'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['verbose_logging'] = $_POST['verbose_logging'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['openappid_detectors'] = $_POST['openappid_detectors'] ? 'on' : 'off'; // If any rule sets are being turned off, then remove them // from the active rules section of each interface. Start @@ -125,34 +140,29 @@ if (!$input_errors) { $config['installedpackages']['snortglobal']['etpro_code'] = $_POST['etpro_code']; $config['installedpackages']['snortglobal']['rm_blocked'] = $_POST['rm_blocked']; - if ($_POST['snortloglimitsize']) { - $config['installedpackages']['snortglobal']['snortloglimit'] = $_POST['snortloglimit']; - $config['installedpackages']['snortglobal']['snortloglimitsize'] = $_POST['snortloglimitsize']; - } else { - $config['installedpackages']['snortglobal']['snortloglimit'] = 'on'; - - /* code will set limit to 21% of slice that is unused */ - $snortloglimitDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') * .22 / 1024); - $config['installedpackages']['snortglobal']['snortloglimitsize'] = $snortloglimitDSKsize; - } $config['installedpackages']['snortglobal']['autorulesupdate7'] = $_POST['autorulesupdate7']; /* Check and adjust format of Rule Update Starttime string to add colon and leading zero if necessary */ - $pos = strpos($_POST['rule_update_starttime'], ":"); - if ($pos === false) { - $tmp = str_pad($_POST['rule_update_starttime'], 4, "0", STR_PAD_LEFT); - $_POST['rule_update_starttime'] = substr($tmp, 0, 2) . ":" . substr($tmp, -2); + if ($_POST['rule_update_starttime']) { + $pos = strpos($_POST['rule_update_starttime'], ":"); + if ($pos === false) { + $tmp = str_pad($_POST['rule_update_starttime'], 4, "0", STR_PAD_LEFT); + $_POST['rule_update_starttime'] = substr($tmp, 0, 2) . ":" . substr($tmp, -2); + } + $config['installedpackages']['snortglobal']['rule_update_starttime'] = str_pad($_POST['rule_update_starttime'], 4, "0", STR_PAD_LEFT); } - $config['installedpackages']['snortglobal']['rule_update_starttime'] = str_pad($_POST['rule_update_starttime'], 4, "0", STR_PAD_LEFT); + $config['installedpackages']['snortglobal']['forcekeepsettings'] = $_POST['forcekeepsettings'] ? 'on' : 'off'; $retval = 0; - /* create whitelist and homenet file then sync files */ - sync_snort_package_config(); - write_config("Snort pkg: modified global settings."); + /* create whitelist and homenet file, then sync files */ + conf_mount_rw(); + sync_snort_package_config(); + conf_mount_ro(); + /* forces page to reload new settings */ header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); @@ -196,7 +206,9 @@ if ($input_errors) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -213,12 +225,12 @@ if ($input_errors) <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tr> <td><input name="snortdownload" type="checkbox" id="snortdownload" value="on" onclick="enable_snort_vrt();" - <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>></td> + <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?> /></td> <td><span class="vexpl"><?php echo gettext("Snort VRT free Registered User or paid Subscriber rules"); ?></span></td> <tr> <td> </td> - <td><a href="https://www.snort.org/signup" target="_blank"><?php echo gettext("Sign Up for a free Registered User Rule Account"); ?> </a><br/> - <a href="http://www.snort.org/vrt/buy-a-subscription" target="_blank"> + <td><a href="https://www.snort.org/users/sign_up" target="_blank"><?php echo gettext("Sign Up for a free Registered User Rule Account"); ?> </a><br/> + <a href="https://www.snort.org/products" target="_blank"> <?php echo gettext("Sign Up for paid Sourcefire VRT Certified Subscriber Rules"); ?></a></td> </tr> </table> @@ -231,9 +243,9 @@ if ($input_errors) </tr> <tr> <td valign="top"><span class="vexpl"><strong><?php echo gettext("Code:"); ?></strong></span></td> - <td><input name="oinkmastercode" type="text" - class="formfld unknown" id="oinkmastercode" size="52" - value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>"><br/> + <td><input name="oinkmastercode" type="text" + class="formfld unknown" id="oinkmastercode" size="52" + value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>" /><br/> <?php echo gettext("Obtain a snort.org Oinkmaster code and paste it here."); ?></td> </tr> </table> @@ -243,8 +255,8 @@ if ($input_errors) <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="on" - <?php if ($config['installedpackages']['snortglobal']['snortcommunityrules']=="on") echo "checked";?> ></td> + <td valign="top" width="8%"><input name="snortcommunityrules" type="checkbox" value="on" + <?php if ($pconfig['snortcommunityrules']=="on") echo "checked";?> /></td> <td 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 echo "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . @@ -259,13 +271,13 @@ if ($input_errors) <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tr> <td valign="top" width="8%"><input name="emergingthreats" type="checkbox" value="on" onclick="enable_et_rules();" - <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?>></td> + <?php if ($pconfig['emergingthreats']=="on") echo "checked"; ?> /></td> <td><span class="vexpl"><?php echo gettext("ETOpen is an open source set of Snort rules whose coverage " . "is more limited than ETPro."); ?></span></td> </tr> <tr> <td valign="top" width="8%"><input name="emergingthreats_pro" type="checkbox" value="on" onclick="enable_etpro_rules();" - <?php if ($config['installedpackages']['snortglobal']['emergingthreats_pro']=="on") echo "checked"; ?>></td> + <?php if ($pconfig['emergingthreats_pro']=="on") echo "checked"; ?>/></td> <td><span class="vexpl"><?php echo gettext("ETPro for Snort offers daily updates and extensive coverage of current malware threats."); ?></span></td> </tr> <tr> @@ -289,13 +301,38 @@ if ($input_errors) <td valign="top"><span class="vexpl"><strong><?php echo gettext("Code:"); ?></strong></span></td> <td><input name="etpro_code" type="text" class="formfld unknown" id="etpro_code" size="52" - value="<?=htmlspecialchars($pconfig['etpro_code']);?>"><br/> + value="<?=htmlspecialchars($pconfig['etpro_code']);?>"/><br/> <?php echo gettext("Obtain an ETPro subscription code and paste it here."); ?></td> </tr> </table> </td> </tr> - +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Install ") . "<strong>" . gettext("OpenAppID") . "</strong>" . gettext(" detectors");?></td> + <td width="78%" class="vtable"> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <tr> + <td valign="top" width="8%"><input name="openappid_detectors" type="checkbox" value="on" onclick="enable_openappid_dnload();" + <?php if ($pconfig['openappid_detectors']=="on") echo "checked";?> /></td> + <td class="vexpl"><?php echo gettext("The OpenAppID package contains the application signatures required by " . + "the AppID preprocessor.");?> + <br/><br/><?php echo "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . + gettext("You must enable download of the OpenAppID detectors package in order to utilize the Application ID ") . + gettext("preprocessor and any user-provided application detection rules. Once enabled, go to the ") . + "<a href='/snort/snort_download_updates.php'>" . gettext("UPDATES") . "</a>" . gettext(" tab and click to download updates.");?></td> + </tr> + <tbody id="openappid_rows"> + <tr> + <td class="vexpl" colspan="2"><br/><strong><?=gettext("OpenAppID Detection Package");?></strong></td> + </tr> + <tr> + <td class="vexpl" valign="top"><strong><?=gettext("VER:");?></strong></td> + <td class="vexpl"><?=htmlspecialchars($openappid_ver);?></td> + </tr> + </tbody> + </table> + </td> +</tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Rules Update Settings"); ?></td> </tr> @@ -307,7 +344,7 @@ if ($input_errors) $interfaces3 = array('never_up' => gettext('NEVER'), '6h_up' => gettext('6 HOURS'), '12h_up' => gettext('12 HOURS'), '1d_up' => gettext('1 DAY'), '4d_up' => gettext('4 DAYS'), '7d_up' => gettext('7 DAYS'), '28d_up' => gettext('28 DAYS')); foreach ($interfaces3 as $iface3 => $ifacename3): ?> <option value="<?=$iface3;?>" - <?php if ($iface3 == $pconfig['autorulesupdate7']) echo "selected"; ?>> + <?php if ($iface3 == $pconfig['autorulesupdate7']) echo "selected"; ?> /> <?=htmlspecialchars($ifacename3);?></option> <?php endforeach; ?> </select><span class="vexpl"> <?php echo gettext("Please select the interval for rule updates. Choosing ") . @@ -317,49 +354,16 @@ if ($input_errors) <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Update Start Time"); ?></td> <td width="78%" class="vtable"><input type="text" class="formfld time" name="rule_update_starttime" id="rule_update_starttime" size="4" - maxlength="5" value="<?=htmlspecialchars($pconfig['rule_update_starttime']);?>" <?php if ($pconfig['autorulesupdate7'] == "never_up") {echo "disabled";} ?>><span class="vexpl"> + maxlength="5" value="<?=htmlspecialchars($pconfig['rule_update_starttime']);?>" <?php if ($pconfig['autorulesupdate7'] == "never_up") {echo "disabled";} ?> /><span class="vexpl"> <?php echo gettext("Enter the rule update start time in 24-hour format (HH:MM). ") . "<strong>" . gettext("Default") . " </strong>" . gettext("is ") . "<strong>" . gettext("00:05") . "</strong></span>"; ?>.<br/><br/> <?php echo gettext("Rules will update at the interval chosen above starting at the time specified here. For example, using the default " . - "start time of 00:03 and choosing 12 Hours for the interval, the rules will update at 00:05 and 12:05 each day."); ?></td> + "start time of 00:05 and choosing 12 Hours for the interval, the rules will update at 00:05 and 12:05 each day."); ?></td> </tr> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Settings"); ?></td> </tr> <tr> -<?php $snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') / 1024); ?> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Log Directory Size " . - "Limit"); ?><br/><br/> - <br/> - <br/> - <span class="red"><strong><?php echo gettext("Note:"); ?></strong></span><br/> - <?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'; ?>><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:"); ?></strong></span> <?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 class="vexpl"><?php echo gettext("Size in ") . "<strong>" . gettext("MB:") . "</strong>";?> - <input name="snortloglimitsize" type="text" class="formfld unknown" id="snortloglimitsize" size="10" value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> - <?php echo gettext("Default is ") . "<strong>" . gettext("20%") . "</strong>" . gettext(" of available space.");?></td> - </tr> - </table> - </td> -</tr> -<tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove Blocked Hosts Interval"); ?></td> <td width="78%" class="vtable"> <select name="rm_blocked" class="formselect" id="rm_blocked"> @@ -367,7 +371,7 @@ if ($input_errors) $interfaces3 = array('never_b' => gettext('NEVER'), '15m_b' => gettext('15 MINS'), '30m_b' => gettext('30 MINS'), '1h_b' => gettext('1 HOUR'), '3h_b' => gettext('3 HOURS'), '6h_b' => gettext('6 HOURS'), '12h_b' => gettext('12 HOURS'), '1d_b' => gettext('1 DAY'), '4d_b' => gettext('4 DAYS'), '7d_b' => gettext('7 DAYS'), '28d_b' => gettext('28 DAYS')); foreach ($interfaces3 as $iface3 => $ifacename3): ?> <option value="<?=$iface3;?>" - <?php if ($iface3 == $pconfig['rm_blocked']) echo "selected"; ?>> + <?php if ($iface3 == $pconfig['rm_blocked']) echo "selected"; ?> /> <?=htmlspecialchars($ifacename3);?></option> <?php endforeach; ?> </select> @@ -376,27 +380,29 @@ if ($input_errors) </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove Blocked Hosts After Deinstall"); ?></td> - <td width="78%" class="vtable"><input name="clearblocks" id="clearblocks" type="checkbox" value="yes" - <?php if ($config['installedpackages']['snortglobal']['clearblocks']=="on") echo " checked"; ?>/> + <td width="78%" class="vtable"><input name="clearblocks" id="clearblocks" type="checkbox" value="yes" + <?php if ($pconfig['clearblocks']=="on") echo " checked"; ?> /> <?php echo gettext("All blocked hosts added by Snort will be removed during package deinstallation."); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove Snort Log Files After Deinstall"); ?></td> - <td width="78%" class="vtable"><input name="clearlogs" id="clearlogs" type="checkbox" value="yes" - <?php if ($config['installedpackages']['snortglobal']['clearlogs']=="on") echo " checked"; ?>/> - <?php echo gettext("All Snort log files will be removed during package deinstallation."); ?></td> -</tr> -<tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Keep Snort Settings After Deinstall"); ?></td> <td width="78%" class="vtable"><input name="forcekeepsettings" - id="forcekeepsettings" type="checkbox" value="yes" - <?php if ($config['installedpackages']['snortglobal']['forcekeepsettings']=="on") echo "checked"; ?> - > <?php echo gettext("Settings will not be removed during package deinstallation."); ?></td> + id="forcekeepsettings" type="checkbox" value="yes" + <?php if ($pconfig['forcekeepsettings']=="on") echo "checked"; ?> /> + <?php echo gettext("Settings will not be removed during package deinstallation."); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Startup/Shutdown Logging"); ?></td> + <td width="78%" class="vtable"><input name="verbose_logging" + id="verbose_logging" type="checkbox" value="yes" + <?php if ($pconfig['verbose_logging']=="on") echo "checked"; ?> /> + <?php echo gettext("Output detailed messages to the system log when Snort is starting and stopping. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>" . gettext("."); ?></td> </tr> <tr> <td width="22%" valign="top"> <td width="78%"> - <input name="save" type="submit" class="formbtn" value="Save" > + <input name="save" type="submit" class="formbtn" value="Save" /> </td> </tr> <tr> @@ -449,11 +455,20 @@ function enable_change_rules_upd() { document.iform.rule_update_starttime.disabled=""; } +function enable_openappid_dnload() { + var endis = document.iform.openappid_detectors.checked; + if (endis) + document.getElementById("openappid_rows").style.display = ""; + else + document.getElementById("openappid_rows").style.display = "none"; +} + // Initialize the form controls state based on saved settings enable_snort_vrt(); enable_et_rules(); enable_etpro_rules(); enable_change_rules_upd(); +enable_openappid_dnload(); //--> </script> diff --git a/config/snort/snort_interfaces_suppress.php b/config/snort/snort_interfaces_suppress.php index ecbd04a7..fd47eed8 100644 --- a/config/snort/snort_interfaces_suppress.php +++ b/config/snort/snort_interfaces_suppress.php @@ -114,7 +114,9 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td> diff --git a/config/snort/snort_interfaces_suppress_edit.php b/config/snort/snort_interfaces_suppress_edit.php index 986bfc38..a861fb7e 100644 --- a/config/snort/snort_interfaces_suppress_edit.php +++ b/config/snort/snort_interfaces_suppress_edit.php @@ -90,7 +90,12 @@ if ($_POST['save']) { $reqdfields = explode(" ", "name"); $reqdfieldsn = array("Name"); - do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); + + $pf_version=substr(trim(file_get_contents("/etc/version")),0,3); + if ($pf_version < 2.1) + $input_errors = eval('do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); return $input_errors;'); + else + do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); if(strtolower($_POST['name']) == "defaultwhitelist") $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; @@ -116,7 +121,7 @@ if ($_POST['save']) { $s_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); if ($_POST['suppresspassthru']) { $s_list['suppresspassthru'] = str_replace("​", "", $s_list['suppresspassthru']); - $s_list['suppresspassthru'] = base64_encode($_POST['suppresspassthru']); + $s_list['suppresspassthru'] = base64_encode(str_replace("\r\n", "\n", $_POST['suppresspassthru'])); } if (isset($id) && $a_suppress[$id]) @@ -125,7 +130,9 @@ if ($_POST['save']) { $a_suppress[] = $s_list; write_config("Snort pkg: modified Suppress List {$s_list['name']}."); + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); header("Location: /snort/snort_interfaces_suppress.php"); exit; @@ -161,7 +168,9 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td></tr> diff --git a/config/snort/snort_ip_list_mgmt.php b/config/snort/snort_ip_list_mgmt.php index ae4a1032..20d486c6 100644 --- a/config/snort/snort_ip_list_mgmt.php +++ b/config/snort/snort_ip_list_mgmt.php @@ -43,7 +43,7 @@ if (!is_array($config['installedpackages']['snortglobal']['rule'])) // Hard-code the path where IP Lists are stored // and disregard any user-supplied path element. -$iprep_path = IPREP_PATH; +$iprep_path = SNORT_IPREP_PATH; // Set default to not show IP List editor controls $iplist_edit_style = "display: none;"; @@ -152,6 +152,7 @@ if ($savemsg) <input type="hidden" name="MAX_FILE_SIZE" value="100000000" /> <input type="hidden" name="iplist_fname" id="iplist_fname" value=""/> <table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tbody> <tr><td> <?php $tab_array = array(); @@ -163,26 +164,26 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), true, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td> </tr> -<tbody id="uploader" style="display: none;" class="tabcont"> - <tr> - <td colspan="4" class="list"><br/><?php echo gettext("Click BROWSE to select a file to import, and then click UPLOAD. Click CLOSE to quit."); ?></td> - </tr> - <tr> - <td colspan="4" class="list"><input type="file" name="iprep_fileup" id="iprep_fileup" class="formfld file" size="50" /> - <input type="submit" name="upload" id="upload" value="<?=gettext("Upload");?>" - title="<?=gettext("Upload selected IP list to firewall");?>"/> <input type="button" - value="<?=gettext("Close");?>" onClick="document.getElementById('uploader').style.display='none';" /><br/></td> - <td class="list"></td> - </tr> -</tbody> <tr> <td> <div id="mainarea"> + + <?php if ($g['platform'] == "nanobsd") : ?> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> + <tbody> + <tr> + <td colspan="2" class="listtopic"><?php echo gettext("IP Reputation is not supported on NanoBSD installs"); ?></td> + </tr> + </tbody> + </table> + <?php else: ?> <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <colgroup> <col style="width: 50%;"> @@ -221,6 +222,18 @@ if ($savemsg) height="17" border="0" title="<?php echo gettext('Delete this IP List');?>"/></td> </tr> <?php endforeach; ?> + <tbody id="uploader" style="display: none;"> + <tr> + <td colspan="4" class="list"><br/><?php echo gettext("Click BROWSE to select a file to import, and then click UPLOAD. Click CLOSE to quit."); ?></td> + </tr> + <tr> + <td colspan="4" class="list"><input type="file" name="iprep_fileup" id="iprep_fileup" class="formfld file" size="50" /> + <input type="submit" name="upload" id="upload" value="<?=gettext("Upload");?>" + title="<?=gettext("Upload selected IP list to firewall");?>"/> <input type="button" + value="<?=gettext("Close");?>" onClick="document.getElementById('uploader').style.display='none';" /><br/></td> + <td colspan="4" class="list"></td> + </tr> + </tbody> <tbody id="iplist_editor" style="<?=$iplist_edit_style;?>"> <tr> <td colspan="4"> </td> @@ -265,9 +278,11 @@ if ($savemsg) <td class="list"></td> </tr> </table> + <?php endif; ?> </div> </td> </tr> +</tbody> </table> </form> <?php include("fend.inc"); ?> diff --git a/config/snort/snort_ip_reputation.php b/config/snort/snort_ip_reputation.php index 3de8c661..4c3065a0 100644 --- a/config/snort/snort_ip_reputation.php +++ b/config/snort/snort_ip_reputation.php @@ -56,7 +56,7 @@ if (!is_array($config['installedpackages']['snortglobal']['rule'][$id]['blist_fi $a_nat = &$config['installedpackages']['snortglobal']['rule']; $pconfig = $a_nat[$id]; -$iprep_path = IPREP_PATH; +$iprep_path = SNORT_IPREP_PATH; $if_real = get_real_interface($a_nat[$id]['interface']); $snort_uuid = $config['installedpackages']['snortglobal']['rule'][$id]['uuid']; @@ -162,7 +162,9 @@ if ($_POST['save'] || $_POST['apply']) { // Update the snort conf file for this interface $rebuild_rules = false; + conf_mount_rw(); snort_generate_conf($a_nat[$id]); + conf_mount_ro(); // Soft-restart Snort to live-load new variables snort_reload_config($a_nat[$id]); @@ -202,6 +204,7 @@ if ($savemsg) <?php endif; ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> <tr> <td> <?php @@ -214,7 +217,9 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td class="tabnavtbl">'; @@ -227,6 +232,7 @@ if ($savemsg) $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), true, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td> @@ -234,6 +240,12 @@ if ($savemsg) <tr> <td><div id="mainarea"> <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> + <tbody> + <?php if ($g['platform'] == "nanobsd") : ?> + <tr> + <td colspan="2" class="listtopic"><?php echo gettext("IP Reputation is not supported on NanoBSD installs"); ?></td> + </tr> + <?php else: ?> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("IP Reputation Preprocessor Configuration"); ?></td> </tr> @@ -363,9 +375,9 @@ if ($savemsg) <td width="22%" valign='top' class='vncell'><?php echo gettext("Whitelist Files"); ?> </td> <td width="78%" class="vtable"> - <table width="95%" border="0" cellpadding="2" cellspacing="0"> <!-- wlist_chooser --> <div id="wlistChooser" name="wlistChooser" style="display:none; border:1px dashed gray; width:98%;"></div> + <table width="95%" border="0" cellpadding="2" cellspacing="0"> <colgroup> <col style="text-align:left;"> <col style="width: 30%; text-align:left;"> @@ -406,12 +418,16 @@ if ($savemsg) </table> </td> </tr> + <?php endif; ?> + </tbody> </table> </div> </td> </tr> + </tbody> </table> +<?php if ($g['platform'] != "nanobsd") : ?> <script type="text/javascript"> Event.observe( window, "load", @@ -499,6 +515,7 @@ function wlistComplete(req) { } </script> +<?php endif; ?> </form> <?php include("fend.inc"); ?> diff --git a/config/snort/snort_iprep_list_browser.php b/config/snort/snort_iprep_list_browser.php index 3e4d6b6a..a13a2d37 100644 --- a/config/snort/snort_iprep_list_browser.php +++ b/config/snort/snort_iprep_list_browser.php @@ -23,7 +23,7 @@ function get_content($dir) { return $files; } -$path = IPREP_PATH; +$path = SNORT_IPREP_PATH; $container = htmlspecialchars($_GET['container']); $target = htmlspecialchars($_GET['target']); diff --git a/config/snort/snort_list_view.php b/config/snort/snort_list_view.php index 8c3d0134..54f4d7f1 100644 --- a/config/snort/snort_list_view.php +++ b/config/snort/snort_list_view.php @@ -66,6 +66,20 @@ if (isset($id) && isset($wlist)) { $contents = str_replace("\r", "", base64_decode($list['suppresspassthru'])); $title = "Suppress List"; } + elseif ($type == "externalnet") { + if ($wlist == "default") { + $list = snort_build_list($a_rule, $a_rule['homelistname']); + $contents = ""; + foreach ($list as $ip) + $contents .= "!{$ip}\n"; + $contents = trim($contents, "\n"); + } + else { + $list = snort_build_list($a_rule, $wlist, false, true); + $contents = implode("\n", $list); + } + $title = "EXTERNAL_NET"; + } else $contents = gettext("\n\nERROR -- Requested List Type entity is not valid!"); } diff --git a/config/snort/snort_log_mgmt.php b/config/snort/snort_log_mgmt.php new file mode 100644 index 00000000..33d94a04 --- /dev/null +++ b/config/snort/snort_log_mgmt.php @@ -0,0 +1,444 @@ +<?php +/* + * snort_log_mgmt.php + * + * Portions of this code are based on original work done for the + * Snort package for pfSense from the following contributors: + * + * Copyright (C) 2005 Bill Marquette <bill.marquette@gmail.com>. + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya Sr. Developer + * Copyright (C) 2012 Ermal Luci + * Copyright (C) 2014 Bill Meeks + * 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; + +$snortdir = SNORTDIR; + +$pconfig = array(); + +// Grab saved settings from configuration +$pconfig['enable_log_mgmt'] = $config['installedpackages']['snortglobal']['enable_log_mgmt'] == 'on' ? 'on' : 'off'; +$pconfig['clearlogs'] = $config['installedpackages']['snortglobal']['clearlogs']; +$pconfig['snortloglimit'] = $config['installedpackages']['snortglobal']['snortloglimit']; +$pconfig['snortloglimitsize'] = $config['installedpackages']['snortglobal']['snortloglimitsize']; +$pconfig['alert_log_limit_size'] = $config['installedpackages']['snortglobal']['alert_log_limit_size']; +$pconfig['alert_log_retention'] = $config['installedpackages']['snortglobal']['alert_log_retention']; +$pconfig['stats_log_limit_size'] = $config['installedpackages']['snortglobal']['stats_log_limit_size']; +$pconfig['stats_log_retention'] = $config['installedpackages']['snortglobal']['stats_log_retention']; +$pconfig['sid_changes_log_limit_size'] = $config['installedpackages']['snortglobal']['sid_changes_log_limit_size']; +$pconfig['sid_changes_log_retention'] = $config['installedpackages']['snortglobal']['sid_changes_log_retention']; +$pconfig['event_pkts_log_limit_size'] = '0'; +$pconfig['event_pkts_log_retention'] = $config['installedpackages']['snortglobal']['event_pkts_log_retention']; +$pconfig['appid_stats_log_limit_size'] = $config['installedpackages']['snortglobal']['appid_stats_log_limit_size']; +$pconfig['appid_stats_log_retention'] = $config['installedpackages']['snortglobal']['appid_stats_log_retention']; + +// Load up some arrays with selection values (we use these later). +// The keys in the $retentions array are the retention period +// converted to hours. The keys in the $log_sizes array are +// the file size limits in KB. +$retentions = array( '0' => gettext('KEEP ALL'), '24' => gettext('1 DAY'), '168' => gettext('7 DAYS'), '336' => gettext('14 DAYS'), + '720' => gettext('30 DAYS'), '1080' => gettext("45 DAYS"), '2160' => gettext('90 DAYS'), '4320' => gettext('180 DAYS'), + '8766' => gettext('1 YEAR'), '26298' => gettext("3 YEARS") ); +$log_sizes = array( '0' => gettext('NO LIMIT'), '50' => gettext('50 KB'), '150' => gettext('150 KB'), '250' => gettext('250 KB'), + '500' => gettext('500 KB'), '750' => gettext('750 KB'), '1000' => gettext('1 MB'), '2000' => gettext('2 MB'), + '5000' => gettext("5 MB"), '10000' => gettext("10 MB") ); + +// Set sensible defaults for any unset parameters +if (empty($pconfig['snortloglimit'])) + $pconfig['snortloglimit'] = 'on'; +if (empty($pconfig['snortloglimitsize'])) { + // Set limit to 20% of slice that is unused */ + $pconfig['snortloglimitsize'] = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') * .20 / 1024); +} + +// Set default retention periods for rotated logs +if (!isset($pconfig['alert_log_retention'])) + $pconfig['alert_log_retention'] = "336"; +if (!isset($pconfig['stats_log_retention'])) + $pconfig['stats_log_retention'] = "168"; +if (!isset($pconfig['sid_changes_log_retention'])) + $pconfig['sid_changes_log_retention'] = "336"; +if (!isset($pconfig['event_pkts_log_retention'])) + $pconfig['event_pkts_log_retention'] = "336"; +if (!isset($pconfig['appid_stats_log_retention'])) + $pconfig['appid_stats_log_retention'] = "168"; + +// Set default log file size limits +if (!isset($pconfig['alert_log_limit_size'])) + $pconfig['alert_log_limit_size'] = "500"; +if (!isset($pconfig['stats_log_limit_size'])) + $pconfig['stats_log_limit_size'] = "500"; +if (!isset($pconfig['sid_changes_log_limit_size'])) + $pconfig['sid_changes_log_limit_size'] = "250"; +if (!isset($pconfig['appid_stats_log_limit_size'])) + $pconfig['appid_stats_log_limit_size'] = "1000"; + +if ($_POST['ResetAll']) { + + // Reset all settings to their defaults + $pconfig['alert_log_retention'] = "336"; + $pconfig['stats_log_retention'] = "168"; + $pconfig['sid_changes_log_retention'] = "336"; + $pconfig['event_pkts_log_retention'] = "336"; + $pconfig['appid_stats_log_retention'] = "168"; + + $pconfig['alert_log_limit_size'] = "500"; + $pconfig['stats_log_limit_size'] = "500"; + $pconfig['sid_changes_log_limit_size'] = "250"; + $pconfig['event_pkts_log_limit_size'] = "0"; + $pconfig['appid_stats_log_limit_size'] = "1000"; + + /* Log a message at the top of the page to inform the user */ + $savemsg = gettext("All log management settings on this page have been reset to their defaults. Click APPLY if you wish to keep these new settings."); +} + +if ($_POST["save"] || $_POST['apply']) { + if ($_POST['enable_log_mgmt'] != 'on') { + $config['installedpackages']['snortglobal']['enable_log_mgmt'] = $_POST['enable_log_mgmt'] ? 'on' :'off'; + write_config("Snort pkg: saved updated configuration for LOGS MGMT."); + conf_mount_rw(); + sync_snort_package_config(); + conf_mount_ro(); + + /* forces page to reload new settings */ + 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' ); + header( 'Cache-Control: post-check=0, pre-check=0', false ); + header( 'Pragma: no-cache' ); + header("Location: /snort/snort_log_mgmt.php"); + exit; + } + + if ($_POST['snortloglimit'] == 'on') { + if (!is_numericint($_POST['snortloglimitsize']) || $_POST['snortloglimitsize'] < 1) + $input_errors[] = gettext("The 'Log Directory Size Limit' must be an integer value greater than zero."); + } + + if (!$input_errors) { + $config['installedpackages']['snortglobal']['enable_log_mgmt'] = $_POST['enable_log_mgmt'] ? 'on' :'off'; + $config['installedpackages']['snortglobal']['clearlogs'] = $_POST['clearlogs'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['snortloglimit'] = $_POST['snortloglimit']; + $config['installedpackages']['snortglobal']['snortloglimitsize'] = $_POST['snortloglimitsize']; + $config['installedpackages']['snortglobal']['alert_log_limit_size'] = $_POST['alert_log_limit_size']; + $config['installedpackages']['snortglobal']['alert_log_retention'] = $_POST['alert_log_retention']; + $config['installedpackages']['snortglobal']['stats_log_limit_size'] = $_POST['stats_log_limit_size']; + $config['installedpackages']['snortglobal']['stats_log_retention'] = $_POST['stats_log_retention']; + $config['installedpackages']['snortglobal']['sid_changes_log_limit_size'] = $_POST['sid_changes_log_limit_size']; + $config['installedpackages']['snortglobal']['sid_changes_log_retention'] = $_POST['sid_changes_log_retention']; + $config['installedpackages']['snortglobal']['event_pkts_log_limit_size'] = $_POST['event_pkts_log_limit_size']; + $config['installedpackages']['snortglobal']['event_pkts_log_retention'] = $_POST['event_pkts_log_retention']; + $config['installedpackages']['snortglobal']['appid_stats_log_limit_size'] = $_POST['appid_stats_log_limit_size']; + $config['installedpackages']['snortglobal']['appid_stats_log_retention'] = $_POST['appid_stats_log_retention']; + + write_config("Snort pkg: saved updated configuration for LOGS MGMT."); + conf_mount_rw(); + sync_snort_package_config(); + conf_mount_ro(); + + /* forces page to reload new settings */ + 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' ); + header( 'Cache-Control: post-check=0, pre-check=0', false ); + header( 'Pragma: no-cache' ); + header("Location: /snort/snort_log_mgmt.php"); + exit; + } +} + +$pgtitle = gettext("Snort: Log Management"); +include_once("head.inc"); + +?> + +<body link="#000000" vlink="#000000" alink="#000000"> + +<?php +include_once("fbegin.inc"); + +/* Display Alert message, under form tag or no refresh */ +if ($input_errors) + print_input_errors($input_errors); +?> + +<form action="snort_log_mgmt.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> + +<?php +if ($savemsg) { + /* Display save message */ + print_info_box($savemsg); +} +?> + +<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"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), true, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array, true); +?> +</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("General Settings"); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove Snort Log Files During Package Uninstall"); ?></td> + <td width="78%" class="vtable"><input name="clearlogs" id="clearlogs" type="checkbox" value="yes" + <?php if ($config['installedpackages']['snortglobal']['clearlogs']=="on") echo " checked"; ?>/> + <?php echo gettext("Snort log files will be removed when the Snort package is uninstalled."); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Auto Log Management"); ?></td> + <td width="78%" class="vtable"><input name="enable_log_mgmt" id="enable_log_mgmt" type="checkbox" value="on" + <?php if ($config['installedpackages']['snortglobal']['enable_log_mgmt']=="on") echo " checked"; ?> onClick="enable_change();"/> + <?php echo gettext("Enable automatic unattended management of Snort logs using parameters specified below."); ?><br/> + <span class="red"><strong><?=gettext("Note: ") . "</strong></span>" . gettext("This must be be enabled in order to set Log Size and Retention Limits below.");?> + </td> +</tr> +<tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Logs Directory Size Limit"); ?></td> +</tr> +<tr> +<?php $snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') / 1024); ?> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log Directory Size " . + "Limit"); ?><br/><br/><br/><br/><br/><br/><br/> + <span class="red"><strong><?php echo gettext("Note:"); ?></strong></span><br/> + <?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" class="vexpl"><input name="snortloglimit" type="radio" id="snortloglimit_on" value="on" + <?php if($pconfig['snortloglimit']=='on') echo 'checked'; ?> onClick="enable_change_dirSize();"/> + <strong><?php echo gettext("Enable"); ?></strong> <?php echo gettext("directory size limit"); ?> (<strong><?php echo gettext("Default"); ?></strong>)</td> + </tr> + <tr> + <td colspan="2" class="vexpl"><input name="snortloglimit" type="radio" id="snortloglimit_off" value="off" + <?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?> onClick="enable_change_dirSize();"/> + <strong><?php echo gettext("Disable"); ?></strong> + <?php echo gettext("directory size limit"); ?><br/> + <br/><span class="red"><strong><?=gettext("Note: ");?></strong></span><?=gettext("this setting imposes a hard-limit on the combined log directory size of all Snort interfaces. ") . + gettext("When the size limit set is reached, rotated logs for all interfaces will be removed, and any active logs pruned to zero-length.");?> + <br/><br/> + <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> <?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 class="vexpl"><?php echo gettext("Size in ") . "<strong>" . gettext("MB:") . "</strong>";?> + <input name="snortloglimitsize" type="text" class="formfld unknown" id="snortloglimitsize" size="10" value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"/> + <?php echo gettext("Default is ") . "<strong>" . gettext("20%") . "</strong>" . gettext(" of available space.");?></td> + </tr> + </table> + </td> +</tr> +<tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Log Size and Retention Limits"); ?></td> +</tr> +<tr> + <td class="vncell" valign="top" width="22%"><?php echo gettext("Text Log Settings");?></td> + <td class="vtable" width="78%"> + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <colgroup> + <col style="width: 15%;"> + <col style="width: 18%;"> + <col style="width: 18%;"> + <col> + </colgroup> + <thead> + <tr> + <th class="listhdrr"><?=gettext("Log Name");?></th> + <th class="listhdrr"><?=gettext("Max Size");?></th> + <th class="listhdrr"><?=gettext("Retention");?></th> + <th class="listhdrr"><?=gettext("Log Description");?></th> + </tr> + </thead> + <tbody> + <tr> + <td class="listbg">alert</td> + <td class="listr" align="center"><select name="alert_log_limit_size" class="formselect" id="alert_log_limit_size"> + <?php foreach ($log_sizes as $k => $l): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['alert_log_limit_size']) echo " selected"; ?>> + <?=htmlspecialchars($l);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listr" align="center"><select name="alert_log_retention" class="formselect" id="alert_log_retention"> + <?php foreach ($retentions as $k => $p): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['alert_log_retention']) echo " selected"; ?>> + <?=htmlspecialchars($p);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listbg"><?=gettext("Snort alerts and event details");?></td> + </tr> + <tr> + <td class="listbg">appid-stats</td> + <td class="listr" align="center"><select name="appid_stats_log_limit_size" class="formselect" id="appid_stats_log_limit_size"> + <?php foreach ($log_sizes as $k => $l): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['appid_stats_log_limit_size']) echo " selected"; ?>> + <?=htmlspecialchars($l);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listr" align="center"><select name="appid_stats_log_retention" class="formselect" id="appid_stats_log_retention"> + <?php foreach ($retentions as $k => $p): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['appid_stats_log_retention']) echo " selected"; ?>> + <?=htmlspecialchars($p);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listbg"><?=gettext("Application ID statistics");?></td> + </tr> + <tr> + <td class="listbg">event pcaps</td> + <td class="listr" align="center"><select name="event_pkts_log_limit_size" class="formselect" id="event_pkts_log_limit_size"> + <option value="0" selected>NO LIMIT</option> + </select> + </td> + <td class="listr" align="center"><select name="event_pkts_log_retention" class="formselect" id="event_pkts_log_retention"> + <?php foreach ($retentions as $k => $p): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['event_pkts_log_retention']) echo " selected"; ?>> + <?=htmlspecialchars($p);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listbg"><?=gettext("Snort alert related packet captures");?></td> + </tr> + <tr> + <td class="listbg">sid_changes</td> + <td class="listr" align="center"><select name="sid_changes_log_limit_size" class="formselect" id="sid_changes_log_limit_size"> + <?php foreach ($log_sizes as $k => $l): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['sid_changes_log_limit_size']) echo "selected"; ?>> + <?=htmlspecialchars($l);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listr" align="center"><select name="sid_changes_log_retention" class="formselect" id="sid_changes_log_retention"> + <?php foreach ($retentions as $k => $p): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['sid_changes_log_retention']) echo " selected"; ?>> + <?=htmlspecialchars($p);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listbg"><?=gettext("SID changes made by SID Mgmt conf files");?></td> + </tr> + <tr> + <td class="listbg">stats</td> + <td class="listr" align="center"><select name="stats_log_limit_size" class="formselect" id="stats_log_limit_size"> + <?php foreach ($log_sizes as $k => $l): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['stats_log_limit_size']) echo " selected"; ?>> + <?=htmlspecialchars($l);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listr" align="center"><select name="stats_log_retention" class="formselect" id="stats_log_retention"> + <?php foreach ($retentions as $k => $p): ?> + <option value="<?=$k;?>" + <?php if ($k == $pconfig['stats_log_retention']) echo " selected"; ?>> + <?=htmlspecialchars($p);?></option> + <?php endforeach; ?> + </select> + </td> + <td class="listbg"><?=gettext("Snort performance statistics");?></td> + </tr> + </tbody> + </table> + <br/><?=gettext("Settings will be ignored for any log in the list above not enabled on the Interface Settings tab. ") . + gettext("When a log reaches the Max Size limit, it will be rotated and tagged with a timestamp. The Retention period determines ") . + gettext("how long rotated logs are kept before they are automatically deleted.");?> + </td> +</tr> +<tr> + <td width="22%"></td> + <td width="78%" class="vexpl"><input name="save" type="submit" class="formbtn" value="Save"/> + <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 Log Management settings to their defaults. Click OK to continue or CANCEL to quit.") . + "');\""; ?>/><br/> + <br/><span class="red"><strong><?php echo gettext("Note:");?></strong> + </span><?php echo gettext("Changing any settings on this page will affect all Snort-configured interfaces.");?></td> +</tr> + </table> +</div><br/> +</td></tr> +</table> +</form> + +<script language="JavaScript"> +function enable_change() { + var endis = !(document.iform.enable_log_mgmt.checked); + document.iform.alert_log_limit_size.disabled = endis; + document.iform.alert_log_retention.disabled = endis; + document.iform.stats_log_limit_size.disabled = endis; + document.iform.stats_log_retention.disabled = endis; + document.iform.sid_changes_log_retention.disabled = endis; + document.iform.sid_changes_log_limit_size.disabled = endis; + document.iform.event_pkts_log_limit_size.disabled = endis; + document.iform.event_pkts_log_retention.disabled = endis; +} + +function enable_change_dirSize() { + var endis = !(document.getElementById('snortloglimit_on').checked); + document.getElementById('snortloglimitsize').disabled = endis; +} + +enable_change(); +enable_change_dirSize(); +</script> + +<?php include("fend.inc"); ?> + +</body> +</html> diff --git a/config/snort/snort_migrate_config.php b/config/snort/snort_migrate_config.php index d483ba47..12ae5d19 100644 --- a/config/snort/snort_migrate_config.php +++ b/config/snort/snort_migrate_config.php @@ -70,6 +70,55 @@ if (empty($config['installedpackages']['snortglobal']['snort_config_ver']) && $updated_cfg = true; } +/**********************************************************/ +/* Create new Auto SID Mgmt settings if not set */ +/**********************************************************/ +if (empty($config['installedpackages']['snortglobal']['auto_manage_sids'])) { + $config['installedpackages']['snortglobal']['auto_manage_sids'] = "off"; + $updated_cfg = true; +} + +/**********************************************************/ +/* Create new LOG MGMT settings if not set */ +/**********************************************************/ +if (empty($config['installedpackages']['snortglobal']['enable_log_mgmt'])) { + $config['installedpackages']['snortglobal']['enable_log_mgmt'] = "on"; + $config['installedpackages']['snortglobal']['alert_log_limit_size'] = "500"; + $config['installedpackages']['snortglobal']['alert_log_retention'] = "336"; + $config['installedpackages']['snortglobal']['appid_stats_log_limit_size'] = "1000"; + $config['installedpackages']['snortglobal']['appid_stats_log_retention'] = "168"; + $config['installedpackages']['snortglobal']['event_pkts_log_limit_size'] = "0"; + $config['installedpackages']['snortglobal']['event_pkts_log_retention'] = "336"; + $config['installedpackages']['snortglobal']['sid_changes_log_limit_size'] = "250"; + $config['installedpackages']['snortglobal']['sid_changes_log_retention'] = "336"; + $config['installedpackages']['snortglobal']['stats_log_limit_size'] = "500"; + $config['installedpackages']['snortglobal']['stats_log_retention'] = "168"; + $updated_cfg = true; +} +if (empty($config['installedpackages']['snortglobal']['appid_stats_log_limit_size'])) + $config['installedpackages']['snortglobal']['appid_stats_log_limit_size'] = "1000"; +if (empty($config['installedpackages']['snortglobal']['appid_stats_log_retention'])) + $config['installedpackages']['snortglobal']['appid_stats_log_retention'] = "168"; + +/**********************************************************/ +/* Create new VERBOSE_LOGGING setting if not set */ +/**********************************************************/ +if (empty($config['installedpackages']['snortglobal']['verbose_logging'])) { + $config['installedpackages']['snortglobal']['verbose_logging'] = "off"; + $updated_cfg = true; +} + +/**********************************************************/ +/* Create new OpenAppID settings if not set */ +/**********************************************************/ +if (empty($config['installedpackages']['snortglobal']['openappid_detectors'])) { + $config['installedpackages']['snortglobal']['openappid_detectors'] = "off"; + $updated_cfg = true; +} + +/**********************************************************/ +/* Migrate per interface settings if required. */ +/**********************************************************/ foreach ($rule as &$r) { // Initialize arrays for supported preprocessors if necessary if (!is_array($r['frag3_engine']['item'])) @@ -344,7 +393,7 @@ foreach ($rule as &$r) { // Since Barnyard2 was enabled, configure the new archived log settings $pconfig['u2_archived_log_retention'] = '168'; $pconfig['barnyard_archive_enable'] = 'on'; - $pconfig['unified2_log_limit'] = '32'; + $pconfig['unified2_log_limit'] = '32M'; $updated_cfg = true; } @@ -357,17 +406,134 @@ foreach ($rule as &$r) { $updated_cfg = true; } + // Migrate new POP3 preprocessor parameter settings + if (empty($pconfig['pop_memcap'])) { + $pconfig['pop_memcap'] = "838860"; + $updated_cfg = true; + } + if (empty($pconfig['pop_b64_decode_depth']) && $pconfig['pop_b64_decode_depth'] != '0') { + $pconfig['pop_b64_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['pop_qp_decode_depth']) && $pconfig['pop_qp_decode_depth'] != '0') { + $pconfig['pop_qp_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['pop_bitenc_decode_depth']) && $pconfig['pop_bitenc_decode_depth'] != '0') { + $pconfig['pop_bitenc_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['pop_uu_decode_depth']) && $pconfig['pop_uu_decode_depth'] != '0') { + $pconfig['pop_uu_decode_depth'] = "0"; + $updated_cfg = true; + } + + // Migrate new IMAP preprocessor parameter settings + if (empty($pconfig['imap_memcap'])) { + $pconfig['imap_memcap'] = "838860"; + $updated_cfg = true; + } + if (empty($pconfig['imap_b64_decode_depth']) && $pconfig['imap_b64_decode_depth'] != '0') { + $pconfig['imap_b64_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['imap_qp_decode_depth']) && $pconfig['imap_qp_decode_depth'] != '0') { + $pconfig['imap_qp_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['imap_bitenc_decode_depth']) && $pconfig['imap_bitenc_decode_depth'] != '0') { + $pconfig['imap_bitenc_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['imap_uu_decode_depth']) && $pconfig['imap_uu_decode_depth'] != '0') { + $pconfig['imap_uu_decode_depth'] = "0"; + $updated_cfg = true; + } + + // Migrate new SMTP preprocessor parameter settings + if (empty($pconfig['smtp_memcap'])) { + $pconfig['smtp_memcap'] = "838860"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_max_mime_mem'])) { + $pconfig['smtp_max_mime_mem'] = "838860"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_b64_decode_depth']) && $pconfig['smtp_b64_decode_depth'] != "0") { + $pconfig['smtp_b64_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_qp_decode_depth']) && $pconfig['smtp_qp_decode_depth'] != "0") { + $pconfig['smtp_qp_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_bitenc_decode_depth']) && $pconfig['smtp_bitenc_decode_depth'] != "0") { + $pconfig['smtp_bitenc_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_uu_decode_depth']) && $pconfig['smtp_uu_decode_depth'] != "0") { + $pconfig['smtp_uu_decode_depth'] = "0"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_email_hdrs_log_depth'])) { + $pconfig['smtp_email_hdrs_log_depth'] = "1464"; + $updated_cfg = true; + } + if (empty($pconfig['smtp_ignore_tls_data'])) { + $pconfig['smtp_ignore_tls_data'] = 'on'; + $updated_cfg = true; + } + if (empty($pconfig['smtp_log_mail_from'])) { + $pconfig['smtp_log_mail_from'] = 'on'; + $updated_cfg = true; + } + if (empty($pconfig['smtp_log_rcpt_to'])) { + $pconfig['smtp_log_rcpt_to'] = 'on'; + $updated_cfg = true; + } + if (empty($pconfig['smtp_log_filename'])) { + $pconfig['smtp_log_filename'] = 'on'; + $updated_cfg = true; + } + if (empty($pconfig['smtp_log_email_hdrs'])) { + $pconfig['smtp_log_email_hdrs'] = 'on'; + $updated_cfg = true; + } + + // Migrate any BY2 limit for unified2 logs to new format + if (!empty($pconfig['unified2_log_limit']) && + !preg_match('/^\d+[g|k|m|G|K|M]/', $pconfig['unified2_log_limit'])) { + $pconfig['unified2_log_limit'] .= "M"; + $updated_cfg = true; + } + + // Default any unconfigured AppID preprocessor settings + if (empty($pconfig['appid_preproc'])) { + $pconfig['appid_preproc'] = 'off'; + $updated_cfg = true; + } + if (empty($pconfig['sf_appid_mem_cap'])) { + $pconfig['sf_appid_mem_cap'] = '256'; + $updated_cfg = true; + } + if (empty($pconfig['sf_appid_statslog'])) { + $pconfig['sf_appid_statslog'] = 'on'; + $updated_cfg = true; + } + if (empty($pconfig['sf_appid_stats_period'])) { + $pconfig['sf_appid_stats_period'] = '300'; + $updated_cfg = true; + } + // Save the new configuration data into the $config array pointer $r = $pconfig; } // Release reference to final array element unset($r); -// Write out the new configuration to disk if we changed anything +// Log a message if we changed anything if ($updated_cfg) { - $config['installedpackages']['snortglobal']['snort_config_ver'] = "3.0.8"; - log_error("[Snort] Saving configuration settings in new format..."); - write_config("Snort pkg: migrate existing settings to new format as part of package upgrade."); + $config['installedpackages']['snortglobal']['snort_config_ver'] = "3.2"; log_error("[Snort] Settings successfully migrated to new configuration format..."); } else diff --git a/config/snort/snort_passlist.php b/config/snort/snort_passlist.php index 2cac9cd4..965f22d7 100644 --- a/config/snort/snort_passlist.php +++ b/config/snort/snort_passlist.php @@ -86,7 +86,9 @@ if ($_POST['del'] && is_numericint($_POST['list_id'])) { if (!$input_errors) { unset($a_passlist[$_POST['list_id']]); write_config("Snort pkg: deleted PASS LIST."); + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); header("Location: /snort/snort_passlist.php"); exit; } @@ -125,7 +127,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), true, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); ?> </td> diff --git a/config/snort/snort_passlist_edit.php b/config/snort/snort_passlist_edit.php index 3be776f4..9f95adb4 100644 --- a/config/snort/snort_passlist_edit.php +++ b/config/snort/snort_passlist_edit.php @@ -39,6 +39,8 @@ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); +$pconfig = array(); + if ($_POST['cancel']) { header("Location: /snort/snort_passlist.php"); exit; @@ -52,24 +54,63 @@ $a_passlist = &$config['installedpackages']['snortglobal']['whitelist']['item']; if (isset($_POST['id']) && is_numericint($_POST['id'])) $id = $_POST['id']; -elseif (isset($_GET['id']) && is_numericint($_GET['id'])) +elseif (isset($_GET['id']) && is_numericint($_GET['id'])) { $id = htmlspecialchars($_GET['id']); +} /* Should never be called without identifying list index, so bail */ if (is_null($id)) { - header("Location: /snort/snort_interfaces_whitelist.php"); + header("Location: /snort/snort_passlist.php"); exit; } +if (isset($id) && isset($a_passlist[$id])) { + /* Retrieve saved settings */ + $pconfig['name'] = $a_passlist[$id]['name']; + $pconfig['uuid'] = $a_passlist[$id]['uuid']; + $pconfig['address'] = $a_passlist[$id]['address']; + $pconfig['descr'] = html_entity_decode($a_passlist[$id]['descr']); + $pconfig['localnets'] = $a_passlist[$id]['localnets']; + $pconfig['wanips'] = $a_passlist[$id]['wanips']; + $pconfig['wangateips'] = $a_passlist[$id]['wangateips']; + $pconfig['wandnsips'] = $a_passlist[$id]['wandnsips']; + $pconfig['vips'] = $a_passlist[$id]['vips']; + $pconfig['vpnips'] = $a_passlist[$id]['vpnips']; +} + +// Check for returned "selected alias" if action is import +if ($_GET['act'] == "import") { + + // Retrieve previously typed values we passed to SELECT ALIAS page + $pconfig['name'] = htmlspecialchars($_GET['name']); + $pconfig['uuid'] = htmlspecialchars($_GET['uuid']); + $pconfig['address'] = htmlspecialchars($_GET['address']); + $pconfig['descr'] = htmlspecialchars($_GET['descr']); + $pconfig['localnets'] = htmlspecialchars($_GET['localnets'])? 'yes' : 'no'; + $pconfig['wanips'] = htmlspecialchars($_GET['wanips'])? 'yes' : 'no'; + $pconfig['wangateips'] = htmlspecialchars($_GET['wangateips'])? 'yes' : 'no'; + $pconfig['wandnsips'] = htmlspecialchars($_GET['wandnsips'])? 'yes' : 'no'; + $pconfig['vips'] = htmlspecialchars($_GET['vips'])? 'yes' : 'no'; + $pconfig['vpnips'] = htmlspecialchars($_GET['vpnips'])? 'yes' : 'no'; + + // Now retrieve the "selected alias" returned from SELECT ALIAS page + if ($_GET['varname'] == "address" && isset($_GET['varvalue'])) + $pconfig[$_GET['varname']] = htmlspecialchars($_GET['varvalue']); +} + /* If no entry for this passlist, then create a UUID and treat it like a new list */ -if (!isset($a_passlist[$id]['uuid'])) { +if (!isset($a_passlist[$id]['uuid']) && empty($pconfig['uuid'])) { $passlist_uuid = 0; while ($passlist_uuid > 65535 || $passlist_uuid == 0) { $passlist_uuid = mt_rand(1, 65535); $pconfig['uuid'] = $passlist_uuid; $pconfig['name'] = "passlist_{$passlist_uuid}"; } -} else +} +elseif (!empty($pconfig['uuid'])) { + $passlist_uuid = $pconfig['uuid']; +} +else $passlist_uuid = $a_passlist[$id]['uuid']; /* returns true if $name is a valid name for a pass list file name or ip */ @@ -83,28 +124,6 @@ function is_validpasslistname($name) { return false; } -if (isset($id) && $a_passlist[$id]) { - /* old settings */ - $pconfig = array(); - $pconfig['name'] = $a_passlist[$id]['name']; - $pconfig['uuid'] = $a_passlist[$id]['uuid']; - $pconfig['detail'] = $a_passlist[$id]['detail']; - $pconfig['address'] = $a_passlist[$id]['address']; - $pconfig['descr'] = html_entity_decode($a_passlist[$id]['descr']); - $pconfig['localnets'] = $a_passlist[$id]['localnets']; - $pconfig['wanips'] = $a_passlist[$id]['wanips']; - $pconfig['wangateips'] = $a_passlist[$id]['wangateips']; - $pconfig['wandnsips'] = $a_passlist[$id]['wandnsips']; - $pconfig['vips'] = $a_passlist[$id]['vips']; - $pconfig['vpnips'] = $a_passlist[$id]['vpnips']; -} - -// Check for returned "selected alias" if action is import -if ($_GET['act'] == "import") { - if ($_GET['varname'] == "address" && isset($_GET['varvalue'])) - $pconfig[$_GET['varname']] = htmlspecialchars($_GET['varvalue']); -} - if ($_POST['save']) { unset($input_errors); $pconfig = $_POST; @@ -112,7 +131,12 @@ if ($_POST['save']) { /* input validation */ $reqdfields = explode(" ", "name"); $reqdfieldsn = explode(",", "Name"); - do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); + + $pf_version=substr(trim(file_get_contents("/etc/version")),0,3); + if ($pf_version < 2.1) + $input_errors = eval('do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); return $input_errors;'); + else + do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); if(strtolower($_POST['name']) == "defaultpasslist") $input_errors[] = gettext("Pass List file names may not be named defaultpasslist."); @@ -121,11 +145,11 @@ if ($_POST['save']) { $input_errors[] = gettext("Pass List 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_passlist as $w_list) { - if (isset($id) && ($a_passlist[$id]) && ($a_passlist[$id] === $w_list)) + foreach ($a_passlist as $p_list) { + if (isset($id) && ($a_passlist[$id]) && ($a_passlist[$id] === $p_list)) continue; - if ($w_list['name'] == $_POST['name']) { + if ($p_list['name'] == $_POST['name']) { $input_errors[] = gettext("A Pass List file name with this name already exists."); break; } @@ -136,30 +160,30 @@ if ($_POST['save']) { $input_errors[] = gettext("A valid alias must be provided"); if (!$input_errors) { - $w_list = array(); + $p_list = array(); /* post user input */ - $w_list['name'] = $_POST['name']; - $w_list['uuid'] = $passlist_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'; - $w_list['vips'] = $_POST['vips']? 'yes' : 'no'; - $w_list['vpnips'] = $_POST['vpnips']? 'yes' : 'no'; - - $w_list['address'] = $_POST['address']; - $w_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); - $w_list['detail'] = $final_address_details; + $p_list['name'] = $_POST['name']; + $p_list['uuid'] = $passlist_uuid; + $p_list['localnets'] = $_POST['localnets']? 'yes' : 'no'; + $p_list['wanips'] = $_POST['wanips']? 'yes' : 'no'; + $p_list['wangateips'] = $_POST['wangateips']? 'yes' : 'no'; + $p_list['wandnsips'] = $_POST['wandnsips']? 'yes' : 'no'; + $p_list['vips'] = $_POST['vips']? 'yes' : 'no'; + $p_list['vpnips'] = $_POST['vpnips']? 'yes' : 'no'; + $p_list['address'] = $_POST['address']; + $p_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); if (isset($id) && $a_passlist[$id]) - $a_passlist[$id] = $w_list; + $a_passlist[$id] = $p_list; else - $a_passlist[] = $w_list; + $a_passlist[] = $p_list; - write_config("Snort pkg: modified PASS LIST {$w_list['name']}."); + write_config("Snort pkg: modified PASS LIST {$p_list['name']}."); /* create pass list and homenet file, then sync files */ + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); header("Location: /snort/snort_passlist.php"); exit; @@ -197,7 +221,9 @@ if ($savemsg) $tab_array[5] = array(gettext("Pass Lists"), true, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array,true); ?> </td> @@ -279,8 +305,8 @@ if ($savemsg) </td> <td width="78%" class="vtable"> <input autocomplete="off" name="address" type="text" class="formfldalias" id="address" size="30" value="<?=htmlspecialchars($pconfig['address']);?>" - title="<?=trim(filter_expand_alias($pconfig['address']));?>"/> - <input type="button" class="formbtns" value="Aliases" onclick="parent.location='snort_select_alias.php?id=0&type=host|network&varname=address&act=import&multi_ip=yes&returl=<?=urlencode($_SERVER['PHP_SELF']);?>'" + title="<?=trim(filter_expand_alias($pconfig['address']));?>"/> + <input type="button" class="formbtns" value="Aliases" onclick="selectAlias();" title="<?php echo gettext("Select an existing IP alias");?>"/> </td> </tr> @@ -321,6 +347,29 @@ function createAutoSuggest() { setTimeout("createAutoSuggest();", 500); +function selectAlias() { + + var loc; + var fields = [ "name", "descr", "localnets", "wanips", "wangateips", "wandnsips", "vips", "vpnips", "address" ]; + + // Scrape current form field values and add to + // the select alias URL as a query string. + var loc = 'snort_select_alias.php?id=<?=$id;?>&act=import&type=host|network'; + loc = loc + '&varname=address&multi_ip=yes'; + loc = loc + '&returl=<?=urlencode($_SERVER['PHP_SELF']);?>'; + loc = loc + '&uuid=<?=$passlist_uuid;?>'; + + // Iterate over just the specific form fields we want to pass to + // the select alias URL. + fields.forEach(function(entry) { + var tmp = $(entry).serialize(); + if (tmp.length > 0) + loc = loc + '&' + tmp; + }); + + window.parent.location = loc; +} + </script> <?php include("fend.inc"); ?> </body> diff --git a/config/snort/snort_post_install.php b/config/snort/snort_post_install.php index 8d3c427d..57e92ce5 100644 --- a/config/snort/snort_post_install.php +++ b/config/snort/snort_post_install.php @@ -5,7 +5,7 @@ * Copyright (C) 2006 Scott Ullrich * Copyright (C) 2009-2010 Robert Zelaya * Copyright (C) 2011-2012 Ermal Luci - * Copyright (C) 2013 Bill Meeks + * Copyright (C) 2013-2014 Bill Meeks * part of pfSense * All rights reserved. * @@ -41,1334 +41,15 @@ require_once("config.inc"); require_once("functions.inc"); require_once("/usr/local/pkg/snort/snort.inc"); +require("/usr/local/pkg/snort/snort_defs.inc"); global $config, $g, $rebuild_rules, $pkg_interface, $snort_gui_include; $snortdir = SNORTDIR; -$snortlibdir = SNORTLIBDIR; +$snortlogdir = SNORTLOGDIR; $rcdir = RCFILEPREFIX; - -// This is a hack to workaround the caching of the old "snort.inc" by the -// Package Manager installation code. We need this new function which is -// in the new snort.inc file during post-installation. -if (!function_exists('snort_expand_port_range')) { - function snort_expand_port_range($ports, $delim = ',') { - // Split the incoming string on the specified delimiter - $tmp = explode($delim, $ports); - - // Look for any included port range and expand it - foreach ($tmp as $val) { - if (is_portrange($val)) { - $start = strtok($val, ":"); - $end = strtok(":"); - if ($end !== false) { - $val = $start . $delim; - for ($i = intval($start) + 1; $i < intval($end); $i++) - $val .= strval($i) . $delim; - $val .= $end; - } - } - $value .= $val . $delim; - } - - // Remove any trailing delimiter in return value - return trim($value, $delim); - } -} - -// This function mirrors the "snort_generate_conf()" function in the -// "snort.inc" file. It is here with a modified name as a workaround -// so that functionality built into the new package version can be -// implemented during installation. During a package reinstall, the -// Package Manager will cache the old version of "snort.inc" and thus -// new features are not available from the new "snort.inc" file in the -// new package. -function snort_build_new_conf($snortcfg) { - - global $config, $g, $rebuild_rules; - - $snortdir = SNORTDIR; - $snortlibdir = SNORTLIBDIR; - $snortlogdir = SNORTLOGDIR; - $flowbit_rules_file = FLOWBITS_FILENAME; - $snort_enforcing_rules_file = ENFORCING_RULES_FILENAME; - - if (!is_array($config['installedpackages']['snortglobal']['rule'])) - return; - - conf_mount_rw(); - - /* 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 = get_real_interface($snortcfg['interface']); - $snort_uuid = $snortcfg['uuid']; - $snortcfgdir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}"; - - /* custom home nets */ - $home_net_list = snort_build_list($snortcfg, $snortcfg['homelistname']); - $home_net = implode(",", $home_net_list); - - $external_net = '!$HOME_NET'; - if (!empty($snortcfg['externallistname']) && $snortcfg['externallistname'] != 'default') { - $external_net_list = snort_build_list($snortcfg, $snortcfg['externallistname']); - $external_net = implode(",", $external_net_list); - } - - /* user added arguments */ - $snort_config_pass_thru = str_replace("\r", "", base64_decode($snortcfg['configpassthru'])); - // Remove the trailing newline - $snort_config_pass_thru = rtrim($snort_config_pass_thru); - - /* create a few directories and ensure the sample files are in place */ - $snort_dirs = array( $snortdir, $snortcfgdir, "{$snortcfgdir}/rules", - "{$snortlogdir}/snort_{$if_real}{$snort_uuid}", - "{$snortlogdir}/snort_{$if_real}{$snort_uuid}/barnyard2", - "{$snortcfgdir}/preproc_rules", - "dynamicrules" => "{$snortlibdir}/dynamicrules", - "dynamicengine" => "{$snortlibdir}/dynamicengine", - "dynamicpreprocessor" => "{$snortcfgdir}/dynamicpreprocessor" - ); - foreach ($snort_dirs as $dir) { - if (!is_dir($dir)) - 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", "attribute_table.dtd", - "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}")) { - $ftime = filemtime("{$snortdir}/{$file}"); - if (!file_exists("{$snortcfgdir}/{$file}") || ($ftime > filemtime("{$snortcfgdir}/{$file}"))) - @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); - } - } - - /* define alertsystemlog */ - $alertsystemlog_type = ""; - if ($snortcfg['alertsystemlog'] == "on") - $alertsystemlog_type = "output alert_syslog: log_alert"; - - /* define snortunifiedlog */ - $snortunifiedlog_type = ""; - if ($snortcfg['barnyard_enable'] == "on") { - if (isset($snortcfg['unified2_log_limit'])) - $u2_log_limit = "limit {$snortcfg['unified2_log_limit']}"; - else - $u2_log_limit = "limit 128"; - - $snortunifiedlog_type = "output unified2: filename snort_{$snort_uuid}_{$if_real}.u2, {$u2_log_limit}"; - if ($snortcfg['barnyard_log_vlan_events'] == 'on') - $snortunifiedlog_type .= ", vlan_event_types"; - if ($snortcfg['barnyard_log_mpls_events'] == 'on') - $snortunifiedlog_type .= ", mpls_event_types"; - } - - /* define spoink */ - $spoink_type = ""; - if ($snortcfg['blockoffenders7'] == "on") { - $pfkill = ""; - if ($snortcfg['blockoffenderskill'] == "on") - $pfkill = "kill"; - $spoink_wlist = snort_build_list($snortcfg, $snortcfg['whitelistname'], true); - /* write whitelist */ - @file_put_contents("{$snortcfgdir}/{$snortcfg['whitelistname']}", implode("\n", $spoink_wlist)); - $spoink_type = "output alert_pf: {$snortcfgdir}/{$snortcfg['whitelistname']},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; - } - - /* define selected suppress file */ - $suppress_file_name = ""; - $suppress = snort_find_list($snortcfg['suppresslistname'], 'suppress'); - if (!empty($suppress)) { - $suppress_data = str_replace("\r", "", base64_decode($suppress['suppresspassthru'])); - @file_put_contents("{$snortcfgdir}/supp{$snortcfg['suppresslistname']}", $suppress_data); - $suppress_file_name = "include {$snortcfgdir}/supp{$snortcfg['suppresslistname']}"; - } - - /* set the snort performance model */ - $snort_performance = "ac-bnfa"; - if(!empty($snortcfg['performance'])) - $snort_performance = $snortcfg['performance']; - - /* if user has defined a custom ssh port, use it */ - if(is_array($config['system']['ssh']) && isset($config['system']['ssh']['port'])) - $ssh_port = $config['system']['ssh']['port']; - else - $ssh_port = "22"; - - /* Define an array of default values for the various preprocessor ports */ - $snort_ports = array( - "dns_ports" => "53", "smtp_ports" => "25", "mail_ports" => "25,465,587,691", - "http_ports" => "36,80,81,82,83,84,85,86,87,88,89,90,311,383,591,593,631,901,1220,1414,1533,1741,1830,2301,2381,2809,3037,3057,3128,3443,3702,4343,4848,5250,6080,6988,7000,7001,7144,7145,7510,7777,7779,8000,8008,8014,8028,8080,8081,8082,8085,8088,8090,8118,8123,8180,8181,8222,8243,8280,8300,8500,8800,8888,8899,9000,9060,9080,9090,9091,9443,9999,10000,11371,15489,29991,33300,34412,34443,34444,41080,44440,50000,50002,51423,55555,56712", - "oracle_ports" => "1024:", "mssql_ports" => "1433", "telnet_ports" => "23", - "snmp_ports" => "161", "ftp_ports" => "21,2100,3535", "ssh_ports" => $ssh_port, - "pop2_ports" => "109", "pop3_ports" => "110", "imap_ports" => "143", - "sip_ports" => "5060,5061,5600", "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,992,993,994,995,7801,7802,7900,7901,7902,7903,7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920", - "file_data_ports" => "\$HTTP_PORTS,110,143", "shellcode_ports" => "!80", - "sun_rpc_ports" => "111,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779", - "DCERPC_NCACN_IP_TCP" => "139,445", "DCERPC_NCADG_IP_UDP" => "138,1024:", - "DCERPC_NCACN_IP_LONG" => "135,139,445,593,1024:", "DCERPC_NCACN_UDP_LONG" => "135,1024:", - "DCERPC_NCACN_UDP_SHORT" => "135,593,1024:", "DCERPC_NCACN_TCP" => "2103,2105,2107", - "DCERPC_BRIGHTSTORE" => "6503,6504", "DNP3_PORTS" => "20000", "MODBUS_PORTS" => "502", - "GTP_PORTS" => "2123,2152,3386" - ); - - /* Check for defined Aliases that may override default port settings as we build the portvars array */ - $portvardef = ""; - foreach ($snort_ports as $alias => $avalue) { - if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) - $snort_ports[$alias] = trim(filter_expand_alias($snortcfg["def_{$alias}"])); - $snort_ports[$alias] = preg_replace('/\s+/', ',', trim($snort_ports[$alias])); - $portvardef .= "portvar " . strtoupper($alias) . " [" . $snort_ports[$alias] . "]\n"; - } - - /* Define the default ports for the Stream5 preprocessor (formatted for easier reading in the snort.conf file) */ - $stream5_ports_client = "21 22 23 25 42 53 70 79 109 110 111 113 119 135 136 137 \\\n"; - $stream5_ports_client .= "\t 139 143 161 445 513 514 587 593 691 1433 1521 1741 \\\n"; - $stream5_ports_client .= "\t 2100 3306 6070 6665 6666 6667 6668 6669 7000 8181 \\\n"; - $stream5_ports_client .= "\t 32770 32771 32772 32773 32774 32775 32776 32777 \\\n"; - $stream5_ports_client .= "\t 32778 32779"; - $stream5_ports_both = "80 81 82 83 84 85 86 87 88 89 90 110 311 383 443 465 563 \\\n"; - $stream5_ports_both .= "\t 591 593 631 636 901 989 992 993 994 995 1220 1414 1533 \\\n"; - $stream5_ports_both .= "\t 1830 2301 2381 2809 3037 3057 3128 3443 3702 4343 4848 \\\n"; - $stream5_ports_both .= "\t 5250 6080 6988 7907 7000 7001 7144 7145 7510 7802 7777 \\\n"; - $stream5_ports_both .= "\t 7779 7801 7900 7901 7902 7903 7904 7905 7906 7908 7909 \\\n"; - $stream5_ports_both .= "\t 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 \\\n"; - $stream5_ports_both .= "\t 8000 8008 8014 8028 8080 8081 8082 8085 8088 8090 8118 \\\n"; - $stream5_ports_both .= "\t 8123 8180 8222 8243 8280 8300 8500 8800 8888 8899 9000 \\\n"; - $stream5_ports_both .= "\t 9060 9080 9090 9091 9443 9999 10000 11371 15489 29991 \\\n"; - $stream5_ports_both .= "\t 33300 34412 34443 34444 41080 44440 50000 50002 51423 \\\n"; - $stream5_ports_both .= "\t 55555 56712"; - - ///////////////////////////// - /* preprocessor code */ - /* def perform_stat */ - $perform_stat = <<<EOD -# Performance Statistics # -preprocessor perfmonitor: time 300 file {$snortlogdir}/snort_{$if_real}{$snort_uuid}/{$if_real}.stats pktcnt 10000 - -EOD; - - /* def ftp_preprocessor */ - $telnet_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['telnet_ports'])); - $ftp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ftp_ports'])); - - // Configure FTP_Telnet global options - $ftp_telnet_globals = "inspection_type "; - if ($snortcfg['ftp_telnet_inspection_type'] != "") { $ftp_telnet_globals .= $snortcfg['ftp_telnet_inspection_type']; }else{ $ftp_telnet_globals .= "stateful"; } - if ($snortcfg['ftp_telnet_alert_encrypted'] == "on") - $ftp_telnet_globals .= " \\\n\tencrypted_traffic yes"; - else - $ftp_telnet_globals .= " \\\n\tencrypted_traffic no"; - if ($snortcfg['ftp_telnet_check_encrypted'] == "on") - $ftp_telnet_globals .= " \\\n\tcheck_encrypted"; - - // Configure FTP_Telnet Telnet protocol options - $ftp_telnet_protocol = "ports { {$telnet_ports} }"; - if ($snortcfg['ftp_telnet_normalize'] == "on") - $ftp_telnet_protocol .= " \\\n\tnormalize"; - if ($snortcfg['ftp_telnet_detect_anomalies'] == "on") - $ftp_telnet_protocol .= " \\\n\tdetect_anomalies"; - if ($snortcfg['ftp_telnet_ayt_attack_threshold'] <> '0') { - $ftp_telnet_protocol .= " \\\n\tayt_attack_thresh "; - if ($snortcfg['ftp_telnet_ayt_attack_threshold'] != "") - $ftp_telnet_protocol .= $snortcfg['ftp_telnet_ayt_attack_threshold']; - else - $ftp_telnet_protocol .= "20"; - } - - // Setup the standard FTP commands used for all FTP Server engines - $ftp_cmds = <<<EOD - ftp_cmds { ABOR ACCT ADAT ALLO APPE AUTH CCC CDUP } \ - ftp_cmds { CEL CLNT CMD CONF CWD DELE ENC EPRT } \ - ftp_cmds { EPSV ESTA ESTP FEAT HELP LANG LIST LPRT } \ - ftp_cmds { LPSV MACB MAIL MDTM MFMT MIC MKD MLSD MLST } \ - ftp_cmds { MODE NLST NOOP OPTS PASS PASV PBSZ PORT } \ - ftp_cmds { PROT PWD QUIT REIN REST RETR RMD RNFR } \ - ftp_cmds { RNTO SDUP SITE SIZE SMNT STAT STOR STOU } \ - ftp_cmds { STRU SYST TEST TYPE USER XCUP XCRC XCWD } \ - ftp_cmds { XMAS XMD5 XMKD XPWD XRCP XRMD XRSQ XSEM } \ - ftp_cmds { XSEN XSHA1 XSHA256 } \ - alt_max_param_len 0 { ABOR CCC CDUP ESTA FEAT LPSV NOOP PASV PWD QUIT REIN STOU SYST XCUP XPWD } \ - alt_max_param_len 200 { ALLO APPE CMD HELP NLST RETR RNFR STOR STOU XMKD } \ - alt_max_param_len 256 { CWD RNTO } \ - alt_max_param_len 400 { PORT } \ - alt_max_param_len 512 { MFMT SIZE } \ - chk_str_fmt { ACCT ADAT ALLO APPE AUTH CEL CLNT CMD } \ - chk_str_fmt { CONF CWD DELE ENC EPRT EPSV ESTP HELP } \ - chk_str_fmt { LANG LIST LPRT MACB MAIL MDTM MIC MKD } \ - chk_str_fmt { MLSD MLST MODE NLST OPTS PASS PBSZ PORT } \ - chk_str_fmt { PROT REST RETR RMD RNFR RNTO SDUP SITE } \ - chk_str_fmt { SIZE SMNT STAT STOR STRU TEST TYPE USER } \ - chk_str_fmt { XCRC XCWD XMAS XMD5 XMKD XRCP XRMD XRSQ } \ - chk_str_fmt { XSEM XSEN XSHA1 XSHA256 } \ - cmd_validity ALLO < int [ char R int ] > \ - cmd_validity EPSV < [ { char 12 | char A char L char L } ] > \ - cmd_validity MACB < string > \ - cmd_validity MDTM < [ date nnnnnnnnnnnnnn[.n[n[n]]] ] string > \ - cmd_validity MODE < char ASBCZ > \ - cmd_validity PORT < host_port > \ - cmd_validity PROT < char CSEP > \ - cmd_validity STRU < char FRPO [ string ] > \ - cmd_validity TYPE < { char AE [ char NTC ] | char I | char L [ number ] } > - -EOD; - - // Configure all the FTP_Telnet FTP protocol options - // Iterate and configure the FTP Client engines - $ftp_default_client_engine = array( "name" => "default", "bind_to" => "all", "max_resp_len" => 256, - "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", - "bounce" => "yes", "bounce_to_net" => "", "bounce_to_port" => "" ); - - if (!is_array($snortcfg['ftp_client_engine']['item'])) - $snortcfg['ftp_client_engine']['item'] = array(); - - // If no FTP client engine is configured, use the default - // to keep from breaking Snort. - if (empty($snortcfg['ftp_client_engine']['item'])) - $snortcfg['ftp_client_engine']['item'][] = $ftp_default_client_engine; - $ftp_client_engine = ""; - - foreach ($snortcfg['ftp_client_engine']['item'] as $f => $v) { - $buffer = "preprocessor ftp_telnet_protocol: ftp client "; - if ($v['name'] == "default" && $v['bind_to'] == "all") - $buffer .= "default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "{$tmp} \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); - continue; - } - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP client '{$v['name']}' ... skipping entry."); - continue; - } - - if ($v['max_resp_len'] == "") - $buffer .= "\tmax_resp_len 256 \\\n"; - else - $buffer .= "\tmax_resp_len {$v['max_resp_len']} \\\n"; - - $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; - $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; - - if ($v['bounce'] == "yes") { - if (is_alias($v['bounce_to_net']) && is_alias($v['bounce_to_port'])) { - $net = trim(filter_expand_alias($v['bounce_to_net'])); - $port = trim(filter_expand_alias($v['bounce_to_port'])); - if (!empty($net) && !empty($port) && - snort_is_single_addr_alias($v['bounce_to_net']) && - (is_port($port) || is_portrange($port))) { - $port = preg_replace('/\s+/', ',', $port); - // Change port range delimiter to comma for ftp_telnet client preprocessor - if (is_portrange($port)) - $port = str_replace(":", ",", $port); - $buffer .= "\tbounce yes \\\n"; - $buffer .= "\tbounce_to { {$net},{$port} }\n"; - } - else { - // One or both of the BOUNCE_TO alias values is not right, - // so figure out which and log an appropriate error. - if (empty($net) || !snort_is_single_addr_alias($v['bounce_to_net'])) - log_error("[snort] ERROR: illegal value for bounce_to Address Alias [{$v['bounce_to_net']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); - if (empty($port) || !(is_port($port) || is_portrange($port))) - log_error("[snort] ERROR: illegal value for bounce_to Port Alias [{$v['bounce_to_port']}] for FTP client engine [{$v['name']}] ... omitting 'bounce_to' option for this client engine."); - $buffer .= "\tbounce yes\n"; - } - } - else - $buffer .= "\tbounce yes\n"; - } - else - $buffer .= "\tbounce no\n"; - - // Add this FTP client engine to the master string - $ftp_client_engine .= "{$buffer}\n"; - } - // Trim final trailing newline - rtrim($ftp_client_engine); - - // Iterate and configure the FTP Server engines - $ftp_default_server_engine = array( "name" => "default", "bind_to" => "all", "ports" => "default", - "telnet_cmds" => "no", "ignore_telnet_erase_cmds" => "yes", - "ignore_data_chan" => "no", "def_max_param_len" => 100 ); - - if (!is_array($snortcfg['ftp_server_engine']['item'])) - $snortcfg['ftp_server_engine']['item'] = array(); - - // If no FTP server engine is configured, use the default - // to keep from breaking Snort. - if (empty($snortcfg['ftp_server_engine']['item'])) - $snortcfg['ftp_server_engine']['item'][] = $ftp_default_server_engine; - $ftp_server_engine = ""; - - foreach ($snortcfg['ftp_server_engine']['item'] as $f => $v) { - $buffer = "preprocessor ftp_telnet_protocol: ftp server "; - if ($v['name'] == "default" && $v['bind_to'] == "all") - $buffer .= "default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "{$tmp} \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); - continue; - } - } - else { - log_error("[snort] ERROR: unable to resolve IP Address Alias '{$v['bind_to']}' for FTP server '{$v['name']}' ... skipping entry."); - continue; - } - - if ($v['def_max_param_len'] == "") - $buffer .= "\tdef_max_param_len 100 \\\n"; - elseif ($v['def_max_param_len'] <> '0') - $buffer .= "\tdef_max_param_len {$v['def_max_param_len']} \\\n"; - - if ($v['ports'] == "default" || !is_alias($v['ports']) || empty($v['ports'])) - $buffer .= "\tports { {$ftp_ports} } \\\n"; - elseif (is_alias($v['ports'])) { - $tmp = trim(filter_expand_alias($v['ports'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $tmp = snort_expand_port_range($tmp, ' '); - $buffer .= "\tports { {$tmp} } \\\n"; - } - else { - log_error("[snort] ERROR: unable to resolve Port Alias '{$v['ports']}' for FTP server '{$v['name']}' ... reverting to defaults."); - $buffer .= "\tports { {$ftp_ports} } \\\n"; - } - } - - $buffer .= "\ttelnet_cmds {$v['telnet_cmds']} \\\n"; - $buffer .= "\tignore_telnet_erase_cmds {$v['ignore_telnet_erase_cmds']} \\\n"; - if ($v['ignore_data_chan'] == "yes") - $buffer .= "\tignore_data_chan yes \\\n"; - $buffer .= "{$ftp_cmds}\n"; - - // Add this FTP server engine to the master string - $ftp_server_engine .= $buffer; - } - // Remove trailing newlines - rtrim($ftp_server_engine); - - $ftp_preprocessor = <<<EOD -# ftp_telnet preprocessor # -preprocessor ftp_telnet: global \ - {$ftp_telnet_globals} - -preprocessor ftp_telnet_protocol: telnet \ - {$ftp_telnet_protocol} - -{$ftp_server_engine} -{$ftp_client_engine} -EOD; - - $pop_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['pop3_ports'])); - $pop_preproc = <<<EOD -# POP preprocessor # -preprocessor pop: \ - ports { {$pop_ports} } \ - memcap 1310700 \ - qp_decode_depth 0 \ - b64_decode_depth 0 \ - bitenc_decode_depth 0 - -EOD; - - $imap_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['imap_ports'])); - $imap_preproc = <<<EOD -# IMAP preprocessor # -preprocessor imap: \ - ports { {$imap_ports} } \ - memcap 1310700 \ - qp_decode_depth 0 \ - b64_decode_depth 0 \ - bitenc_decode_depth 0 - -EOD; - - $smtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['mail_ports'])); - /* def smtp_preprocessor */ - $smtp_preprocessor = <<<EOD -# SMTP preprocessor # -preprocessor SMTP: \ - ports { {$smtp_ports} } \ - inspection_type stateful \ - normalize cmds \ - ignore_tls_data \ - valid_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT \ - NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX QUEU \ - STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE \ - XQUEU XSTA XTRN XUSR } \ - normalize_cmds { MAIL RCPT HELP HELO ETRN EHLO EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY \ - IDENT NOOP RSET SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT \ - ONEX QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 \ - XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ - max_header_line_len 1000 \ - max_response_line_len 512 \ - alt_max_command_line_len 260 { MAIL } \ - alt_max_command_line_len 300 { RCPT } \ - alt_max_command_line_len 500 { HELP HELO ETRN EHLO } \ - alt_max_command_line_len 255 { EXPN VRFY ATRN SIZE BDAT DEBUG EMAL ESAM ESND ESOM EVFY IDENT NOOP RSET } \ - alt_max_command_line_len 246 { SEND SAML SOML AUTH TURN ETRN PIPELINING CHUNKING DATA DSN RSET QUIT ONEX } \ - alt_max_command_line_len 246 { QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR } \ - alt_max_command_line_len 246 { XAUTH XCIR XEXCH50 XGEN XLICENSE XQUEU XSTA XTRN XUSR } \ - xlink2state { enable } \ - log_mailfrom \ - log_rcptto \ - log_email_hdrs \ - email_hdrs_log_depth 1464 \ - log_filename \ - qp_decode_depth 0 \ - b64_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']; - $sf_pscan_ignore_scanners = "\$HOME_NET"; - if (!empty($snortcfg['pscan_ignore_scanners']) && is_alias($snortcfg['pscan_ignore_scanners'])) { - $sf_pscan_ignore_scanners = trim(filter_expand_alias($snortcfg['pscan_ignore_scanners'])); - $sf_pscan_ignore_scanners = preg_replace('/\s+/', ',', trim($sf_pscan_ignore_scanners)); - } - - $sf_portscan = <<<EOD -# sf Portscan # -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} } - -EOD; - - /* def ssh_preproc */ - $ssh_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssh_ports'])); - $ssh_preproc = <<<EOD -# SSH preprocessor # -preprocessor ssh: \ - server_ports { {$ssh_ports} } \ - autodetect \ - max_client_bytes 19600 \ - max_encrypted_packets 20 \ - max_server_version_len 100 \ - enable_respoverflow enable_ssh1crc32 \ - enable_srvoverflow enable_protomismatch - -EOD; - - /* def other_preprocs */ - $sun_rpc_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sun_rpc_ports'])); - $other_preprocs = <<<EOD -# Other preprocs # -preprocessor rpc_decode: \ - {$sun_rpc_ports} \ - no_alert_multiple_requests \ - no_alert_large_fragments \ - no_alert_incomplete - -# Back Orifice preprocessor # -preprocessor bo - -EOD; - - /* def dce_rpc_2 */ - $dce_rpc_2 = <<<EOD -# DCE/RPC 2 # -preprocessor dcerpc2: \ - memcap 102400, \ - events [co] - -preprocessor dcerpc2_server: default, \ - policy WinXP, \ - detect [smb [{$snort_ports['smb_ports']}], \ - tcp 135, \ - udp 135, \ - rpc-over-http-server 593], \ - autodetect [tcp 1025:, \ - udp 1025:, \ - rpc-over-http-server 1025:], \ - smb_max_chain 3, smb_invalid_shares ["C$", "D$", "ADMIN$"] - -EOD; - - $sip_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['sip_ports'])); - $sip_preproc = <<<EOD -# SIP preprocessor # -preprocessor sip: \ - max_sessions 40000, \ - ports { {$sip_ports} }, \ - methods { invite \ - cancel \ - ack \ - bye \ - register \ - options \ - refer \ - subscribe \ - update \ - join \ - info \ - message \ - notify \ - benotify \ - do \ - qauth \ - sprack \ - publish \ - service \ - unsubscribe \ - prack }, \ - max_call_id_len 80, \ - max_from_len 256, \ - max_to_len 256, \ - max_via_len 1024, \ - max_requestName_len 50, \ - max_uri_len 512, \ - ignore_call_channel, \ - max_content_len 2048, \ - max_contact_len 512 - -EOD; - - $dns_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['dns_ports'])); - /* def dns_preprocessor */ - $dns_preprocessor = <<<EOD -# DNS preprocessor # -preprocessor dns: \ - ports { {$dns_ports} } \ - enable_rdata_overflow - -EOD; - - /* def dnp3_preprocessor */ - $dnp3_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['DNP3_PORTS'])); - $dnp3_preproc = <<<EOD -# DNP3 preprocessor # -preprocessor dnp3: \ - ports { {$dnp3_ports} } \ - memcap 262144 \ - check_crc - -EOD; - - /* def modbus_preprocessor */ - $modbus_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['MODBUS_PORTS'])); - $modbus_preproc = <<<EOD -# Modbus preprocessor # -preprocessor modbus: \ - ports { {$modbus_ports} } - -EOD; - - /* def gtp_preprocessor */ - $gtp_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['GTP_PORTS'])); - $gtp_preproc = <<<EOD -# GTP preprocessor # -preprocessor gtp: \ - ports { {$gtp_ports} } - -EOD; - - /* def ssl_preprocessor */ - $ssl_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['ssl_ports'])); - $ssl_preproc = <<<EOD -# SSL preprocessor # -preprocessor ssl: \ - ports { {$ssl_ports} }, \ - trustservers, \ - noinspect_encrypted - -EOD; - - /* def sensitive_data_preprocessor */ - if ($snortcfg['sdf_mask_output'] == "on") - $sdf_mask_output = "\\\n\tmask_output"; - else - $sdf_mask_output = ""; - if (empty($snortcfg['sdf_alert_threshold'])) - $snortcfg['sdf_alert_threshold'] = 25; - $sensitive_data = <<<EOD -# SDF preprocessor # -preprocessor sensitive_data: \ - alert_threshold {$snortcfg['sdf_alert_threshold']} {$sdf_mask_output} - -EOD; - - /* define IP Reputation preprocessor */ - if (is_array($snortcfg['blist_files']['item'])) { - $blist_files = ""; - $bIsFirst = TRUE; - foreach ($snortcfg['blist_files']['item'] as $blist) { - if ($bIsFirst) { - $blist_files .= "blacklist " . IPREP_PATH . $blist; - $bIsFirst = FALSE; - } - else - $blist_files .= ", \\ \n\tblacklist " . IPREP_PATH . $blist; - } - } - if (is_array($snortcfg['wlist_files']['item'])) { - $wlist_files = ""; - $bIsFirst = TRUE; - foreach ($snortcfg['wlist_files']['item'] as $wlist) { - if ($bIsFirst) { - $wlist_files .= "whitelist " . IPREP_PATH . $wlist; - $bIsFirst = FALSE; - } - else - $wlist_files .= ", \\ \n\twhitelist " . IPREP_PATH . $wlist; - } - } - if (!empty($blist_files)) - $ip_lists = $blist_files; - if (!empty($wlist_files)) - $ip_lists .= ", \\ \n" . $wlist_files; - if ($snortcfg['iprep_scan_local'] == 'on') - $ip_lists .= ", \\ \n\tscan_local"; - - $reputation_preproc = <<<EOD -# IP Reputation preprocessor # -preprocessor reputation: \ - memcap {$snortcfg['iprep_memcap']}, \ - priority {$snortcfg['iprep_priority']}, \ - nested_ip {$snortcfg['iprep_nested_ip']}, \ - white {$snortcfg['iprep_white']}, \ - {$ip_lists} - -EOD; - - /* define servers as IP variables */ - $snort_servers = array ( - "dns_servers" => "\$HOME_NET", "smtp_servers" => "\$HOME_NET", "http_servers" => "\$HOME_NET", - "www_servers" => "\$HOME_NET", "sql_servers" => "\$HOME_NET", "telnet_servers" => "\$HOME_NET", - "snmp_servers" => "\$HOME_NET", "ftp_servers" => "\$HOME_NET", "ssh_servers" => "\$HOME_NET", - "pop_servers" => "\$HOME_NET", "imap_servers" => "\$HOME_NET", "sip_proxy_ip" => "\$HOME_NET", - "sip_servers" => "\$HOME_NET", "rpc_servers" => "\$HOME_NET", "dnp3_server" => "\$HOME_NET", - "dnp3_client" => "\$HOME_NET", "modbus_server" => "\$HOME_NET", "modbus_client" => "\$HOME_NET", - "enip_server" => "\$HOME_NET", "enip_client" => "\$HOME_NET", - "aim_servers" => "64.12.24.0/23,64.12.28.0/23,64.12.161.0/24,64.12.163.0/24,64.12.200.0/24,205.188.3.0/24,205.188.5.0/24,205.188.7.0/24,205.188.9.0/24,205.188.153.0/24,205.188.179.0/24,205.188.248.0/24" - ); - - // Change old name from "var" to new name of "ipvar" for IP variables because - // Snort is deprecating the old "var" name in newer versions. - $ipvardef = ""; - foreach ($snort_servers as $alias => $avalue) { - if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) { - $avalue = trim(filter_expand_alias($snortcfg["def_{$alias}"])); - $avalue = preg_replace('/\s+/', ',', trim($avalue)); - } - $ipvardef .= "ipvar " . strtoupper($alias) . " [{$avalue}]\n"; - } - - $snort_preproc_libs = array( - "dce_rpc_2" => "dce2_preproc", "dns_preprocessor" => "dns_preproc", "ftp_preprocessor" => "ftptelnet_preproc", "imap_preproc" => "imap_preproc", - "pop_preproc" => "pop_preproc", "reputation_preproc" => "reputation_preproc", "sensitive_data" => "sdf_preproc", - "sip_preproc" => "sip_preproc", "gtp_preproc" => "gtp_preproc", "smtp_preprocessor" => "smtp_preproc", "ssh_preproc" => "ssh_preproc", - "ssl_preproc" => "ssl_preproc", "dnp3_preproc" => "dnp3_preproc", "modbus_preproc" => "modbus_preproc" - ); - $snort_preproc = array ( - "perform_stat", "other_preprocs", "ftp_preprocessor", "smtp_preprocessor", "ssl_preproc", "sip_preproc", "gtp_preproc", "ssh_preproc", "sf_portscan", - "dce_rpc_2", "dns_preprocessor", "sensitive_data", "pop_preproc", "imap_preproc", "dnp3_preproc", "modbus_preproc", "reputation_preproc" - ); - $default_disabled_preprocs = array( - "sf_portscan", "gtp_preproc", "sensitive_data", "dnp3_preproc", "modbus_preproc", "reputation_preproc", "perform_stat" - ); - $snort_preprocessors = ""; - foreach ($snort_preproc as $preproc) { - 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("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so")) { - @copy("{$snortlibdir}/dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } else - log_error("Could not find the {$preproclib} file. Snort might error out!"); - } else { - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } - } else { - $snort_preprocessors .= $$preproc; - $snort_preprocessors .= "\n"; - } - } - } - // Remove final trailing newline - $snort_preprocessors = rtrim($snort_preprocessors); - - $snort_misc_include_rules = ""; - if (file_exists("{$snortcfgdir}/reference.config")) - $snort_misc_include_rules .= "include {$snortcfgdir}/reference.config\n"; - if (file_exists("{$snortcfgdir}/classification.config")) - $snort_misc_include_rules .= "include {$snortcfgdir}/classification.config\n"; - if (!file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") || !file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules")) { - $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; - log_error("[Snort] Seems preprocessor and/or decoder rules are missing, enabling autogeneration of them in conf file."); - } - - /* generate rule sections to load */ - /* The files are always configured so the update process is easier */ - $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"; - - // Remove trailing newlines - $snort_misc_include_rules = rtrim($snort_misc_include_rules); - $selected_rules_sections = rtrim($selected_rules_sections); - - /* 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 detection config options */ - $cfg_detect_settings = "search-method {$snort_performance} max-pattern-len 20 max_queue_events 5"; - if ($snortcfg['fpm_split_any_any'] == "on") - $cfg_detect_settings .= " split-any-any"; - if ($snortcfg['fpm_search_optimize'] == "on") - $cfg_detect_settings .= " search-optimize"; - if ($snortcfg['fpm_no_stream_inserts'] == "on") - $cfg_detect_settings .= " no_stream_inserts"; - - /* Pull in user-configurable options for Frag3 preprocessor settings */ - /* Get global Frag3 options first and put into a string */ - $frag3_global = "preprocessor frag3_global: "; - if (!empty($snortcfg['frag3_memcap']) || $snortcfg['frag3_memcap'] == "0") - $frag3_global .= "memcap {$snortcfg['frag3_memcap']}, "; - else - $frag3_global .= "memcap 4194304, "; - if (!empty($snortcfg['frag3_max_frags'])) - $frag3_global .= "max_frags {$snortcfg['frag3_max_frags']}"; - else - $frag3_global .= "max_frags 8192"; - if ($snortcfg['frag3_detection'] == "off") - $frag3_global .= ", disabled"; - - $frag3_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", - "timeout" => 60, "min_ttl" => 1, "detect_anomalies" => "on", - "overlap_limit" => 0, "min_frag_len" => 0 ); - $frag3_engine = ""; - - // Now iterate configured Frag3 engines and write them to a string if enabled - if ($snortcfg['frag3_detection'] == "on") { - if (!is_array($snortcfg['frag3_engine']['item'])) - $snortcfg['frag3_engine']['item'] = array(); - - // If no frag3 tcp engine is configured, use the default - if (empty($snortcfg['frag3_engine']['item'])) - $snortcfg['frag3_engine']['item'][] = $frag3_default_tcp_engine; - - foreach ($snortcfg['frag3_engine']['item'] as $f => $v) { - $frag3_engine .= "preprocessor frag3_engine: "; - $frag3_engine .= "policy {$v['policy']}"; - if ($v['bind_to'] <> "all") { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ',', $tmp); - if (strpos($tmp, ",") !== false) - $frag3_engine .= " \\\n\tbind_to [{$tmp}]"; - else - $frag3_engine .= " \\\n\tbind_to {$tmp}"; - } - else - log_error("[snort] WARNING: unable to resolve IP List Alias '{$v['bind_to']}' for Frag3 engine '{$v['name']}' ... using 0.0.0.0 failsafe."); - } - $frag3_engine .= " \\\n\ttimeout {$v['timeout']}"; - $frag3_engine .= " \\\n\tmin_ttl {$v['min_ttl']}"; - if ($v['detect_anomalies'] == "on") { - $frag3_engine .= " \\\n\tdetect_anomalies"; - $frag3_engine .= " \\\n\toverlap_limit {$v['overlap_limit']}"; - $frag3_engine .= " \\\n\tmin_fragment_length {$v['min_frag_len']}"; - } - // Add newlines to terminate this engine - $frag3_engine .= "\n\n"; - } - // Remove trailing newline - $frag3_engine = rtrim($frag3_engine); - } - - // Grab any user-customized value for Protocol Aware Flushing (PAF) max PDUs - $paf_max_pdu_config = "config paf_max: "; - if (empty($snortcfg['max_paf']) || $snortcfg['max_paf'] == '0') - $paf_max_pdu_config .= "0"; - else - $paf_max_pdu_config .= $snortcfg['max_paf']; - - // Pull in user-configurable options for Stream5 preprocessor settings - // Get global options first and put into a string - $stream5_global = "preprocessor stream5_global: \\\n"; - if ($snortcfg['stream5_reassembly'] == "off") - $stream5_global .= "\tdisabled, \\\n"; - if ($snortcfg['stream5_track_tcp'] == "off") - $stream5_global .= "\ttrack_tcp no,"; - else { - $stream5_global .= "\ttrack_tcp yes,"; - if (!empty($snortcfg['stream5_max_tcp'])) - $stream5_global .= " \\\n\tmax_tcp {$snortcfg['stream5_max_tcp']},"; - else - $stream5_global .= " \\\n\tmax_tcp 262144,"; - } - if ($snortcfg['stream5_track_udp'] == "off") - $stream5_global .= " \\\n\ttrack_udp no,"; - else { - $stream5_global .= " \\\n\ttrack_udp yes,"; - if (!empty($snortcfg['stream5_max_udp'])) - $stream5_global .= " \\\n\tmax_udp {$snortcfg['stream5_max_udp']},"; - else - $stream5_global .= " \\\n\tmax_udp 131072,"; - } - if ($snortcfg['stream5_track_icmp'] == "on") { - $stream5_global .= " \\\n\ttrack_icmp yes,"; - if (!empty($snortcfg['stream5_max_icmp'])) - $stream5_global .= " \\\n\tmax_icmp {$snortcfg['stream5_max_icmp']},"; - else - $stream5_global .= " \\\n\tmax_icmp 65536,"; - } - else - $stream5_global .= " \\\n\ttrack_icmp no,"; - if (!empty($snortcfg['stream5_mem_cap'])) - $stream5_global .= " \\\n\tmemcap {$snortcfg['stream5_mem_cap']},"; - else - $stream5_global .= " \\\n\tmemcap 8388608,"; - - if (!empty($snortcfg['stream5_prune_log_max']) || $snortcfg['stream5_prune_log_max'] == '0') - $stream5_global .= " \\\n\tprune_log_max {$snortcfg['stream5_prune_log_max']}"; - else - $stream5_global .= " \\\n\tprune_log_max 1048576"; - if ($snortcfg['stream5_flush_on_alert'] == "on") - $stream5_global .= ", \\\n\tflush_on_alert"; - - $stream5_default_tcp_engine = array( "name" => "default", "bind_to" => "all", "policy" => "bsd", "timeout" => 30, - "max_queued_bytes" => 1048576, "detect_anomalies" => "off", "overlap_limit" => 0, - "max_queued_segs" => 2621, "require_3whs" => "off", "startup_3whs_timeout" => 0, - "no_reassemble_async" => "off", "dont_store_lg_pkts" => "off", "max_window" => 0, - "use_static_footprint_sizes" => "off", "check_session_hijacking" => "off", "ports_client" => "default", - "ports_both" => "default", "ports_server" => "none" ); - $stream5_tcp_engine = ""; - - // Now iterate configured Stream5 TCP engines and write them to a string if enabled - if ($snortcfg['stream5_reassembly'] == "on") { - if (!is_array($snortcfg['stream5_tcp_engine']['item'])) - $snortcfg['stream5_tcp_engine']['item'] = array(); - - // If no stream5 tcp engine is configured, use the default - if (empty($snortcfg['stream5_tcp_engine']['item'])) - $snortcfg['stream5_tcp_engine']['item'][] = $stream5_default_tcp_engine; - - foreach ($snortcfg['stream5_tcp_engine']['item'] as $f => $v) { - $buffer = "preprocessor stream5_tcp: "; - $buffer .= "policy {$v['policy']},"; - if ($v['bind_to'] <> "all") { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ',', $tmp); - if (strpos($tmp, ",") !== false) - $buffer .= " \\\n\tbind_to [{$tmp}],"; - else - $buffer .= " \\\n\tbind_to {$tmp},"; - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for Stream5 TCP engine '{$v['name']}' ... skipping this engine."); - continue; - } - } - $stream5_tcp_engine .= $buffer; - $stream5_tcp_engine .= " \\\n\ttimeout {$v['timeout']},"; - $stream5_tcp_engine .= " \\\n\toverlap_limit {$v['overlap_limit']},"; - $stream5_tcp_engine .= " \\\n\tmax_window {$v['max_window']},"; - $stream5_tcp_engine .= " \\\n\tmax_queued_bytes {$v['max_queued_bytes']},"; - $stream5_tcp_engine .= " \\\n\tmax_queued_segs {$v['max_queued_segs']}"; - if ($v['use_static_footprint_sizes'] == "on") - $stream5_tcp_engine .= ", \\\n\tuse_static_footprint_sizes"; - if ($v['check_session_hijacking'] == "on") - $stream5_tcp_engine .= ", \\\n\tcheck_session_hijacking"; - if ($v['dont_store_lg_pkts'] == "on") - $stream5_tcp_engine .= ", \\\n\tdont_store_large_packets"; - if ($v['no_reassemble_async'] == "on") - $stream5_tcp_engine .= ", \\\n\tdont_reassemble_async"; - if ($v['detect_anomalies'] == "on") - $stream5_tcp_engine .= ", \\\n\tdetect_anomalies"; - if ($v['require_3whs'] == "on") - $stream5_tcp_engine .= ", \\\n\trequire_3whs {$v['startup_3whs_timeout']}"; - if (!empty($v['ports_client'])) { - $stream5_tcp_engine .= ", \\\n\tports client"; - if ($v['ports_client'] == " all") - $stream5_tcp_engine .= " all"; - elseif ($v['ports_client'] == "default") - $stream5_tcp_engine .= " {$stream5_ports_client}"; - else { - $tmp = trim(filter_expand_alias($v['ports_client'])); - if (!empty($tmp)) - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - else { - $stream5_tcp_engine .= " {$stream5_ports_client}"; - log_error("[snort] WARNING: unable to resolve Ports Client Alias [{$v['ports_client']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); - } - } - } - if (!empty($v['ports_both'])) { - $stream5_tcp_engine .= ", \\\n\tports both"; - if ($v['ports_both'] == " all") - $stream5_tcp_engine .= " all"; - elseif ($v['ports_both'] == "default") - $stream5_tcp_engine .= " {$stream5_ports_both}"; - else { - $tmp = trim(filter_expand_alias($v['ports_both'])); - if (!empty($tmp)) - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - else { - $stream5_tcp_engine .= " {$stream5_ports_both}"; - log_error("[snort] WARNING: unable to resolve Ports Both Alias [{$v['ports_both']}] for Stream5 TCP engine '{$v['name']}' ... using default value."); - } - } - } - if (!empty($v['ports_server']) && $v['ports_server'] <> "none" && $v['ports_server'] <> "default") { - if ($v['ports_server'] == " all") { - $stream5_tcp_engine .= ", \\\n\tports server"; - $stream5_tcp_engine .= " all"; - } - else { - $tmp = trim(filter_expand_alias($v['ports_server'])); - if (!empty($tmp)) { - $stream5_tcp_engine .= ", \\\n\tports server"; - $stream5_tcp_engine .= " " . trim(preg_replace('/\s+/', ' ', $tmp)); - } - else - log_error("[snort] WARNING: unable to resolve Ports Server Alias [{$v['ports_server']}] for Stream5 TCP engine '{$v['name']}' ... defaulting to none."); - } - } - - // Make sure the "ports" parameter is set, or else default to a safe value - if (strpos($stream5_tcp_engine, "ports ") === false) - $stream5_tcp_engine .= ", \\\n\tports both all"; - - // Add a pair of newlines to terminate this engine - $stream5_tcp_engine .= "\n\n"; - } - // Trim off the final trailing newline - $stream5_tcp_engine = rtrim($stream5_tcp_engine); - } - - // Configure the Stream5 UDP engine if it and Stream5 reassembly are enabled - if ($snortcfg['stream5_track_udp'] == "off" || $snortcfg['stream5_reassembly'] == "off") - $stream5_udp_engine = ""; - else { - $stream5_udp_engine = "preprocessor stream5_udp: "; - if (!empty($snortcfg['stream5_udp_timeout'])) - $stream5_udp_engine .= "timeout {$snortcfg['stream5_udp_timeout']}"; - else - $stream5_udp_engine .= "timeout 30"; - } - - // Configure the Stream5 ICMP engine if it and Stream5 reassembly are enabled - if ($snortcfg['stream5_track_icmp'] == "on" && $snortcfg['stream5_reassembly'] == "on") { - $stream5_icmp_engine = "preprocessor stream5_icmp: "; - if (!empty($snortcfg['stream5_icmp_timeout'])) - $stream5_icmp_engine .= "timeout {$snortcfg['stream5_icmp_timeout']}"; - else - $stream5_icmp_engine .= "timeout 30"; - } - else - $stream5_icmp_engine = ""; - - // Check for and configure Host Attribute Table if enabled - $host_attrib_config = ""; - if ($snortcfg['host_attribute_table'] == "on" && !empty($snortcfg['host_attribute_data'])) { - file_put_contents("{$snortcfgdir}/host_attributes", base64_decode($snortcfg['host_attribute_data'])); - $host_attrib_config = "# Host Attribute Table #\n"; - $host_attrib_config .= "attribute_table filename {$snortcfgdir}/host_attributes\n"; - if (!empty($snortcfg['max_attribute_hosts'])) - $host_attrib_config .= "config max_attribute_hosts: {$snortcfg['max_attribute_hosts']}\n"; - if (!empty($snortcfg['max_attribute_services_per_host'])) - $host_attrib_config .= "config max_attribute_services_per_host: {$snortcfg['max_attribute_services_per_host']}"; - } - - // Configure the HTTP_INSPECT preprocessor - // Get global options first and put into a string - $http_inspect_global = "preprocessor http_inspect: global "; - if ($snortcfg['http_inspect'] == "off") - $http_inspect_global .= "disabled "; - $http_inspect_global .= "\\\n\tiis_unicode_map unicode.map 1252 \\\n"; - $http_inspect_global .= "\tcompress_depth 65535 \\\n"; - $http_inspect_global .= "\tdecompress_depth 65535 \\\n"; - if (!empty($snortcfg['http_inspect_memcap'])) - $http_inspect_global .= "\tmemcap {$snortcfg['http_inspect_memcap']} \\\n"; - else - $http_inspect_global .= "\tmemcap 150994944 \\\n"; - if (!empty($snortcfg['http_inspect_max_gzip_mem'])) - $http_inspect_global .= "\tmax_gzip_mem {$snortcfg['http_inspect_max_gzip_mem']}"; - else - $http_inspect_global .= "\tmax_gzip_mem 838860"; - if ($snortcfg['http_inspect_proxy_alert'] == "on") - $http_inspect_global .= " \\\n\tproxy_alert"; - - $http_inspect_default_engine = array( "name" => "default", "bind_to" => "all", "server_profile" => "all", "enable_xff" => "off", - "log_uri" => "off", "log_hostname" => "off", "server_flow_depth" => 65535, "enable_cookie" => "on", - "client_flow_depth" => 1460, "extended_response_inspection" => "on", "no_alerts" => "off", - "unlimited_decompress" => "on", "inspect_gzip" => "on", "normalize_cookies" =>"on", "normalize_headers" => "on", - "normalize_utf" => "on", "normalize_javascript" => "on", "allow_proxy_use" => "off", "inspect_uri_only" => "off", - "max_javascript_whitespaces" => 200, "post_depth" => -1, "max_headers" => 0, "max_spaces" => 0, - "max_header_length" => 0, "ports" => "default" ); - $http_ports = str_replace(",", " ", snort_expand_port_range($snort_ports['http_ports'])); - $http_inspect_servers = ""; - - // Iterate configured HTTP_INSPECT servers and write them to string if HTTP_INSPECT enabled - if ($snortcfg['http_inspect'] <> "off") { - if (!is_array($snortcfg['http_inspect_engine']['item'])) - $snortcfg['http_inspect_engine']['item'] = array(); - - // If no http_inspect_engine is configured, use the default - if (empty($snortcfg['http_inspect_engine']['item'])) - $snortcfg['http_inspect_engine']['item'][] = $http_inspect_default_engine; - - foreach ($snortcfg['http_inspect_engine']['item'] as $f => $v) { - $buffer = "preprocessor http_inspect_server: \\\n"; - if ($v['name'] == "default") - $buffer .= "\tserver default \\\n"; - elseif (is_alias($v['bind_to'])) { - $tmp = trim(filter_expand_alias($v['bind_to'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $buffer .= "\tserver { {$tmp} } \\\n"; - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); - continue; - } - } - else { - log_error("[snort] WARNING: unable to resolve IP Address Alias [{$v['bind_to']}] for HTTP_INSPECT server '{$v['name']}' ... skipping this server engine."); - continue; - } - $http_inspect_servers .= $buffer; - $http_inspect_servers .= "\tprofile {$v['server_profile']} \\\n"; - - if ($v['no_alerts'] == "on") - $http_inspect_servers .= "\tno_alerts \\\n"; - - if ($v['ports'] == "default" || empty($v['ports'])) - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - elseif (is_alias($v['ports'])) { - $tmp = trim(filter_expand_alias($v['ports'])); - if (!empty($tmp)) { - $tmp = preg_replace('/\s+/', ' ', $tmp); - $tmp = snort_expand_port_range($tmp, ' '); - $http_inspect_servers .= "\tports { {$tmp} } \\\n"; - } - else { - log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - } - } - else { - log_error("[snort] WARNING: unable to resolve Ports Alias [{$v['ports']}] for HTTP_INSPECT server '{$v['name']}' ... using safe default instead."); - $http_inspect_servers .= "\tports { {$http_ports} } \\\n"; - } - - $http_inspect_servers .= "\tserver_flow_depth {$v['server_flow_depth']} \\\n"; - $http_inspect_servers .= "\tclient_flow_depth {$v['client_flow_depth']} \\\n"; - $http_inspect_servers .= "\thttp_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 } \\\n"; - $http_inspect_servers .= "\tpost_depth {$v['post_depth']} \\\n"; - $http_inspect_servers .= "\tmax_headers {$v['max_headers']} \\\n"; - $http_inspect_servers .= "\tmax_header_length {$v['max_header_length']} \\\n"; - $http_inspect_servers .= "\tmax_spaces {$v['max_spaces']}"; - if ($v['enable_xff'] == "on") - $http_inspect_servers .= " \\\n\tenable_xff"; - if ($v['enable_cookie'] == "on") - $http_inspect_servers .= " \\\n\tenable_cookie"; - if ($v['normalize_cookies'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_cookies"; - if ($v['normalize_headers'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_headers"; - if ($v['normalize_utf'] == "on") - $http_inspect_servers .= " \\\n\tnormalize_utf"; - if ($v['allow_proxy_use'] == "on") - $http_inspect_servers .= " \\\n\tallow_proxy_use"; - if ($v['inspect_uri_only'] == "on") - $http_inspect_servers .= " \\\n\tinspect_uri_only"; - if ($v['extended_response_inspection'] == "on") { - $http_inspect_servers .= " \\\n\textended_response_inspection"; - if ($v['inspect_gzip'] == "on") { - $http_inspect_servers .= " \\\n\tinspect_gzip"; - if ($v['unlimited_decompress'] == "on") - $http_inspect_servers .= " \\\n\tunlimited_decompress"; - } - if ($v['normalize_javascript'] == "on") { - $http_inspect_servers .= " \\\n\tnormalize_javascript"; - $http_inspect_servers .= " \\\n\tmax_javascript_whitespaces {$v['max_javascript_whitespaces']}"; - } - } - if ($v['log_uri'] == "on") - $http_inspect_servers .= " \\\n\tlog_uri"; - if ($v['log_hostname'] == "on") - $http_inspect_servers .= " \\\n\tlog_hostname"; - - // Add a pair of trailing newlines to terminate this server config - $http_inspect_servers .= "\n\n"; - } - /* Trim off the final trailing newline */ - $http_inspect_server = rtrim($http_inspect_server); - } - - // Finally, build the Snort configuration file - $snort_conf_text = <<<EOD -# snort configuration file -# generated automatically by the pfSense subsystems do not modify manually - -# Define Local Network # -ipvar HOME_NET [{$home_net}] -ipvar EXTERNAL_NET [{$external_net}] - -# Define Rule Path # -var RULE_PATH {$snortcfgdir}/rules - -# Define Servers # -{$ipvardef} - -# Define Server Ports # -{$portvardef} - -# Configure quiet startup mode # -config quiet - -# Configure the snort decoder # -config checksum_mode: {$cksumcheck} -config disable_decode_alerts -config disable_tcpopt_experimental_alerts -config disable_tcpopt_obsolete_alerts -config disable_ttcp_alerts -config disable_tcpopt_alerts -config disable_ipopt_alerts -config disable_decode_drops - -# Enable the GTP decoder # -config enable_gtp - -# Configure PCRE match limitations -config pcre_match_limit: 3500 -config pcre_match_limit_recursion: 1500 - -# Configure the detection engine # -config detection: {$cfg_detect_settings} -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 # -{$paf_max_pdu_config} - -# Configure dynamically loaded libraries -dynamicpreprocessor directory {$snort_dirs['dynamicpreprocessor']} -dynamicengine directory {$snort_dirs['dynamicengine']} -dynamicdetection directory {$snort_dirs['dynamicrules']} - -# Inline packet normalization. For more information, see README.normalize -# Disabled since we do not use "inline" mode with pfSense -# preprocessor normalize_ip4 -# preprocessor normalize_tcp: ips ecn stream -# preprocessor normalize_icmp4 -# preprocessor normalize_ip6 -# preprocessor normalize_icmp6 - -# Flow and stream # -{$frag3_global} - -{$frag3_engine} - -{$stream5_global} - -{$stream5_tcp_engine} - -{$stream5_udp_engine} - -{$stream5_icmp_engine} - -# HTTP Inspect # -{$http_inspect_global} - -{$http_inspect_servers} -{$snort_preprocessors} -{$host_attrib_config} - -# Snort Output Logs # -output alert_csv: alert timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority -{$alertsystemlog_type} -{$snortunifiedlog_type} -{$spoink_type} - -# Misc Includes # -{$snort_misc_include_rules} - -{$suppress_file_name} - -# Snort user pass through configuration -{$snort_config_pass_thru} - -# Rules Selection # -{$selected_rules_sections} -EOD; - - // Write out snort.conf file - file_put_contents("{$snortcfgdir}/snort.conf", $snort_conf_text); - conf_mount_ro(); - unset($snort_conf_text, $selected_rules_sections, $suppress_file_name, $snort_misc_include_rules, $spoink_type, $snortunifiedlog_type, $alertsystemlog_type); - unset($home_net, $external_net, $ipvardef, $portvardef); -} - -/*****************************************************************************/ -/* This starts the actual post-install code */ -/*****************************************************************************/ +$flowbit_rules_file = FLOWBITS_FILENAME; +$snort_enforcing_rules_file = SNORT_ENFORCING_RULES_FILENAME; /* Hard kill any running Snort processes that may have been started by any */ /* of the pfSense scripts such as check_reload_status() or rc.start_packages */ @@ -1376,29 +57,33 @@ if(is_process_running("snort")) { exec("/usr/bin/killall -z snort"); sleep(2); // Delete any leftover snort PID files in /var/run - unlink_if_exists("/var/run/snort_*.pid"); + unlink_if_exists("{$g['varrun_path']}/snort_*.pid"); } // Hard kill any running Barnyard2 processes if(is_process_running("barnyard")) { exec("/usr/bin/killall -z barnyard2"); sleep(2); // Delete any leftover barnyard2 PID files in /var/run - unlink_if_exists("/var/run/barnyard2_*.pid"); + unlink_if_exists("{$g['varrun_path']}/barnyard2_*.pid"); } /* Set flag for post-install in progress */ $g['snort_postinstall'] = true; +/* Set conf partition to read-write so we can make changes there */ +conf_mount_rw(); + /* cleanup default files */ @rename("{$snortdir}/snort.conf-sample", "{$snortdir}/snort.conf"); @rename("{$snortdir}/threshold.conf-sample", "{$snortdir}/threshold.conf"); @rename("{$snortdir}/sid-msg.map-sample", "{$snortdir}/sid-msg.map"); @rename("{$snortdir}/unicode.map-sample", "{$snortdir}/unicode.map"); +@rename("{$snortdir}/file_magic.conf-sample", "{$snortdir}/file_magic.conf"); @rename("{$snortdir}/classification.config-sample", "{$snortdir}/classification.config"); @rename("{$snortdir}/generators-sample", "{$snortdir}/generators"); @rename("{$snortdir}/reference.config-sample", "{$snortdir}/reference.config"); @rename("{$snortdir}/gen-msg.map-sample", "{$snortdir}/gen-msg.map"); -@rename("{$snortdir}/attribute_table.dtd-sample", "{$snortdir}/attribute_table.dtd"); +//@rename("{$snortdir}/attribute_table.dtd-sample", "{$snortdir}/attribute_table.dtd"); /* fix up the preprocessor rules filenames from a PBI package install */ $preproc_rules = array("decoder.rules", "preprocessor.rules", "sensitive-data.rules"); @@ -1408,13 +93,15 @@ foreach ($preproc_rules as $file) { } /* Remove any previously installed scripts since we rebuild them */ -@unlink("{$snortdir}/sid"); -@unlink("{$rcdir}/snort.sh"); -@unlink("{$rcdir}/barnyard2"); +unlink_if_exists("{$snortdir}/sid"); +unlink_if_exists("{$rcdir}snort.sh"); +unlink_if_exists("{$rcdir}barnyard2"); /* Create required log and db directories in /var */ safe_mkdir(SNORTLOGDIR); -safe_mkdir(IPREP_PATH); +safe_mkdir(SNORT_IPREP_PATH); +safe_mkdir(SNORT_SID_MODS_PATH); +safe_mkdir(SNORT_APPID_ODP_PATH); /* If installed, absorb the Snort Dashboard Widget into this package */ /* by removing it as a separately installed package. */ @@ -1423,7 +110,6 @@ if ($pkgid >= 0) { log_error(gettext("[Snort] Removing legacy 'Dashboard Widget: Snort' package because the widget is now part of the Snort package.")); unset($config['installedpackages']['package'][$pkgid]); unlink_if_exists("/usr/local/pkg/widget-snort.xml"); - write_config("Snort pkg: removed legacy Snort Dashboard Widget."); } /* Define a default Dashboard Widget Container for Snort */ @@ -1433,29 +119,87 @@ $snort_widget_container = "snort_alerts-container:col2:close"; if ($config['installedpackages']['snortglobal']['forcekeepsettings'] == 'on') { log_error(gettext("[Snort] Saved settings detected... rebuilding installation with saved settings...")); update_status(gettext("Saved settings detected...")); + + /****************************************************************/ + /* Do test and fix for duplicate UUIDs if this install was */ + /* impacted by the DUP (clone) bug that generated a duplicate */ + /* UUID for the cloned interface. */ + /****************************************************************/ + if (count($config['installedpackages']['snortglobal']['rule']) > 0) { + $uuids = array(); + $fixed_duplicate = FALSE; + $snortconf = &$config['installedpackages']['snortglobal']['rule']; + foreach ($snortconf as &$snortcfg) { + // Check for and fix a duplicate UUID + $if_real = get_real_interface($snortcfg['interface']); + if (!isset($uuids[$snortcfg['uuid']])) { + $uuids[$snortcfg['uuid']] = $if_real; + continue; + } + else { + // Found a duplicate UUID, so generate a + // new one for the affected interface. + $old_uuid = $snortcfg['uuid']; + $new_uuid = snort_generate_id(); + if (file_exists("{$snortlogdir}snort_{$if_real}{$old_uuid}/")) + @rename("{$snortlogdir}snort_{$if_real}{$old_uuid}/", "{$snortlogdir}snort_{$if_real}{$new_uuid}/"); + $snortcfg['uuid'] = $new_uuid; + $uuids[$new_uuid] = $if_real; + log_error(gettext("[Snort] updated UUID for interface " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) . " from {$old_uuid} to {$new_uuid}.")); + $fixed_duplicate = TRUE; + } + } + unset($uuids); + } + /****************************************************************/ + /* End of duplicate UUID bug fix. */ + /****************************************************************/ + /* Do one-time settings migration for new multi-engine configurations */ update_output_window(gettext("Please wait... migrating settings to new configuration...")); - include('/usr/local/www/snort/snort_migrate_config.php'); + include('/usr/local/pkg/snort/snort_migrate_config.php'); update_output_window(gettext("Please wait... rebuilding installation with saved settings...")); log_error(gettext("[Snort] Downloading and updating configured rule types...")); - update_output_window(gettext("Please wait... downloading and updating configured rule types...")); + update_output_window(gettext("Please wait... downloading and updating configured rule sets...")); if ($pkg_interface <> "console") $snort_gui_include = true; - include('/usr/local/www/snort/snort_check_for_rule_updates.php'); + include('/usr/local/pkg/snort/snort_check_for_rule_updates.php'); update_status(gettext("Generating snort.conf configuration file from saved settings...")); $rebuild_rules = true; + conf_mount_rw(); /* Create the snort.conf files for each enabled interface */ $snortconf = $config['installedpackages']['snortglobal']['rule']; - foreach ($snortconf as $value) { - $if_real = get_real_interface($value['interface']); + foreach ($snortconf as $snortcfg) { + $if_real = get_real_interface($snortcfg['interface']); + $snort_uuid = $snortcfg['uuid']; + $snortcfgdir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}"; + update_output_window(gettext("Generating configuration for " . convert_friendly_interface_to_friendly_descr($snortcfg['interface']) . "...")); + + // Pull in the PHP code that generates the snort.conf file + // variables that will be substituted further down below. + include("/usr/local/pkg/snort/snort_generate_conf.php"); + + // Pull in the boilerplate template for the snort.conf + // configuration file. The contents of the template along + // with substituted variables are stored in $snort_conf_text + // (which is defined in the included file). + include("/usr/local/pkg/snort/snort_conf_template.inc"); - /* create a snort.conf file for interface */ - snort_build_new_conf($value); + // Now write out the conf file using $snort_conf_text contents + @file_put_contents("{$snortcfgdir}/snort.conf", $snort_conf_text); + unset($snort_conf_text); - /* create barnyard2.conf file for interface */ - if ($value['barnyard_enable'] == 'on') - snort_generate_barnyard2_conf($value, $if_real); + // Create the actual rules files and save them in the interface directory + snort_prepare_rule_files($snortcfg, $snortcfgdir); + + // Clean up variables we no longer need and free memory + unset($snort_conf_text, $selected_rules_sections, $suppress_file_name, $snort_misc_include_rules, $spoink_type, $snortunifiedlog_type, $alertsystemlog_type); + unset($home_net, $external_net, $ipvardef, $portvardef); + + // Create barnyard2.conf file for interface + if ($snortcfg['barnyard_enable'] == 'on') + snort_generate_barnyard2_conf($snortcfg, $if_real); } /* create snort bootup file snort.sh */ @@ -1466,36 +210,40 @@ if ($config['installedpackages']['snortglobal']['forcekeepsettings'] == 'on') { snort_rm_blocked_install_cron($config['installedpackages']['snortglobal']['rm_blocked'] != "never_b" ? true : false); snort_rules_up_install_cron($config['installedpackages']['snortglobal']['autorulesupdate7'] != "never_up" ? true : false); - /* Add the recurring jobs created above to crontab */ - configure_cron(); - /* Restore the last Snort Dashboard Widget setting if none is set */ if (!empty($config['installedpackages']['snortglobal']['dashboard_widget']) && stristr($config['widgets']['sequence'], "snort_alerts-container") === FALSE) $config['widgets']['sequence'] .= "," . $config['installedpackages']['snortglobal']['dashboard_widget']; $rebuild_rules = false; - update_output_window(gettext("Finished rebuilding Snort configuration files...")); + if ($pkg_interface <> "console") + update_output_window(gettext("Finished rebuilding Snort configuration 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...")); - update_output_window(gettext("Please wait... while Snort is started...")); - log_error(gettext("[Snort] Starting Snort using rebuilt configuration...")); - start_service("snort"); - update_output_window(gettext("Snort has been started using the rebuilt configuration...")); + if (!($g['booting'])) { + if ($pkg_interface <> "console") { + update_status(gettext("Starting Snort using rebuilt configuration...")); + update_output_window(gettext("Please wait while Snort is started...")); + mwexec("{$rcdir}snort.sh start"); + update_output_window(gettext("Snort has been started using the rebuilt configuration...")); + } + else + mwexec_bg("{$rcdir}snort.sh start"); } } +/* We're finished with conf partition mods, return to read-only */ +conf_mount_ro(); + /* If an existing Snort Dashboard Widget container is not found, */ /* then insert our default Widget Dashboard container. */ if (stristr($config['widgets']['sequence'], "snort_alerts-container") === FALSE) $config['widgets']['sequence'] .= ",{$snort_widget_container}"; /* Update Snort package version in configuration */ -$config['installedpackages']['snortglobal']['snort_config_ver'] = "3.0.8"; -write_config("Snort pkg: post-install configuration saved."); +$config['installedpackages']['snortglobal']['snort_config_ver'] = "3.2"; +write_config("Snort pkg v3.2: post-install configuration saved."); /* Done with post-install, so clear flag */ unset($g['snort_postinstall']); diff --git a/config/snort/snort_preprocessors.php b/config/snort/snort_preprocessors.php index 5cee95df..9f6879ef 100755 --- a/config/snort/snort_preprocessors.php +++ b/config/snort/snort_preprocessors.php @@ -117,16 +117,64 @@ if (isset($id) && isset($a_nat[$id])) { if (empty($pconfig['smtp_preprocessor'])) $pconfig['smtp_preprocessor'] = 'on'; + if (empty($pconfig['smtp_memcap'])) + $pconfig['smtp_memcap'] = "838860"; + if (empty($pconfig['smtp_max_mime_mem'])) + $pconfig['smtp_max_mime_mem'] = "838860"; + if (empty($pconfig['smtp_b64_decode_depth'])) + $pconfig['smtp_b64_decode_depth'] = "0"; + if (empty($pconfig['smtp_qp_decode_depth'])) + $pconfig['smtp_qp_decode_depth'] = "0"; + if (empty($pconfig['smtp_bitenc_decode_depth'])) + $pconfig['smtp_bitenc_decode_depth'] = "0"; + if (empty($pconfig['smtp_uu_decode_depth'])) + $pconfig['smtp_uu_decode_depth'] = "0"; + if (empty($pconfig['smtp_email_hdrs_log_depth']) && $pconfig['smtp_email_hdrs_log_depth'] != '0') + $pconfig['smtp_email_hdrs_log_depth'] = "1464"; + if (empty($pconfig['smtp_ignore_tls_data'])) + $pconfig['smtp_ignore_tls_data'] = 'on'; + if (empty($pconfig['smtp_log_mail_from'])) + $pconfig['smtp_log_mail_from'] = 'on'; + if (empty($pconfig['smtp_log_rcpt_to'])) + $pconfig['smtp_log_rcpt_to'] = 'on'; + if (empty($pconfig['smtp_log_filename'])) + $pconfig['smtp_log_filename'] = 'on'; + if (empty($pconfig['smtp_log_email_hdrs'])) + $pconfig['smtp_log_email_hdrs'] = '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['pop_memcap'])) + $pconfig['pop_memcap'] = "838860"; + if (empty($pconfig['pop_b64_decode_depth'])) + $pconfig['pop_b64_decode_depth'] = "0"; + if (empty($pconfig['pop_qp_decode_depth'])) + $pconfig['pop_qp_decode_depth'] = "0"; + if (empty($pconfig['pop_bitenc_decode_depth'])) + $pconfig['pop_bitenc_decode_depth'] = "0"; + if (empty($pconfig['pop_uu_decode_depth'])) + $pconfig['pop_uu_decode_depth'] = "0"; + if (empty($pconfig['imap_preproc'])) $pconfig['imap_preproc'] = 'on'; + if (empty($pconfig['imap_memcap'])) + $pconfig['imap_memcap'] = "838860"; + if (empty($pconfig['imap_b64_decode_depth'])) + $pconfig['imap_b64_decode_depth'] = "0"; + if (empty($pconfig['imap_qp_decode_depth'])) + $pconfig['imap_qp_decode_depth'] = "0"; + if (empty($pconfig['imap_bitenc_decode_depth'])) + $pconfig['imap_bitenc_decode_depth'] = "0"; + if (empty($pconfig['imap_uu_decode_depth'])) + $pconfig['imap_uu_decode_depth'] = "0"; + if (empty($pconfig['sip_preproc'])) $pconfig['sip_preproc'] = 'on'; if (empty($pconfig['other_preprocs'])) @@ -192,12 +240,22 @@ $disabled_rules_log = "{$if_friendly}_disabled_preproc_rules.log"; // Check for returned "selected alias" if action is import if ($_GET['act'] == "import" && isset($_GET['varname']) && !empty($_GET['varvalue'])) { - $pconfig[$_GET['varname']] = htmlspecialchars($_GET['varvalue']); + + // Retrieve previously typed values we passed to SELECT ALIAS page + $pconfig['sf_portscan'] = htmlspecialchars($_GET['sf_portscan'])? 'on' : 'off'; + $pconfig['pscan_ignore_scanners'] = htmlspecialchars($_GET['pscan_ignore_scanners']); + $pconfig['pscan_protocol'] = htmlspecialchars($_GET['pscan_protocol']); + $pconfig['pscan_type'] = htmlspecialchars($_GET['pscan_type']); + $pconfig['pscan_memcap'] = htmlspecialchars($_GET['pscan_memcap']); + $pconfig['pscan_sense_level'] = htmlspecialchars($_GET['pscan_sense_level']); + + // Now retrieve the "selected alias" returned from SELECT ALIAS page + $pconfig[$_GET['varname']] = htmlspecialchars($_GET['varvalue']); } // Handle deleting of any of the multiple configuration engines if ($_POST['del_http_inspect']) { - if (isset($_POST['eng_id']) && isset($id) && issset($a_nat[$id])) { + if (isset($_POST['eng_id']) && isset($id) && isset($a_nat[$id])) { unset($a_nat[$id]['http_inspect_engine']['item'][$_POST['eng_id']]); write_config("Snort pkg: deleted http_inspect engine for {$a_nat[$id]['interface']}."); header("Location: snort_preprocessors.php?id=$id#httpinspect_row"); @@ -270,6 +328,23 @@ if ($_POST['ResetAll']) { $pconfig['ftp_telnet_detect_anomalies'] = "on"; $pconfig['ftp_telnet_ayt_attack_threshold'] = "20"; $pconfig['smtp_preprocessor'] = "on"; + $pconfig['smtp_memcap'] = "838860"; + $pconfig['smtp_max_mime_mem'] = "838860"; + $pconfig['smtp_b64_decode_depth'] = "0"; + $pconfig['smtp_qp_decode_depth'] = "0"; + $pconfig['smtp_bitenc_decode_depth'] = "0"; + $pconfig['smtp_uu_decode_depth'] = "0"; + $pconfig['smtp_email_hdrs_log_depth'] = "1464"; + $pconfig['smtp_ignore_data'] = 'off'; + $pconfig['smtp_ignore_tls_data'] = 'on'; + $pconfig['smtp_log_mail_from'] = 'on'; + $pconfig['smtp_log_rcpt_to'] = 'on'; + $pconfig['smtp_log_filename'] = 'on'; + $pconfig['smtp_log_email_hdrs'] = 'on'; + $pconfig['appid_preproc'] = "off"; + $pconfig['sf_appid_mem_cap'] = "256"; + $pconfig['sf_appid_statslog'] = "on"; + $pconfig['sf_appid_stats_period'] = "300"; $pconfig['sf_portscan'] = "off"; $pconfig['pscan_protocol'] = "all"; $pconfig['pscan_type'] = "all"; @@ -284,7 +359,17 @@ if ($_POST['ResetAll']) { $pconfig['sdf_mask_output'] = "off"; $pconfig['ssl_preproc'] = "on"; $pconfig['pop_preproc'] = "on"; + $pconfig['pop_memcap'] = "838860"; + $pconfig['pop_b64_decode_depth'] = "0"; + $pconfig['pop_qp_decode_depth'] = "0"; + $pconfig['pop_bitenc_decode_depth'] = "0"; + $pconfig['pop_uu_decode_depth'] = "0"; $pconfig['imap_preproc'] = "on"; + $pconfig['imap_memcap'] = "838860"; + $pconfig['imap_b64_decode_depth'] = "0"; + $pconfig['imap_qp_decode_depth'] = "0"; + $pconfig['imap_bitenc_decode_depth'] = "0"; + $pconfig['imap_uu_decode_depth'] = "0"; $pconfig['sip_preproc'] = "on"; $pconfig['dnp3_preproc'] = "off"; $pconfig['modbus_preproc'] = "off"; @@ -312,6 +397,60 @@ if ($_POST['save']) { $input_errors[] = gettext("You must select at least one sensitive data type to inspect for when Sensitive Data detection is enabled."); } + // Validate POP3 parameter values if POP3 Decoder is enabled + if ($_POST['pop_preproc'] == 'on') { + if ($_POST['pop_memcap'] < 3276 || $_POST['pop_memcap'] > 104857600) + $input_errors[] = gettext("The value for POP3 Decoder Memory Cap must be between 3,276 and 104,857,600."); + if ($_POST['pop_b64_decode_depth'] < -1 || $_POST['pop_b64_decode_depth'] > 65535) + $input_errors[] = gettext("The value for POP3 Decoder Base64 Decode Depth must be between -1 and 65,535."); + if ($_POST['pop_qp_decode_depth'] < -1 || $_POST['pop_qp_decode_depth'] > 65535) + $input_errors[] = gettext("The value for POP3 Decoder Quoted-Printable (QP) Decode Depth must be between -1 and 65,535."); + if ($_POST['pop_bitenc_decode_depth'] < -1 || $_POST['pop_bitenc_decode_depth'] > 65535) + $input_errors[] = gettext("The value for POP3 Decoder Non-Encoded MIME Extraction Depth must be between -1 and 65,535."); + if ($_POST['pop_uu_decode_depth'] < -1 || $_POST['pop_uu_decode_depth'] > 65535) + $input_errors[] = gettext("The value for POP3 Decoder Unix-to-Unix (UU) Decode Depth must be between -1 and 65,535."); + } + + // Validate IMAP parameter values if IMAP Decoder is enabled + if ($_POST['imap_preproc'] == 'on') { + if ($_POST['imap_memcap'] < 3276 || $_POST['imap_memcap'] > 104857600) + $input_errors[] = gettext("The value for IMAP Decoder Memory Cap must be between 3,276 and 104,857,600."); + if ($_POST['imap_b64_decode_depth'] < -1 || $_POST['imap_b64_decode_depth'] > 65535) + $input_errors[] = gettext("The value for IMAP Decoder Base64 Decode Depth must be between -1 and 65,535."); + if ($_POST['imap_qp_decode_depth'] < -1 || $_POST['imap_qp_decode_depth'] > 65535) + $input_errors[] = gettext("The value for IMAP Decoder Quoted-Printable (QP) Decode Depth must be between -1 and 65,535."); + if ($_POST['imap_bitenc_decode_depth'] < -1 || $_POST['imap_bitenc_decode_depth'] > 65535) + $input_errors[] = gettext("The value for IMAP Decoder Non-Encoded MIME Extraction Depth must be between -1 and 65,535."); + if ($_POST['imap_uu_decode_depth'] < -1 || $_POST['imap_uu_decode_depth'] > 65535) + $input_errors[] = gettext("The value for IMAP Decoder Unix-to-Unix (UU) Decode Depth must be between -1 and 65,535."); + } + + // Validate SMTP parameter values if SMTP Decoder is enabled + if ($_POST['smtp_preprocessor'] == 'on') { + if ($_POST['smtp_memcap'] < 3276 || $_POST['smtp_memcap'] > 104857600) + $input_errors[] = gettext("The value for SMTP Decoder Memory Cap must be between 3,276 and 104,857,600."); + if ($_POST['smtp_max_mime_mem'] < 3276 || $_POST['smtp_max_mime_mem'] > 104857600) + $input_errors[] = gettext("The value for SMTP Decoder Maximum MIME Memory must be between 3,276 and 104,857,600."); + if ($_POST['smtp_b64_decode_depth'] < -1 || $_POST['smtp_b64_decode_depth'] > 65535) + $input_errors[] = gettext("The value for SMTP Decoder Base64 Decode Depth must be between -1 and 65,535."); + if ($_POST['smtp_qp_decode_depth'] < -1 || $_POST['smtp_qp_decode_depth'] > 65535) + $input_errors[] = gettext("The value for SMTP Decoder Quoted-Printable (QP) Decode Depth must be between -1 and 65,535."); + if ($_POST['smtp_bitenc_decode_depth'] < -1 || $_POST['smtp_bitenc_decode_depth'] > 65535) + $input_errors[] = gettext("The value for SMTP Decoder Non-Encoded MIME Extraction Depth must be between -1 and 65,535."); + if ($_POST['smtp_uu_decode_depth'] < -1 || $_POST['smtp_uu_decode_depth'] > 65535) + $input_errors[] = gettext("The value for SMTP Decoder Unix-to-Unix (UU) Decode Depth must be between -1 and 65,535."); + if ($_POST['smtp_email_hdrs_log_depth'] < 0 || $_POST['smtp_email_hdrs_log_depth'] > 20480) + $input_errors[] = gettext("The value for SMTP Decoder E-Mail Headers Log Depth must be between 0 and 20,480."); + } + + // Validate AppID parameter values if AppID Detector is enabled + if ($_POST['appid_preproc'] == 'on') { + if ($_POST['sf_appid_mem_cap'] < 32 || $_POST['sf_appid_mem_cap'] > 3000) + $input_errors[] = gettext("The value for Application ID Memory Cap must be between 32 and 3000."); + if ($_POST['sf_appid_stats_period'] < 60 || $_POST['sf_appid_stats_period'] > 3600) + $input_errors[] = gettext("The value for Application ID Stats Period must be between 60 and 3600."); + } + /* if no errors write to conf */ if (!$input_errors) { /* post new options */ @@ -337,6 +476,25 @@ if ($_POST['save']) { if ($_POST['ftp_telnet_inspection_type'] != "") { $natent['ftp_telnet_inspection_type'] = $_POST['ftp_telnet_inspection_type']; }else{ $natent['ftp_telnet_inspection_type'] = "stateful"; } if ($_POST['ftp_telnet_ayt_attack_threshold'] != "") { $natent['ftp_telnet_ayt_attack_threshold'] = $_POST['ftp_telnet_ayt_attack_threshold']; }else{ $natent['ftp_telnet_ayt_attack_threshold'] = "20"; } if ($_POST['sdf_alert_threshold'] != "") { $natent['sdf_alert_threshold'] = $_POST['sdf_alert_threshold']; }else{ $natent['sdf_alert_threshold'] = "25"; } + if ($_POST['pop_memcap'] != "") { $natent['pop_memcap'] = $_POST['pop_memcap']; }else{ $natent['pop_memcap'] = "838860"; } + if ($_POST['pop_b64_decode_depth'] != "") { $natent['pop_b64_decode_depth'] = $_POST['pop_b64_decode_depth']; }else{ $natent['pop_b64_decode_depth'] = "0"; } + if ($_POST['pop_qp_decode_depth'] != "") { $natent['pop_qp_decode_depth'] = $_POST['pop_qp_decode_depth']; }else{ $natent['pop_qp_decode_depth'] = "0"; } + if ($_POST['pop_bitenc_decode_depth'] != "") { $natent['pop_bitenc_decode_depth'] = $_POST['pop_bitenc_decode_depth']; }else{ $natent['pop_bitenc_decode_depth'] = "0"; } + if ($_POST['pop_uu_decode_depth'] != "") { $natent['pop_uu_decode_depth'] = $_POST['pop_uu_decode_depth']; }else{ $natent['pop_uu_decode_depth'] = "0"; } + if ($_POST['imap_memcap'] != "") { $natent['imap_memcap'] = $_POST['imap_memcap']; }else{ $natent['imap_memcap'] = "838860"; } + if ($_POST['imap_b64_decode_depth'] != "") { $natent['imap_b64_decode_depth'] = $_POST['imap_b64_decode_depth']; }else{ $natent['imap_b64_decode_depth'] = "0"; } + if ($_POST['imap_qp_decode_depth'] != "") { $natent['imap_qp_decode_depth'] = $_POST['imap_qp_decode_depth']; }else{ $natent['imap_qp_decode_depth'] = "0"; } + if ($_POST['imap_bitenc_decode_depth'] != "") { $natent['imap_bitenc_decode_depth'] = $_POST['imap_bitenc_decode_depth']; }else{ $natent['imap_bitenc_decode_depth'] = "0"; } + if ($_POST['imap_uu_decode_depth'] != "") { $natent['imap_uu_decode_depth'] = $_POST['imap_uu_decode_depth']; }else{ $natent['imap_uu_decode_depth'] = "0"; } + if ($_POST['smtp_memcap'] != "") { $natent['smtp_memcap'] = $_POST['smtp_memcap']; }else{ $natent['smtp_memcap'] = "838860"; } + if ($_POST['smtp_max_mime_mem'] != "") { $natent['smtp_max_mime_mem'] = $_POST['smtp_max_mime_mem']; }else{ $natent['smtp_max_mime_mem'] = "838860"; } + if ($_POST['smtp_b64_decode_depth'] != "") { $natent['smtp_b64_decode_depth'] = $_POST['smtp_b64_decode_depth']; }else{ $natent['smtp_b64_decode_depth'] = "0"; } + if ($_POST['smtp_qp_decode_depth'] != "") { $natent['smtp_qp_decode_depth'] = $_POST['smtp_qp_decode_depth']; }else{ $natent['smtp_qp_decode_depth'] = "0"; } + if ($_POST['smtp_bitenc_decode_depth'] != "") { $natent['smtp_bitenc_decode_depth'] = $_POST['smtp_bitenc_decode_depth']; }else{ $natent['smtp_bitenc_decode_depth'] = "0"; } + if ($_POST['smtp_uu_decode_depth'] != "") { $natent['smtp_uu_decode_depth'] = $_POST['smtp_uu_decode_depth']; }else{ $natent['smtp_uu_decode_depth'] = "0"; } + if ($_POST['smtp_email_hdrs_log_depth'] != "") { $natent['smtp_email_hdrs_log_depth'] = $_POST['smtp_email_hdrs_log_depth']; }else{ $natent['smtp_email_hdrs_log_depth'] = "1464"; } + if ($_POST['sf_appid_mem_cap'] != "") { $natent['sf_appid_mem_cap'] = $_POST['sf_appid_mem_cap']; }else{ $natent['sf_appid_mem_cap'] = "256"; } + if ($_POST['sf_appid_stats_period'] != "") { $natent['sf_appid_stats_period'] = $_POST['sf_appid_stats_period']; }else{ $natent['sf_appid_stats_period'] = "300"; } // Set SDF inspection types $natent['sdf_alert_data_type'] = implode(",",$_POST['sdf_alert_data_type']); @@ -352,6 +510,13 @@ if ($_POST['save']) { $natent['ftp_telnet_normalize'] = $_POST['ftp_telnet_normalize'] ? 'on' : 'off'; $natent['ftp_telnet_detect_anomalies'] = $_POST['ftp_telnet_detect_anomalies'] ? 'on' : 'off'; $natent['smtp_preprocessor'] = $_POST['smtp_preprocessor'] ? 'on' : 'off'; + $natent['smtp_ignore_data'] = $_POST['smtp_ignore_data'] ? 'on' : 'off'; + $natent['smtp_ignore_tls_data'] = $_POST['smtp_ignore_tls_data'] ? 'on' : 'off'; + $natent['smtp_log_mail_from'] = $_POST['smtp_log_mail_from'] ? 'on' : 'off'; + $natent['smtp_log_rcpt_to'] = $_POST['smtp_log_rcpt_to'] ? 'on' : 'off'; + $natent['smtp_log_filename'] = $_POST['smtp_log_filename'] ? 'on' : 'off'; + $natent['smtp_log_email_hdrs'] = $_POST['smtp_log_email_hdrs'] ? 'on' : 'off'; + $natent['sf_portscan'] = $_POST['sf_portscan'] ? 'on' : 'off'; $natent['dce_rpc_2'] = $_POST['dce_rpc_2'] ? 'on' : 'off'; $natent['dns_preprocessor'] = $_POST['dns_preprocessor'] ? 'on' : 'off'; @@ -374,6 +539,8 @@ if ($_POST['save']) { $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['appid_preproc'] = $_POST['appid_preproc'] ? 'on' : 'off'; + $natent['sf_appid_statslog'] = $_POST['sf_appid_statslog'] ? 'on' : 'off'; if (isset($id) && isset($a_nat[$id])) { $a_nat[$id] = $natent; @@ -385,7 +552,9 @@ if ($_POST['save']) { /* rules for this interface. */ /*************************************************/ $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($natent); + conf_mount_ro(); $rebuild_rules = false; /* If 'preproc_auto_rule_disable' is off, then clear log file */ @@ -497,7 +666,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td>'; @@ -510,6 +681,7 @@ if ($savemsg) { $tab_array[] = array($menu_iface . gettext("Preprocs"), true, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -529,14 +701,14 @@ if ($savemsg) { <tr> <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 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"; ?>> + 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> @@ -553,7 +725,7 @@ if ($savemsg) { <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 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"> @@ -583,7 +755,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> <td width="78%" class="vtable"><input name="host_attribute_table" type="checkbox" value="on" id="host_attribute_table" onclick="host_attribute_table_enable_change();" - <?php if ($pconfig['host_attribute_table']=="on") echo "checked"; ?>> + <?php if ($pconfig['host_attribute_table']=="on") echo "checked"; ?>/> <?php echo gettext("Use a Host Attribute Table file to auto-configure applicable preprocessors. " . "Default is "); ?><strong><?php echo gettext("Not Checked"); ?></strong>.</td> </tr> @@ -667,7 +839,7 @@ if ($savemsg) { <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" id="http_inspect" onclick="http_inspect_enable_change();" - <?php if ($pconfig['http_inspect']=="on" || empty($pconfig['http_inspect'])) echo "checked";?>> + <?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> @@ -675,7 +847,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Proxy Alert"); ?></td> <td width="78%" class="vtable"><input name="http_inspect_proxy_alert" type="checkbox" value="on" id="http_inspect_proxy_alert" - <?php if ($pconfig['http_inspect_proxy_alert']=="on") echo "checked";?>> + <?php if ($pconfig['http_inspect_proxy_alert']=="on") echo "checked";?>/> <?php echo gettext("Enable global alerting on HTTP server proxy usage. Default is ");?> <strong><?php echo gettext("Not Checked"); ?></strong>.<br/><br/><span class="red"><strong> <?php echo gettext("Note: ") . "</strong></span>" . gettext("By adding Server Configurations below and enabling " . @@ -760,7 +932,7 @@ if ($savemsg) { <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";?>> + <?php if ($pconfig['frag3_detection']=="on") echo "checked";?>/> <?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> @@ -828,14 +1000,14 @@ if ($savemsg) { <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 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 id="stream5_flushonalert_row"> <td width="22%" valign="top" class="vncell"><?php echo gettext("Flush On Alert"); ?></td> <td width="78%" class="vtable"><input name="stream5_flush_on_alert" type="checkbox" value="on" - <?php if ($pconfig['stream5_flush_on_alert']=="on") echo "checked"; ?>> + <?php if ($pconfig['stream5_flush_on_alert']=="on") echo "checked"; ?>/> <?php echo gettext("Flush a TCP stream when an alert is generated on that stream. Default is ") . "<strong>" . gettext("Not Checked") . "</strong><br/><span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . gettext("This parameter is for backwards compatibility.");?></td> @@ -979,6 +1151,53 @@ if ($savemsg) { </table> </td> </tr> + + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Application ID Detection"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> + <td width="78%" class="vtable"><input name="appid_preproc" onclick="appid_preproc_enable_change();" + type="checkbox" value="on" id="appid_preproc" + <?php if ($pconfig['appid_preproc']=="on") echo "checked"; ?>/> + <?php echo gettext("Use OpenAppID to detect various applications. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>"; ?>.</td> + </tr> + <tbody id="appid_rows"> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td class="vtable"> + <input name="sf_appid_mem_cap" type="text" class="formfld unknown" id="sf_appid_mem_cap" size="9" + value="<?=htmlspecialchars($pconfig['sf_appid_mem_cap']);?>"> + <?php echo gettext("Memory for App ID structures. Min is ") . "<strong>" . gettext("32") . "</strong>" . + gettext(" (32 MB) and Max is ") . "<strong>" . gettext("3000") . "</strong>" . + gettext(" (3 GB) bytes.");?><br/> + <?php echo gettext("The memory cap in megabytes used by AppID internal structures " . + "in RAM. Default value is ") . "<strong>" . gettext("256") . "</strong>" . gettext(" (256 MB)."); ?><br/> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("AppID Stats Logging"); ?></td> + <td width="78%" class="vtable"> + <input name="sf_appid_statslog" type="checkbox" value="on" id="sf_appid_statslog" + <?php if ($pconfig['sf_appid_statslog']=="on") echo "checked"; ?>/> + <?php echo gettext("Enable OpenAppID statistics logging. Default is ") . + "<strong>" . gettext("Checked") . "</strong>" . gettext("."); ?><br/><br/> + <span class="red"><strong><?php echo gettext("Note: ") . "</strong></span>" . gettext("log size and retention limits for AppID Stats Logging") . + gettext(" can be set on the ") . "<a href='/snort/snort_log_mgmt.php'>" . gettext("LOG MGMT") . "</a>" . gettext(" tab.");?> </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("AppID Stats Period"); ?></td> + <td class="vtable"> + <input name="sf_appid_stats_period" type="text" class="formfld unknown" id="sf_appid_stats_period" size="9" + value="<?=htmlspecialchars($pconfig['sf_appid_stats_period']);?>"> + <?php echo gettext("Bucket size in seconds for AppID stats. Min is ") . "<strong>" . gettext("60") . "</strong>" . + gettext(" (1 minute) and Max is ") . "<strong>" . gettext("3600") . "</strong>" . gettext(" (1 hour).");?><br/> + <?php echo gettext("The bucket size in seconds used to collecxt AppID statistics. " . + "Default value is ") . "<strong>" . gettext("300") . "</strong>" . gettext(" (5 minutes)."); ?><br/> + </td> + </tr> + </tbody> <tr> <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Portscan Detection"); ?></td> </tr> @@ -986,7 +1205,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></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 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> @@ -1094,7 +1313,7 @@ if ($savemsg) { value="<?=$pconfig['pscan_ignore_scanners'];?>" title="<?=trim(filter_expand_alias($pconfig['pscan_ignore_scanners']));?>"> <?php echo gettext("Leave blank for default. ") . gettext("Default value is ") . "<strong>" . gettext("\$HOME_NET") . "</strong>"; ?>.</td> <td class="vexpl" align="right"> - <input type="button" class="formbtns" value="Aliases" onclick="parent.location='snort_select_alias.php?id=<?=$id;?>&type=host|network&varname=pscan_ignore_scanners&act=import&multi_ip=yes&returl=<?=urlencode($_SERVER['PHP_SELF']);?>'" + <input type="button" class="formbtns" value="Aliases" onclick="selectAlias();" title="<?php echo gettext("Select an existing IP alias");?>"/></td> </tr> <tr> @@ -1131,14 +1350,14 @@ if ($savemsg) { <tr id="ftp_telnet_row_encrypted_check"> <td width="22%" valign="top" class="vncell"><?php echo gettext("Check Encrypted Traffic"); ?></td> <td width="78%" class="vtable"><input name="ftp_telnet_check_encrypted" type="checkbox" value="on" - <?php if ($pconfig['ftp_telnet_check_encrypted']=="on") echo "checked"; ?>> + <?php if ($pconfig['ftp_telnet_check_encrypted']=="on") echo "checked"; ?>/> <?php echo gettext("Continue to check an encrypted session for subsequent command to cease encryption. Default is ") . "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr id="ftp_telnet_row_encrypted_alert"> <td width="22%" valign="top" class="vncell"><?php echo gettext("Alert on Encrypted Commands"); ?></td> <td width="78%" class="vtable"><input name="ftp_telnet_alert_encrypted" type="checkbox" value="on" - <?php if ($pconfig['ftp_telnet_alert_encrypted']=="on") echo "checked"; ?>> + <?php if ($pconfig['ftp_telnet_alert_encrypted']=="on") echo "checked"; ?>/> <?php echo gettext("Alert on encrypted FTP and Telnet command channels. Default is ") . "<strong>" . gettext("Not Checked") . "</strong>"; ?>.</td> </tr> @@ -1148,14 +1367,14 @@ if ($savemsg) { <tr id="ftp_telnet_row_normalize"> <td width="22%" valign="top" class="vncell"><?php echo gettext("Normalization"); ?></td> <td width="78%" class="vtable"><input name="ftp_telnet_normalize" type="checkbox" value="on" - <?php if ($pconfig['ftp_telnet_normalize']=="on") echo "checked"; ?>> + <?php if ($pconfig['ftp_telnet_normalize']=="on") echo "checked"; ?>/> <?php echo gettext("Normalize Telnet traffic by eliminating Telnet escape sequences. Default is ") . "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr id="ftp_telnet_row_detect_anomalies"> <td width="22%" valign="top" class="vncell"><?php echo gettext("Detect Anomalies"); ?></td> <td width="78%" class="vtable"><input name="ftp_telnet_detect_anomalies" type="checkbox" value="on" - <?php if ($pconfig['ftp_telnet_detect_anomalies']=="on") echo "checked"; ?>> + <?php if ($pconfig['ftp_telnet_detect_anomalies']=="on") echo "checked"; ?>/> <?php echo gettext("Alert on Telnet subnegotiation begin without corresponding subnegotiation end. Default is ") . "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> @@ -1267,7 +1486,7 @@ if ($savemsg) { echo "checked"; elseif ($vrt_enabled == "off") echo "disabled"; - ?>> + ?>/> <?php echo gettext("Sensitive data searches for credit card numbers, 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 ") . @@ -1302,72 +1521,338 @@ if ($savemsg) { <input name="sdf_mask_output" type="checkbox" value="on" <?php if ($pconfig['sdf_mask_output'] == "on") echo "checked"; - ?>> + ?>/> <?php echo gettext("Replace all but last 4 digits of PII with \"X\"s on credit card and Social Security Numbers. ") . gettext("Default is ") . "<strong>" . gettext("Not Checked") . "</strong>."; ?> </td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Preprocessors"); ?></td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("POP3 Decoder Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable 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"; ?>> - <?php echo gettext("Normalize/Decode RPC traffic and detects Back Orifice traffic on the network. Default is ") . + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable POP3 Decoder"); ?></td> + <td width="78%" class="vtable"><input name="pop_preproc" type="checkbox" value="on" + <?php if ($pconfig['pop_preproc']=="on") echo "checked"; ?> onclick="pop_enable_change();"/> + <?php echo gettext("Normalize/Decode POP3 protocol for enforcement and buffer overflows. Default is ") . "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> + <tbody id="pop_setting_rows"> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable POP Normalizer"); ?></td> - <td width="78%" class="vtable"><input name="pop_preproc" type="checkbox" value="on" - <?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> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td width="78%" class="vtable"> + <input name="pop_memcap" type="text" class="formfld unknown" id="pop_memcap" size="9" + value="<?=htmlspecialchars($pconfig['pop_memcap']);?>"> + <?php echo gettext("Maximum memory in bytes to use for decoding attachments. ") . + gettext("Default is ") . "<strong>" . gettext("838860") . "</strong>" . + gettext(" bytes."); ?><br/><br/> + <?php echo gettext("The minimum value is ") . "<strong>" . gettext("3276") . "</strong>" . gettext(" bytes and the maximum is ") . + "<strong>" . gettext("100 MB") . "</strong>" . gettext(" (104857600). An IMAP preprocessor alert with sid 3 is ") . + gettext("generated (when enabled) if this limit is exceeded."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Base64 Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="pop_b64_decode_depth" type="text" class="formfld unknown" id="pop_b64_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['pop_b64_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode base64 encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the base64 decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of base64 encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of base64 MIME attachments, and applies per attachment. A POP preprocessor alert with sid 4 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Quoted Printable Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="pop_qp_decode_depth" type="text" class="formfld unknown" id="pop_qp_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['pop_qp_decode_depth']);?>"> + <?php echo gettext("Byte depth to decode Quoted Printable (QP) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the QP decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of QP encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of QP MIME attachments, and applies per attachment. A POP preprocessor alert with sid 5 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable IMAP Normalizer"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Non-Encoded MIME Extraction Depth"); ?></td> + <td width="78%" class="vtable"><input name="pop_bitenc_decode_depth" type="text" class="formfld unknown" id="pop_bitenc_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['pop_bitenc_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to extract non-encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the extraction of non-encoded MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the extraction of non-encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the extraction of non-encoded MIME attachments, and applies per attachment.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Unix-to-Unix Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="pop_uu_decode_depth" type="text" class="formfld unknown" id="pop_uu_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['pop_uu_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode Unix-to-Unix (UU) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the UU decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of UU encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of UU MIME attachments, and applies per attachment. A POP preprocessor alert with sid 7 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + </tbody> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("IMAP Decoder Settings"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable IMAP Decoder"); ?></td> <td width="78%" class="vtable"><input name="imap_preproc" type="checkbox" value="on" - <?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> + <?php if ($pconfig['imap_preproc']=="on") echo "checked"; ?> onclick="imap_enable_change();"/> + <?php echo gettext("Normalize/Decode IMAP protocol for enforcement and buffer overflows. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?> + </td> + </tr> + <tbody id="imap_setting_rows"> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td width="78%" class="vtable"> + <input name="imap_memcap" type="text" class="formfld unknown" id="imap_memcap" size="9" + value="<?=htmlspecialchars($pconfig['imap_memcap']);?>"> + <?php echo gettext("Maximum memory in bytes to use for decoding attachments. ") . + gettext("Default is ") . "<strong>" . gettext("838860") . "</strong>" . + gettext(" bytes."); ?><br/><br/> + <?php echo gettext("The minimum value is ") . "<strong>" . gettext("3276") . "</strong>" . gettext(" bytes and the maximum is ") . + "<strong>" . gettext("100 MB") . "</strong>" . gettext(" (104857600). An IMAP preprocessor alert with sid 3 is ") . + gettext("generated (when enabled) if this limit is exceeded."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Base64 Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="imap_b64_decode_depth" type="text" class="formfld unknown" id="imap_b64_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['imap_b64_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode base64 encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the base64 decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of base64 encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of base64 MIME attachments, and applies per attachment. An IMAP preprocessor alert with sid 4 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Quoted Printable Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="imap_qp_decode_depth" type="text" class="formfld unknown" id="imap_qp_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['imap_qp_decode_depth']);?>"> + <?php echo gettext("Byte depth to decode Quoted Printable (QP) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the QP decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of QP encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of QP MIME attachments, and applies per attachment. An IMAP preprocessor alert with sid 5 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Non-Encoded MIME Extraction Depth"); ?></td> + <td width="78%" class="vtable"><input name="imap_bitenc_decode_depth" type="text" class="formfld unknown" id="imap_bitenc_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['imap_bitenc_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to extract non-encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the extraction of non-encoded MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the extraction of non-encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the extraction of non-encoded MIME attachments, and applies per attachment.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Unix-to-Unix Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="imap_uu_decode_depth" type="text" class="formfld unknown" id="imap_uu_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['imap_uu_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode Unix-to-Unix (UU) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the UU decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of UU encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of UU MIME attachments, and applies per attachment. An IMAP preprocessor alert with sid 7 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + </tbody> + + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("SMTP Decoder Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable SMTP Normalizer"); ?></td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable SMTP Decoder"); ?></td> <td width="78%" class="vtable"><input name="smtp_preprocessor" type="checkbox" value="on" - <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?>> - <?php echo gettext("Normalize/Decode SMTP protocol for enforcement and buffer overflows. Default is ") . + <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?> onclick="smtp_enable_change();"/> + <?php echo gettext("Normalize/Decode SMTP protocol for enforcement and buffer overflows. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?> + </td> + </tr> + <tbody id="smtp_setting_rows"> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Memory Cap"); ?></td> + <td width="78%" class="vtable"> + <input name="smtp_memcap" type="text" class="formfld unknown" id="smtp_memcap" size="9" + value="<?=htmlspecialchars($pconfig['smtp_memcap']);?>"/> + <?php echo gettext("Max memory in bytes used to log filename, addresses and headers. ") . + gettext("Default is ") . "<strong>" . gettext("838860") . "</strong>" . gettext(" bytes."); ?><br/><br/> + <?php echo gettext("The minimum value is ") . "<strong>" . gettext("3276") . "</strong>" . gettext(" bytes and the maximum is ") . + "<strong>" . gettext("100 MB") . "</strong>" . gettext(" (104857600). When this memcap is reached, ") . + gettext("SMTP will stop logging the filename, MAIL FROM address, RCPT TO addresses and email headers until memory becomes available."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Ignore Data"); ?></td> + <td width="78%" class="vtable"><input name="smtp_ignore_data" type="checkbox" value="on" + <?php if ($pconfig['smtp_ignore_data']=="on") echo "checked"; ?>/> + <?php echo gettext("Ignore data section of mail (except for mail headers) when processing rules. Default is ") . + "<strong>" . gettext("Not Checked") . "</strong>."; ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Ignore TLS Data"); ?></td> + <td width="78%" class="vtable"><input name="smtp_ignore_tls_data" type="checkbox" value="on" + <?php if ($pconfig['smtp_ignore_tls_data']=="on") echo "checked"; ?>/> + <?php echo gettext("Ignore TLS-encrypted data when processing rules. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log Mail From"); ?></td> + <td width="78%" class="vtable"><input name="smtp_log_mail_from" type="checkbox" value="on" + <?php if ($pconfig['smtp_log_mail_from']=="on") echo "checked"; ?>/> + <?php echo gettext("Log sender email address extracted from MAIL FROM command. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?><br/> + <span class="red"><strong><?php echo gettext("Note: "); ?></strong></span> + <?php echo gettext("this is logged only with the unified2 (Barnyard2) output enabled."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log Receipt To"); ?></td> + <td width="78%" class="vtable"><input name="smtp_log_rcpt_to" type="checkbox" value="on" + <?php if ($pconfig['smtp_log_rcpt_to']=="on") echo "checked"; ?>/> + <?php echo gettext("Log recipient email addresses extracted from RCPT TO command. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?><br/> + <span class="red"><strong><?php echo gettext("Note: "); ?></strong></span> + <?php echo gettext("this is logged only with the unified2 (Barnyard2) output enabled."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log Filename"); ?></td> + <td width="78%" class="vtable"><input name="smtp_log_filename" type="checkbox" value="on" + <?php if ($pconfig['smtp_log_filename']=="on") echo "checked"; ?>/> + <?php echo gettext("Log MIME attachment filenames extracted from Content-Disposition header. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?><br/> + <span class="red"><strong><?php echo gettext("Note: "); ?></strong></span> + <?php echo gettext("this is logged only with the unified2 (Barnyard2) output enabled."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log E-Mail Headers"); ?></td> + <td width="78%" class="vtable"><input name="smtp_log_email_hdrs" type="checkbox" value="on" + <?php if ($pconfig['smtp_log_email_hdrs']=="on") echo "checked"; ?>/> + <?php echo gettext("Log SMTP email headers extracted from SMTP data. Default is ") . + "<strong>" . gettext("Checked") . "</strong>."; ?><br/> + <span class="red"><strong><?php echo gettext("Note: "); ?></strong></span> + <?php echo gettext("this is logged only with the unified2 (Barnyard2) output enabled."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("E-Mail Headers Log Depth"); ?></td> + <td width="78%" class="vtable"> + <input name="smtp_email_hdrs_log_depth" type="text" class="formfld unknown" id="smtp_email_hdrs_log_depth" size="9" + value="<?=htmlspecialchars($pconfig['smtp_email_hdrs_log_depth']);?>"/> + <?php echo gettext("Memory in bytes to use for logging e-mail headers. ") . + gettext("Default is ") . "<strong>" . gettext("1464") . "</strong>" . gettext(" bytes."); ?><br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("0") . "</strong>" . gettext(" to ") . + "<strong>" . gettext("20480") . "</strong>" . gettext(". A value of ") . "<strong>" . gettext("0") . "</strong>" . + gettext(" will disable e-mail headers logging."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Maximum MIME Memory"); ?></td> + <td width="78%" class="vtable"> + <input name="smtp_max_mime_mem" type="text" class="formfld unknown" id="smtp_max_mime_mem" size="9" + value="<?=htmlspecialchars($pconfig['smtp_max_mime_mem']);?>"/> + <?php echo gettext("Maximum memory in bytes to use for decoding attachments. ") . + gettext("Default is ") . "<strong>" . gettext("838860") . "</strong>" . gettext(" bytes."); ?><br/><br/> + <?php echo gettext("The minimum value is ") . "<strong>" . gettext("3276") . "</strong>" . gettext(" bytes and the maximum is ") . + "<strong>" . gettext("100 MB") . "</strong>" . gettext(" (104857600)."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Base64 Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="smtp_b64_decode_depth" type="text" class="formfld unknown" id="smtp_b64_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['smtp_b64_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode base64 encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the base64 decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of base64 encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of base64 MIME attachments, and applies per attachment. An SMTP preprocessor alert with sid 10 ") . + gettext("is generated when the decoding fails.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Quoted Printable Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="smtp_qp_decode_depth" type="text" class="formfld unknown" id="smtp_qp_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['smtp_qp_decode_depth']);?>"> + <?php echo gettext("Byte depth to decode Quoted Printable (QP) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the QP decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of QP encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of QP MIME attachments, and applies per attachment. An SMTP preprocessor alert with sid 11 ") . + gettext("is generated when the decoding fails.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Non-Encoded MIME Extraction Depth"); ?></td> + <td width="78%" class="vtable"><input name="smtp_bitenc_decode_depth" type="text" class="formfld unknown" id="smtp_bitenc_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['smtp_bitenc_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to extract non-encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the extraction of non-encoded MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the extraction of non-encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the extraction of non-encoded MIME attachments, and applies per attachment.");?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Unix-to-Unix Decoding Depth"); ?></td> + <td width="78%" class="vtable"><input name="smtp_uu_decode_depth" type="text" class="formfld unknown" id="smtp_uu_decode_depth" size="9" value="<?=htmlspecialchars($pconfig['smtp_uu_decode_depth']);?>"> + <?php echo gettext("Depth in bytes to decode Unix-to-Unix (UU) encoded MIME attachments. Default is ") . "<strong>" . gettext("0") . "</strong>" . gettext(" (unlimited)");?>.<br/><br/> + <?php echo gettext("Allowable values range from ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" to ") . "<strong>" . gettext("65535") . "</strong>" . + gettext(". A value of ") . "<strong>" . gettext("-1") . "</strong>" . gettext(" turns off the UU decoding of MIME attachments. ") . + gettext("A value of ") . "<strong>" . gettext("0") . "</strong>" . gettext(" sets the decoding of UU encoded MIME attachments to unlimited. ") . + gettext("A value other than 0 or -1 restricts the decoding of UU MIME attachments, and applies per attachment. An SMTP preprocessor alert with sid 13 ") . + gettext("is generated (if enabled) when the decoding fails.");?> + </td> + </tr> + </tbody> + + + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Preprocessors"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable 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"; ?>/> + <?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 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"; ?>> + <?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 SIP Detection"); ?></td> <td width="78%" class="vtable"><input name="sip_preproc" type="checkbox" value="on" - <?php if ($pconfig['sip_preproc']=="on") echo "checked"; ?>> + <?php if ($pconfig['sip_preproc']=="on") echo "checked"; ?>/> <?php echo gettext("The SIP preprocessor decodes SIP traffic and detects vulnerabilities. Default is ") . "<strong>" . gettext("Checked") . "</strong>"; ?>.</td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable GTP Detection"); ?></td> <td width="78%" class="vtable"><input name="gtp_preproc" type="checkbox" value="on" - <?php if ($pconfig['gtp_preproc']=="on") echo "checked"; ?>> + <?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> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable SSH Detection"); ?></td> <td width="78%" class="vtable"><input name="ssh_preproc" type="checkbox" value="on" - <?php if ($pconfig['ssh_preproc']=="on") echo "checked"; ?>> + <?php if ($pconfig['ssh_preproc']=="on") echo "checked"; ?>/> <?php echo gettext("The SSH preprocessor detects various Secure Shell exploit attempts."); ?></td> </tr> <tr> <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable DNS Detection"); ?></td> <td width="78%" class="vtable"><input name="dns_preprocessor" type="checkbox" value="on" - <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?>> + <?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> @@ -1375,7 +1860,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable SSL Data"); ?></td> <td width="78%" class="vtable"> <input name="ssl_preproc" type="checkbox" value="on" - <?php if ($pconfig['ssl_preproc']=="on") echo "checked"; ?>> + <?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> @@ -1386,7 +1871,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable Modbus Detection"); ?></td> <td width="78%" class="vtable"> <input name="modbus_preproc" type="checkbox" value="on" - <?php if ($pconfig['modbus_preproc']=="on") echo "checked"; ?>> + <?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/>" . "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . gettext("If your network does not contain Modbus-enabled devices, you can leave this preprocessor disabled."); ?> @@ -1396,7 +1881,7 @@ if ($savemsg) { <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable DNP3 Detection"); ?></td> <td width="78%" class="vtable"> <input name="dnp3_preproc" type="checkbox" value="on" - <?php if ($pconfig['dnp3_preproc']=="on") echo "checked"; ?>> + <?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/>" . "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . gettext("If your network does not contain DNP3-enabled devices, you can leave this preprocessor disabled."); ?> @@ -1411,7 +1896,7 @@ if ($savemsg) { <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> + "');\""; ?>/></td> </tr> <tr> <td width="22%" valign="top"> </td> @@ -1556,12 +2041,20 @@ function http_inspect_enable_change() { var endis = !(document.iform.http_inspect.checked); document.iform.http_inspect_memcap.disabled=endis; - // Hide the "icmp session timeout " row if stream5_track_icmp disabled - if (endis) { - document.getElementById("httpinspect_memcap_row").style.display="none"; - document.getElementById("httpinspect_maxgzipmem_row").style.display="none"; - document.getElementById("httpinspect_proxyalert_row").style.display="none"; - document.getElementById("httpinspect_engconf_row").style.display="none"; + if (!document.iform.http_inspect.checked) { + var msg = "WARNING: Disabling the http_inspect 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 http_inspect, or CANCEL to quit."; + if (!confirm(msg)) { + document.iform.http_inspect.checked=true; + } + else { + document.getElementById("httpinspect_memcap_row").style.display="none"; + document.getElementById("httpinspect_maxgzipmem_row").style.display="none"; + document.getElementById("httpinspect_proxyalert_row").style.display="none"; + document.getElementById("httpinspect_engconf_row").style.display="none"; + } } else { document.getElementById("httpinspect_memcap_row").style.display="table-row"; @@ -1591,6 +2084,16 @@ function sf_portscan_enable_change() { } } +function appid_preproc_enable_change() { + var endis = !(document.iform.appid_preproc.checked); + + // Hide the AppID configuration rows if appid_preproc disabled + if (endis) + document.getElementById("appid_rows").style.display="none"; + else + document.getElementById("appid_rows").style.display=""; +} + function stream5_enable_change() { if (!document.iform.stream5_reassembly.checked) { var msg = "WARNING: Stream5 is a critical preprocessor, and disabling it is not recommended! "; @@ -1598,7 +2101,8 @@ function stream5_enable_change() { 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 + " GTP\t\tDNP3\t\tMODBUS\n"; + msg = msg + " APP_ID\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."; @@ -1617,6 +2121,7 @@ function stream5_enable_change() { document.iform.dns_preprocessor.checked=false; document.iform.modbus_preproc.checked=false; document.iform.dnp3_preproc.checked=false; + document.iform.appid_preproc.checked=false; document.iform.sf_portscan.checked=false; sf_portscan_enable_change(); } @@ -1692,9 +2197,40 @@ function sensitive_data_enable_change() { } } +function pop_enable_change() { + var endis = !(document.iform.pop_preproc.checked); + + // Hide POP3 configuration rows if POP preprocessor disabled + if (endis) + document.getElementById("pop_setting_rows").style.display = "none"; + else + document.getElementById("pop_setting_rows").style.display = ""; +} + +function imap_enable_change() { + var endis = !(document.iform.imap_preproc.checked); + + // Hide IMAP configuration rows if IMAP preprocessor disabled + if (endis) + document.getElementById("imap_setting_rows").style.display = "none"; + else + document.getElementById("imap_setting_rows").style.display = ""; +} + +function smtp_enable_change() { + var endis = !(document.iform.smtp_preprocessor.checked); + + // Hide SMTP configuration rows if SMTP preprocessor disabled + if (endis) + document.getElementById("smtp_setting_rows").style.display = "none"; + else + document.getElementById("smtp_setting_rows").style.display = ""; +} + function enable_change_all() { http_inspect_enable_change(); sf_portscan_enable_change(); + appid_preproc_enable_change(); // -- Enable/Disable Host Attribute Table settings -- host_attribute_table_enable_change(); @@ -1746,6 +2282,9 @@ function enable_change_all() { stream5_track_icmp_enable_change(); ftp_telnet_enable_change(); sensitive_data_enable_change(); + pop_enable_change(); + imap_enable_change(); + smtp_enable_change(); } function wopen(url, name, w, h) @@ -1763,6 +2302,29 @@ function wopen(url, name, w, h) win.focus(); } +function selectAlias() { + + var loc; + var fields = [ "sf_portscan", "pscan_protocol", "pscan_type", "pscan_sense_level", "pscan_memcap", "pscan_ignore_scanners" ]; + + // Scrape current form field values and add to + // the select alias URL as a query string. + var loc = 'snort_select_alias.php?id=<?=$id;?>&act=import&type=host|network'; + loc = loc + '&varname=pscan_ignore_scanners&multi_ip=yes'; + loc = loc + '&returl=<?=urlencode($_SERVER['PHP_SELF']);?>'; + loc = loc + '&uuid=<?=$passlist_uuid;?>'; + + // Iterate over just the specific form fields we want to pass to + // the select alias URL. + fields.forEach(function(entry) { + var tmp = $(entry).serialize(); + if (tmp.length > 0) + loc = loc + '&' + tmp; + }); + + window.parent.location = loc; +} + // Set initial state of form controls enable_change_all(); diff --git a/config/snort/snort_rules.php b/config/snort/snort_rules.php index e69152c3..b9050b35 100755 --- a/config/snort/snort_rules.php +++ b/config/snort/snort_rules.php @@ -36,6 +36,7 @@ require_once("/usr/local/pkg/snort/snort.inc"); global $g, $rebuild_rules; $snortdir = SNORTDIR; +$snortbindir = SNORT_PBI_BINDIR; $rules_map = array(); $categories = array(); $pconfig = array(); @@ -109,6 +110,29 @@ $categories[] = "custom.rules"; $categories[] = "decoder.rules"; $categories[] = "preprocessor.rules"; $categories[] = "sensitive-data.rules"; + +// Get any automatic rule category enable/disable modifications +// if auto-SID Mgmt is enabled, and adjust the available rulesets +// in the CATEGORY drop-down box as necessary. +$cat_mods = snort_sid_mgmt_auto_categories($a_rule[$id], FALSE); +foreach ($cat_mods as $k => $v) { + switch ($v) { + case 'disabled': + if (($key = array_search($k, $categories)) !== FALSE) + unset($categories[$key]); + break; + + case 'enabled': + if (!in_array($k, $categories)) + $categories[] = $k; + break; + + default: + break; + } +} + +// Add any enabled IPS-Policy and Auto-Flowbits File if (!empty($a_rule[$id]['ips_policy'])) $categories[] = "IPS Policy - " . ucfirst($a_rule[$id]['ips_policy']); if ($a_rule[$id]['autoflowbitrules'] == 'on') @@ -146,6 +170,9 @@ if ($currentruleset != 'custom.rules') { $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."); } +/* Process the current category rules through any auto SID MGMT changes if enabled */ +snort_auto_sid_mgmt($rules_map, $a_rule[$id], FALSE); + /* Load up our enablesid and disablesid arrays with enabled or disabled SIDs */ $enablesid = snort_load_sid_mods($a_rule[$id]['rule_sid_on']); $disablesid = snort_load_sid_mods($a_rule[$id]['rule_sid_off']); @@ -157,12 +184,16 @@ if ($_POST['toggle'] && is_numeric($_POST['sid']) && is_numeric($_POST['gid']) & $sid = $_POST['sid']; // See if the target SID is in our list of modified SIDs, - // and toggle it back to default if present; otherwise, - // add it to the appropriate modified SID list. - if (isset($enablesid[$gid][$sid])) + // and toggle if present; otherwise, add it to the + // appropriate modified SID list. + if (isset($enablesid[$gid][$sid])) { unset($enablesid[$gid][$sid]); - elseif (isset($disablesid[$gid][$sid])) + $disablesid[$gid][$sid] = "disablesid"; + } + elseif (isset($disablesid[$gid][$sid])) { unset($disablesid[$gid][$sid]); + $enablesid[$gid][$sid] = "enablesid"; + } else { if ($rules_map[$gid][$sid]['disabled'] == 1) $enablesid[$gid][$sid] = "enablesid"; @@ -198,6 +229,10 @@ if ($_POST['toggle'] && is_numeric($_POST['sid']) && is_numeric($_POST['gid']) & /* Update the config.xml file. */ write_config("Snort pkg: modified state for rule {$gid}:{$sid} on {$a_rule[$id]['interface']}."); + // We changed a rule state, remind user to apply the changes + mark_subsystem_dirty('snort_rules'); + + // Set a scroll-to anchor location $anchor = "rule_{$gid}_{$sid}"; } elseif ($_POST['disable_all'] && !empty($rules_map)) { @@ -237,6 +272,9 @@ elseif ($_POST['disable_all'] && !empty($rules_map)) { unset($a_rule[$id]['rule_sid_off']); write_config("Snort pkg: disabled all rules in category {$currentruleset} for {$a_rule[$id]['interface']}."); + + // We changed a rule state, remind user to apply the changes + mark_subsystem_dirty('snort_rules'); } elseif ($_POST['enable_all'] && !empty($rules_map)) { @@ -274,6 +312,9 @@ elseif ($_POST['enable_all'] && !empty($rules_map)) { unset($a_rule[$id]['rule_sid_off']); write_config("Snort pkg: enable all rules in category {$currentruleset} for {$a_rule[$id]['interface']}."); + + // We changed a rule state, remind user to apply the changes + mark_subsystem_dirty('snort_rules'); } elseif ($_POST['resetcategory'] && !empty($rules_map)) { @@ -313,6 +354,9 @@ elseif ($_POST['resetcategory'] && !empty($rules_map)) { unset($a_rule[$id]['rule_sid_off']); write_config("Snort pkg: remove enablesid/disablesid changes for category {$currentruleset} on {$a_rule[$id]['interface']}."); + + // We changed a rule state, remind user to apply the changes + mark_subsystem_dirty('snort_rules'); } elseif ($_POST['resetall'] && !empty($rules_map)) { @@ -322,31 +366,42 @@ elseif ($_POST['resetall'] && !empty($rules_map)) { /* Update the config.xml file. */ write_config("Snort pkg: remove all enablesid/disablesid changes for {$a_rule[$id]['interface']}."); + + // We changed a rule state, remind user to apply the changes + mark_subsystem_dirty('snort_rules'); } else if ($_POST['cancel']) { $pconfig['customrules'] = base64_decode($a_rule[$id]['customrules']); + clear_subsystem_dirty('snort_rules'); } elseif ($_POST['clear']) { unset($a_rule[$id]['customrules']); write_config("Snort pkg: clear all custom rules for {$a_rule[$id]['interface']}."); $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($a_rule[$id]); + conf_mount_ro(); $rebuild_rules = false; $pconfig['customrules'] = ''; + + // Sync to configured CARP slaves if any are enabled + snort_sync_on_changes(); } elseif ($_POST['save']) { $pconfig['customrules'] = $_POST['customrules']; if ($_POST['customrules']) - $a_rule[$id]['customrules'] = base64_encode($_POST['customrules']); + $a_rule[$id]['customrules'] = base64_encode(str_replace("\r\n", "\n", $_POST['customrules'])); else unset($a_rule[$id]['customrules']); write_config("Snort pkg: save modified custom rules for {$a_rule[$id]['interface']}."); $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($a_rule[$id]); + conf_mount_ro(); $rebuild_rules = false; $output = ""; $retcode = ""; - exec("/usr/local/bin/snort -T -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf 2>&1", $output, $retcode); + exec("{$snortbindir}snort -T -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf 2>&1", $output, $retcode); if (intval($retcode) != 0) { $error = ""; $start = count($output); @@ -358,9 +413,13 @@ elseif ($_POST['save']) { else { /* Soft-restart Snort to live-load new rules */ snort_reload_config($a_rule[$id]); - $savemsg = gettext("Custom rules validated successfully and have been saved to the Snort configuration files. "); - $savemsg .= gettext("Any active Snort process on this interface has been signalled to live-load the new rules."); + $savemsg = gettext("Custom rules validated successfully and any active Snort process on this interface has been signalled to live-load the new rules."); } + + clear_subsystem_dirty('snort_rules'); + + // Sync to configured CARP slaves if any are enabled + snort_sync_on_changes(); } else if ($_POST['apply']) { /* Save new configuration */ @@ -371,14 +430,24 @@ else if ($_POST['apply']) { /* rules for this interface. */ /*************************************************/ $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($a_rule[$id]); + conf_mount_ro(); $rebuild_rules = false; /* Soft-restart Snort to live-load new rules */ snort_reload_config($a_rule[$id]); + + // We have saved changes and done a soft restart, so clear "dirty" flag + clear_subsystem_dirty('snort_rules'); + + // Sync to configured CARP slaves if any are enabled + snort_sync_on_changes(); + + if (snort_is_running($snort_uuid, $if_real)) + $savemsg = gettext("Snort is 'live-reloading' the new rule set."); } -require_once("guiconfig.inc"); include_once("head.inc"); $if_friendly = convert_friendly_interface_to_friendly_descr($a_rule[$id]['interface']); @@ -405,6 +474,11 @@ if ($savemsg) { <input type='hidden' name='openruleset' id='openruleset' value='<?=$currentruleset;?>'/> <input type='hidden' name='sid' id='sid' value=''/> <input type='hidden' name='gid' id='gid' value=''/> + +<?php if (is_subsystem_dirty('snort_rules')): ?><p> +<?php print_info_box_np(gettext("A change has been made to a rule state.") . "<br/>" . gettext("Click APPLY when finished to send the changes to the running configuration."));?> +<?php endif; ?> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -417,7 +491,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array,true); echo '</td></tr>'; echo '<tr><td class="tabnavtbl">'; @@ -430,6 +506,7 @@ if ($savemsg) { $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -564,8 +641,8 @@ if ($savemsg) { <col axis="string"> </colgroup> <thead> - <tr> - <th class="list"> </th> + <tr class="sortableHeaderRowIdentifier"> + <th class="list sorttable_nosort"> </th> <th class="listhdrr"><?php echo gettext("GID"); ?></th> <th class="listhdrr"><?php echo gettext("SID"); ?></th> <th class="listhdrr"><?php echo gettext("Proto"); ?></th> @@ -578,18 +655,36 @@ if ($savemsg) { </thead> <tbody> <?php - $counter = $enable_cnt = $disable_cnt = 0; + $counter = $enable_cnt = $disable_cnt = $user_enable_cnt = $user_disable_cnt = $managed_count = 0; foreach ($rules_map as $k1 => $rulem) { foreach ($rulem as $k2 => $v) { $sid = $k2; $gid = $k1; - - if (isset($disablesid[$gid][$sid])) { + $ruleset = $currentruleset; + $style = ""; + + if ($v['managed'] == 1) { + if ($v['disabled'] == 1) { + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $style= "style=\"opacity: 0.4; filter: alpha(opacity=40);\""; + $title = gettext("Auto-disabled by settings on SID Mgmt tab"); + } + else { + $textss = $textse = ""; + $ruleset = "suricata.rules"; + $title = gettext("Auto-managed by settings on SID Mgmt tab"); + } + $iconb = "icon_advanced.gif"; + $managed_count++; + } + elseif (isset($disablesid[$gid][$sid])) { $textss = "<span class=\"gray\">"; $textse = "</span>"; $iconb = "icon_reject_d.gif"; $disable_cnt++; - $title = gettext("Disabled by user. Click to toggle to default state"); + $user_disable_cnt++; + $title = gettext("Disabled by user. Click to toggle to enabled state"); } elseif (($v['disabled'] == 1) && (!isset($enablesid[$gid][$sid]))) { $textss = "<span class=\"gray\">"; @@ -602,7 +697,8 @@ if ($savemsg) { $textss = $textse = ""; $iconb = "icon_reject.gif"; $enable_cnt++; - $title = gettext("Enabled by user. Click to toggle to default state"); + $user_enable_cnt++; + $title = gettext("Enabled by user. Click to toggle to disabled state"); } else { $textss = $textse = ""; @@ -632,12 +728,18 @@ if ($savemsg) { $message = snort_get_msg($v['rule']); // description field $sid_tooltip = gettext("View the raw text for this rule"); - echo "<tr><td class=\"listt\" align=\"left\" valign=\"middle\" sorttable_customkey=\"\">{$textss} - <a id=\"rule_{$gid}_{$sid}\" href=''><input type=\"image\" onClick=\"document.getElementById('sid').value='{$sid}'; - document.getElementById('gid').value='{$gid}';\" - src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" - title='{$title}' name=\"toggle[]\"/></a>{$textse} - </td> + echo "<tr><td class=\"listt\" style=\"align:center;\" valign=\"middle\">{$textss}"; + if ($v['managed'] == 1) { + echo "<img {$style} src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" + title='{$title}'/>{$textse}"; + } + else { + echo "<a id=\"rule_{$gid}_{$sid}\" href='#'><input type=\"image\" onClick=\"document.getElementById('sid').value='{$sid}'; + document.getElementById('gid').value='{$gid}';\" + src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" + title='{$title}' name=\"toggle[]\"/></a>{$textse}"; + } + echo "</td> <td class=\"listr\" align=\"center\" ondblclick=\"wopen('snort_rules_edit.php?id={$id}&openruleset={$currentruleset}&sid={$sid}&gid={$gid}','FileViewer',800,600);\"> {$textss}{$gid}{$textse} </td> @@ -687,8 +789,8 @@ if ($savemsg) { <col align="left" axis="string"> </colgroup> <thead> - <tr> - <th class="list"> </th> + <tr class="sortableHeaderRowIdentifier"> + <th class="list" sorttable_nosort> </th> <th class="listhdrr"><?php echo gettext("GID"); ?></th> <th class="listhdrr"><?php echo gettext("SID"); ?></th> <th class="listhdrr"><?php echo gettext("Classification"); ?></th> @@ -698,17 +800,36 @@ if ($savemsg) { </thead> <tbody> <?php - $counter = $enable_cnt = $disable_cnt = 0; + $counter = $enable_cnt = $disable_cnt = $user_enable_cnt = $user_disable_cnt = $managed_count = 0; foreach ($rules_map as $k1 => $rulem) { foreach ($rulem as $k2 => $v) { + $ruleset = $currentruleset; + $style = ""; $sid = snort_get_sid($v['rule']); $gid = snort_get_gid($v['rule']); - if (isset($disablesid[$gid][$sid])) { + + if ($v['managed'] == 1) { + if ($v['disabled'] == 1) { + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $style= "style=\"opacity: 0.4; filter: alpha(opacity=40);\""; + $title = gettext("Auto-disabled by settings on SID Mgmt tab"); + } + else { + $textss = $textse = ""; + $ruleset = "suricata.rules"; + $title = gettext("Auto-managed by settings on SID Mgmt tab"); + } + $iconb = "icon_advanced.gif"; + $managed_count++; + } + elseif (isset($disablesid[$gid][$sid])) { $textss = "<span class=\"gray\">"; $textse = "</span>"; $iconb = "icon_reject_d.gif"; $disable_cnt++; - $title = gettext("Disabled by user. Click to toggle to default state"); + $user_disable_cnt++; + $title = gettext("Disabled by user. Click to toggle to enabled state"); } elseif (($v['disabled'] == 1) && (!isset($enablesid[$gid][$sid]))) { $textss = "<span class=\"gray\">"; @@ -721,7 +842,8 @@ if ($savemsg) { $textss = $textse = ""; $iconb = "icon_reject.gif"; $enable_cnt++; - $title = gettext("Enabled by user. Click to toggle to default state"); + $user_enable_cnt++; + $title = gettext("Enabled by user. Click to toggle to disabled state"); } else { $textss = $textse = ""; @@ -741,12 +863,18 @@ if ($savemsg) { else $policy = "none"; - echo "<tr><td class=\"listt\" align=\"left\" valign=\"middle\" sorttable_customkey=\"\">{$textss} - <input type=\"image\" onClick=\"document.getElementById('sid').value='{$sid}'; - document.getElementById('gid').value='{$gid}';\" - src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" - title='{$title}' name=\"toggle[]\"/>{$textse} - </td> + echo "<tr><td class=\"listt\" style=\"align:center;\" valign=\"middle\">{$textss}"; + if ($v['managed'] == 1) { + echo "<img {$style} src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" + title='{$title}'/>{$textse}"; + } + else { + echo "<a id=\"rule_{$gid}_{$sid}\" href='#'><input type=\"image\" onClick=\"document.getElementById('sid').value='{$sid}'; + document.getElementById('gid').value='{$gid}';\" + src=\"../themes/{$g['theme']}/images/icons/{$iconb}\" width=\"11\" height=\"11\" border=\"0\" + title='{$title}' name=\"toggle[]\"/></a>{$textse}"; + } + echo "</td> <td class=\"listr\" align=\"center\" ondblclick=\"wopen('snort_rules_edit.php?id={$id}&openruleset={$currentruleset}&sid={$sid}&gid={$gid}','FileViewer',800,600);\"> {$textss}{$gid}{$textse} </td> @@ -788,7 +916,10 @@ if ($savemsg) { <strong><?php echo gettext("--- Category Rules Summary ---") . "</strong><br/>" . gettext("Total Rules: {$counter}") . " " . gettext("Enabled: {$enable_cnt}") . " " . - gettext("Disabled: {$disable_cnt}"); ?></td> + gettext("Disabled: {$disable_cnt}") . " " . + gettext("User Enabled: {$user_enable_cnt}") . " " . + gettext("User Disabled: {$user_disable_cnt}") . " " . + gettext("Auto-Managed: {$managed_count}"); ?></td> </tr> <tr> <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" @@ -810,6 +941,18 @@ if ($savemsg) { width="11" height="11"></td> <td nowrap><?php echo gettext("Rule changed to Disabled by user"); ?></td> </tr> + <?php if (!empty($cat_mods)): ?> + <tr> + <td width="16"><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_advanced.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule auto-enabled by files configured on SID Mgmt tab"); ?></td> + </tr> + <tr> + <td width="16"><img style="opacity: 0.4; filter: alpha(opacity=40);" src="../themes/<?= $g['theme']; ?>/images/icons/icon_advanced.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule auto-disabled by files configured on SID Mgmt tab"); ?></td> + </tr> + <?php endif; ?> </table> </td> </tr> diff --git a/config/snort/snort_rules_flowbits.php b/config/snort/snort_rules_flowbits.php index daf1c4ef..fff7a13c 100644 --- a/config/snort/snort_rules_flowbits.php +++ b/config/snort/snort_rules_flowbits.php @@ -53,7 +53,7 @@ if (is_null($id)) { // Set who called us so we can return to the correct page with // the RETURN ('cancel') button. -if ($_POST['referrer']) +if (isset($_POST['referrer']) && strpos($_POST['referrer'], '://'.$_SERVER['SERVER_NAME'].'/') !== FALSE) $referrer = $_POST['referrer']; else $referrer = $_SERVER['HTTP_REFERER']; @@ -127,7 +127,9 @@ if ($_POST['addsuppress'] && is_numeric($_POST['sid']) && is_numeric($_POST['gid if ($found_list) { write_config("Snort pkg: modified Suppress List for {$a_nat[$id]['interface']}."); $rebuild_rules = false; + conf_mount_rw(); sync_snort_package_config(); + conf_mount_ro(); snort_reload_config($a_nat[$id]); $savemsg = gettext("An entry to suppress the Alert for 'gen_id {$_POST['gid']}, sig_id {$_POST['sid']}' has been added to Suppress List '{$a_nat[$id]['suppresslistname']}'."); } @@ -216,7 +218,7 @@ if ($savemsg) <col axis="string"> </colgroup> <thead> - <tr> + <tr class="sortableHeaderRowIdentifier"> <th class="listhdrr" axis="number"><?php echo gettext("SID"); ?></th> <th class="listhdrr" axis="string"><?php echo gettext("Proto"); ?></th> <th class="listhdrr" axis="string"><?php echo gettext("Source"); ?></th> @@ -263,7 +265,7 @@ if ($savemsg) // Use "echo" to write the table HTML row-by-row. echo "<tr>" . - "<td class=\"listr\" sorttable_customkey=\"{$sid}\">{$sid} {$supplink}</td>" . + "<td class=\"listr\" style=\"sorttable_customkey:{$sid};\" sorttable_customkey=\"{$sid}\">{$sid} {$supplink}</td>" . "<td class=\"listr\" style=\"text-align:center;\">{$protocol}</td>" . "<td class=\"listr\" style=\"overflow: hidden; text-overflow: ellipsis; text-align:center;\" nowrap><span title=\"{$rule_content[2]}\">{$source}</span></td>" . "<td class=\"listr\" style=\"overflow: hidden; text-overflow: ellipsis; text-align:center;\" nowrap><span title=\"{$rule_content[5]}\">{$destination}</span></td>" . diff --git a/config/snort/snort_rulesets.php b/config/snort/snort_rulesets.php index 79365f5f..c29b1810 100755 --- a/config/snort/snort_rulesets.php +++ b/config/snort/snort_rulesets.php @@ -57,8 +57,11 @@ if (isset($id) && $a_nat[$id]) { $pconfig['enable'] = $a_nat[$id]['enable']; $pconfig['interface'] = $a_nat[$id]['interface']; $pconfig['rulesets'] = $a_nat[$id]['rulesets']; - $pconfig['autoflowbitrules'] = $a_nat[$id]['autoflowbitrules']; - $pconfig['ips_policy_enable'] = $a_nat[$id]['ips_policy_enable']; + if (empty($a_nat[$id]['autoflowbitrules'])) + $pconfig['autoflowbitrules'] = 'on'; + else + $pconfig['autoflowbitrules'] = $a_nat[$id]['autoflowbitrules'] == 'on' ? 'on' : 'off';; + $pconfig['ips_policy_enable'] = $a_nat[$id]['ips_policy_enable'] == 'on' ? 'on' : 'off';; $pconfig['ips_policy'] = $a_nat[$id]['ips_policy']; } @@ -93,17 +96,6 @@ if (!file_exists("{$snortdir}/rules/" . GPL_FILE_PREFIX . "community.rules")) 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}") && - 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"; -} -else - $btn_view_flowb_rules = " disabled"; - // If a Snort VRT policy is enabled and selected, remove all Snort VRT // rules from the configured rule sets to allow automatic selection. if ($a_nat[$id]['ips_policy_enable'] == 'on') { @@ -150,7 +142,7 @@ if ($_POST["save"]) { else { $a_nat[$id]['autoflowbitrules'] = 'off'; if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}")) - @unlink("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}"); + unlink_if_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$flowbit_rules_file}"); } write_config("Snort pkg: save enabled rule categories for {$a_nat[$id]['interface']}."); @@ -160,7 +152,9 @@ if ($_POST["save"]) { /* rules for this interface. */ /*************************************************/ $rebuild_rules = true; + conf_mount_rw(); snort_generate_conf($a_nat[$id]); + conf_mount_ro(); $rebuild_rules = false; /* Soft-restart Snort to live-load new rules */ @@ -170,6 +164,9 @@ if ($_POST["save"]) { $enabled_rulesets_array = explode("||", $enabled_items); if (snort_is_running($snort_uuid, $if_real)) $savemsg = gettext("Snort is 'live-reloading' the new rule set."); + + // Sync to configured CARP slaves if any are enabled + snort_sync_on_changes(); } if ($_POST['unselectall']) { @@ -190,13 +187,26 @@ if ($_POST['unselectall']) { $enabled_rulesets_array = array(); $savemsg = gettext("All rule categories have been de-selected. "); - if ($a_nat[$id]['ips_policy_enable'] = 'on') + if ($pconfig['ips_policy_enable'] == 'on') $savemsg .= gettext("Only the rules included in the selected IPS Policy will be used."); else $savemsg .= gettext("There currently are no inspection rules enabled for this Snort instance!"); } if ($_POST['selectall']) { + if ($_POST['ips_policy_enable'] == "on") { + $a_nat[$id]['ips_policy_enable'] = 'on'; + $a_nat[$id]['ips_policy'] = $_POST['ips_policy']; + } + else { + $a_nat[$id]['ips_policy_enable'] = 'off'; + unset($a_nat[$id]['ips_policy']); + } + + $pconfig['autoflowbits'] = $_POST['autoflowbits']; + $pconfig['ips_policy_enable'] = $_POST['ips_policy_enable']; + $pconfig['ips_policy'] = $_POST['ips_policy']; + $enabled_rulesets_array = array(); if ($emergingdownload == 'on') { @@ -224,6 +234,22 @@ if ($_POST['selectall']) { } } +// Get any automatic rule category enable/disable modifications +// if auto-SID Mgmt is enabled. +$cat_mods = snort_sid_mgmt_auto_categories($a_nat[$id], FALSE); + +// Enable the VIEW button for auto-flowbits file if we have a valid flowbits file +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) { + $btn_view_flowb_rules = " title=\"" . gettext("View flowbit-required rules") . "\""; + } + else + $btn_view_flowb_rules = " disabled"; +} +else + $btn_view_flowb_rules = " disabled"; + $if_friendly = convert_friendly_interface_to_friendly_descr($a_nat[$id]['interface']); $pgtitle = gettext("Snort: Interface {$if_friendly} - Categories"); include_once("head.inc"); @@ -259,7 +285,9 @@ if ($savemsg) { $tab_array[5] = array(gettext("Pass Lists"), false, "/snort/snort_passlist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); - $tab_array[8] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + $tab_array[8] = array(gettext("SID Mgmt"), false, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); display_top_tabs($tab_array, true); echo '</td></tr>'; echo '<tr><td class="tabnavtbl">'; @@ -272,6 +300,7 @@ if ($savemsg) { $tab_array[] = array($menu_iface . gettext("Preprocs"), false, "/snort/snort_preprocessors.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); $tab_array[] = array($menu_iface . gettext("IP Rep"), false, "/snort/snort_ip_reputation.php?id={$id}"); + $tab_array[] = array($menu_iface . gettext("Logs"), false, "/snort/snort_interface_logs.php?id={$id}"); display_top_tabs($tab_array, true); ?> </td></tr> @@ -316,7 +345,7 @@ if ($savemsg) { <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" || empty($a_nat[$id]['autoflowbitrules'])) echo "checked"; ?>/> + <?php if ($pconfig['autoflowbitrules'] == "on") 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> @@ -342,21 +371,21 @@ if ($savemsg) { </td> </tr> <tr> - <td colspan="6" class="listtopic"><?php echo gettext("Snort IPS Policy selection"); ?><br/></td> + <td colspan="6" class="listtopic"><?php echo gettext("Snort VRT IPS Policy selection"); ?><br/></td> </tr> <tr> <td colspan="6" valign="center" class="listn"> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <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()"/> <span class="vexpl"> + <td width="85%"><input name="ips_policy_enable" id="ips_policy_enable" type="checkbox" value="on" <?php if ($pconfig['ips_policy_enable'] == "on") echo "checked "; ?> + <?php if ($snortdownload == "off") echo "disabled " ?> onClick="enable_change()"/> <span class="vexpl"> <?php echo gettext("If checked, Snort will use rules from one of three pre-defined IPS policies."); ?></span></td> </tr> <tr> <td width="15%" class="vncell" id="ips_col1"> </td> <td width="85%" class="vtable" id="ips_col2"> - <?php echo "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . gettext("You must be using the Snort VRT rules to use this option."); ?> + <?php echo "<span class=\"red\"><strong>" . gettext("Note: ") . "</strong></span>" . gettext("You must enable download of the Snort VRT rules to enable and use this option."); ?> <?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/></td> @@ -387,14 +416,25 @@ if ($savemsg) { </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 categories to enforcing rules"); ?>"/></td> - <td valign="middle"><input value="Unselect All" class="formbtns" type="submit" name="unselectall" id="unselectall" title="<?php echo gettext("Remove categories all from enforcing rules"); ?>"/></td> - <td valign="middle"><input value=" Save " class="formbtns" type="submit" name="save" id="save" 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> + <table width="95%" style="margin-left: auto; margin-right: auto;" border="0" cellpadding="2" cellspacing="0"> + <tbody> + <tr height="32px"> + <td style="vertical-align: middle;"><input value="Select All" class="formbtns" type="submit" name="selectall" id="selectall" title="<?php echo gettext("Add all to enforcing rules"); ?>"/></td> + <td style="vertical-align: middle;"><input value="Unselect All" class="formbtns" type="submit" name="unselectall" id="unselectall" title="<?php echo gettext("Remove all from enforcing rules"); ?>"/></td> + <td style="vertical-align: middle;"><input value=" Save " class="formbtns" type="submit" name="save" id="save" title="<?php echo gettext("Save changes to enforcing rules and rebuild"); ?>"/></td> + <td style="vertical-align: middle;"><span class="vexpl"><?php echo gettext("Click to save changes and auto-resolve flowbit rules (if option is selected above)"); ?></span></td> + </tr> + <?php if (!empty($cat_mods)): ?> + <tr height="20px"> + <td colspan="4" style="vertical-align: middle;"><img style="vertical-align: text-top;" src="../themes/<?=$g['theme'];?>/images/icons/icon_advanced.gif" width="11" height="11" border="0" /> + <?=gettext("- Category is auto-enabled by SID Mgmt conf files");?> + <img style="opacity: 0.4; filter: alpha(opacity=40); vertical-align: text-top;" src="../themes/<?=$g['theme'];?>/images/icons/icon_advanced.gif" width="11" height="11" border="0" /> + <?=gettext("- Category is auto-disabled by SID Mgmt conf files");?></td> </tr> + <?php endif; ?> + </tbody> </table> + </td> </tr> <?php if ($no_community_files) $msg_community = "NOTE: Snort Community Rules have not been downloaded. Perform a Rules Update to enable them."; @@ -403,26 +443,38 @@ if ($savemsg) { $community_rules_file = GPL_FILE_PREFIX . "community.rules"; ?> <?php if ($snortcommunitydownload == 'on'): ?> - <tr id="frheader"> + <tr> <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($community_rules_file, $enabled_rulesets_array)): ?> + <?php if (isset($cat_mods[$community_rules_file])): ?> + <?php if ($cat_mods[$community_rules_file] == 'enabled') : ?> + <tr> + <td width="5%" class="listr" style="text-align: center;"> + <img src="../themes/<?=$g['theme'];?>/images/icons/icon_advanced.gif" width="11" height="11" border="0" title="<?=gettext("Auto-managed by settings on SID Mgmt tab");?>" /></td> + <td colspan="5" class="listr"><a href='suricata_rules.php?id=<?=$id;?>&openruleset=<?=$community_rules_file;?>'><?=gettext("{$msg_community}");?></a></td> + </tr> + <?php else: ?> + <tr> + <td width="5%" class="listr" style="text-align: center;"> + <img style="opacity: 0.4; filter: alpha(opacity=40);" src="../themes/<?=$g['theme'];?>/images/icons/icon_advanced.gif" width="11" height="11" border="0" title="<?=gettext("Auto-managed by settings on SID Mgmt tab");?>" /></td> + <td colspan="5" class="listr"><?=gettext("{$msg_community}"); ?></td> + </tr> + <?php endif; ?> + <?php elseif (in_array($community_rules_file, $enabled_rulesets_array)): ?> <tr> - <td width="5" class="listr" align="center" valign="top"> + <td width="5%" class="listr" style="text-align: center;"> <input type="checkbox" name="toenable[]" value="<?=$community_rules_file;?>" checked="checked"/></td> - <td colspan="5" class="listr"><a href='snort_rules.php?id=<?=$id;?>&openruleset=<?=$community_rules_file;?>'><?php echo gettext("{$msg_community}"); ?></a></td> + <td colspan="5" class="listr"><a href='suricata_rules.php?id=<?=$id;?>&openruleset=<?=$community_rules_file;?>'><?php echo gettext("{$msg_community}"); ?></a></td> </tr> <?php else: ?> <tr> - <td width="5" class="listr" align="center" valign="top"> + <td width="5%" class="listr" style="text-align: center;"> <input type="checkbox" name="toenable[]" value="<?=$community_rules_file;?>" <?php if ($snortcommunitydownload == 'off') echo "disabled"; ?>/></td> <td colspan="5" class="listr"><?php echo gettext("{$msg_community}"); ?></td> </tr> - <?php endif; ?> <?php endif; ?> - <?php if ($no_emerging_files && ($emergingdownload == 'on' || $etpro == 'on')) $msg_emerging = "have not been downloaded."; else @@ -432,7 +484,7 @@ if ($savemsg) { else $msg_snort = "are not enabled."; ?> - <tr id="frheader"> + <tr> <?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: ET Open Rules');?></td> @@ -487,15 +539,28 @@ if ($savemsg) { echo "<tr>\n"; if (!empty($emergingrules[$j])) { $file = $emergingrules[$j]; - echo "<td width='5%' class='listr' align=\"center\" valign=\"top\">"; + echo "<td width='5%' class='listr' align=\"center\">"; if(is_array($enabled_rulesets_array)) { - if(in_array($file, $enabled_rulesets_array)) + if(in_array($file, $enabled_rulesets_array) && !isset($cat_mods[$file])) $CHECKED = " checked=\"checked\""; else $CHECKED = ""; } else $CHECKED = ""; - echo " \n<input type='checkbox' name='toenable[]' value='$file' {$CHECKED} />\n"; + if (isset($cat_mods[$file])) { + if (in_array($file, $enabled_rulesets_array)) + echo "<input type='hidden' name='toenable[]' value='{$file}' />\n"; + if ($cat_mods[$file] == 'enabled') { + $CHECKED = "enabled"; + echo " \n<img src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-enabled by settings on SID Mgmt tab") . "\" />\n"; + } + else { + echo " \n<img style=\"opacity: 0.4; filter: alpha(opacity=40);\" src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-disabled by settings on SID Mgmt tab") . "\" />\n"; + } + } + else { + echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + } echo "</td>\n"; echo "<td class='listr' width='25%' >\n"; if (empty($CHECKED)) @@ -508,17 +573,30 @@ if ($savemsg) { if (!empty($snortrules[$j])) { $file = $snortrules[$j]; - echo "<td class='listr' width='5%' align=\"center\" valign=\"top\">"; + echo "<td class='listr' width='5%' align=\"center\">"; if(is_array($enabled_rulesets_array)) { if (!empty($disable_vrt_rules)) $CHECKED = $disable_vrt_rules; - elseif(in_array($file, $enabled_rulesets_array)) + elseif(in_array($file, $enabled_rulesets_array) && !isset($cat_mods[$file])) $CHECKED = " checked=\"checked\""; else $CHECKED = ""; } else $CHECKED = ""; - echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + if (isset($cat_mods[$file])) { + if (in_array($file, $enabled_rulesets_array)) + echo "<input type='hidden' name='toenable[]' value='{$file}' />\n"; + if ($cat_mods[$file] == 'enabled') { + $CHECKED = "enabled"; + echo " \n<img src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-enabled by settings on SID Mgmt tab") . "\" />\n"; + } + else { + echo " \n<img style=\"opacity: 0.4; filter: alpha(opacity=40);\" src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-disabled by settings on SID Mgmt tab") . "\" />\n"; + } + } + else { + echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + } echo "</td>\n"; echo "<td class='listr' width='25%' >\n"; if (empty($CHECKED) || $CHECKED == "disabled") @@ -528,22 +606,39 @@ if ($savemsg) { echo "</td>\n"; } else echo "<td class='listbggrey' width='30%' colspan='2'><br/></td>\n"; + if (!empty($snortsorules[$j])) { $file = $snortsorules[$j]; echo "<td class='listr' width='5%' align=\"center\" valign=\"top\">"; if(is_array($enabled_rulesets_array)) { if (!empty($disable_vrt_rules)) $CHECKED = $disable_vrt_rules; - elseif(in_array($file, $enabled_rulesets_array)) + elseif(in_array($file, $enabled_rulesets_array) && !isset($cat_mods[$file])) $CHECKED = " checked=\"checked\""; else $CHECKED = ""; } else $CHECKED = ""; - echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + if (isset($cat_mods[$file])) { + if (in_array($file, $enabled_rulesets_array)) + echo "<input type='hidden' name='toenable[]' value='{$file}' />\n"; + if ($cat_mods[$file] == 'enabled') { + $CHECKED = "enabled"; + echo " \n<img src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-enabled by settings on SID Mgmt tab") . "\" />\n"; + } + else { + echo " \n<img style=\"opacity: 0.4; filter: alpha(opacity=40);\" src=\"../themes/{$g['theme']}/images/icons/icon_advanced.gif\" width=\"11\" height=\"11\" border=\"0\" title=\"" . gettext("Auto-disabled by settings on SID Mgmt tab") . "\" />\n"; + } + } + else { + echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + } echo "</td>\n"; echo "<td class='listr' width='25%' >\n"; + if (empty($CHECKED) || $CHECKED == "disabled") echo $file; + else + echo "<a href='snort_rules.php?id={$id}&openruleset=" . urlencode($file) . "'>{$file}</a>\n"; echo "</td>\n"; } else echo "<td class='listbggrey' width='30%' colspan='2'><br/></td>\n"; diff --git a/config/snort/snort_select_alias.php b/config/snort/snort_select_alias.php index c632b388..de504b7f 100644 --- a/config/snort/snort_select_alias.php +++ b/config/snort/snort_select_alias.php @@ -47,29 +47,31 @@ else // Retrieve any passed QUERY STRING or POST variables if (isset($_POST['type'])) - $type = $_POST['type']; + $type = htmlspecialchars($_POST['type']); elseif (isset($_GET['type'])) $type = htmlspecialchars($_GET['type']); if (isset($_POST['varname'])) - $varname = $_POST['varname']; + $varname = htmlspecialchars($_POST['varname']); elseif (isset($_GET['varname'])) $varname = htmlspecialchars($_GET['varname']); if (isset($_POST['multi_ip'])) - $multi_ip = $_POST['multi_ip']; + $multi_ip = htmlspecialchars($_POST['multi_ip']); elseif (isset($_GET['multi_ip'])) $multi_ip = htmlspecialchars($_GET['multi_ip']); -if (isset($_POST['returl'])) +if (isset($_POST['returl']) && substr($_POST['returl'], 0, 1) == '/') $referrer = urldecode($_POST['returl']); -elseif (isset($_GET['returl'])) +elseif (isset($_GET['returl']) && substr($_GET['returl'], 0, 1) == '/') $referrer = urldecode($_GET['returl']); +else + $referrer = $_SERVER['HTTP_REFERER']; // Make sure we have a valid VARIABLE name // and ALIAS TYPE, or else bail out. if (is_null($type) || is_null($varname)) { - header("Location: http://{$referrer}?{$querystr}"); + header("Location: {$referrer}?{$querystr}"); exit; } @@ -132,8 +134,8 @@ include("head.inc"); <input type="hidden" name="varname" value="<?=$varname;?>"/> <input type="hidden" name="type" value="<?=$type;?>"/> <input type="hidden" name="multi_ip" value="<?=$multi_ip;?>"/> -<input type="hidden" name="returl" value="<?=$referrer;?>"/> -<input type="hidden" name="org_querystr" value="<?=$querystr;?>"/> +<input type="hidden" name="returl" value="<?=htmlspecialchars($referrer);?>"/> +<input type="hidden" name="org_querystr" value="<?=htmlspecialchars($querystr);?>"/> <?php if ($input_errors) print_input_errors($input_errors); ?> <div id="boxarea"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> diff --git a/config/snort/snort_sid_mgmt.php b/config/snort/snort_sid_mgmt.php new file mode 100644 index 00000000..016cc96d --- /dev/null +++ b/config/snort/snort_sid_mgmt.php @@ -0,0 +1,606 @@ +<?php +/* + * snort_sid_mgmt.php + * + * Portions of this code are based on original work done for the + * Snort package for pfSense from the following contributors: + * + * Copyright (C) 2005 Bill Marquette <bill.marquette@gmail.com>. + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya Sr. Developer + * Copyright (C) 2012 Ermal Luci + * Copyright (C) 2014 Bill Meeks + * 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, $config, $rebuild_rules; + +$snortdir = SNORTDIR; +$pconfig = array(); + +// Grab saved settings from configuration +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$pconfig['auto_manage_sids'] = $config['installedpackages']['snortglobal']['auto_manage_sids']; + +// Hard-code the path where SID Mods Lists are stored +// and disregard any user-supplied path element. +$sidmods_path = SNORT_SID_MODS_PATH; + +// Set default to not show SID modification lists editor controls +$sidmodlist_edit_style = "display: none;"; + +if (!empty($_POST)) + $pconfig = $_POST; + +function snort_is_sidmodslist_active($sidlist) { + + /***************************************************** + * This function checks all the configured Snort * + * interfaces to see if the passed SID Mods List is * + * used by an interface. * + * * + * Returns: TRUE if List is in use * + * FALSE if List is not in use * + *****************************************************/ + + global $g, $config; + + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return FALSE; + + foreach ($config['installedpackages']['snortglobal']['rule'] as $rule) { + if ($rule['enable_sid_file'] == $sidlist) { + return TRUE; + } + if ($rule['disable_sid_file'] == $sidlist) { + return TRUE; + } + if ($rule['modify_sid_file'] == $sidlist) { + return TRUE; + } + } + return FALSE; +} + +if (isset($_POST['upload'])) { + if ($_FILES["sidmods_fileup"]["error"] == UPLOAD_ERR_OK) { + $tmp_name = $_FILES["sidmods_fileup"]["tmp_name"]; + $name = basename($_FILES["sidmods_fileup"]["name"]); + move_uploaded_file($tmp_name, "{$sidmods_path}{$name}"); + } + else + $input_errors[] = gettext("Failed to upload file {$_FILES["sidmods_fileup"]["name"]}"); +} + +if (isset($_POST['sidlist_delete']) && isset($_POST['sidlist_fname'])) { + if (!snort_is_sidmodslist_active(basename($_POST['sidlist_fname']))) + unlink_if_exists($sidmods_path . basename($_POST['sidlist_fname'])); + else + $input_errors[] = gettext("This SID Mods List is currently assigned to an interface and cannot be deleted."); +} + +if (isset($_POST['sidlist_edit']) && isset($_POST['sidlist_fname'])) { + $file = $sidmods_path . basename($_POST['sidlist_fname']); + $data = file_get_contents($file); + if ($data !== FALSE) { + $sidmodlist_data = htmlspecialchars($data); + $sidmodlist_edit_style = "display: table-row-group;"; + $sidmodlist_name = basename($_POST['sidlist_fname']); + unset($data); + } + else { + $input_errors[] = gettext("An error occurred reading the file."); + } +} + +if (isset($_POST['save']) && isset($_POST['sidlist_data'])) { + if (strlen(basename($_POST['sidlist_name'])) > 0) { + $file = $sidmods_path . basename($_POST['sidlist_name']); + $data = str_replace("\r\n", "\n", $_POST['sidlist_data']); + file_put_contents($file, $data); + unset($data); + } + else { + $input_errors[] = gettext("You must provide a valid filename for the SID Mods List."); + $sidmodlist_edit_style = "display: table-row-group;"; + } +} + +if (isset($_POST['save_auto_sid_conf'])) { + $config['installedpackages']['snortglobal']['auto_manage_sids'] = $pconfig['auto_manage_sids'] ? "on" : "off"; + + // Grab the SID Mods config for the interfaces from the form's controls array + foreach ($_POST['sid_state_order'] as $k => $v) { + $a_nat[$k]['sid_state_order'] = $v; + } + foreach ($_POST['enable_sid_file'] as $k => $v) { + if ($v == "None") { + unset($a_nat[$k]['enable_sid_file']); + continue; + } + $a_nat[$k]['enable_sid_file'] = $v; + } + foreach ($_POST['disable_sid_file'] as $k => $v) { + if ($v == "None") { + unset($a_nat[$k]['disable_sid_file']); + continue; + } + $a_nat[$k]['disable_sid_file'] = $v; + } + foreach ($_POST['modify_sid_file'] as $k => $v) { + if ($v == "None") { + unset($a_nat[$k]['modify_sid_file']); + continue; + } + $a_nat[$k]['modify_sid_file'] = $v; + } + + // Write the new configuration + write_config("Snort pkg: updated automatic SID management settings."); + + $intf_msg = ""; + + // If any interfaces were marked for restart, then do it + if (is_array($_POST['torestart'])) { + foreach ($_POST['torestart'] as $k) { + // Update the snort.conf file and + // rebuild rules for this interface. + $rebuild_rules = true; + conf_mount_rw(); + snort_generate_conf($a_nat[$k]); + conf_mount_ro(); + $rebuild_rules = false; + + // Signal Snort to "live reload" the rules + snort_reload_config($a_nat[$k]); + + $intf_msg .= convert_friendly_interface_to_friendly_descr($a_nat[$k]['interface']) . ", "; + } + $savemsg = gettext("Changes were applied to these interfaces: " . trim($intf_msg, ' ,') . " and Snort signaled to live-load the new rules."); + + // Sync to configured CARP slaves if any are enabled + snort_sync_on_changes(); + } +} + +if (isset($_POST['sidlist_dnload']) && isset($_POST['sidlist_fname'])) { + $file = $sidmods_path . basename($_POST['sidlist_fname']); + if (file_exists($file)) { + ob_start(); //important or other posts will fail + if (isset($_SERVER['HTTPS'])) { + header('Pragma: '); + header('Cache-Control: '); + } else { + header("Pragma: private"); + header("Cache-Control: private, must-revalidate"); + } + header("Content-Type: application/octet-stream"); + header("Content-length: " . filesize($file)); + header("Content-disposition: attachment; filename = " . basename($file)); + ob_end_clean(); //important or other post will fail + readfile($file); + } + else + $savemsg = gettext("Unable to locate the file specified!"); +} + +if (isset($_POST['sidlist_dnload_all_x'])) { + $save_date = date("Y-m-d-H-i-s"); + $file_name = "snort_sid_conf_files_{$save_date}.tar.gz"; + exec("cd {$sidmods_path} && /usr/bin/tar -czf {$g['tmp_path']}/{$file_name} *"); + + if (file_exists("{$g['tmp_path']}/{$file_name}")) { + ob_start(); //important or other posts will fail + if (isset($_SERVER['HTTPS'])) { + header('Pragma: '); + header('Cache-Control: '); + } else { + header("Pragma: private"); + header("Cache-Control: private, must-revalidate"); + } + header("Content-Type: application/octet-stream"); + header("Content-length: " . filesize("{$g['tmp_path']}/{$file_name}")); + header("Content-disposition: attachment; filename = {$file_name}"); + ob_end_clean(); //important or other post will fail + readfile("{$g['tmp_path']}/{$file_name}"); + + // Clean up the temp file + unlink_if_exists("{$g['tmp_path']}/{$file_name}"); + } + else + $savemsg = gettext("An error occurred while creating the gzip archive!"); +} + +// Get all files in the SID Mods Lists sub-directory as an array +// Leave this as the last thing before spewing the page HTML +// so we can pick up any changes made to files in code above. +$sidmodfiles = return_dir_as_array($sidmods_path); +$sidmodselections = array_merge(Array( "None" ), $sidmodfiles); + +$pgtitle = gettext("Snort: SID Management"); +include_once("head.inc"); + +?> + +<body link="#000000" vlink="#000000" alink="#000000"> + +<?php +include_once("fbegin.inc"); + +/* Display Alert message, under form tag or no refresh */ +if ($input_errors) + print_input_errors($input_errors); +?> + +<form action="snort_sid_mgmt.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> +<input type="hidden" name="MAX_FILE_SIZE" value="100000000" /> +<input type="hidden" name="sidlist_fname" id="sidlist_fname" value=""/> + +<?php +if ($savemsg) { + /* Display save message */ + print_info_box($savemsg); +} +?> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <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("Pass Lists"), false, "/snort/snort_passlist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("IP Lists"), false, "/snort/snort_ip_list_mgmt.php"); + $tab_array[8] = array(gettext("SID Mgmt"), true, "/snort/snort_sid_mgmt.php"); + $tab_array[9] = array(gettext("Log Mgmt"), false, "/snort/snort_log_mgmt.php"); + $tab_array[10] = array(gettext("Sync"), false, "/pkg_edit.php?xml=snort/snort_sync.xml"); + display_top_tabs($tab_array, true); + ?> + </td></tr> + <tr><td> + <div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> + <tbody> + <?php if ($g['platform'] == "nanobsd") : ?> + <tr> + <td colspan="2" class="listtopic"><?php echo gettext("SID auto-management is not supported on NanoBSD installs"); ?></td> + </tr> + <?php else: ?> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Settings"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable Automatic SID State Management"); ?></td> + <td width="78%" class="vtable"><input type="checkbox" id="auto_manage_sids" name="auto_manage_sids" value="on" + <?php if ($pconfig['auto_manage_sids'] == 'on') echo " checked"; ?> onclick="enable_sid_conf();" /> <?=gettext("Enable automatic management of rule state ") . + gettext("and content using configuration files. Default is ") . "<strong>" . gettext("Not Checked") . "</strong>";?>.<br/><br/> + <?=gettext("Snort will automatically enable/disable/modify text rules upon each update using criteria specified in configuration files. ") . + gettext("The supported configuration file format is the same as that used in the PulledPork and Oinkmaster enablesid.conf, disablesid.conf and ") . + gettext("modifysid.conf files. You can either upload existing files or create your own."); ?> + </td> + </tr> + </tbody> + <tbody id="sid_conf_rows"> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("SID Management Configuration Files"); ?></td> + </tr> + <tr> + <td colspan="2" class="vtable" align="center" > + <table width="100%" border="0" cellpadding="4" cellspacing="0"> + <tbody id="uploader" style="display: none;"> + <tr> + <td class="list"><br/><?php echo gettext("Click BROWSE to select a file to import, and then click UPLOAD. Click CLOSE to quit."); ?></td> + </tr> + <tr> + <td class="list"><input type="file" name="sidmods_fileup" id="sidmods_fileup" class="formfld file" size="50" /> + <input type="submit" name="upload" id="upload" value="<?=gettext("Upload");?>" + title="<?=gettext("Upload selected SID mods list to firewall");?>"/> <input type="button" + value="<?=gettext("Close");?>" onClick="document.getElementById('uploader').style.display='none';" /><br/></td> + <td class="list"></td> + </tr> + </tbody> + <tbody> + <tr> + <td> + <table id="maintable" width="100%" border="0" cellpadding="4" cellspacing="0"> + <colgroup> + <col style="width: 45%;"> + <col style="width: 25%;"> + <col style="width: 15%;"> + <col style="width: 15%;"> + </colgroup> + <thead> + <tr> + <th class="listhdrr"><?php echo gettext("SID Mods List File Name"); ?></th> + <th class="listhdrr"><?php echo gettext("Last Modified Time"); ?></th> + <th class="listhdrr"><?php echo gettext("File Size"); ?></th> + <th class="list" align="left"><img style="cursor:pointer;" name="sidlist_new" id="sidlist_new" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" + height="17" border="0" title="<?php echo gettext('Create a new SID Mods List');?>" + onClick="document.getElementById('sidlist_data').value=''; document.getElementById('sidlist_name').value=''; document.getElementById('sidlist_editor').style.display='table-row-group'; document.getElementById('sidlist_name').focus();" /> + <img style="cursor:pointer;" name="sidlist_import" id="sidlist_import" + onClick="document.getElementById('uploader').style.display='table-row-group';" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_import_alias.gif" width="17" + height="17" border="0" title="<?php echo gettext('Import/Upload a SID Mods List');?>"/> + <input type="image" name="sidlist_dnload_all" id="sidlist_dnload_all" + src="../tree/page-file_play.gif" width="16" height="16" border="0" + title="<?php echo gettext('Download all SID Mods List files in a single gzip archive');?>"/> + </th> + </tr> + </thead> + <tbody> + <?php foreach ($sidmodfiles as $file): ?> + <tr> + <td class="listr"><?php echo gettext($file); ?></td> + <td class="listr"><?=date('M-d Y g:i a', filemtime("{$sidmods_path}{$file}")); ?></td> + <td class="listr"><?=format_bytes(filesize("{$sidmods_path}{$file}")); ?> </td> + <td class="list"><input type="image" name="sidlist_edit[]" id="sidlist_edit[]" + onClick="document.getElementById('sidlist_fname').value='<?=$file;?>';" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" + height="17" border="0" title="<?php echo gettext('Edit this SID Mods List');?>"/> + <input type="image" name="sidlist_delete[]" id="sidlist_delete[]" + onClick="document.getElementById('sidlist_fname').value='<?=$file;?>'; + return confirm('<?=gettext("Are you sure you want to permanently delete this file? Click OK to continue or CANCEL to quit.");?>');" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" + height="17" border="0" title="<?php echo gettext('Delete this SID Mods List');?>"/> + <input type="image" name="sidlist_dnload[]" id="sidlist_dnload[]" + onClick="document.getElementById('sidlist_fname').value='<?=$file;?>';" + src="../tree/page-file_play.gif" width="16" height="16" border="0" + title="<?php echo gettext('Download this SID Mods List file');?>"/> + </td> + </tr> + <?php endforeach; ?> + </tbody> + <tbody id="sidlist_editor" style="<?=$sidmodlist_edit_style;?>"> + <tr> + <td colspan="4"> </td> + </tr> + <tr> + <td colspan="4"><strong><?=gettext("File Name: ");?></strong><input type="text" size="45" class="formfld file" id="sidlist_name" name="sidlist_name" value="<?=$sidmodlist_name;?>" /> + <input type="submit" id="save" name="save" value="<?=gettext(" Save ");?>" title="<?=gettext("Save changes and close editor");?>" /> + <input type="button" id="cancel" name="cancel" value="<?=gettext("Cancel");?>" onClick="document.getElementById('sidlist_editor').style.display='none';" + title="<?=gettext("Abandon changes and quit editor");?>" /></td> + </tr> + <tr> + <td colspan="4"> </td> + </tr> + <tr> + <td colspan="4"><textarea wrap="off" cols="80" rows="20" name="sidlist_data" id="sidlist_data" + style="width:95%; height:100%;"><?=$sidmodlist_data;?></textarea> + </td> + </tr> + </tbody> + <tbody> + <tr> + <td colspan="3" class="vexpl"><br/><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> + <br/><?php echo gettext("SID Mods Lists are stored as local files on the firewall and their contents are " . + "not saved as part of the firewall configuration file."); ?></td> + <td class="list"></td> + </tr> + <tr> + <td colspan="3" class="vexpl"><br/><strong><?php echo gettext("File List Controls:"); ?></strong><br/><br/> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" /> + <?=gettext("Opens the editor window to create a new SID Mods List. You must provide a valid filename before saving.");?><br/> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_import_alias.gif" width="17" height="17" border="0" /> + <?=gettext("Opens the file upload control for uploading a new SID Mods List from your local machine.");?><br/> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" /> + <?=gettext("Opens the SID Mods List in a text edit control for viewing or editing its contents.");?><br/> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" /> + <?=gettext("Deletes the SID Mods List from the file system after confirmation.");?><br/> + <img src="../tree/page-file_play.gif" width="16" height="16" border="0" /> + <?=gettext("Downloads the SID Mods List file to your local machine.");?><br/> + </td> + <td class="list"></td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Interface SID Management File Assignments"); ?></td> + </tr> + <tr> + <td colspan="2" class="vtable" align="center" > + <table width="100%" border="0" cellpadding="2" cellspacing="0"> + <tbody> + <tr> + <td> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <colgroup> + <col width="4%" align="center"> + <col width="20" align="center"> + <col width="16%" align="center"> + <col width="20%" align="center"> + <col width="20%" align="center"> + <col width="20%" align="center"> + </colgroup> + <thead> + <tr> + <th class="listhdrr"><?=gettext("Rebuild"); ?></th> + <th class="listhdrr"><?=gettext("Interface"); ?></th> + <th class="listhdrr"><?=gettext("SID State Order"); ?></th> + <th class="listhdrr"><?=gettext("Enable SID File"); ?></th> + <th class="listhdrr"><?=gettext("Disable SID File"); ?></th> + <th class="listhdrr"><?=gettext("Modify SID File"); ?></th> + </tr> + </thead> + <tbody> + <?php foreach ($a_nat as $k => $natent): ?> + <tr> + <td class="listr" align="center"> + <input type="checkbox" name="torestart[]" id="torestart[]" value="<?=$k;?>" title="<?=gettext("Apply new configuration and rebuild rules for this interface when saving");?>" /> + </td> + <td class="listbg"><?=convert_friendly_interface_to_friendly_descr($natent['interface']); ?></td> + <td class="listr" align="center"> + <select name="sid_state_order[<?=$k?>]" class="formselect" id="sid_state_order[<?=$k?>]"> + <?php + foreach (array("disable_enable" => "Disable, Enable", "enable_disable" => "Enable, Disable") as $key => $order) { + if ($key == $natent['sid_state_order']) + echo "<option value='{$key}' selected>"; + else + echo "<option value='{$key}'>"; + echo htmlspecialchars($order) . '</option>'; + } + ?> + </select> + </td> + <td class="listr" align="center"> + <select name="enable_sid_file[<?=$k?>]" class="formselect" id="enable_sid_file[<?=$k?>]"> + <?php + foreach ($sidmodselections as $choice) { + if ($choice == $natent['enable_sid_file']) + echo "<option value='{$choice}' selected>"; + else + echo "<option value='{$choice}'>"; + echo htmlspecialchars(gettext($choice)) . '</option>'; + } + ?> + </select> + </td> + <td class="listr" align="center"> + <select name="disable_sid_file[<?=$k?>]" class="formselect" id="disable_sid_file[<?=$k?>]"> + <?php + foreach ($sidmodselections as $choice) { + if ($choice == $natent['disable_sid_file']) + echo "<option value='{$choice}' selected>"; + else + echo "<option value='{$choice}'>"; + echo htmlspecialchars(gettext($choice)) . '</option>'; + } + ?> + </select> + </td> + <td class="listr" align="center"> + <select name="modify_sid_file[<?=$k?>]" class="formselect" id="modify_sid_file[<?=$k?>]"> + <?php + foreach ($sidmodselections as $choice) { + if ($choice == $natent['modify_sid_file']) + echo "<option value='{$choice}' selected>"; + else + echo "<option value='{$choice}'>"; + echo htmlspecialchars(gettext($choice)) . '</option>'; + } + ?> + </select> + </td> + </tr> + <?php endforeach; ?> + </tbody> + </table> + </td> + </tr> + <tr> + <td class="vexpl"> + </td> + </tr> + <tr> + <td> + <table width="100%" cellpadding="2" cellspacing="2" border="0"> + <tbody> + <tr> + <td colspan="2" class="vexpl" style="text-align: bottom;"><strong><span class="red"><?=gettext("Notes:");?></span></strong></td> + </tr> + <tr> + <td class="vexpl" style="vertical-align: top;"><?=gettext("1.");?></td> + <td class="vexpl"><?=gettext("Check the box beside an interface to immediately apply new auto-SID management ") . + gettext("changes and signal Snort to live-load the new rules for the interface when clicking SAVE; ") . + gettext("otherwise only the new file assignments will be saved.");?> + </td> + </tr> + <tr> + <td class="vexpl" style="vertical-align: top;"><?=gettext("2.");?></td> + <td class="vexpl"><?=gettext("SID State Order controls the order in which enable and disable state modifications are performed. ") . + gettext("An example would be to disable an entire category and later enable only a rule or two from it. In this case you would ") . + gettext("choose 'disable,enable' for the State Order. Note that the last action performed takes priority.");?> + </td> + </tr> + <tr> + <td class="vexpl" style="vertical-align: top;"><?=gettext("3.");?></td> + <td class="vexpl"><?=gettext("The Enable SID File, Disable SID File and Modify SID File controls specify which rule modification ") . + gettext("files are run automatically for the interface. Setting a file control to 'None' disables that modification. ") . + gettext("Setting all file controls for an interface to 'None' disables automatic SID state management for the interface.");?> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + <tbody> + <tr> + <td colspan="2" class="vexpl" align="center"><input type="submit" id="save_auto_sid_conf" name="save_auto_sid_conf" class="formbtn" value="<?=gettext("Save");?>" title="<?=gettext("Save SID Management configuration");?>" /> + <?=gettext("Remember to save changes before exiting this page"); ?> + </td> + </tr> + <?php endif; ?> + </tbody> + </table> + </div> + </td></tr> + </tbody> +</table> +</form> + +<?php include("fend.inc"); ?> + +<?php if ($g['platform'] != "nanobsd") : ?> +<script type="text/javascript"> + +function enable_sid_conf() { + var endis = !document.iform.auto_manage_sids.checked; + if (endis) { + document.getElementById("sid_conf_rows").style.display = "none"; + } + else { + document.getElementById("sid_conf_rows").style.display = ""; + } +} + +enable_sid_conf(); + +</script> +<?php endif; ?> + +</body> +</html> diff --git a/config/snort/snort_sync.xml b/config/snort/snort_sync.xml index 2b9594ea..f3db2ce9 100755 --- a/config/snort/snort_sync.xml +++ b/config/snort/snort_sync.xml @@ -53,39 +53,58 @@ POSSIBILITY OF SUCH DAMAGE. <tab> <text>Snort Interfaces</text> <url>/snort/snort_interfaces.php</url> + <no_drop_down/> </tab> <tab> <text>Global Settings</text> <url>/snort/snort_interfaces_global.php</url> + <no_drop_down/> </tab> <tab> <text>Updates</text> <url>/snort/snort_download_updates.php</url> + <no_drop_down/> </tab> <tab> <text>Alerts</text> <url>/snort/snort_alerts.php</url> + <no_drop_down/> </tab> <tab> <text>Blocked</text> <url>/snort/snort_blocked.php</url> + <no_drop_down/> </tab> <tab> <text>Pass Lists</text> <url>/snort/snort_passlist.php</url> + <no_drop_down/> </tab> <tab> <text>Suppress</text> <url>/snort/snort_interfaces_suppress.php</url> + <no_drop_down/> </tab> <tab> <text>IP Lists</text> <url>/snort/snort_ip_list_mgmt.php</url> + <no_drop_down/> + </tab> + <tab> + <text>SID Mgmt</text> + <url>/snort/snort_sid_mgmt.php</url> + <no_drop_down/> + </tab> + <tab> + <text>Log Mgmt</text> + <url>/snort/snort_log_mgmt.php</url> + <no_drop_down/> </tab> <tab> <text>Sync</text> <url>/pkg_edit.php?xml=snort/snort_sync.xml</url> <active/> + <no_drop_down/> </tab> </tabs> <fields> @@ -188,6 +207,6 @@ POSSIBILITY OF SUCH DAMAGE. <custom_delete_php_command> </custom_delete_php_command> <custom_php_resync_config_command> - write_config();snort_sync_on_changes(); + write_config("Snort pkg: saved changes to XMLRPC sync configuration.");snort_sync_on_changes(); </custom_php_resync_config_command> </packagegui> |